text
stringlengths 184
4.48M
|
---|
{% extends "base.html" %}
{% block content %}
<div class="center-container">
<h2>Add new printer</h2>
</div>
<form method="POST">
<input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
<div class="form-row">
<div class="form-item">
<label for="printer_serial_number">Printer Serial Number:<span class="required"> *</span></label>
<input type="text" id="printer_serial_number" name="printer_serial_number" required pattern=".{9,}">
</div>
<div class="form-item">
<label for="model">Printer Model:</label>
<input type="text" id="model" name="model" required>
</div>
</div>
<div class="form-row">
<div class="form-item">
<label for="assigned">Assigned:</label>
<input type="checkbox" id="assigned" name="assigned">
</div>
<div class="form-item">
<label for="active">Active:</label>
<input type="checkbox" id="active" name="active" checked>
</div>
</div>
<div class="form-row">
<div class="form-item">
<label for="company">Client - Company name:</label>
<input list="companies" type="text" id="company" name="company">
<datalist id="companies">
{% for client in clients %}
<option value="{{ client['company'] }}">
{% endfor %}
</datalist>
</div>
<div class="form-item">
<label for="contract_id">Contract/Warranty ID:</label>
<input type="text" id="contract_id" name="contract_id">
</div>
</div>
<div class="form-row">
<div class="form-item">
<label for="counter_black">Counter Black:</label>
<input type="number" id="counter_black" name="counter_black" value="0" min="0">
</div>
<div class="form-item">
<label for="counter_color">Counter Color:</label>
<input type="number" id="counter_color" name="counter_color" value="0" min="0">
</div>
</div>
<div class="form-row">
<div class="form-item">
<label for="warranty">Warranty:</label>
<input type="checkbox" id="warranty" name="warranty">
</div>
<div class="form-item">
<label for="warranty_duration">Warranty Duration:</label>
<input type="number" id="warranty_duration" name="warranty_duration" min="0">
</div>
</div>
<div class="form-row">
<div class="form-item">
<label for="service_contract">Service Contract:</label>
<input type="checkbox" id="service_contract" name="service_contract">
</div>
<div class="form-item">
<label for="lease_rent">Lease Rent:</label>
<input type="number" id="lease_rent" name="lease_rent" min="0" step="0.1">
</div>
</div>
<div class="form-row">
<div class="form-item">
<label for="price_black">Price Black:</label>
<input type="number" id="price_black" name="price_black" min="0" step="0.01">
</div>
<div class="form-item">
<label for="price_color">Price Color:</label>
<input type="number" id="price_color" name="price_color" min="0" step="0.01">
</div>
</div>
<div class="form-row">
<div class="form-item">
<label for="start_date">Start Date:</label>
<input type="date" id="start_date" name="start_date">
</div>
<div class="form-item">
<label for="contract_duration">Contract Duration:</label>
<input type="number" id="contract_duration" name="contract_duration" min="0">
</div>
</div>
<div class="form-row">
<div class="form-item">
<label for="additional_info">Additional Info:</label>
<input type="text" id="additional_info" name="additional_info">
</div>
</div>
<div class="button-group">
<input type="submit" value="Submit">
<button type="button" onclick="window.location.href='/index'">Discard</button>
</div>
<div><span class="required">*</span> - required field.</div>
</form>
<script>
var printerModels = {{ printer_models | tojson | safe }};
document.getElementById('printer_serial_number').addEventListener('input', function(e) {
var inputValue = e.target.value.toUpperCase();
var model = 'Unknown model';
for (var prefix in printerModels) {
if (inputValue.startsWith(prefix)) {
model = printerModels[prefix];
break;
}
}
document.getElementById('model').value = model;
});
var warrantyCheckbox = document.getElementById('warranty');
var serviceContractCheckbox = document.getElementById('service_contract');
var warrantyDurationInput = document.getElementById('warranty_duration');
var leaseRentInput = document.getElementById('lease_rent');
var priceBlackInput = document.getElementById('price_black');
var priceColorInput = document.getElementById('price_color');
var contractDurationInput = document.getElementById('contract_duration');
var printerSerialNumberInput = document.getElementById('printer_serial_number');
priceBlackInput.disabled = true;
priceColorInput.disabled = true;
leaseRentInput.disabled = true;
warrantyDurationInput.disabled = true;
contractDurationInput.disabled = true;
warrantyCheckbox.addEventListener('change', function() {
if (this.checked) {
serviceContractCheckbox.disabled = true;
warrantyDurationInput.disabled = false;
} else {
serviceContractCheckbox.disabled = false;
warrantyDurationInput.disabled = true;
}
});
printerSerialNumberInput.addEventListener('input', function() {
this.value = this.value.toUpperCase();
});
serviceContractCheckbox.addEventListener('change', function() {
if (this.checked) {
warrantyCheckbox.disabled = true;
warrantyDurationInput.disabled = true;
priceBlackInput.disabled = false;
priceColorInput.disabled = false;
leaseRentInput.disabled = false;
contractDurationInput.disabled = false;
} else {
warrantyCheckbox.disabled = false;
warrantyDurationInput.disabled = false;
priceBlackInput.disabled = true;
priceColorInput.disabled = true;
leaseRentInput.disabled = true;
contractDurationInput.disabled = true;
}
});
var assignedCheckbox = document.getElementById('assigned');
var clientInput = document.getElementById('company');
assignedCheckbox.addEventListener('change', function() {
if (this.checked) {
clientInput.disabled = false;
} else {
clientInput.disabled = true;
}
});
</script>
{% endblock %} |
import { Injectable } from '@nestjs/common';
import { log } from 'console';
import { UserDTO } from 'src/DTO/user.dto';
import { DataBaseConnectionService } from 'src/data-base-connection/data-base-connection.service';
import * as bcrypt from 'bcrypt';
import { JwtService } from '@nestjs/jwt';
import { jwtConstants } from './constants';
import { EmailService } from 'src/email/email.service';
@Injectable()
export class LoginService {
private codes = {}
users: UserDTO[] = [];
salt = '$2b$10$bakP3knpCwhf6vQoCZsh4.'
constructor(private ser: DataBaseConnectionService, private email: EmailService, private jwtService: JwtService) { }
getAll() {
return this.users;
}
async getUserById(id: Number) {
let user = await this.ser.getUser(id);
return user;
}
async updateUser(user: UserDTO) {
return this.ser.updateUser(user)
}
async login(user: UserDTO) {
this.users = await this.ser.getUsers();
user.password = await this.hashPassword(user.password);
if (user.name == undefined) {
//login
let user_login = this.users.find(u => u.email == user.email && u.password == user.password);
if (!user_login)
return { stat: 400, desc: "email or password incorrect" };
else {
const payload = { username: user_login.name, id: user_login.id };
return {
stat: 200,
desc: this.createToken(payload)
}
}
}
else {
//sign up
let user_email = this.users.find(u => u.email == user.email);
if (user_email)
return { stat: 400, desc: 'this email already exists' };
else
if (user.name && user.password && user.email) {
let newId = await this.ser.insertUser(user);
const payload = { username: user.name, id: newId };
return { stat: 201, desc: this.createToken(payload) };
} else
return { stat: 400, desc: 'missing some information' };
}
}
async forgotPassword(email) {
let user = await this.ser.getUserByEmail(email)
if(!user)
return 401
let pass = ''
for (let i = 0; i <2; i++) { //TODO change loop to 6 iterations
pass += Math.round(Math.random() * 9)
}
this.codes[email] = pass
console.log(pass, 'code');
this.email.sendEmail(email, 'קוד אימות ', " קוד האימות הוא:" + pass)
return 200
}
ifCodeTrue(email, code) {
console.log(this.codes,"codes");
console.log(this.codes[email] == code);
if (this.codes[email] == code){
return true
}
return false
}
async newPassword(email, newPassword){
let payload = await this.ser.changePassword(email,await this.hashPassword(newPassword))
let token = this.createToken(payload)
return token
}
private createToken(payload) {
const expireIn = 5 * 60 * 60 * 1000 + " ";
return {
access_token: this.jwtService.sign(payload, {
expiresIn: expireIn,
secret: jwtConstants.secret,
})
}
}
async hashPassword(password: string): Promise<string> {
const hash = await bcrypt.hash(password, this.salt);
return hash;
}
} |
# Engineering Lab 1 - Digital Freight Matching
## What is this API for?
See [Problem Statement](ProblemStatement.md) for more details
## Prerequisites
Before you begin, ensure you have met the following requirements:
- Ruby 3.2.2 (use `rbenv` or `rvm` to install)
- Bundler (installed via `gem install bundler`)
- Rails 7.0.8
## Getting Started
To get the project up and running on your local machine, follow these steps:
1. **Clone the Repository:**
```bash
git clone git@github.com:yogimathius/digital_freight_matcher_eng_lab.git
cd digital_freight_matcher_eng_lab
```
2. **Install Dependencies:**
```bash
bundle install
```
3. **Database Setup:**
```bash
rails db:create
rails db:migrate
rails db:seed
```
4. **Run the Server:**
```bash
rails server
```
The application will be accessible at [http://localhost:3000](http://localhost:3000).
## Testing
For main test suite
```bash
bin/rails test
```
To run large batch tests with csv data:
```bash
RUN_LARGE_TEST_SUITE=1 bin/rails test
```
For model validation tests:
```bash
bundle exec rspec
```
## How To Use
This API is designed to receive orders in the following format:
### Order Structure
```
{
cargo: {
"packages": [1, 60, 'standard'] // CBM (vol.), weight (pounds), type
},
pick_up: {
"latitude": 33.754413815792205,
"longitude": -84.3875298776525
},
drop_off: {
"latitude": 34.87433824316913,
"longitude": -85.08447506395166
}
}
```
To attempt adding an order to a route:
- using a REST client like [Postman](https://www.postman.com/) or [VSCode's REST Client](https://marketplace.visualstudio.com/items?itemName=humao.rest-client) or CURL:
- make a `POST` request to `http://localhost:3000/orders` using the above [Order Structure](#order-structure), if you wish
- if the order is within 1km proximity (using heron's formula, margin for error with large batch tests is ~0.2%) of a route's linear distance, the route can fit the order in it's shift duration and the truck has capacity for all of the packages, it will add the order to that route, and return the following data structure:
```
{
"message": "Success! adding to route #1, heading from Atlanta to Ringgold",
"order": {
"id": 6,
"origin_id": 13,
"destination_id": 14,
"client_id": 6,
"route_id": 1,
"created_at": "2023-12-03T05:51:49.479Z",
"updated_at": "2023-12-03T05:51:49.479Z",
"backlog_id": null
}
}
```
- If no routes are found for the order, a generic response `No routes found` will be given
- If the order matches routes but the all route's shift duration have been maxed already, the following response will be given:
```
{
"message": "Shift duration maxed, adding to backlog",
"order": {
"id": 12,
"origin_id": 25,
"destination_id": 26,
"client_id": 13,
"route_id": 1,
"created_at": "2023-12-03T06:15:53.454Z",
"updated_at": "2023-12-03T06:15:53.454Z",
"backlog_id": 1 // Notice backlog ID
}
}
```
- If the order matches routes but all truck capacity is full, the following response will be given:
```
{
"message": "Truck capacity maxed, adding to backlog",
"order": {
"id": 3,
"origin_id": 7,
"destination_id": 8,
"client_id": 3,
"route_id": 1,
"created_at": "2023-12-03T06:17:56.344Z",
"updated_at": "2023-12-03T06:17:56.344Z",
"backlog_id": 1
}
}
```
- WIP: If the order contains a package with type `medicine`, or route contains `medicine` packages and `food` or `standard` is attempted to be mixed with `medicine` the following response will be given:
```
{
"message": "Current routes can't mix with medicine, adding to backlog",
"order": {
"id": 6,
"origin_id": 13,
"destination_id": 14,
"client_id": 6,
"route_id": null,
"created_at": "2023-12-03T06:58:07.216Z",
"updated_at": "2023-12-03T06:58:07.216Z",
"backlog_id": 1
}
}
```
- order is always added to the backlog of the first matching route, which should be the most profitable
- truckers will take a 30 min break if shift duration exceeds 4 hours
### TODOS
- TODO: Sort matching routes by most profitable. We can usually rely on just one route being found based on proximity unless both pickup and dropoff are close to one Atlanta. In this case it is unlikely the profitability would be significant, but this would still be good to handle.
- TODO: wire up check that pallets have been dropped before medicine can be picked up (have to test pickup, dropoff)
- TODO: Complete test coverage for major functions (97% currently, but not all methods are tested.. these are covered through parent functions and a significant amount of child functions were added as a burst refactor)
- TODO: Clear backlog after X amount of time? Queue backlog to next day's shifts?
- TODO: Fix failing tests ~11000 assertions with `RUN_LARGE_TEST_SUITE=1 bin/rails test`, and 30 failures. Some of these are due to inaccurate lat/long, some are due to triangular formula for proximity. |
<html class="dark">
<head>
<title>WAKEUPSERVER</title>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="color-scheme" content="light dark">
<meta name="theme-color" content="#111111" media="(prefers-color-scheme: light)">
<meta name="theme-color" content="#eeeeee" media="(prefers-color-scheme: dark)">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous"> -->
<!-- <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css" integrity="sha384-/Y6pD6FV/Vv2HJnA6t+vslU6fwYXjCFtcEpHbNJ0lyAFsXTsjBbfaDjzALeQsN6M" crossorigin="anonymous"> -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.0.0/dist/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" integrity="sha384-wvfXpqpZZVQGK6TAh5PVlGOfQNHSoD2xbE+QkPxCAFlNEevoEH3Sl0sibVcOQVnN" crossorigin="anonymous">
<style>
.hideMe {
display: none;
}
#snackbar {
min-width: 250px;
margin-left: -125px;
background-color: #333;
color: #fff;
text-align: center;
border-radius: 2px;
padding: 16px;
position: fixed;
z-index: 1;
left: 50%;
bottom: 30px;
border-radius: 10px;
}
</style>
</head>
<body>
<div class="container-fluid bg-dark text-white">
<div class="row">
<div class="col-12" role="main">
<h1><span class="fa fa-qq"></span> WAKEUPSERVER <small>Wake servers up!</small></h1>
<div id="snackbar" class="alert hideMe">
Message comes here
</div>
<form id="addComputerForm" class="form-outline form-white" method="POST" action="/api/computer/add" >
<div class="row">
<div class="form-group col-4">
<label for="computerName">Computer Name</label>
<input type="text" class="form-control bg-dark text-white" id="computerName" placeholder="Enter Computer Name">
</div>
<div class="form-group col-4">
<label for="computerMAC">Computer MAC</label>
<input type="text" class="form-control bg-dark text-white" id="computerMAC" placeholder="Enter Computer MAC">
</div>
<div class="form-group col-4">
<label for="computerBroadcastIP">Computer Broadcast IP</label>
<input type="text" class="form-control bg-dark text-white" id="computerBroadcastIP" placeholder="Enter Computer IP">
</div>
</div>
<button type="submit" class="btn btn-primary">Add Computer</button>
</form>
<style>
/* form split in line */
.form-inline .form-group {
display: inline-block;
margin-bottom: 0;
vertical-align: middle;
}
</style>
<table class="table table-striped table-dark">
<thead>
<tr>
<th>
<b>
<button id="bn_wakeUpAll" name="wolbutton" value="wakeUpAll" class="btn btn-success btn-sm" onclick="$.wakeUpAllComputers()">
<span class="fa fa-qq"></span> WakeUp All
</button>
</b>
</th>
<th>Computer</th>
<th>MAC Adress</th>
<th>Broadcast IP Address</th>
<th>API URL</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
{{range .}}
<tr>
<td class="align-middle"><b><button id="bn_{{.Name}}" name="wolbutton" value="{{.Name}}" class="btn btn-success btn-sm" onclick="$.wakeUpComputerByName('{{.Name}}')">WakeUp</button></b></td>
<td class="align-middle">{{.Name}}</td>
<td class="align-middle">{{.Mac}}</td>
<td class="align-middle">{{.BroadcastIPAddress}}</td>
<td class="align-middle">/api/wakeup/computer/{{.Name}}</td>
<td class="align-middle">
<button id="bn_delete_{{.Name}}" name="deletebutton" value="{{.Name}}" class="btn btn-danger btn-sm" onclick="$.deleteComputerByName('{{.Name}}')">Delete</button>
</td>
</tr>
{{end}}
</tbody>
</table>
<hr>
<p>
<h3>REST API Usage</h3>
<b>/api/wakeup/computer/<span class="text-info"><ComputerName></span></b>
<b>Returns a JSON Object</b>
<p>
<pre class="text-white">
{
"success":true,
"message":"Succesfully Wakeup Computer Computer1 with Mac 64-07-2D-BB-BB-BF on Broadcast IP 192.168.10.254:9",
"error":null
}
</pre>
</p>
<dl class="dl-horizontal">
<dt>success</dt>
<dd>True or False if the WakeOnLan Paket was send</dd>
<dt>message</dt>
<dd>Message as string what happen</dd>
<dt>error</dt>
<dd>Encoded Jsonobject from GOLANG Error Object</dd>
</dl>
</p>
<hr>
<p>
<span class="fa fa-github"></span> Project Page: <a href="https://github.com/shawnsavour/WakeupServer">https://github.com/shawnsavour/WakeupServer</a>
</p>
<p>
<small>Build with <span class="fa fa-heart text-danger" aria-hidden="true"></span> by <a href="https://shawnsavour.com">ShawnSavour</a> <span class="fa fa-github"></span> <a href="https://github.com/shawnsavour">https://github.com/shawnsavour</a></small>
</p>
</div>
</div>
</div>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/tether/1.4.0/js/tether.min.js" integrity="sha384-DztdAPBWPRXSA/3eYEEUWrWCy7G5KFbe8fFjk5JAIxUYHKkDx6Qin1DkWx51bBrb" crossorigin="anonymous"></script>
<!-- <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/js/bootstrap.min.js" integrity="sha384-vBWWzlZJ8ea9aCX4pEW3rVHjgjt7zpkNpZk+02D9phzyeVkE+jo0ieGizqPLForn" crossorigin="anonymous"></script> -->
<!-- <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script> -->
<script src="https://cdn.jsdelivr.net/npm/popper.js@1.12.9/dist/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@4.0.0/dist/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
<!-- <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p" crossorigin="anonymous"></script> -->
<script>
$(document).ready(function() {
jQuery.showSnackBar = function(data){
$('#snackbar').text(data.message);
if( data.error != null) {
$('#snackbar').addClass('alert-danger');
$('#snackbar').removeClass('alert-success')
}else{
$('#snackbar').removeClass('alert-danger')
$('#snackbar').addClass('alert-success')
}
$('#snackbar').show();
// After 2 seconds, hide the Div Again
setTimeout(function(){
$('#snackbar').hide();
}, 2000);
};
jQuery.wakeUpComputerByName = function(computerName) {
$.ajax({
type: "GET",
url: "/api/wakeup/computer/" + computerName,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data) {
$.showSnackBar(data);
},
error: function(data,err)
{
$.showSnackBar(data);
console.error(data);
}
})
};
// wake all computers
jQuery.wakeUpAllComputers = function() {
$.ajax({
type: "GET",
url: "/api/wakeup/all",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data) {
$.showSnackBar(data);
},
error: function(data,err)
{
$.showSnackBar(data);
console.error(data);
}
})
};
jQuery.deleteComputerByName = function(computerName) {
$.ajax({
type: "DELETE",
url: "/api/computer/" + computerName,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data) {
$.showSnackBar(data);
location.reload();
},
error: function(data,err)
{
$.showSnackBar(data);
console.error(data);
}
})
};
// form submit as json
$('#addComputerForm').submit(function(e) {
e.preventDefault();
var computerName = $('#computerName').val();
var computerMAC = $('#computerMAC').val();
var computerBroadcastIP = $('#computerBroadcastIP').val();
// check if all fields are filled
if(computerName == "" || computerMAC == "" || computerBroadcastIP == ""){
$.showSnackBar({message: "Please fill all fields", error: null});
return;
}
// check if mac is valid
if(!computerMAC.match(/^([0-9A-Fa-f]{2}[:-]){5}([0-9A-Fa-f]{2})$/)){
$.showSnackBar({message: "Please enter a valid MAC Address", error: null});
return;
}
// check if ip is valid
if(!computerBroadcastIP.match(/^([0-9]{1,3}\.){3}[0-9]{1,3}:[0-9]{1,5}$/)){
$.showSnackBar({message: "Please enter a valid Broadcast IP Address", error: null});
return;
}
// check if hostname is duplicate
if($('#bn_' + computerName).length > 0){
$.showSnackBar({message: "Computername already exists", error: null});
return;
}
var data = {
"name": computerName,
"mac": computerMAC,
"broadcastIPAddress": computerBroadcastIP
};
$.ajax({
type: "POST",
url: "/api/computer/add",
data: JSON.stringify(data),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data) {
$.showSnackBar(data);
location.reload();
},
error: function(data,err)
{
$.showSnackBar(data);
console.error(data);
}
})
});
});
</script>
</body>
</html> |
<!DOCTYPE html>
<!--
Site responsivo com menu lateral e barra de navegação com botão de busca.
Feito usando apenas HTML/CSS, seguindo os exemplos na pagina https://www.w3schools.com/
Trabalho para o curso de ADS ead.
Aluno: João Paulo Cruz Rosa.
//-->
<html>
<head>
<!--importando os estilos CSS externos-->
<link rel="stylesheet" type="text/css" href="meuestilo.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
</head>
<body>
<!--Cria a barra de navegação-->
<ul>
<!--Cria o menu drop down-->
<li class="dropdown">
<a href="javascript:void(0)" class="dropbtn"><b>☰ </b></a>
<div class="dropdown-content">
<a href="noticias.html" target="iframe_a">☇ Notícias principais</a>
<a href="paravoce.html" target="iframe_a">♡ Para você</a>
<a href="favoritos.html" target="iframe_a">☆ Favoritos</a>
<a href="#">☉ Pesquisas salvas</a>
<p>——————————</p>
<a href="#">⚐ Brasil</a>
<a href="#">⚪ Mundo</a>
<a href="#">✈ Local</a>
<a href="#">✍ Negócios</a>
<a href="#">☢ Ciência e tecnologia</a>
<a href="#">⚅ Entretenimento</a>
<a href="#">⚯ Esportes</a>
<a href="#">⚕ Saúde</a>
</div>
</li>
<li><a href="favoritos.html" target="iframe_a">Home</a></li>
<li><a href="noticias.html" target="iframe_a">News</a></li>
<!--Cria o botão de pesquisa-->
<form class="example" action="/action_page.php" style="float: right;"> <!--Coloca o botão do lado direito-->
<input type="text" placeholder="Search.." name="search">
<button type="submit"><i class="fa fa-search"></i></button>
</form>
</ul>
<!--Cria coluna com o conteudo do site-->
<div class="row">
<div class="column">
</div>
<!--Conteudo textual do site-->
<div class="column">
<iframe height="820px" width="100%" src="noticias.html" name="iframe_a" style="border:none;"></iframe>
<!--"-->
</div>
<div class="column">
</div>
</div>
<footer>
<address>© João Paulo 2019 - Contact <a href="mailto:joao.rosa1@alunos.unis.edu.br">me</a></address>
</footer>
</body>
</html> |
/* SecuDroid - An open source, free manager for SECU-3 engine control unit
Copyright (C) 2020 Vitaliy O. Kosharskiy. Ukraine, Kharkiv
SECU-3 - An open source, free engine control unit
Copyright (C) 2007 Alexey A. Shabelnikov. Ukraine, Kyiv
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/>.
contacts:
http://secu-3.org
email: vetalkosharskiy@gmail.com
*/
package org.secu3.android.models.packets.params
import org.secu3.android.models.packets.BaseOutputPacket
data class AnglesParamPacket(
var maxAngle: Float = 0f,
var minAngle: Float = 0f,
var angleCorrection: Float = 0f,
var angleDecSpeed: Float = 0f,
var angleIncSpeed: Float = 0f,
var zeroAdvAngle: Int = 0,
var ignFlags: Int = 0,
var shiftIgnTim: Float = 0f
) : BaseOutputPacket(){
var ignTimWrkMap: Boolean
get() = ignFlags.getBitValue(0) > 0
set(value) {ignFlags = ignFlags.setBitValue(value, 0)}
var manIngTimIdl: Boolean
get() = ignFlags.getBitValue(1) > 0
set(value) {ignFlags = ignFlags.setBitValue(value, 1)}
var zeroAdvAngOct: Boolean
get() = ignFlags.getBitValue(2) > 0
set(value) {ignFlags = ignFlags.setBitValue(value, 2)}
companion object {
internal const val DESCRIPTOR = 'm'
fun parse(data: String) = AnglesParamPacket().apply {
maxAngle = data.get2Bytes(2).toFloat() / ANGLE_DIVIDER
minAngle = data.get2Bytes(4).toFloat() / ANGLE_DIVIDER
angleCorrection = data.get2Bytes(6).toShort().toFloat() / ANGLE_DIVIDER
angleDecSpeed = data.get2Bytes(8).toFloat() / ANGLE_DIVIDER
angleIncSpeed = data.get2Bytes(10).toFloat() / ANGLE_DIVIDER
zeroAdvAngle = data[12].code
ignFlags = data[13].code
shiftIgnTim = data.get2Bytes(14).toShort().toFloat()/ ANGLE_DIVIDER
}
}
override fun pack(): String {
var data = "$OUTPUT_PACKET_SYMBOL$DESCRIPTOR"
data += data.write2Bytes(maxAngle.times(LOAD_PHYSICAL_MAGNITUDE_MULTIPLIER).toInt())
data += data.write2Bytes(minAngle.times(LOAD_PHYSICAL_MAGNITUDE_MULTIPLIER).toInt())
data += data.write2Bytes(angleCorrection.times(LOAD_PHYSICAL_MAGNITUDE_MULTIPLIER).toInt())
data += data.write2Bytes(angleDecSpeed.times(LOAD_PHYSICAL_MAGNITUDE_MULTIPLIER).toInt())
data += data.write2Bytes(angleIncSpeed.times(LOAD_PHYSICAL_MAGNITUDE_MULTIPLIER).toInt())
data += zeroAdvAngle.toChar()
return data
}
} |
# @eth-optimism/indexer
## Getting started
### Configuration
The `indexer.toml` contains configuration for the indexer. The file is templated for the local devnet, however presets are available for [known networks](https://github.com/ethereum-optimism/optimism/blob/develop/indexer/config/presets.go). The file also templates keys needed for custom networks such as the rollup contract addresses and the `l1-starting-height` for the deployment height.
Required configuration is network specific `(l1|l2)-rpc` urls that point to archival nodes as well as the `(l1|l2)-polling-interval` & `(l1|l2)-header-buffer-size` keys which controls the of rate data retrieval from these notes.
### Testing
All tests can be ran by running `make test` from the `/indexer` directory. This will run all unit and e2e tests.
> **NOTE:** Successfully running the E2E tests requires spinning up a local devnet via [op-e2e](https://github.com/ethereum-optimism/optimism/tree/develop/op-e2e) and pre-populating it with necessary bedrock genesis state. This genesis state is generated by invoking the`make devnet-allocs` target from the root of the optimism monorepo before running the indexer tests. More information on this can be found in the [op-e2e README](../op-e2e/README.md). A postgres database through pwd-less user $DB_USER env variable on port 5432 must be available as well.
### Run the Indexer (docker-compose)
The local [docker-compose.go](https://github.com/ethereum-optimism/optimism/blob/develop/indexer/docker-compose.yml) file spins up **index, api, postgres, prometheus and grafana** services. The `indexer.toml` file is setup for the local devnet. To run against a live network, update the `indexer.toml` with the desired configuration.
> The API, Postgres, and Grafana services are the only ones with ports mapped externally. Postgres database is mapped to port 5433 to deconflict any instances already running on the default port
1. Install Deps: Docker, Genesis State: `make devnet-allocs`
2. Start Devnet `make devnet up`, Otherwise update `indexer.toml` to desired network config.
3. Start Indexer: `cd indexer && docker-compose up`
4. View the Grafana dashboard at http://localhost:3000
- **User**: admin
- **Password**: optimism
### Run the Indexer (Go Binary or Dockerfile)
1. Prepare the `indexer.toml` file
2. **Run database migrations**: `indexer migrate --config <indexer.toml>`
3. Run index service, cmd: `indexer index --config <indexer.toml>`
4. Run the api service, cmd: `indexer api --config <indexer.toml>`
> Both the index and api services listen on an HTTP and Metrics port. Migrations should **always** be run prior to start the indexer to ensure latest schemas are set.
## Architecture

The indexer application supports two separate services for collective operation:
**Indexer API** - Provides a lightweight API service that supports paginated lookups for bridge data.
**Indexer Service** - A polling based service that constantly reads and persists OP Stack chain data (i.e, block meta, system contract events, synchronized bridge events) from a L1 and L2 chain.
### Indexer API
See `api/api.go` & `api/routes/` for available API endpoints to for paginated retrieval of bridge data. **TDB** docs.
### Indexer Service

The indexer service is responsible for polling and processing real-time batches of L1 and L2 chain data. The indexer service is currently composed of the following key components:
- **Poller Routines** - Individually polls the L1/L2 chain for new blocks and OP Stack contract events.
- **Insertion Routines** - Awaits new batches from the poller routines and inserts them into the database upon retrieval.
- **Bridge Routine** - Polls the database directly for new L1 blocks and bridge events. Upon retrieval, the bridge routine will:
* Process and persist new bridge events
* Synchronize L1 proven/finalized withdrawals with their L2 initialization counterparts
#### L1 Poller
L1 blocks are only indexed if they contain L1 contract events. This is done to reduce the amount of unnecessary data that is indexed. Because of this, the `l1_block_headers` table will not contain every L1 block header unlike L2 blocks.
An **exception** to this is if no log activity has been observed over the specified `ETLAllowedInactivityWindowSeconds` value in the [chain config](https://github.com/ethereum-optimism/optimism/blob/develop/indexer/config/config.go) -- disabled by default with a zero value. Past this duration, the L1 ETL will index the latest
observed L1 header.
#### Database
The indexer service currently supports a Postgres database for storing L1/L2 OP Stack chain data. The most up-to-date database schemas can be found in the `./migrations` directory. **Run the idempotent migrations prior to starting the indexer**
#### HTTP
The indexer service runs a lightweight health server adjacently to the main service. The health server exposes a single endpoint `/healthz` that can be used to check the health of the indexer service. The health assessment doesn't check dependency health (ie. database) but rather checks the health of the indexer service itself.
#### Metrics
The indexer services exposes a set of Prometheus metrics that can be used to monitor the health of the service. The metrics are exposed via the `/metrics` endpoint on the health server.
## Security
All security related issues should be filed via github issues and will be triaged by the team. The following are some security considerations to be taken when running the service:
- Since the Indexer API only performs read operations on the database, access to the database for any API instances should be restricted to read-only operations.
- The API has no rate limiting or authentication/authorization mechanisms. It is recommended to place the API behind a reverse proxy that can provide these features.
- Postgres connection timeouts are unenforced in the services. It is recommended to configure the database to enforce connection timeouts to prevent connection exhaustion attacks.
- Setting confirmation count values too low can result in indexing failures due to chain reorgs.
## Troubleshooting
Please advise the [troubleshooting](./ops/docs/troubleshooting.md) guide for common failure scenarios and how to resolve them. |
package com.fyp.CourseRegistration.SecurityConfig;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import java.util.Arrays;
import java.util.Collections;
@Configuration
@EnableWebSecurity
public class ApplicationSecurityConfig {
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception{
http
.csrf()
.disable()
.authorizeHttpRequests()
.requestMatchers("/api/student/**", "/api/courseregistration/**")
.permitAll()
// .requestMatchers("/api/announcement/**").hasAuthority(ApplicationUserPermissions.ANNOUNCEMENT_WRITE.getPermission())
.anyRequest()
.authenticated()
.and()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.addFilterBefore(new JwtTokenValidator(), BasicAuthenticationFilter.class)
.httpBasic()
.and()
.formLogin();
return http.build();
}
private CorsConfigurationSource corsConfigurationSource() {
return new CorsConfigurationSource() {
@Override
public CorsConfiguration getCorsConfiguration(HttpServletRequest request) {
CorsConfiguration cfg = new CorsConfiguration();
cfg.setAllowedOrigins(Arrays.asList("http://localhost:3000"));
cfg.setAllowedMethods(Collections.singletonList("*"));
cfg.setAllowCredentials(true);
cfg.setAllowedHeaders(Collections.singletonList("*"));
cfg.setExposedHeaders(Arrays.asList("Authorization"));
cfg.setMaxAge(3600L);
return cfg;
}
};
}
} |
---
create_date: 2022-11-18T20:37:55 (UTC +08:00)
tags:
- 读书笔记/唐诗
aliases: null
pagetitle: 枫桥夜泊原文、翻译及赏析_张继古诗_古诗文网
source: https://so.gushiwen.cn/shiwenv_6fb73f607ad3.aspx
author: 张继
status: 已完成
category: null
notes: false
recite: true
uid: null
date updated: 2022-11-19 09:37
---
location:: 江苏/苏州
## 枫桥夜泊
[张继](https://so.gushiwen.cn/authorv_623fb18b7792.aspx) [〔唐代〕](https://so.gushiwen.cn/shiwens/default.aspx?cstr=%e5%94%90%e4%bb%a3)
月落乌啼霜满天,江枫渔火对愁眠。\
<mark style="background: #FFB86CA6;">姑苏城外寒山寺,夜半钟声到客船。</mark>
## 译文及注释
**译文\
**月亮已落下乌鸦啼叫寒气满天,面对江边枫树与船上渔火,我忧愁难眠。\
姑苏城外那[寒山](https://so.gushiwen.cn/authorv_891602ebe5d9.aspx)古寺,半夜里敲响的钟声传到了我乘坐的客船。
**注释**\
枫桥:在今苏州市阊门外。\
夜泊:夜间把船停靠在岸边。\
乌啼:一说为乌鸦啼鸣,一说为乌啼镇。\
霜满天:霜,不可能满天,这个“霜”字应当体会作严寒;霜满天,是空气极冷的形象语。\
江枫:一般解释作“江边枫树”,江指吴淞江,源自太湖,流经上海,汇入长江,俗称苏州河。另外有人认为指“江村桥”和“枫桥”。“枫桥”在吴县南门(阊阖门)外西郊,本名“封桥”,因张继此诗而改为“枫桥”。\
渔火:通常解释,“鱼火”就是渔船上的灯火;也有说法指“渔火”实际上就是一同打渔的伙伴。\
对愁眠:伴愁眠之意,此句把江枫和渔火二词拟人化。就是后世有不解诗的人,怀疑江枫渔火怎么能对愁眠,于是附会出一种讲法,说愁眠是寒山寺对面的山名。\
姑苏:苏州的别称,因城西南有姑苏山而得名。\
寒山寺:在枫桥附近,始建于南朝梁代。相传因唐代僧人寒山、[拾得](https://so.gushiwen.cn/authorv_a083c50638a3.aspx)曾住此而得名。在今苏州市西枫桥镇。本名“妙利普明塔院”,又名枫桥寺;另一种说法,“寒山”乃泛指肃寒之山,非寺名。寺曾经数次重建,现在的寺宇,为太平天国以后新建。寺钟在第二次世界大战时,被日本人运走,下落不明。\
夜半钟声:当今的佛寺(春节)半夜敲钟,但当时有半夜敲钟的习惯,也叫「无常钟」或「分夜钟」。宋朝大文豪[欧阳修](https://so.gushiwen.cn/authorv_7ab3b8200774.aspx)曾提出疑问表示:“诗人为了贪求好句,以至于道理说不通,这是作文章的毛病,如张继诗句“夜半钟声到客船”,句子虽好,但那有三更半夜打钟的道理?”可是经过许多人的实地查访,才知苏州和邻近地区的佛寺,有打半夜钟的风俗。▲
参考资料:
1、 张国举.唐诗精华注译评.长春:长春出版社,2010:367
## 创作背景
天宝十四载一月爆发了安史之乱。因为当时[江南](https://so.gushiwen.cn/authorv_487654addba8.aspx)政局比较安定,所以不少文士纷纷逃到今江苏、浙江一带避乱,其中也包括张继。一个秋天的夜晚,诗人泊舟苏州城外的枫桥。江南水乡秋夜幽美的景色,吸引着这位怀着旅愁的客子,使写下了这首意境清远的小诗。
参考资料:
1、 刘学锴 等.唐诗鉴赏辞典.上海:上海辞书出版社,1983:634-635
## 赏析
唐朝安史之乱后,张继途经[寒山](https://so.gushiwen.cn/authorv_891602ebe5d9.aspx)寺时写下这首羁旅诗。此诗精确而细腻地描述了一个客船夜泊者对[江南](https://so.gushiwen.cn/authorv_487654addba8.aspx)深秋夜景的观察和感受,勾画了月落乌啼、霜天寒夜、江枫渔火、孤舟客子等景象,有景有情有声有色。此外,这首诗也将作者羁旅之思,家国之忧,以及身处乱世尚无归宿的顾虑充分地表现出来,是写愁的代表作。全诗句句形象鲜明,可感可画,句与句之间逻辑关系又非常清晰合理,内容晓畅易解。
这首七绝以一“愁”字统起。前二句意象密集:落月、啼乌、满天霜、江枫、渔火、不眠人,造成一种意韵浓郁的审美情境。后两句意象疏宕:城、寺、船、钟声,是一种空灵旷远的意境。江畔秋夜渔火点点,羁旅客子卧闻静夜钟声。所有景物的挑选都独具慧眼:一静一动、一明一暗、江边岸上,景物的搭配与人物的心情达到了高度的默契与交融,共同形成了这个成为后世典范的艺术境界。
全诗抓住一个“愁”字展开。如果说“月落乌啼霜满天”多少透示着凄清悲凉,那么“江枫渔火”难道不给诗人一点光明与温暖吗?然而,“对愁眠”却凸现在人们面前。旅途的孤独、寂寞,牵起诗人的满怀愁绪,更遇上残月衔山、乌鸦悲啼,满目寒霜洒遍江天,一个迷茫、凄清、寂寥的背景已经形成,奠定了全诗以“愁”为中心的基调。人在逆境中(从诗的字里行间可以品味出来),最忌的是景物伤怀,诗人泊船于枫桥之下,本来心情就已凄恻,却偏逢残月。外出旅游者(也许作者不是旅游家)往往会对家人无限牵挂,可谓归心似箭,盼望与家人团圆,然而,他却客舟孤苦、愁怀难遣。残月也许已给诗人一丝莫名的预示,更兼乌鸦悲鸣的不祥之兆!(听到乌鸦啼叫,人们都会将其与不详联系)满天的飞霜又怎能不令诗人一阵阵心寒?
“江枫渔火对愁眠”。经霜后鲜红似火的枫叶与渔船上星星点点的灯火,在霜天夜晚呈现出一种朦胧美,给这幅秋江月夜图平添几分悦目赏心的风姿,绘景已达到美得无瑕的境界!然而,作者着力渲染秋江月夜的美景时,笔束一顿便绘出一个“愁”字来。作者为什么愁?有几多愁?景愈美则情(愁)愈烈。诗人面对美景,却没有半点的欢乐,愁得辗转反侧,这是为什么?我们回顾前文“月落”、“乌啼”、“霜满天”,俗话说天黑怕鬼,诗人心中的“鬼”是什么?是他的仕途得失、宦海沉浮?还是家事索怀、亲朋离散?诗中没说,不得而知。但诗人无心欣赏夜景、孤独难眠,我们不难想象他心中之愁。郁结难抒,确实不是言语说得清的。从他害怕乌啼,我们可以觉察他心中一定有什么事(或人)令他担心,以至乌鸦的啼叫声也令他心烦意乱。霜,是诗人描绘的这幅秋江月夜图的组成部分。玉屑般的飞霜给人一种素雅高洁的美感,然而和“乌啼”“愁眠”联系起来理解,这霜就有点“不妙”了。既然诗人听到乌啼已感意乱,那么飞霜岂不是令他心寒吗?意乱心烦自是他“愁眠”之因了。“姑苏城外寒山寺,夜半钟声到客船。”夜,静得可怕,静得令人难以入睡。
诗的前幅布景密度很大,十四个字写了六种景象,后幅却特别疏朗,两句诗只写了一件事:卧闻山寺夜钟。这是因为,诗人在枫桥夜泊中所得到的最鲜明深刻、最具诗意美的感觉印象,就是这寒山寺的夜半钟声。月落乌啼、霜天寒夜、江枫渔火、孤舟客子等景象,固然已从各方面显示出枫桥夜泊的特征,但还不足以尽传它的神韵。在暗夜中,人的听觉升居为对外界事物景象感受的首位。而静夜钟声,给予人的印象又特别强烈。这样,“夜半钟声”就不但衬托出了夜的静谧,而且揭示了夜的深永和清寥,而诗人卧听疏钟时的种种难以言传的感受也就尽在不言中了。
《枫桥夜泊》是一首情与景交织在一起的古诗,全诗除了“对愁眠”外,其余都是刻意绘景。它不是直抒胸臆,而是通过描绘秋江月夜的美景,间接而自然地把诗人旅途寂寞的郁结愁思寄托于景物而抒发出来。欲抒情,先绘景,情随景发,是这首古诗显著的艺术特点。由此可见,在借景抒情的古诗中,作者的情感是通过所描绘的景物来抒发的。在教学这类古诗时,我们既要欣赏作者描绘的景物,更重要的是理解他凭借景物巧妙抒情的技巧,这样才能真正地读懂了古诗。▲
参考资料:
1、 萧涤非 等.唐诗鉴赏辞典.上海:上海辞书出版社,1983:634-635
## 赏析二
全诗以一愁字统起。前二句意象密集:落月、啼乌、满天霜、江枫、渔火、不眠人,造成一种意韵浓郁的审美情境。这二句既描写了秋夜江边之景,又表达了作者思乡之情。后两句意象疏宕:城、寺、船、钟声,是一种空灵旷远的意境。夜行无月,本难见物,而渔火醒目,霜寒可感;夜半乃阗寂之时,却闻乌啼钟鸣。如此明灭对照,无声与有声的衬托,使景皆为情中之景,声皆为意中之音,意境疏密错落,浑融幽远。一缕淡淡的客愁被点染得朦胧隽永,在姑苏城的夜空中摇曳飘忽,为那里的一桥一水,一寺一城平添了千古风情,吸引着古往今来的寻梦者。《唐诗三集合编》“全篇诗意自‘愁眠’上起,妙在不说出。”《碛砂唐诗》:“‘对愁眠’三字为全章关目。明逗一‘愁’字,虚写竟夕光景,辗转反侧之意自见。”《古唐诗合解》:“此诗装句法最妙,似连而断,似断而连。”
为什么诗人一夜未眠呢?首句写了“月落、乌啼、霜满天”这三种有密切关联的景象。上弦月升起得早,到“月落”时大约天将晓,树上的栖鸟也在黎明时分发出啼鸣,秋天夜晚的“霜”透着浸肌砭骨的寒意,从四面八方围向诗人夜泊的小船,使他感到身外茫茫夜空中正弥漫着满天霜华。第二句写诗人一夜伴着“江枫”和“渔火”未眠的情景。
诗人运思细密,短短四句诗中包蕴了六景一事,用最具诗意的语言构造出一个清幽寂远的意境:江畔秋夜渔火点点,羁旅客子卧闻静夜钟声。所有景物的挑选都独具慧眼:一静一动、一明一暗、江边岸上,景物的搭配与人物的心情达到了高度的默契与交融,共同形成了这个成为后世典范的艺术境界。其名句有:“姑苏城外[寒山](https://so.gushiwen.cn/authorv_891602ebe5d9.aspx)寺,夜半钟声到客船。”
这首诗采用倒叙的写法,先写拂晓时景物,然后追忆昨夜的景色及夜半钟声,全诗有声有色,有情有景,情景交融。▲
[**张继**](https://so.gushiwen.cn/authorv_623fb18b7792.aspx) !
张继(约715~约779)字懿孙,汉族,襄州人(今湖北襄阳人)。唐代诗人,他的生平不甚可知。据诸家记录,仅知他是天宝十二年(公元七五三年)的进士。大历中,以检校祠部员外郎为洪州(今江西南昌市)盐铁判官。他的诗爽朗激越,不事雕琢,比兴幽深,事理双切,对后世颇有影响。但可惜流传下来的不到50首。他的最著名的诗是《枫桥夜泊》。[► 54篇诗文](https://so.gushiwen.cn/shiwens/default.aspx?astr=%e5%bc%a0%e7%bb%a7) [► 11条名句](https://so.gushiwen.cn/mingjus/default.aspx?astr=%e5%bc%a0%e7%bb%a7) |
import 'package:authentication_repository/authentication_repository.dart';
import 'package:equatable/equatable.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:form_inputs/form_inputs.dart';
import 'package:formz/formz.dart';
part 'login_state.dart';
class LoginCubit extends Cubit<LoginState> {
final AuthenticationRepository _authenticationRepository;
LoginCubit(this._authenticationRepository) : super(const LoginState());
void emailChanged(String value) {
final email = Email.dirty(value);
emit(
state.copyWith(
email: email,
isValid: Formz.validate([email, state.password]),
),
);
}
void otpChanged(String value) {
final otp = OTP.dirty(value);
emit(
state.copyWith(
otp: otp,
isValid: Formz.validate([otp]),
),
);
}
void phoneChanged(String value) {
final phone = Phone.dirty(value);
emit(
state.copyWith(
phone: phone,
isValid: Formz.validate([state.phone]),
),
);
}
void passwordChanged(String value) {
final password = Password.dirty(value);
emit(
state.copyWith(
password: password,
isValid: Formz.validate([state.email, password]),
),
);
}
Future<void> logInWithCredentials() async {
if (!state.isValid) return;
emit(state.copyWith(status: FormzSubmissionStatus.inProgress));
try {
await _authenticationRepository.logInWithEmailAndPassword(
email: state.email.value,
password: state.password.value,
);
emit(state.copyWith(status: FormzSubmissionStatus.success));
} on LogInWithEmailAndPasswordFailure catch (e) {
emit(
state.copyWith(
errorMessage: e.message,
status: FormzSubmissionStatus.failure,
),
);
} catch (_) {
emit(state.copyWith(status: FormzSubmissionStatus.failure));
}
}
Future<void> logInWithPhone() async {
if (!state.isValid) return;
emit(state.copyWith(status: FormzSubmissionStatus.inProgress));
try {
await _authenticationRepository.logInWithPhoneNumber(
phone: state.phone.value,
);
await Future.delayed(const Duration(seconds: 3));
emit(state.copyWith(status: FormzSubmissionStatus.success, isSend: true));
} catch (e) {
emit(
state.copyWith(
errorMessage: e.toString(),
status: FormzSubmissionStatus.failure,
),
);
}
}
Future<void> verifyOTPCode() async {
if (!state.isValid) return;
emit(state.copyWith(status: FormzSubmissionStatus.inProgress));
try {
await _authenticationRepository.logInWithPhoneNumber(
phone: state.phone.value,
otp: state.otp.value,
);
await Future.delayed(const Duration(seconds: 4));
emit(state.copyWith(status: FormzSubmissionStatus.success, isSend: true));
} catch (e) {
emit(
state.copyWith(
errorMessage: e.toString(),
status: FormzSubmissionStatus.failure,
),
);
}
}
} |
@extends('layouts.backend')
@section('css_before')
<style>
.folder-name {
font-weight: bold;
font-size: 1.5em;
margin-left: 10px; /* Ajoutez un peu d'espace entre l'icône et le nom du dossier */
}
.folder {
cursor: pointer; /* Pour montrer que les dossiers sont cliquables */
margin-bottom: 10px; /* Espace entre les dossiers */
}
.folder-icon {
font-size: 1.5em; /* Agrandir l'icône de dossier */
}
</style>
<link rel="stylesheet" href="{{ asset('js/plugins/datatables/dataTables.bootstrap4.css') }}">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.1/css/all.min.css">
@endsection
@section('js_after')
<!-- Page JS Plugins -->
<script src="{{ asset('js/plugins/datatables/jquery.dataTables.min.js') }}"></script>
<script src="{{ asset('js/plugins/datatables/dataTables.bootstrap4.min.js') }}"></script>
<!-- Page JS Code -->
<script src="{{ asset('js/pages/tables_datatables.js') }}"></script>
@endsection
@section('content')
<!-- Page Content -->
<div class="content">
<div class="my-50 text-center">
<h2 class="font-w700 text-black mb-10">Documents Utiles</h2>
</div>
<!-- Info -->
<div class="row justify-content-center">
<div class="col-md-6">
<div class="block">
<div class="block-content">
<p class="text-muted">
Vous trouverez ici une liste de documents importants à consulter ou à télécharger. Les administrateurs peuvent ajouter ou supprimer des documents.
</p>
</div>
</div>
</div>
</div>
<!-- END Info -->
<!-- Dynamic Table Full -->
<div class="block">
<div class="block-header block-header-default">
<h3 class="block-title">Liste des dossiers</h3>
</div>
<div class="block-content">
@foreach($folders as $folder)
<div class="folder" data-folder-id="{{ $folder->id }}">
<i class="fa fa-folder folder-icon"></i> <!-- icône de dossier -->
<span class="folder-name">{{ ucfirst($folder->name) }}</span>
</div>
<div class="documents" id="documents_{{ $folder->id }}" style="display: none;">
<table class="table table-bordered">
<thead>
<tr>
<th>Nom du document</th>
<th>Type</th>
<th>Visualiser</th>
<th>Télécharger</th>
@if(Auth::user()->droit == 1)
<th>Droits</th>
<th>Actions</th>
@endif
</tr>
</thead>
<tbody>
@foreach($documents as $document)
@if($document->folder == $folder->id)
<tr>
<td><a href="{{ route('documents.show', ['id' => $document->id]) }}" title="Aperçu"><i class="fa fa-eye"></i></a> {{$document->title}}</td>
<td>{{ pathinfo($document->file_path, PATHINFO_EXTENSION) }}</td>
<td><a href="{{ route('documents.download', ['id' => $document->id]) }}" title="Télécharger"><i class="fa fa-download"></i></a></td>
<td><a href="{{ route('documents.show', ['id' => $document->id]) }}" title="Aperçu"><i class="fa fa-eye"></i></a></td>
@if(Auth::user()->droit == 1)
<td>
@if($document->droit_access == 1)
Admin only
@elseif($document->droit_access == 2)
Tout le monde
@else
Inconnu
@endif
</td>
<td>
<a href="{{ route("admin.documents.edit", ["id" => $document->id])}}" title="Editer" class="table__link"><i class="fa fa-pencil-square-o"></i></a>
<form action="{{ route("admin.documents.destroy", ["id" => $document->id])}}" method="POST" style="display:inline;">
@csrf
@method('DELETE')
<a href="#" title="Supprimer" class="table__link" onclick="this.closest('form').submit();return false;"><i class="fa fa-trash"></i></a>
</form>
</td>
@endif
</tr>
@endif
@endforeach
</tbody>
</table>
</div>
@endforeach
</div>
</div>
@if(Auth::user()->droit == 1)
<a href="{{route("documents.add")}}" class="bouton bouton--admin" title="Ajouter un document"><i class="fa fa-plus"></i> Ajouter un document</a>
@endif
</div>
<!-- END Page Content -->
@endsection
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
document.addEventListener('DOMContentLoaded', function() {
let folders = document.querySelectorAll('.folder');
folders.forEach(function(folder) {
folder.addEventListener('click', function() {
let folderId = folder.getAttribute('data-folder-id');
let documentsDiv = document.getElementById('documents_' + folderId);
let icon = folder.querySelector('.folder-icon');
if (icon) {
if (documentsDiv.style.display === 'none' || documentsDiv.innerHTML.trim() === '') {
icon.classList.remove('fa-folder');
icon.classList.add('fa-folder-open');
documentsDiv.style.display = 'block';
} else {
icon.classList.remove('fa-folder-open');
icon.classList.add('fa-folder');
documentsDiv.style.display = 'none';
}
} else {
console.warn("Icon not found for folder with id:", folderId);
}
// Si vous faites un appel AJAX pour charger les documents, placez-le ici.
});
});
});
</script> |
// The common way to pass objects through functions is like this
const oldCivic = {
name: 'civic',
year: 2000,
broken: true
}
const printVehicle = (vehicle: {name: string, year: number, broken: boolean}): void=>{
console.log(vehicle.name);
console.log(vehicle.year);
console.log(vehicle.broken);
}
printVehicle(oldCivic);
// But this is not appropiate when we have to add more properties to our object
// because we would need to update each functions that uses these objects
// This is why we create interfaces, it's a simplier way to manage our records properties
// and the type of a function param
interface Vehicle {
name: string;
year: number;
broken: boolean;
}
const newPrintVehicle = (vehicle: Vehicle): void=>{
console.log(vehicle.name);
console.log(vehicle.year);
console.log(vehicle.broken);
}
// Also, as our oldCivic object contains the same params as a Vehicle
// interface, so the TS compiler won't mark it as an error
// But if we don't fit the same tags or types, TS would mark an error
newPrintVehicle(oldCivic);
// And the object can have more properties than the interface has,
// this won't mark an error
// Another important thing about interfaces is that you can reutilize some properties
// or functions, an example is
// Also this is how we declare functions inside interfaces
interface Reportable {
summary() : string;
}
// Object similar to the Vehicle interface
const newCivic = {
name: 'civic',
year: new Date(),
broken: false,
summary():string{
return `Car Name: ${this.name}
Year: ${this.year}
is Broken?: ${this.broken}`;
}
}
// Object Drink of another interface that we don't declare here
const drinkExample = {
color: 'green',
carbonated: true,
sugar: 40,
summary():string{
return `This drink is ${this.color}`;
}
}
// Both objects can use the following function
const printSummary = (item: Reportable):void =>{
console.log(item.summary());
}
// This is how our function works for both, vehicles and drinks
printSummary(drinkExample);
printSummary(newCivic);
// The important thing here, is that our objects satisfy the interfaces to work with our functions
// but is not so important to fit exactly the object to an interface |
import React from "react";
import {
useContextSelector as useSelectorContext,
createContext,
Context,
} from "use-context-selector";
import { shallowEqual } from "../utils/shallowEqual";
import { genericSelector } from "../utils/genericSelector";
import { Person } from "../entites/Person";
// New ContextSelector with eqFunc.
export const useContextSelector = <T extends any, R extends any>(
ctx: Context<T>,
selector: (val: T) => R,
isEql?: (a: R | null, b: R) => boolean
) => {
const patchedSelector = React.useMemo(() => {
let prevValue: R | null = null;
return (state: T) => {
const nextValue: R = selector(state);
if (prevValue !== null && isEql?.(prevValue, nextValue)) {
return prevValue;
}
prevValue = nextValue;
return nextValue;
};
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [isEql]);
return useSelectorContext(ctx, patchedSelector);
};
type UsePersonReturn = {
people: Person[];
selectedPerson: Person | null;
addPerson: (person: Person) => void;
selectPerson: (person: Person) => void;
};
const usePerson = (): UsePersonReturn => {
const [people, setPeople] = React.useState<Person[]>([]);
const [selectedPerson, setSelectedPerson] = React.useState<Person | null>(
null
);
const addPerson = React.useCallback((person: Person) => {
setPeople((prev) => [...prev, person]);
}, []);
const selectPerson = React.useCallback((person: Person) => {
setSelectedPerson(person);
}, []);
return {
people,
selectedPerson,
addPerson,
selectPerson,
};
};
const PersonsContext = createContext({} as UsePersonReturn);
const PersonsProvider: React.FC = ({ children }) => {
return (
<PersonsContext.Provider value={usePerson()}>
{children}
</PersonsContext.Provider>
);
};
// This implementation does not work :)
const selectForm = (ctx: UsePersonReturn) => ({ addPerson: ctx.addPerson });
const selectList = (ctx: UsePersonReturn) => ({
people: ctx.people,
selectPerson: ctx.selectPerson,
});
const selectView = (ctx: UsePersonReturn) => ({
selectedPerson: ctx.selectedPerson,
});
// type GenericFunction<T> = (ctx: UsePersonReturn) => T;
// const usePersonContext = <T extends any>(key: GenericFunction<T>) => {
// const context = useContextSelector(PersonsContext, key);
// return context;
// };
// This implementation violates rules-of-hooks
const neededStates = {
selectForm: ["addPerson"],
selectList: ["people", "selectPerson"],
selectView: ["selectedPerson"],
} as const;
type NeededStatesKeys = keyof typeof neededStates;
// const usePersonContext = <T extends NeededStatesKeys>(key: T) => {
// let hooks = {} as Pick<UsePersonReturn, typeof neededStates[T][number]>;
// neededStates[key].forEach((keyValue) => {
// // eslint-disable-next-line react-hooks/rules-of-hooks
// hooks[keyValue as typeof neededStates[T][number]] = useContextSelector(
// PersonsContext,
// (ctx) => ctx[keyValue as typeof neededStates[T][number]]
// );
// });
// return hooks;
// };
// This implementation came from the issue https://github.com/dai-shi/use-context-selector/issues/19
const usePersonContext = <T extends NeededStatesKeys>(key: T) => {
const hooks = useContextSelector(
PersonsContext,
genericSelector(neededStates[key] as any),
shallowEqual
) as Pick<UsePersonReturn, typeof neededStates[T][number]>;
return hooks;
};
export {
PersonsProvider,
usePersonContext,
selectForm,
selectList,
selectView,
}; |
{% load static %}
<!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://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
<link rel="stylesheet" href="https://kit.fontawesome.com/367278d2a4.css">
<title>Art Puppet World</title>
<style>
.header {
background-color: #f0f0f0;
padding: 10px 0;
}
.navbar-brand img {
max-width: 50px;
height: 50px;
}
.nav-link {
font-size: 1.2rem;
}
.header-buttons {
display: flex;
gap: 10px;
}
.header-buttons .btn {
font-size: 1rem;
}
</style>
</head>
<body>
<!-- Navigation Bar -->
<nav class="navbar navbar-expand-lg navbar-light header">
<div class="container">
<a class="navbar-brand" href="{% url 'home' %}">
<img src="{% static 'media/logos/hand-puppet-show-kids.jpg' %}" alt="Art Puppet World Logo">
</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarNav">
<ul class="navbar-nav mr-auto">
<li class="nav-item">
<a class="nav-link" href="{% url 'home' %}">Начало</a>
</li>
<li class="nav-item">
{% comment %} <a class="nav-link" href="{% url 'puppet_theatre' %}">Куклен театър</a> {% endcomment %}
<a class="nav-link" href="#">Куклен театър</a>
</li>
<li class="nav-item">
{% comment %} <a class="nav-link" href="{% url 'workshop' %}">Работиличка</a> {% endcomment %}
<a class="nav-link" href="#">Работилничка</a>
</li>
</ul>
<ul class="navbar-nav ml-auto">
{% if request.user.is_authenticated %}
<li class="nav-item">
<a class="nav-link" href="{% url 'account:details_account' pk=request.user.pk %}">
<i class="fas fa-user-circle"></i> Профил
</a>
</li>
<li class="nav-item">
<form action="{% url 'account:logout' %}" method="post" class="form-inline">
{% csrf_token %}
<button type="submit" class="btn btn-danger">
<i class="fas fa-sign-out-alt"></i> Изход
</button>
</form>
</li>
{% else %}
<div class="header-buttons">
<a href="{% url 'account:login' %}" class="btn btn-primary">Вход</a>
<a href="{% url 'account:register' %}" class="btn btn-secondary">Регистрация</a>
</div>
{% endif %}
</ul>
</div>
</div>
</nav>
<div class="container">
{% block main_content %}
{% endblock %}
</div>
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.9.2/dist/umd/popper.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
</body>
</html> |
import { Button, Card, InputNumber, Space, notification } from 'antd'
import axios from 'axios';
import React, { useState } from 'react'
const AddToCart = ({ productId, onClose,addedToCart,Plantdetailsview}) => {
const [value, setValue] = useState('1');
const addToCart = async () => {
const user = localStorage.getItem('user');
const email = user ? JSON.parse(user).email : null;
if (!email) {
notification.open({
type: 'warning',
message: 'Please Login first to add items to cart',
placement: 'topLeft',
})
return;
}
if (Plantdetailsview.stock < 1 ) {
// Plant is not available
notification.open({
type: 'error',
message: 'This plant is out of stock now',
placement: 'topLeft',
});
return;
}
try {
const response = await axios.post('http://localhost:4005/cart/add-to-cart', {
email,
productId,
quantity: value,
});
console.log(response.data);
addedToCart();
} catch (error) {
console.error('Error:', error.message); // Log the error message
}
};
return (
<Card title="Add To Cart">
<Space>
Select Quantity <InputNumber min={1} max={100} value={value} onChange={setValue} />
<Button
type="primary"
onClick={() => {
setValue(1);
}}
>
Reset
</Button>
</Space>
<h3 style={{marginLeft:'28px'}}>Quantity : {value}</h3>
<br />
<Space size="large" style={{ marginTop: '0px' }}>
<Button type="primary" onClick={onClose}>Cancel</Button>
<Button type="primary" onClick={addToCart}>Add To Cart</Button>
</Space>
</Card>
)
}
export default AddToCart |
import Cartography
import UIKit
public final class ReminderTableViewCell: UITableViewCell {
struct Constants {
static let timeLabelSize: CGFloat = 32
static let reminderNameLabelSize: CGFloat = 20
static let repetitionLabelSize: CGFloat = 16
static let minSpacing: CGFloat = 4
static let defaultSpacing: CGFloat = 17
static let middleSpacing: CGFloat = 20
static let maxSpacing: CGFloat = 30
}
private let timeLabel: UILabel = {
let label = UILabel()
label.font = UIFont.boldSystemFont(ofSize: Constants.timeLabelSize)
label.textColor = Asset.ColorAssets.brandBlue.color
label.textAlignment = .center
return label
}()
private let reminderNameLabel: UILabel = {
let label = UILabel()
label.font = UIFont.systemFont(ofSize: Constants.reminderNameLabelSize)
label.textColor = .black
label.textAlignment = .left
return label
}()
private let repetitionLabel: UILabel = {
let label = UILabel()
label.font = UIFont.systemFont(ofSize: Constants.repetitionLabelSize)
label.textColor = .black
label.textAlignment = .left
return label
}()
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
configure()
}
@available(*, unavailable)
required init?(coder: NSCoder) {
nil
}
private func configure() {
backgroundColor = .white
selectionStyle = .none
contentView.addSubview(timeLabel)
contentView.addSubview(reminderNameLabel)
contentView.addSubview(repetitionLabel)
setupConstraints()
}
private func setupConstraints() {
constrain(timeLabel, reminderNameLabel, repetitionLabel, contentView) { time, name, repetition, cell in
time.leading == cell.leading + Constants.maxSpacing
time.top == cell.top + Constants.middleSpacing
time.bottom == cell.bottom - Constants.middleSpacing
name.leading == time.trailing + Constants.defaultSpacing
name.top == cell.top + Constants.defaultSpacing
repetition.leading == time.trailing + Constants.defaultSpacing
repetition.top == name.bottom - Constants.minSpacing
}
}
func configure(reminder: Reminder) {
timeLabel.text = reminder.time
reminderNameLabel.text = reminder.name
repetitionLabel.text = reminder.type.description
}
} |
import subprocess
from pathlib import Path
import pygame
pygame.init()
class Display:
def __init__(self, path: Path) -> None:
self.PATH_ORIGIN = path
self.max_name_per_row = 4
self.screen = pygame.display.set_mode((1200, 600))
# screen = pygame.display.set_mode((0, 0), pygame.FULLSCREEN)
# pygame.display.toggle_fullscreen()
pygame.display.set_caption("explorer2")
ICONFILE = "icon.png"
if Path(ICONFILE).exists():
programIcon = pygame.image.load(ICONFILE)
pygame.display.set_icon(programIcon)
self.WIDTH, self.HEIGHT = self.screen.get_size()
self.BTN_WIDTH = 200
self.BTN_HEIGHT = 50
self.BTN_SPACE = 50
self.COLOR_FONT = (50, 50, 50)
self.COLOR_BACKGROUND = (255, 236, 236)
self.COLOR_BUTTON_DIRECTORY_BACKGROUND = (205, 237, 252)
self.COLOR_BUTTON_FILE_BACKGROUND = (255, 128, 128)
self.FONT_BUTTON = pygame.font.SysFont("Corbel", 35)
self.call_page(path)
def run(self) -> None:
self.running = True
while self.running:
for event in pygame.event.get():
self.catch_event(event)
pygame.display.flip()
pygame.quit()
# display page
def call_page(self, path: Path) -> None:
if path.suffix == ".pdf":
self.display_file(path)
else:
self.display_directory(path)
def get_pos_btn(self, nb_total: int) -> list[list[int]]:
pos = []
nb_list = (nb_total // self.max_name_per_row) * [self.max_name_per_row] + [
nb_total % self.max_name_per_row
]
for row in range(1 + nb_total // self.max_name_per_row):
nb = nb_list[row]
x = self.WIDTH // 2
if nb % 2 == 1:
x -= self.BTN_WIDTH // 2
else:
x += self.BTN_SPACE // 2
for _ in range(nb // 2):
x -= self.BTN_WIDTH + self.BTN_SPACE
for _ in range(nb):
pos.append(
[x, (self.HEIGHT // 4) + row * (self.BTN_HEIGHT + self.BTN_SPACE)]
)
x += self.BTN_WIDTH + self.BTN_SPACE
return pos
def display_directory(self, path):
# background
surface = pygame.display.set_mode((self.WIDTH, self.HEIGHT))
surface.fill(self.COLOR_BACKGROUND)
# buttons
self.zone_button = []
files = [file for file in path.glob("*")]
files_pos = self.get_pos_btn(len(files))
for i, file in enumerate(files):
pos_button = files_pos[i] + [self.BTN_WIDTH, self.BTN_HEIGHT]
text_button = self.FONT_BUTTON.render(file.stem, True, self.COLOR_FONT)
textRect = text_button.get_rect()
textRect.center = (
pos_button[0] + self.BTN_WIDTH // 2,
pos_button[1] + self.BTN_HEIGHT // 2,
)
background_color = (
self.COLOR_BUTTON_FILE_BACKGROUND
if file.suffix == ".pdf"
else self.COLOR_BUTTON_DIRECTORY_BACKGROUND
)
pygame.draw.rect(self.screen, background_color, pos_button)
self.screen.blit(text_button, textRect)
self.zone_button.append((pos_button, file))
if path != self.PATH_ORIGIN:
text_button = self.FONT_BUTTON.render("<-", True, self.COLOR_FONT)
pos_button = [100, 60, 150, 50]
pygame.draw.rect(
self.screen, self.COLOR_BUTTON_DIRECTORY_BACKGROUND, pos_button
)
textRect = text_button.get_rect()
textRect.center = (
pos_button[0] + self.BTN_WIDTH // 2,
pos_button[1] + self.BTN_HEIGHT // 2,
)
self.screen.blit(text_button, textRect)
self.zone_button.append((pos_button, path.parent))
text_button = self.FONT_BUTTON.render(str(path), True, self.COLOR_FONT)
self.screen.blit(text_button, [800, 60])
def display_file(self, path):
subprocess.Popen([path], shell=True)
# events
def catch_event(self, event):
if event.type == pygame.QUIT:
self.running = False
elif event.type == pygame.KEYDOWN:
match event.key:
case pygame.K_p:
self.running = False
case _:
pass
elif event.type == pygame.MOUSEBUTTONDOWN:
mouse = pygame.mouse.get_pos()
self.catch_button(mouse)
def catch_button(self, mouse):
for (x1, y1, x2, y2), path in self.zone_button:
if x1 < mouse[0] < x1 + x2 and y1 < mouse[1] < y1 + y2:
self.call_page(path)
break
display = Display(Path("./test/"))
display.run() |
import {addTodolistAC, todolistsReducer} from "./todolists-reducer";
import {tasksReducer} from "./tasks-reducer";
import {TaskStateType, TodolistType} from "../App";
test('new array should be added when new todolist is added', () => {
const startState: TaskStateType = {
'todolistId1': [
{id: '1', title: 'CSS', isDone: false},
{id: '2', title: 'JS', isDone: true},
{id: '3', title: 'React', isDone: false}
],
'todolistId2': [
{id: '1', title: 'bread', isDone: false},
{id: '2', title: 'milk', isDone: true},
{id: '3', title: 'tea', isDone: false}
]
}
const action = addTodolistAC('new todolist')
const endState = tasksReducer(startState, action)
const keys = Object.keys(endState)
const newKey = keys.find(k => k != 'todolistId1' && k != 'todolistId2')
if (!newKey) {
throw Error('new key should be added')
}
expect(keys.length).toBe(3)
expect(endState[newKey]).toEqual([])
})
test('ids should be equals', () => {
const startTasksState: TaskStateType = {}
const startTodolistsState: Array<TodolistType> = []
const action = addTodolistAC('new todolist')
const endTasksState = tasksReducer(startTasksState, action)
const endTodolistsState = todolistsReducer(startTodolistsState, action)
const keys = Object.keys(endTasksState)
const idFromTasks = keys[0]
const idFromTodolists = endTodolistsState[0].id
expect(idFromTasks).toBe(action.todolistID)
expect(idFromTodolists).toBe(action.todolistID)
}) |
import { GetStaticPaths, GetStaticProps } from "next";
import Head from "next/head";
import NProgress from "nprogress";
import { useEffect } from "react";
import useSWR from "swr";
import DistrictInfo from "../../components/district-info";
import Search from "../../components/search";
import { calendarByDistrict, Center } from "../../lib/cowin";
import { getDistricts } from "../../lib/node-utils";
import { genDistrictName, sortCenters, todayDate } from "../../lib/utils";
type DistrictProps = {
centers: Center[];
districts: CT.District[];
initSelected: CT.District;
lastUpdatedISO: string;
};
const District = ({
centers,
districts,
initSelected,
lastUpdatedISO,
}: DistrictProps) => {
// hybrid ssg and spa arch, page loads with static data that is built every 10 mins
// and served from cache. On load the app will update the centers every 1 mins
// static and dynamic :)
const { data, isValidating } = useSWR(
[initSelected.district_id, todayDate()],
calendarByDistrict,
{
initialData: {
centers,
lastUpdatedISO,
},
refreshInterval: 60000,
}
);
useEffect(() => {
if (isValidating) {
NProgress.start();
} else {
NProgress.done();
}
}, [isValidating]);
return (
<>
<Head>
<title>{genDistrictName(initSelected)}</title>
<meta name="description" content={genDistrictName(initSelected)} />
</Head>
<Search districts={districts} showModal initSelected={initSelected} />
<DistrictInfo
centers={data?.centers ?? centers}
lastUpdated={new Date(data?.lastUpdatedISO ?? lastUpdatedISO)}
/>
</>
);
};
export const getStaticProps: GetStaticProps = async (context) => {
const districts = getDistricts();
const districtId = context?.params?.district_id as string;
const initSelected = districts.find((x) => x.district_id === districtId);
try {
if (!initSelected) {
throw Error("Invalid district id");
}
const calender = await calendarByDistrict(districtId, todayDate());
return {
props: {
centers: sortCenters(calender.centers) ?? [],
lastUpdatedISO: calender.lastUpdatedISO ?? new Date().toISOString(),
districts,
initSelected,
},
// revalidates every 5 mins
revalidate: 5000,
};
} catch (error) {
console.error(error);
return {
props: {
centers: [],
lastUpdatedISO: new Date().toISOString(),
districts,
initSelected,
},
// revalidates every 5 mins
revalidate: 5000,
};
}
};
export const getStaticPaths: GetStaticPaths = async () => {
const districts = getDistricts();
const paths = districts.map((d) => ({
params: d,
}));
return { paths, fallback: "blocking" };
};
export default District; |
Inference - Wikipedia
Inference
From Wikipedia, the free encyclopedia
Jump to navigation Jump to search
Act or process of deriving logical conclusions from premises known or assumed to be true
For the 1992 album by pianist Marilyn Crispell and saxophonist Tim Berne, see Inference (album). For the process in statistics and machine learning, see Statistical inference.
This article includes a list of general references, but it remains largely unverified because it lacks sufficient corresponding inline citations. Please help to improve this article by introducing more precise citations. (April 2010) (Learn how and when to remove this template message)
Inferences are steps in reasoning, moving from premises to logical consequences; etymologically, the word infer means to "carry forward". Inference is theoretically traditionally divided into deduction and induction, a distinction that in Europe dates at least to Aristotle (300s BCE). Deduction is inference deriving logical conclusions from premises known or assumed to be true, with the laws of valid inference being studied in logic. Induction is inference from particular premises to a universal conclusion. A third type of inference is sometimes distinguished, notably by Charles Sanders Peirce, contradistinguishing abduction from induction.
Various fields study how inference is done in practice. Human inference (i.e. how humans draw conclusions) is traditionally studied within the fields of logic, argumentation studies, and cognitive psychology; artificial intelligence researchers develop automated inference systems to emulate human inference. Statistical inference uses mathematics to draw conclusions in the presence of uncertainty. This generalizes deterministic reasoning, with the absence of uncertainty as a special case. Statistical inference uses quantitative or qualitative (categorical) data which may be subject to random variations.
Contents
1 Definition
2 Examples
2.1 Example for definition #1
2.2 Example for definition #2
3 Incorrect inference
4 Applications
4.1 Inference engines
4.1.1 Prolog engine
4.2 Semantic web
4.3 Bayesian statistics and probability logic
4.4 Fuzzy logic
4.5 Non-monotonic logic
5 See also
6 References
7 Further reading
8 External links
Definition
The process by which a conclusion is inferred from multiple observations is called inductive reasoning. The conclusion may be correct or incorrect, or correct to within a certain degree of accuracy, or correct in certain situations. Conclusions inferred from multiple observations may be tested by additional observations.
This definition is disputable (due to its lack of clarity. Ref: Oxford English dictionary: "induction ... 3. Logic the inference of a general law from particular instances.") The definition given thus applies only when the "conclusion" is general.
Two possible definitions of "inference" are:
A conclusion reached on the basis of evidence and reasoning.
The process of reaching such a conclusion.
Examples
Example for definition #1
Ancient Greek philosophers defined a number of syllogisms, correct three part inferences, that can be used as building blocks for more complex reasoning. We begin with a famous example:
All humans are mortal.
All Greeks are humans.
All Greeks are mortal.
The reader can check that the premises and conclusion are true, but logic is concerned with inference: does the truth of the conclusion follow from that of the premises?
The validity of an inference depends on the form of the inference. That is, the word "valid" does not refer to the truth of the premises or the conclusion, but rather to the form of the inference. An inference can be valid even if the parts are false, and can be invalid even if some parts are true. But a valid form with true premises will always have a true conclusion.
For example, consider the form of the following symbological track:
All meat comes from animals.
All beef is meat.
Therefore, all beef comes from animals.
If the premises are true, then the conclusion is necessarily true, too.
Now we turn to an invalid form.
All A are B.
All C are B.
Therefore, all C are A.
To show that this form is invalid, we demonstrate how it can lead from true premises to a false conclusion.
All apples are fruit. (True)
All bananas are fruit. (True)
Therefore, all bananas are apples. (False)
A valid argument with a false premise may lead to a false conclusion, (this and the following examples do not follow the Greek syllogism):
All tall people are French. (False)
John Lennon was tall. (True)
Therefore, John Lennon was French. (False)
When a valid argument is used to derive a false conclusion from a false premise, the inference is valid because it follows the form of a correct inference.
A valid argument can also be used to derive a true conclusion from a false premise:
All tall people are musicians. (Valid, False)
John Lennon was tall. (Valid, True)
Therefore, John Lennon was a musician. (Valid, True)
In this case we have one false premise and one true premise where a true conclusion has been inferred.
Example for definition #2
Evidence: It is the early 1950s and you are an American stationed in the Soviet Union. You read in the Moscow newspaper that a soccer team from a small city in Siberia starts winning game after game. The team even defeats the Moscow team. Inference: The small city in Siberia is not a small city anymore. The Soviets are working on their own nuclear or high-value secret weapons program.
Knowns: The Soviet Union is a command economy: people and material are told where to go and what to do. The small city was remote and historically had never distinguished itself; its soccer season was typically short because of the weather.
Explanation: In a command economy, people and material are moved where they are needed. Large cities might field good teams due to the greater availability of high quality players; and teams that can practice longer (weather, facilities) can reasonably be expected to be better. In addition, you put your best and brightest in places where they can do the most good—such as on high-value weapons programs. It is an anomaly for a small city to field such a good team. The anomaly (i.e. the soccer scores and great soccer team) indirectly described a condition by which the observer inferred a new meaningful pattern—that the small city was no longer small. Why would you put a large city of your best and brightest in the middle of nowhere? To hide them, of course.
Incorrect inference
An incorrect inference is known as a fallacy. Philosophers who study informal logic have compiled large lists of them, and cognitive psychologists have documented many biases in human reasoning that favor incorrect reasoning.
Applications
Inference engines
Main articles: Reasoning system, Inference engine, expert system, and business rule engine
AI systems first provided automated logical inference and these were once extremely popular research topics, leading to industrial applications under the form of expert systems and later business rule engines. More recent work on automated theorem proving has had a stronger basis in formal logic.
An inference system's job is to extend a knowledge base automatically. The knowledge base (KB) is a set of propositions that represent what the system knows about the world. Several techniques can be used by that system to extend KB by means of valid inferences. An additional requirement is that the conclusions the system arrives at are relevant to its task.
Prolog engine
Prolog (for "Programming in Logic") is a programming language based on a subset of predicate calculus. Its main job is to check whether a certain proposition can be inferred from a KB (knowledge base) using an algorithm called backward chaining.
Let us return to our Socrates syllogism. We enter into our Knowledge Base the following piece of code:
mortal(X) :- man(X).
man(socrates).
( Here :- can be read as "if". Generally, if P
→
Q (if P then Q) then in Prolog we would code Q:-P (Q if P).) This states that all men are mortal and that Socrates is a man. Now we can ask the Prolog system about Socrates:
?- mortal(socrates).
(where ?- signifies a query: Can mortal(socrates). be deduced from the KB using the rules) gives the answer "Yes".
On the other hand, asking the Prolog system the following:
?- mortal(plato).
gives the answer "No".
This is because Prolog does not know anything about Plato, and hence defaults to any property about Plato being false (the so-called closed world assumption). Finally ?- mortal(X) (Is anything mortal) would result in "Yes" (and in some implementations: "Yes": X=socrates) Prolog can be used for vastly more complicated inference tasks. See the corresponding article for further examples.
Semantic web
Recently automatic reasoners found in semantic web a new field of application. Being based upon description logic, knowledge expressed using one variant of OWL can be logically processed, i.e., inferences can be made upon it.
Bayesian statistics and probability logic
Main article: Bayesian inference
Philosophers and scientists who follow the Bayesian framework for inference use the mathematical rules of probability to find this best explanation. The Bayesian view has a number of desirable features—one of them is that it embeds deductive (certain) logic as a subset (this prompts some writers to call Bayesian probability "probability logic", following E. T. Jaynes).
Bayesians identify probabilities with degrees of beliefs, with certainly true propositions having probability 1, and certainly false propositions having probability 0. To say that "it's going to rain tomorrow" has a 0.9 probability is to say that you consider the possibility of rain tomorrow as extremely likely.
Through the rules of probability, the probability of a conclusion and of alternatives can be calculated. The best explanation is most often identified with the most probable (see Bayesian decision theory). A central rule of Bayesian inference is Bayes' theorem.
Fuzzy logic
Main article: Fuzzy logic
This section needs expansion. You can help by adding to it. (October 2016)
Non-monotonic logic
Main article: Non-monotonic logic
A relation of inference is monotonic if the addition of premises does not undermine previously reached conclusions; otherwise the relation is non-monotonic. Deductive inference is monotonic: if a conclusion is reached on the basis of a certain set of premises, then that conclusion still holds if more premises are added.
By contrast, everyday reasoning is mostly non-monotonic because it involves risk: we jump to conclusions from deductively insufficient premises. We know when it is worth or even necessary (e.g. in medical diagnosis) to take the risk. Yet we are also aware that such inference is defeasible—that new information may undermine old conclusions. Various kinds of defeasible but remarkably successful inference have traditionally captured the attention of philosophers (theories of induction, Peirce's theory of abduction, inference to the best explanation, etc.). More recently logicians have begun to approach the phenomenon from a formal point of view. The result is a large body of theories at the interface of philosophy, logic and artificial intelligence.
See also
A priori and a posteriori
Abductive reasoning
Deductive reasoning
Inductive reasoning
Entailment
Epilogism
Analogy
Axiom system
Axiom
Immediate inference
Inferential programming
Inquiry
Logic
Logic of information
Logical assertion
Logical graph
Rule of inference
List of rules of inference
Theorem
Transduction (machine learning)
Philosophy portal
Psychology portal
References
^ Fuhrmann, André. Nonmonotonic Logic (PDF). Archived from the original (PDF) on 9 December 2003.
Further reading
Hacking, Ian (2001). An Introduction to Probability and Inductive Logic. Cambridge University Press. ISBN 978-0-521-77501-4.
Jaynes, Edwin Thompson (2003). Probability Theory: The Logic of Science. Cambridge University Press. ISBN 978-0-521-59271-0. Archived from the original on 2004-10-11. Retrieved 2004-11-29.
McKay, David J.C. (2003). Information Theory, Inference, and Learning Algorithms. Cambridge University Press. ISBN 978-0-521-64298-9.
Russell, Stuart J.; Norvig, Peter (2003), Artificial Intelligence: A Modern Approach (2nd ed.), Upper Saddle River, New Jersey: Prentice Hall, ISBN 0-13-790395-2
Tijms, Henk (2004). Understanding Probability. Cambridge University Press. ISBN 978-0-521-70172-3.
Inductive inference:
Carnap, Rudolf; Jeffrey, Richard C., eds. (1971). Studies in Inductive Logic and Probability. Vol. 1. The University of California Press.
Jeffrey, Richard C., ed. (1980). Studies in Inductive Logic and Probability. Vol. 2. The University of California Press. ISBN 9780520038264.
Angluin, Dana (1976). An Application of the Theory of Computational Complexity to the Study of Inductive Inference (Ph.D.). University of California at Berkeley.
Angluin, Dana (1980). "Inductive Inference of Formal Languages from Positive Data" (PDF). Information and Control. 45 (2): 117–135. doi:10.1016/s0019-9958(80)90285-5.
Angluin, Dana; Smith, Carl H. (Sep 1983). "Inductive Inference: Theory and Methods" (PDF). Computing Surveys. 15 (3): 237–269. doi:10.1145/356914.356918. S2CID 3209224.
Gabbay, Dov M.; Hartmann, Stephan; Woods, John, eds. (2009). Inductive Logic. Handbook of the History of Logic. Vol. 10. Elsevier.
Goodman, Nelson (1983). Fact, Fiction, and Forecast. Harvard University Press. ISBN 9780674290716.
Abductive inference:
O'Rourke, P.; Josephson, J., eds. (1997). Automated abduction: Inference to the best explanation. AAAI Press.
Psillos, Stathis (2009). Gabbay, Dov M.; Hartmann, Stephan; Woods, John (eds.). An Explorer upon Untrodden Ground: Peirce on Abduction (PDF). Handbook of the History of Logic. Vol. 10. Elsevier. pp. 117–152.
Ray, Oliver (Dec 2005). Hybrid Abductive Inductive Learning (Ph.D.). University of London, Imperial College. CiteSeerX 10.1.1.66.1877.
Psychological investigations about human reasoning:
deductive:
Johnson-Laird, Philip Nicholas; Byrne, Ruth M. J. (1992). Deduction. Erlbaum.
Byrne, Ruth M. J.; Johnson-Laird, P. N. (2009). ""If" and the Problems of Conditional Reasoning" (PDF). Trends in Cognitive Sciences. 13 (7): 282–287. doi:10.1016/j.tics.2009.04.003. PMID 19540792. S2CID 657803. Archived from the original (PDF) on 2014-04-07. Retrieved 2013-08-09.
Knauff, Markus; Fangmeier, Thomas; Ruff, Christian C.; Johnson-Laird, P. N. (2003). "Reasoning, Models, and Images: Behavioral Measures and Cortical Activity" (PDF). Journal of Cognitive Neuroscience. 15 (4): 559–573. CiteSeerX 10.1.1.318.6615. doi:10.1162/089892903321662949. hdl:11858/00-001M-0000-0013-DC8B-C. PMID 12803967. S2CID 782228. Archived from the original (PDF) on 2015-05-18. Retrieved 2013-08-09.
Johnson-Laird, Philip N. (1995). Gazzaniga, M. S. (ed.). Mental Models, Deductive Reasoning, and the Brain (PDF). MIT Press. pp. 999–1008.
Khemlani, Sangeet; Johnson-Laird, P. N. (2008). "Illusory Inferences about Embedded Disjunctions" (PDF). Proceedings of the 30th Annual Conference of the Cognitive Science Society. Washington/DC. pp. 2128–2133.
statistical:
McCloy, Rachel; Byrne, Ruth M. J.; Johnson-Laird, Philip N. (2009). "Understanding Cumulative Risk" (PDF). The Quarterly Journal of Experimental Psychology. 63 (3): 499–515. doi:10.1080/17470210903024784. PMID 19591080. S2CID 7741180. Archived from the original (PDF) on 2015-05-18. Retrieved 2013-08-09.
Johnson-Laird, Philip N. (1994). "Mental Models and Probabilistic Thinking" (PDF). Cognition. 50 (1–3): 189–209. doi:10.1016/0010-0277(94)90028-0. PMID 8039361. S2CID 9439284.,
analogical:
Burns, B. D. (1996). "Meta-Analogical Transfer: Transfer Between Episodes of Analogical Reasoning". Journal of Experimental Psychology: Learning, Memory, and Cognition. 22 (4): 1032–1048. doi:10.1037/0278-7393.22.4.1032.
spatial:
Jahn, Georg; Knauff, Markus; Johnson-Laird, P. N. (2007). "Preferred mental models in reasoning about spatial relations" (PDF). Memory & Cognition. 35 (8): 2075–2087. doi:10.3758/bf03192939. PMID 18265622. S2CID 25356700.
Knauff, Markus; Johnson-Laird, P. N. (2002). "Visual imagery can impede reasoning" (PDF). Memory & Cognition. 30 (3): 363–371. doi:10.3758/bf03194937. PMID 12061757. S2CID 7330724.
Waltz, James A.; Knowlton, Barbara J.; Holyoak, Keith J.; Boone, Kyle B.; Mishkin, Fred S.; de Menezes Santos, Marcia; Thomas, Carmen R.; Miller, Bruce L. (Mar 1999). "A System for Relational Reasoning in Human Prefrontal Cortex". Psychological Science. 10 (2): 119–125. doi:10.1111/1467-9280.00118. S2CID 44019775.
moral:
Bucciarelli, Monica; Khemlani, Sangeet; Johnson-Laird, P. N. (Feb 2008). "The Psychology of Moral Reasoning" (PDF). Judgment and Decision Making. 3 (2): 121–139.
External links
Look up inference or infer in Wiktionary, the free dictionary.
Inference at PhilPapers
Inference example and definition
Inference at the Indiana Philosophy Ontology Project
v
t
e
Logic
Outline
History
Fields
Computer science
Formal semantics (natural language)
Inference
Philosophy of logic
Proof
Semantics of logic
Syntax
Logics
Classical
Informal
Critical thinking
Reason
Mathematical
Non-classical
Philosophical
Theories
Argumentation
Metalogic
Metamathematics
Set
Foundations
Abduction
Analytic and synthetic propositions
Contradiction
Paradox
Antinomy
Deduction
Deductive closure
Definition
Description
Entailment
Linguistic
Form
Induction
Logical truth
Name
Necessity and sufficiency
Premise
Probability
Reference
Statement
Substitution
Truth
Validity
Lists
topics
Mathematical logic
Boolean algebra
Set theory
other
Logicians
Rules of inference
Paradoxes
Fallacies
Logic symbols
Philosophy portal
Category
WikiProject (talk)
changes
v
t
e
Philosophy
Branches
Traditional
Axiology
Aesthetics
Ethics
Epistemology
Logic
Metaphysics
Ontology
Philosophy of...
Action
Art
Design
Music
Film
Color
Cosmology
Culture
Education
Environment
Geography
History
Human nature
Feminism
Language
Law
Life
Literature
Logic
Mathematics
Medicine
Healthcare
Psychiatry
Mind
Pain
Happiness
Humor
Psychology
Perception
Philosophy
Religion
Science
Physics
Chemistry
Biology
Sexuality
Social science
Business
Economics
Politics
Society
Space and time
Sport
Technology
Artificial intelligence
Computer science
Engineering
Information
War
Schools of thought
By era
Ancient
Western
Medieval
Renaissance
Early modern
Modern
Contemporary
Ancient
Chinese
Agriculturalism
Confucianism
Legalism
Logicians
Mohism
Chinese naturalism
Neotaoism
Taoism
Yangism
Chan
Greco-Roman
Aristotelianism
Atomism
Cynicism
Cyrenaics
Eleatics
Eretrian school
Epicureanism
Hermeneutics
Ionian
Ephesian
Milesian
Megarian school
Neoplatonism
Peripatetic
Platonism
Pluralism
Presocratic
Pyrrhonism
Pythagoreanism
Neopythagoreanism
Sophistic
Stoicism
Indian
Hindu
Samkhya
Nyaya
Vaisheshika
Yoga
Mīmāṃsā
Ājīvika
Ajñana
Cārvāka
Jain
Anekantavada
Syādvāda
Buddhist
Śūnyatā
Madhyamaka
Yogacara
Sautrāntika
Svatantrika
Persian
Mazdakism
Mithraism
Zoroastrianism
Zurvanism
Medieval
European
Christian
Augustinianism
Scholasticism
Thomism
Scotism
Occamism
Renaissance humanism
East Asian
Korean Confucianism
Edo neo-Confucianism
Neo-Confucianism
Indian
Vedanta
Acintya bheda abheda
Advaita
Bhedabheda
Dvaita
Nimbarka Sampradaya
Shuddhadvaita
Vishishtadvaita
Navya-Nyāya
Islamic
Averroism
Avicennism
Illuminationism
ʿIlm al-Kalām
Sufi
Jewish
Judeo-Islamic
Modern
People
Cartesianism
Kantianism
Neo
Kierkegaardianism
Krausism
Hegelianism
Marxism
Newtonianism
Nietzscheanism
Spinozism
0
Anarchism
Classical Realism
Liberalism
Collectivism
Conservatism
Determinism
Dualism
Empiricism
Existentialism
Foundationalism
Historicism
Holism
Humanism
Anti-
Idealism
Absolute
British
German
Objective
Subjective
Transcendental
Individualism
Kokugaku
Materialism
Modernism
Monism
Naturalism
Natural law
Nihilism
New Confucianism
Neo-scholasticism
Pragmatism
Phenomenology
Positivism
Reductionism
Rationalism
Social contract
Socialism
Transcendentalism
Utilitarianism
Contemporary
Analytic
Applied ethics
Analytic feminism
Analytical Marxism
Communitarianism
Consequentialism
Critical rationalism
Experimental philosophy
Falsificationism
Foundationalism / Coherentism
Internalism and externalism
Logical positivism
Legal positivism
Normative ethics
Meta-ethics
Moral realism
Quinean naturalism
Ordinary language philosophy
Postanalytic philosophy
Quietism
Rawlsian
Reformed epistemology
Systemics
Scientism
Scientific realism
Scientific skepticism
Transactionalism
Contemporary utilitarianism
Vienna Circle
Wittgensteinian
Continental
Critical theory
Deconstruction
Existentialism
Feminist
Frankfurt School
New Historicism
Hermeneutics
Neo-Marxism
Phenomenology
Posthumanism
Postmodernism
Post-structuralism
Social constructionism
Structuralism
Western Marxism
Other
Kyoto School
Objectivism
Postcritique
Russian cosmism
more...
Positions
Aesthetics
Formalism
Institutionalism
Aesthetic response
Ethics
Consequentialism
Deontology
Virtue
Free will
Compatibilism
Determinism
Hard
Incompatibilism
Hard
Libertarianism
Metaphysics
Atomism
Dualism
Idealism
Monism
Naturalism
Realism
Epistemology
Empiricism
Fideism
Naturalism
Particularism
Rationalism
Skepticism
Solipsism
Mind
Behaviorism
Emergentism
Eliminativism
Epiphenomenalism
Functionalism
Objectivism
Subjectivism
Normativity
Absolutism
Particularism
Relativism
Nihilism
Skepticism
Universalism
Ontology
Action
Event
Process
Reality
Anti-realism
Conceptualism
Idealism
Materialism
Naturalism
Nominalism
Physicalism
Realism
By region
Related lists
Miscellaneous
By region
African
Bantu
Egyptian
Ethiopian
Eastern
Chinese
Indian
Indonesian
Japanese
Korean
Taiwanese
Pakistani
Vietnamese
Middle Eastern
Iranian
Jewish
Turkish
Western
American
Australian
British
Scottish
Canada
Czech
Danish
Dutch
French
German
Greek
Italian
Maltese
Polish
Slovene
Spanish
Miscellaneous
Amerindian
Aztec
Yugoslav
Romanian
Russian
Lists
Outline
Index
Years
Problems
Schools
Glossary
Philosophers
Movements
Publications
Miscellaneous
Natural law
Sage
Theoretical philosophy / Practical philosophy
Women in philosophy
Portal
Category
Authority control: National libraries
France (data)
Germany
United States
Japan
Retrieved from "https://en.wikipedia.org/w/index.php?title=Inference&oldid=1060334286"
Categories:
Inference
Concepts in epistemology
Concepts in logic
Concepts in metaphilosophy
Concepts in metaphysics
Concepts in the philosophy of mind
History of logic
Intellectual history
Logic
Logic and statistics
Logical consequence
Metaphysics of mind
Reasoning
Sources of knowledge
Thought
Hidden categories:
Articles with short description
Short description matches Wikidata
Articles lacking in-text citations from April 2010
All articles lacking in-text citations
Wikipedia articles needing clarification from August 2013
Articles to be expanded from October 2016
All articles to be expanded
Articles using small message boxes
Articles with BNF identifiers
Articles with GND identifiers
Articles with LCCN identifiers
Articles with NDL identifiers
Navigation menu
Personal tools
Not logged in
Talk
Contributions
Create account
Log in
Namespaces
Article
Talk
English expanded collapsed
Views
Read
Edit
View history
More expanded collapsed
Search
Navigation
Main page
Contents
Current events
Random article
About Wikipedia
Contact us
Donate
Contribute
Help
Learn to edit
Community portal
Recent changes
Upload file
Tools
What links here
Related changes
Upload file
Special pages
Permanent link
Page information
Cite this page
Wikidata item
Print/export
Download as PDF
Printable version
Languages
العربية
Asturianu
Azərbaycanca
Български
Bosanski
Brezhoneg
Català
Dansk
Deutsch
Español
Esperanto
Euskara
فارسی
Français
한국어
Հայերեն
हिन्दी
Hrvatski
Bahasa Indonesia
Italiano
עברית
Қазақша
Latina
La .lojban.
Nederlands
日本語
ਪੰਜਾਬੀ
پنجابی
Plattdüütsch
Polski
Português
Română
Русский
Slovenčina
Српски / srpski
Suomi
Svenska
Tagalog
தமிழ்
ไทย
Türkçe
Українська
اردو
Tiếng Việt
吴语
中文
Edit links
This page was last edited on 14 December 2021, at 21:51 (UTC).
Text is available under the Creative Commons Attribution-ShareAlike License; additional terms may apply. By using this site, you agree to the Terms of Use and Privacy Policy. Wikipedia® is a registered trademark of the Wikimedia Foundation, Inc., a non-profit organization.
Privacy policy
About Wikipedia
Disclaimers
Contact Wikipedia
Mobile view
Developers
Statistics
Cookie statement |
# FindNetwork v2.1 (Beta)
Use these python codes to visit the NeuPrint hemibrain connectomes datasets.
Find direct or indirect connections between neuron clusters and visulize them.
Docstrings of most classes, and functions are available in the codes.
## Basic functions
### FindDirect.py
This script is used for finding direct connections between neuron clusters.
```python
fc = FindNeuronConnection(
token='',
dataset = 'hemibrain:v1.2.1',
data_folder=R'D:\connectome_data',
sourceNeurons = ['KC.*'],
targetNeurons = ['MBON03'],
custom_source_name = '',
custom_target_name = '',
min_synapse_num = 1,
min_traversal_probability = 0.001,
showfig = False,
)
```
in the main codes, we call the ```FindNeuronConnection``` class at first. In the class, you should input your own token obtained from [Neuprint Account Page](https://neuprint.janelia.org/account).
```python
fc = FindNeuronConnection(
... # other parameters
token = 'Your Auth Token',
... # other parameters
)
```
And you can specify the ```dataset``` to use (default is ```"hemibrain:v1.2.1"```).
```python
fc = FindNeuronConnection(
... # other parameters
dataset = 'hemibrain:v1.2.1',
... # other parameters
)
# All available datasets are listed below:
'''
'fib19:v1.0',
'hemibrain:v0.9',
'hemibrain:v1.0.1',
'hemibrain:v1.1',
'hemibrain:v1.2.1',
'manc:v1.0'
'''
```
If ```data_folder``` was not specified, all fetched data will be saved in the "connection_data" folder in the current directory. We highly recommand you to specify the ```data_folder``` to save all data in a specific directory. Then each time you run the codes, the data will be saved in a new folder with auto-generated name in the specified ```data_folder``` directory.
```python
fc = FindNeuronConnection(
... # other parameters
data_folder = R'D:\connectome_data',
... # other parameters
)
```
Alternatively, you can specify the save_folder to save the current data in a specific directory for this time only.
```python
fc = FindNeuronConnection(
... # other parameters
save_folder = R'D:\connectome_data\current_data',
... # other parameters
)
```
Source neurons and target neurons should be specified as ```bodyId```, ```type```, or ```instance``` (use regular expression to search for instances matching the regular expression). See details in the docstrings by hanging your cursor over the parameter name.
```python
fc = FindNeuronConnection(
... # other parameters
sourceNeurons = ['KC.*'],
targetNeurons = ['MBON03'],
# sourceNeurons = pd.read_excel('sourceNeurons.xlsx', header=None).iloc[:,0].tolist(),
# targetNeurons = pd.read_excel('targetNeurons.xlsx', header=None).iloc[:,0].tolist(),
... # other parameters
)
# sourceNeurons and targetNeurons can also be read from other files, e.g. xlsx, csv, txt, etc.
# when reading xlsx and csv files, you can use:
import pandas as pd
neuron_list_1 = pd.read_excel('sourceNeurons.xlsx', header=None).iloc[:,0].tolist()
neuron_list_2 = pd.read_csv('sourceNeurons.csv', header=None).iloc[:,0].tolist()
# to read the first column of the file as a list of bodyIds, types, or instances, without the header.
```
If your source or target neurons are too many items in a list, you can specify a custom name for them.
```python
fc = FindNeuronConnection(
... # other parameters
custom_source_name = 'all_KCs',
custom_target_name = 'my_MBON',
... # other parameters
)
```
In the ```min_synapse_num``` parameter, you can specify the minimum number of synapses between each pair of the connected neurons.
```python
fc = FindNeuronConnection(
... # other parameters
min_synapse_num = 10,
... # other parameters
)
```
In the ```min_traversal_probability``` parameter, you can specify the minimum traversal probability between each pair of the connected neurons. This probability is calculated by the number of synapses between each pair of the connected neurons divided by the (30% total number) of input synapses of the downstream neuron. $p = max(1, w_{ij} / (W_j*0.3))$, where $w_{ij}$ is the number of synapses between neuron $i$ and $j$, and $W_j$ is the total number of input synapses of neuron $j$.
```python
fc = FindNeuronConnection(
... # other parameters
min_traversal_probability = 1e-3, # 0.001
... # other parameters
)
```
If you want to show the figure of the connection matrix, set ```showfig``` to ```True```, otherwise set it to False.
```python
fc = FindNeuronConnection(
... # other parameters
showfig = False, # default is True
... # other parameters
)
```
after specified necessary parameters, you can run the codes to find the direct connections between the source neurons and the target neurons.
To find the direct connections, we call the ```FindNeuronConnection.InitializeNeuronInfo()``` method to initialize before running the ```FindNeuronConnection.FindDirectConnection()``` method.
```python
fc.InitializeNeuronInfo()
fc.FindDirectConnection()
```
In the ```FindNeuronConnection.FindDirectConnection()``` method, you can specify the ```full_data``` parameter to ```True``` (defaulty ```False```) to do clustering and other analysis on the connection data.
```python
fc.FindDirectConnection(full_data=True) # defaultly, full_data is False
```
### FindPath.py
Use this function to find direct and indirect connection paths between the neuron clusters.
```python
fc = FindNeuronConnection(
token='',
dataset = 'hemibrain:v1.2.1',
data_folder=R'D:\connectome_data',
sourceNeurons = ['.*_.*PN.*'],
targetNeurons = ['MBON.*'],
custom_source_name = '',
custom_target_name = '',
min_synapse_num = 1,
min_traversal_probability = 0.001,
showfig = False,
max_interlayer=2,
keyword_in_path_to_remove=['None'],
)
```
Comparing with the FindDirect.py, the call of FindNeuronConnection in FindPath.py uses two more parameters: ```max_interlayer``` and ```keyword_in_path_to_remove```.
the max_interlayer parameter is used to specify the maximum number of layers between the source neurons and the target neurons to search for the indirect connection paths.
The ```keyword_in_path_to_remove``` parameter is used to specify the keywords in the indirect connection paths to remove. For example, if you want to remove the paths that contain the keyword 'None', you can set the ```keyword_in_path_to_remove``` parameter to ['None'] (most neurons in the dataset are not labels, which has a type of "None" in the found paths). If you want to remove paths containing the APL neuron and the "None" neurons, you can set the ```keyword_in_path_to_remove``` parameter to ['APL','None'].
```python
fc = FindNeuronConnection(
... # other parameters
max_interlayer=2, # default is 2
keyword_in_path_to_remove=['APL', 'None'],
... # other parameters
)
```
Optionally, there are more parameters you can specify in the ```FindNeuronConnection``` call.
### plot3dSkeleton.py
Use this function to plot the 3D skeleton of the neuron clusters at different layers, you can also input a single layer to plot the skeleton of all the neurons in that layer.
We use ```statvis.LogInHemibrain()``` to provide your token and specify the dataset.
```python
import statvis as sv
sv.LogInHemibrain(token='', dataset='hemibrain:v1.2.1')
```
Then, by calling the ```VisualizeSkeleton``` class, we can initialize the parameters for plotting the 3D skeleton.
```python
from coana import VisualizeSkeleton as vs
vs = VisualizeSkeleton(
data_folder = R'',
neuron_layers = ['VA1d_adPN', 'LHCENT3', 'MBON01'], # or in the format: 'VA1d_adPN -> LHCENT3 -> MBON01'
custom_layer_names = ['VA1d PN', 'my LHN', 'MBON_1'],
neuron_alpha = 0.2,
saveas = None,
min_synapse_num = 1,
synapse_size = 3,
synapse_alpha = 0.6,
mesh_roi = ['LH(R)','AL(R)','EB','gL(R)'],
skeleton_mode = 'tube',
synapse_mode = 'scatter',
legend_mode = 'merge',
use_size_slider = True,
show_fig = True,
)
```
After that, we use the ```plot_neuron()``` method to plot the 3D skeleton. and export the 3-D skeleton to a video with rotating objects by using the ```export_video()``` method. See details in the docstrings of the methods.
```python
vs.plot_neurons()
vs.export_video(fps=30,rotate_plane='xy',synapse_size=2,scale=2,)
```
parameters of the ```export_video()``` determines the properties of the video.
## Installation: For users who can prepare the python environments by themselves
package requirements are in the setup.py (pandas should be 1.5.1)
## Installation: For users who have troubles with preparing the environments
I. Download python 3.11.3 in [Python Downloads](https://www.python.org/downloads/release/python-3113/). Please scroll down and download the circled installer according to your operating system (MacOS or Windows) and install it. Remember to check the "Add Python 3.11 to PATH" at the bottom of the installer.


II. Download Visual Studio Code (vscode) in [Visual Studio Code](https://code.visualstudio.com/) and install it. Click the "Extensions" button at the left bar to search for "Python" and "VSC-Essentials" and install them, respectively. Then, It's highly recommended to press 'Ctrl + ,' (or click the "manage" button in the bottom left corner and click 'Settings') to open the 'Settings' and search for "Auto Save" and select "OnFocusChange" to automatically save the codes, and search for "Execute In File Dir" and check the box to automatically run the codes in the current file directory.


III. Use vscode to open setup.py, then select the python3.11.3 at the bottom right corner. Click run at the top right corner (red circle in the picture below) to install the requirements. If any error raised, please disconnect the VPN proxy and try again.

IV. Get your own token from [NeuPrint](https://neuprint.janelia.org/account). You should log in with your Google account and found your token in the "Account" page by clicking the "LOGIN" button at the top right corner.
V. Input the token in the downloaded codes, you can specify the token in statvis.LogInHemigrain() or coana.FindConnection() functions, which should be embraced by the quotation marks (' ') as:
```python
token = 'your_token',
```


VI. You can find the introduction of the functions and their arguments in the codes by move your cursor over the name, e.g.

Now you can run the codes and get the results. |
class Review {
final int? rating;
final String? comment;
final String? date;
final String? reviewerName;
final String? reviewerEmail;
Review({
this.rating,
this.comment,
this.date,
this.reviewerName,
this.reviewerEmail,
});
factory Review.empty() {
return Review(
rating: 0,
comment: '',
date: '',
reviewerName: '',
reviewerEmail: '',
);
}
factory Review.fromJson(Map<String, dynamic> json) {
return Review(
rating: json['rating'] ?? 0,
comment: json['comment'] ?? '',
date: json['date'] ?? '',
reviewerName: json['reviewerName'] ?? '',
reviewerEmail: json['reviewerEmail'] ?? '',
);
}
Map<String, dynamic> toJson() {
return {
'rating': rating,
'comment': comment,
'date': date,
'reviewerName': reviewerName,
'reviewerEmail': reviewerEmail,
};
}
} |
const titor = require('../lib/titor');
// Introduction
console.log();
console.log('\x1b[7mTitor Test Suite is now Running.\x1b[0m');
console.log();
// Test variables
let description, actual, expected, comparison;
// Test data
const date = new Date('1982-07-09 5:00'); // Friday, July 9, 1982 @ 5:00 a.m.
// Pass / failure tracking
const passes = [];
const failures = [];
const test = (description, actual, expected, comparison) => comparison ? passes.push(description) : failures.push({description, actual, expected});
// d
description = 'd provides the numerical day of the month with leading zero';
actual = titor('d', date);
expected = '09';
comparison = actual === expected;
test(description, actual, expected, comparison);
// D
description = 'D provides the textual day of the week as three letters';
actual = titor('D', date);
expected = 'Fri';
comparison = actual === expected;
test(description, actual, expected, comparison);
// j
description = 'j provides the numeric day of the month with no leading zero';
actual = titor('j', date);
expected = '9';
comparison = actual === expected;
test(description, actual, expected, comparison);
// l
description = 'l provides the textual day of the week';
actual = titor('l', date);
expected = 'Friday';
comparison = actual === expected;
test(description, actual, expected, comparison);
// N
description = 'N provides the numeric day of the week (1=Monday, 7=Sunday)';
actual = titor('N', date);
expected = '5';
comparison = actual === expected;
test(description, actual, expected, comparison);
// S
description = 'S provides the suffix for the day of the month (st, nd, rd, th) [test #1]';
actual = titor('S', date);
expected = 'th';
comparison = actual === expected;
test(description, actual, expected, comparison);
description = 'S provides the suffix for the day of the month (st, nd, rd, th) [test #2]';
actual = titor('S', new Date('2024-05-11 5:00'));
expected = 'th';
comparison = actual === expected;
test(description, actual, expected, comparison);
description = 'S provides the suffix for the day of the month (st, nd, rd, th) [test #3]';
actual = titor('S', new Date('2024-05-01 5:00'));
expected = 'st';
comparison = actual === expected;
test(description, actual, expected, comparison);
description = 'S provides the suffix for the day of the month (st, nd, rd, th) [test #4]';
actual = titor('S', new Date('2024-05-02 5:00'));
expected = 'nd';
comparison = actual === expected;
test(description, actual, expected, comparison);
description = 'S provides the suffix for the day of the month (st, nd, rd, th) [test #5]';
actual = titor('S', new Date('2024-05-03 5:00'));
expected = 'rd';
comparison = actual === expected;
test(description, actual, expected, comparison);
// w
description = 'w provides the numeric day of the week (0=Sunday, 6=Saturday)';
actual = titor('w', date);
expected = '5';
comparison = actual === expected;
test(description, actual, expected, comparison);
// z
description = 'z provides the numeric day of the year (0-365) [test #1]';
actual = titor('z', date);
expected = '189';
comparison = actual === expected;
test(description, actual, expected, comparison);
description = 'z provides the numeric day of the year (0-365) [test #2]';
actual = titor('z', new Date('1982-01-01 5:00'));
expected = '0';
comparison = actual === expected;
test(description, actual, expected, comparison);
// W
description = 'W provides the ISO-8601 week number of the year (weeks starting with Monday)';
actual = titor('W', date);
expected = '27';
comparison = actual === expected;
test(description, actual, expected, comparison);
// F
description = 'F provides the textual month of the year';
actual = titor('F', date);
expected = 'July';
comparison = actual === expected;
test(description, actual, expected, comparison);
// m
description = 'm provides the numeric month of the year (01-12)';
actual = titor('m', date);
expected = '07';
comparison = actual === expected;
test(description, actual, expected, comparison);
// M
description = 'M provides the textual month of the year as three letters';
actual = titor('M', date);
expected = 'Jul';
comparison = actual === expected;
test(description, actual, expected, comparison);
// n
description = 'n provides the numeric month of the year without leading zeros';
actual = titor('n', date);
expected = '7';
comparison = actual === expected;
test(description, actual, expected, comparison);
// t
description = 't provides the number of days in the month';
actual = titor('t', date);
expected = '31';
comparison = actual === expected;
test(description, actual, expected, comparison);
// L
description = 'L provides a 1 if it is a leap year, or a 0 if it is not [Test #1]';
actual = titor('L', date);
expected = '0';
comparison = actual === expected;
test(description, actual, expected, comparison);
description = 'L provides a 1 if it is a leap year, or a 0 if it is not [Test #2]';
actual = titor('L', new Date('2024-05-25 5:00'));
expected = '1';
comparison = actual === expected;
test(description, actual, expected, comparison);
// o
description = 'o provides the ISO-8601 year number';
actual = titor('o', date);
expected = '1982';
comparison = actual === expected;
test(description, actual, expected, comparison);
// Y
description = 'Y provides the year as four digits';
actual = titor('Y', date);
expected = '1982';
comparison = actual === expected;
test(description, actual, expected, comparison);
// y
description = 'y provides the year as two digits';
actual = titor('y', date);
expected = '82';
comparison = actual === expected;
test(description, actual, expected, comparison);
// a
description = 'a provides the period of day in lowercase (am or pm)';
actual = titor('a', date);
expected = 'am';
comparison = actual === expected;
test(description, actual, expected, comparison);
// A
description = 'A provides the period of day in lowercase (am or pm)';
actual = titor('A', date);
expected = 'AM';
comparison = actual === expected;
test(description, actual, expected, comparison);
// B https://en.wikipedia.org/wiki/Swatch_Internet_Time
description = 'B provides the Swatch Internet time (000-999)';
actual = titor('B', new Date(Date.UTC(1982, 6, 9, 5, 0, 0))); // Using UTC time for this experiment
expected = '250';
comparison = actual === expected;
test(description, actual, expected, comparison);
// g
description = 'g provides the hour of the day in 12-hour (1-12)';
actual = titor('g', date);
expected = '5';
comparison = actual === expected;
test(description, actual, expected, comparison);
// G
description = 'G provides the hour of the day in 24-hour (0-23)';
actual = titor('G', date);
expected = '5';
comparison = actual === expected;
test(description, actual, expected, comparison);
// h
description = 'h provides the hour of the day in 12-hour (01-12)';
actual = titor('h', date);
expected = '05';
comparison = actual === expected;
test(description, actual, expected, comparison);
// H
description = 'H provides the hour of the day in 24-hour (00-23)';
actual = titor('H', date);
expected = '05';
comparison = actual === expected;
test(description, actual, expected, comparison);
// i
description = 'i provides the minute of the hour with leading zero';
actual = titor('i', date);
expected = '00';
comparison = actual === expected;
test(description, actual, expected, comparison);
// s
description = 's provides the second of the minute with leading zero';
actual = titor('s', date);
expected = '00';
comparison = actual === expected;
test(description, actual, expected, comparison);
// u
description = 'u provides the microseconds';
actual = titor('u', date);
expected = '000000';
comparison = actual === expected;
test(description, actual, expected, comparison);
// e
description = 'e provides the timezone identifier';
actual = titor('e', new Date(Date.UTC(1982, 6, 9, 5, 0, 0)));
expected = 'UTC';
comparison = actual === expected;
test(description, actual, expected, comparison);
// I
description = 'I provides a 1 if it is daylight savings time, or a 0 if it is not';
actual = titor('I', new Date(Date.UTC(1982, 6, 9, 5, 0, 0)));
expected = '1';
comparison = actual === expected;
test(description, actual, expected, comparison);
// O
description = 'O provides difference to Greenwich time (GMT) in hours (+0000)';
actual = titor('O', new Date(Date.UTC(1982, 6, 9, 5, 0, 0)));
expected = '+0000';
comparison = actual === expected;
test(description, actual, expected, comparison);
// P
description = 'P provides difference to Greenwich time (GMT) in hours and minutes (colon-separated)';
actual = titor('P', new Date(Date.UTC(1982, 6, 9, 5, 0, 0)));
expected = '+00:00';
comparison = actual === expected;
test(description, actual, expected, comparison);
// T
description = 'T provides timezone abbreviation (EST)';
actual = titor('T', new Date(Date.UTC(1982, 6, 9, 5, 0, 0)));
expected = 'UTC';
comparison = actual === expected;
test(description, actual, expected, comparison);
// Z
description = 'Z provides the timezone offset in seconds (west of UTC are negative)';
actual = titor('Z', new Date(Date.UTC(1982, 6, 9, 5, 0, 0)));
expected = '0';
comparison = actual === expected;
test(description, actual, expected, comparison);
// c
description = 'c provides the ISO-8601 date (1982-07-09T05:00:00+00:00)';
actual = titor('c', new Date(Date.UTC(1982, 6, 9, 5, 0, 0)));
expected = '1982-07-09T05:00:00+00:00';
comparison = actual === expected;
test(description, actual, expected, comparison);
// r
description = 'r provides the RFC 2822 date (Fri, 09 Jul 1982 05:00:00 +0000)';
actual = titor('r', new Date(Date.UTC(1982, 6, 9, 5, 0, 0)));
expected = 'Fri, 09 Jul 1982 05:00:00 +0000';
comparison = actual === expected;
test(description, actual, expected, comparison);
// U
description = 'U provides the number of seconds since the Unix Epoch';
actual = titor('U', new Date(Date.UTC(1982, 6, 9, 5, 0, 0)));
expected = '395038800';
comparison = actual === expected;
test(description, actual, expected, comparison);
// Format pass and failure strings
const formattedPasses = passes.map(pass => `\t• \x1b[1m\x1b[32m✔ Passed: \x1b[0m\x1b[32m${pass}\x1b[0m`);
const formattedFailures = failures.map(failure => `\t• \x1b[1m\x1b[31m❌ Failed: \x1b[0m\x1b[31m${failure.description}\x1b[0m`+
`\r\n\t\t\x1b[1mActual: \x1b[0m\x1b[33m${failure.actual}\x1b[0m`+
`\r\n\t\t\x1b[1mExpected: \x1b[0m\x1b[33m${failure.expected}\x1b[0m`);
// Display test status information
if(formattedPasses.length > 0) {
console.log();
console.log('\x1b[4mPassing Tests:\x1b[0m');
console.log();
for(const pass of formattedPasses) console.log(pass);
console.log();
}
if(formattedFailures.length > 0) {
console.log();
console.log('\x1b[4mFailing Tests:\x1b[0m');
console.log();
for(const failure of formattedFailures) console.log(failure);
console.log();
}
const totalTests = passes.length + failures.length;
const padding = String(totalTests).length;
console.log();
console.log('\x1b[7mTesting Complete:\x1b[0m');
console.log();
if(passes.length > 0) console.log(`\t• Tests \x1b[32mPassing: ${String(passes.length).padStart(padding, '0')}\x1b[0m/${String(totalTests).padStart(padding, '0')}`);
if(failures.length > 0) console.log(`\t• Tests \x1b[31mFailing: ${String(failures.length).padStart(padding, '0')}\x1b[0m/${String(totalTests).padStart(padding, '0')}`);
console.log();
// Exit with failure or success code
if(failures.length > 0) process.exit(1);
else process.exit(); |
data Lista a = Cons a (Lista a) | Vazio
deriving (Eq, Show)
ex1 :: Lista Int
ex1 = Cons 1 (Cons 2(Cons 3(Cons 4 Vazio)))
ex2 :: Lista Int
ex2 = Cons 7 (Cons 8(Cons 9(Cons 0 Vazio)))
tamanho :: Lista a -> Int
tamanho Vazio = 0
tamanho (Cons x xs) = 1 + tamanho xs
mapList :: (a->b) -> Lista a -> Lista b
mapList f Vazio = Vazio
mapList f (Cons x xs) = Cons (f x) (mapList f xs)
foldrLista :: (a->a->a) -> Lista a -> a
foldrLista f (Cons x Vazio) = x
foldrLista f (Cons x xs) = f x (foldrLista f xs)
filterLista :: (a->Bool) -> Lista a -> Lista a
filterLista f Vazio = Vazio
filterLista f (Cons x xs)
| f x = Cons x (filterLista f xs)
| otherwise = filterLista f xs
concatLista :: Lista a -> Lista a -> Lista a
concatLista Vazio (Cons x xs) = (Cons x xs)
concatLista (Cons x xs) Vazio = (Cons x xs)
concatLista (Cons x xs) (Cons y ys) = Cons x (concatLista xs (Cons y ys)) |
using Microsoft.AspNetCore.Http;
using System.ComponentModel.DataAnnotations;
using System.Xml.Linq;
namespace WebApp.Models
{
public class CrearAmigoModel
{
//TODO: Se crean las validaciones para cada uno de los campos del modelo
[Required(ErrorMessage = "*Obligatorio"), MaxLength(20, ErrorMessage = "*Máximo 20 caracteres")]
public string Nombre { get; set; }
[Required(ErrorMessage = "*Obligatorio"), MaxLength(50, ErrorMessage = "*Máximo 50 caracteres")]
[Display(Name = "Correo electronico")]
[RegularExpression(@"^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$", ErrorMessage = "*Formato invalido")]
public string Email { get; set; }
public string ProfilePictureUrl { get; set; }
[Required(ErrorMessage = "*Debe seleccionar una ciudad")]
public Provincia? Ciudad { get; set; }
public IFormFile Foto { get; set; }
}
} |
import { itAstExpression, testAst } from './ast-test-utils';
import { AstNodeType } from '../ast-node';
describe('Binary Ast Expressions', function () {
it(`should parse expression "69 + 1337" correctly`, () => {
const leftNumber = 69;
const rightNumber = 1337;
testAst(`${leftNumber} + ${rightNumber}`, {
type: AstNodeType.BinaryExpression,
left: {
type: AstNodeType.NumberLiteral,
value: leftNumber
},
operator: '+',
right: {
type: AstNodeType.NumberLiteral,
value: rightNumber
}
});
});
it(`should parse expression "69 + 1337 + 33" correctly`, () => {
const firstNumber = 69;
const secondNumber = 1337;
const thirdNumber = 1337;
testAst(`${firstNumber} + ${secondNumber} + ${thirdNumber}`, {
type: AstNodeType.BinaryExpression,
left: {
type: AstNodeType.BinaryExpression,
left: {
type: AstNodeType.NumberLiteral,
value: firstNumber
},
operator: '+',
right: {
type: AstNodeType.NumberLiteral,
value: secondNumber
}
},
operator: '+',
right: {
type: AstNodeType.NumberLiteral,
value: thirdNumber
}
});
});
it(`should parse expression "3 + 2 * 5" correctly`, () => {
const firstNumber = 3;
const secondNumber = 2;
const thirdNumber = 5;
testAst(`${firstNumber} + ${secondNumber} * ${thirdNumber}`, {
type: AstNodeType.BinaryExpression,
left: {
type: AstNodeType.NumberLiteral,
value: firstNumber
},
operator: '+',
right: {
type: AstNodeType.BinaryExpression,
left: {
type: AstNodeType.NumberLiteral,
value: secondNumber
},
operator: '*',
right: {
type: AstNodeType.NumberLiteral,
value: thirdNumber
}
}
});
});
it('should parse expression "3 * 2 ** 5" correctly', () => {
const firstNumber = 3;
const secondNumber = 2;
const thirdNumber = 5;
testAst(`${firstNumber} * ${secondNumber} ** ${thirdNumber}`, {
type: AstNodeType.BinaryExpression,
left: {
type: AstNodeType.NumberLiteral,
value: firstNumber
},
operator: '*',
right: {
type: AstNodeType.BinaryExpression,
left: {
type: AstNodeType.NumberLiteral,
value: secondNumber
},
operator: '**',
right: {
type: AstNodeType.NumberLiteral,
value: thirdNumber
}
}
});
});
it('should parse expression "true + false" correctly', () => {
testAst(`true + false`, {
type: AstNodeType.BinaryExpression,
left: {
type: AstNodeType.BooleanLiteral,
value: true
},
operator: '+',
right: {
type: AstNodeType.BooleanLiteral,
value: false
}
});
});
it('should parse expression `"left string" + "right string"` correctly', () => {
testAst(`"left string" + "right string"`, {
type: AstNodeType.BinaryExpression,
left: {
type: AstNodeType.StringLiteral,
value: 'left string'
},
operator: '+',
right: {
type: AstNodeType.StringLiteral,
value: 'right string'
}
});
});
itAstExpression('2 > 1 < 3 >= 3 <= 4', {
type: AstNodeType.BinaryExpression,
left: {
type: AstNodeType.BinaryExpression,
left: {
type: AstNodeType.BinaryExpression,
left: {
type: AstNodeType.BinaryExpression,
left: {
type: AstNodeType.NumberLiteral,
value: 2
},
operator: '>',
right: {
type: AstNodeType.NumberLiteral,
value: 1
}
},
operator: '<',
right: {
type: AstNodeType.NumberLiteral,
value: 3
}
},
operator: '>=',
right: {
type: AstNodeType.NumberLiteral,
value: 3
}
},
operator: '<=',
right: {
type: AstNodeType.NumberLiteral,
value: 4
}
});
itAstExpression('true || false && true', {
type: AstNodeType.BinaryExpression,
left: {
type: AstNodeType.BooleanLiteral,
value: true,
},
operator: '||',
right: {
type: AstNodeType.BinaryExpression,
left: {
type: AstNodeType.BooleanLiteral,
value: false,
},
operator: '&&',
right: {
type: AstNodeType.BooleanLiteral,
value: true
}
}
});
itAstExpression('5 * 5 / 5 % 2', {
type: AstNodeType.BinaryExpression,
left: {
type: AstNodeType.BinaryExpression,
left: {
type: AstNodeType.BinaryExpression,
left: {
type: AstNodeType.NumberLiteral,
value: 5
},
operator: '*',
right: {
type: AstNodeType.NumberLiteral,
value: 5
}
},
operator: '/',
right: {
type: AstNodeType.NumberLiteral,
value: 5
}
},
operator: '%',
right: {
type: AstNodeType.NumberLiteral,
value: 2
}
});
itAstExpression('a = 5;', {
type: AstNodeType.Assignment,
id: {
type: AstNodeType.Identifier,
name: 'a'
},
kind: '=',
init: {
type: AstNodeType.NumberLiteral,
value: 5,
},
})
}); |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<link rel="stylesheet" href="../styles.css" />
<link rel="preconnect" href="https://fonts.googleapis.com" />
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
<link
href="https://fonts.googleapis.com/css2?family=Montserrat:ital,wght@0,100..900;1,100..900&display=swap"
rel="stylesheet"
/>
<style>
.calendar {
font-family: Arial, sans-serif;
max-width: 300px;
border: 1px solid #ccc;
padding: 10px;
}
.calendar-header {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 10px;
}
.calendar-header select {
padding: 5px;
font-size: 16px;
}
.calendar-body {
display: grid;
grid-template-columns: repeat(7, 1fr);
}
.calendar-day {
padding: 5px;
text-align: center;
cursor: pointer;
}
.calendar-day:hover {
background-color: #f0f0f0;
}
.today {
background-color: #f2f2f2;
}
</style>
</head>
<body>
<header class="title">
<img class="kpi" src="../images/kpi-symbol.png" alt="" />
<div class="title-text">
<p>
звіти з лабораторних робіт <br />
з дисципліни "web-орієнтовані технології. основи frontend та backend
розробок"
</p>
<p>Студента групи ІО-13 <span>Міхолата Євгена Олеговича</span></p>
</div>
<img
class="face-photo" style="height: 100px; width: 80px; margin-right: 40px;"
src="../images/photo.PNG"
alt=""
/>
</header>
<main>
<div class="labs">
<a href="../lab1/1lab.html" class="lab">Лаба №1</a>
<a href="../lab2/2lab.html" class="lab">Лаба №2</a>
<a href="../lab3/3lab.html" class="lab">Лаба №3</a>
<a href="../lab4/4lab.html" class="lab">Лаба №4</a>
<a href="5lab.html" class="lab">Лаба №5</a>
<a href="../lab6/6lab.html" class="lab">Лаба №6</a>
<a href="../lab7/7lab.html" class="lab">Лаба №7</a>
<a href="../lab8/8lab.html" class="lab">Лаба №8</a>
<a href="../lab9/9lab.html" class="lab">Лаба №9</a>
</div>
<div class="labs-content">
<div class="list">
<a href="5lab.html" class="list-item"
>Тема, мета, місце розташування лаби</a
>
<a href="" class="list-item" id="selectors" style="text-align: center;">Способи функціонального застосування JAVASCRIPT</a>
<ul class="tags">
<li><a href="url.html" class="list-item">Схема URL</a></li>
<li><a href="event.html" class="list-item">Обробник подій</a></li>
<li>
<a href="entity.html" class="list-item"
>Підстановка (Entity) </a
>
</li>
<li>
<a href="entity.html" class="list-item">Вставка (тег SCRIPT)</a>
</li>
</ul>
<a href="arrays.html" class="list-item">Пункт 4. Масиви </a>
<a href="calendar.html" class="list-item">Пункт 6 </a>
<a href="task7.html" class="list-item">Завдання 5.2 </a>
<a href="conclusions5.html" class="list-item">Висновки</a>
</div>
<div class="list-content" style="overflow-y: auto;">
<h2>Тег <script></h2>
<p>Тег <script>
- це HTML-тег, який використовується для включення JavaScript коду в HTML-документ. Він дозволяє вбудовувати JavaScript код безпосередньо в
сторінку, що дозволяє створювати інтерактивні веб-сайти, змінювати вміст сторінок динамічно, реагувати на події користувача та виконувати інші завдання</p>
<h4>Основні атрибути тегу <script> :</h4>
<ul>
<li>
src: Цей атрибут вказує шлях до зовнішнього файлу JavaScript, який повинен бути включений. Cлугує альтернативою вставки скрипта беспосередньо в документ Наприклад:
<img style="display: block;" src="../images/tag1.PNG" alt="">
</li>
<li>
type: Цей атрибут вказує тип мови скрипту, який використовується в тегу <script>. Зазвичай він має значення "text/javascript", але це значення за замовчуванням і може бути опущеним.
<img style="display: block;" src="../images/tag2.PNG" alt="">
</li>
</ul>
<h4>Розміщення тегу <script> :</h4>
<p>Тег <script> може бути включений в різні частини HTML-документа, такі як:</p>
<ul>
<li>
У розділі <head> : Це місце, де зазвичай включають скрипти, які не впливають на відображення сторінки, але виконують інші завдання, наприклад, завантаження ресурсів чи налаштування.
</li>
<li>
Після вмісту сторінки (перед закриваючим тегом </body>): Це місце для скриптів, які впливають на відображення сторінки, такі як маніпуляції DOM, обробка подій користувача.
</li>
</ul>
</div>
</div>
</main>
</body>
</html> |
import 'dart:convert';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:hive_flutter/hive_flutter.dart';
import 'package:todolist/database/database.dart';
import 'package:todolist/text_page.dart';
import 'dialog_box.dart';
import 'todo_tile.dart';
class HomePage extends StatefulWidget{
const HomePage({super.key});
@override
State<HomePage> createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
//refernce the hive box
final _myBox = Hive.box('mybox');
ToDoDataBase db = ToDoDataBase();
@override
void initState() {
if(_myBox.get("TODOLIST")== null) {
db.createInitialData();
}else{
db.loadData();
}
super.initState();
}
//text controller
final _controller =TextEditingController();
//checkbox was tapped
void checkBoxChanged(bool? value, int index) {
setState(() {
db.toDoList[index][1] = !db.toDoList[index][1];
});
db.updateDataBase();
}
//save new task
void SaveNewTask() {
setState(() {
db.toDoList.add([_controller.text, false]);
_controller.clear();
});
Navigator.of(context).pop();
db.updateDataBase();
}
//create new task
void createNewTask(context) {
showDialog(
context: context,
builder: (context) {
return DialogueBox(
controller:
_controller
,
onSave: SaveNewTask,
onCancel: () => Navigator.of(context).pop(),
);
},
);
}
//delete task
void deleteTask(int index) {
setState(() {
db.toDoList.removeAt(index);
});
db.updateDataBase();
}
@override
Widget build(BuildContext context) {
void _openTextPage() {
Navigator.push(context, MaterialPageRoute(builder: (context){
return TextPage();
}));
}
return Scaffold(
backgroundColor: Colors.blueGrey[200],
appBar: AppBar(
actions: <Widget>[
PopupMenuButton(
itemBuilder: (context) =>[
PopupMenuItem(
child: Row(
children: [
SizedBox(
width: 10,
),
Text(
"Select all",
style: TextStyle(
color: Colors.grey,
),
),
],
))
]),
],
title: Text('To-dos'),
elevation: 0,
centerTitle: true,
),
floatingActionButton: FloatingActionButton(
onPressed: () => createNewTask(context),
child: Icon(Icons.add),
),
body: Padding(
padding: const EdgeInsets.all(8.0),
child: InkWell(
child: ListView.builder(
itemCount:db.toDoList.length,
itemBuilder: (context, index) {
onPressed: () => _openTextPage();
return ToDoTile(
taskName: db.toDoList[index][0],
taskCompleted: db.toDoList[index][1],
onChange: (value) => checkBoxChanged(value, index),
deleteFunction: (context) => deleteTask(index),
);
},
),
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => TextPage(),
)
);
},
),
),
);
}
} |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>弹性盒</title>
<style type="text/css">
*{
margin: 0;
padding: 0;
}
ul{
width: 800px;
border: 10px red solid;
list-style: none;
display: flex;
/*flex-direction :指定容器中排列方式
-row : 水平排列(左向右)
-row-reverse 水平反向排列
-column 垂直排列 自上向下
-column-reverse 类似
主轴:弹性元素的排列方向:主轴 row:主轴自左向右;row-reverse:反向
侧轴:与主轴垂直方向叫侧轴*/
/*flex-direction: row;*/
}
li{
width: 300px;
height: 100px;
background-color: #bfa;
font-size: 50px;
line-height: 100px;
text-align: center;
/* 弹性元素的属性*/
/* flex-grow 指定弹性元素的伸展的效果
当父元素有多余的空间时:子元素如何伸展
flex-shrink当父元素的空间不足以满足子元素的时候*/
/*flex-shrink: 指定元素收缩效果 如何对子元素进行收缩;
0: 不收缩*/
flex-shrink: 1;
}
li:nth-child(1){
/*flex-grow: 0;*/
}
li:nth-child(2){
background-color: rebeccapurple;
/*flex-grow: 2;*/
}
li:nth-child(3){
background-color: #b9cb41;
/*flex-grow: 3;*/
}
</style>
</head>
<body>
<!--flex弹性盒 或者伸缩盒 主要用来代替浮动进行布局
可以使元素具有弹性 根据屏幕的大小改变
弹性容器:
-使用弹性盒 必须设置一个元素为弹性元素
-可以通过display来设置弹性容器
display:flex 块级的弹性容器
display: inline-flex 行内的弹性容器
弹性元素:
-弹性元素的直接子元素叫做弹性元素(弹性项)
-一个元素可以同时为弹性容器和弹性元素-->
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
</ul>
aa
</body>
</html> |
const db = require("../models");
const Truth = db.truths;
// Create and Save a new Truth
exports.create = (req, res) => {
// Validate request
if (!req.body.text) {
res.status(400).send({ message: "Truth text can not be empty!" });
return;
}
if (!req.body.singer) {
res.status(400).send({ message: "Truth singer can not empty!" });
return;
}
// Create a Truth
const truth = new Truth({
text: req.body.text,
song: req.body.song ? req.body.song : '',
singer: req.body.singer
});
// Save Truth in the database
truth
.save(truth)
.then(data => {
res.send(data);
})
.catch(err => {
res.status(500).send({
message:
err.message || "Some error occurred while creating the Truth."
});
});
};
// Retrieve all Truths from the database.
exports.findAll = (req, res) => {
Truth.find()
.then(data => {
res.send(data);
})
.catch(err => {
res.status(500).send({
message:
err.message || "Some error occurred while retrieving Truths."
});
});
};
// Find a single Truth with an id
exports.findOne = (req, res) => {
const id = req.params.id;
Truth.findById(id)
.then(data => {
if (!data)
res.status(404).send({ message: "Not found Truth with id " + id });
else res.send(data);
})
.catch(err => {
res
.status(500)
.send({ message: "Error retrieving Truth with id=" + id });
});
};
// Update a Truth by the id in the request
exports.update = (req, res) => {
if (!req.body) {
return res.status(400).send({
message: "Data to update can not be empty!"
});
}
const id = req.params.id;
Truth.findByIdAndUpdate(id, req.body, { useFindAndModify: false })
.then(data => {
if (!data) {
res.status(404).send({
message: `Cannot update Truth with id=${id}. Maybe Truth was not found!`
});
} else res.send({ message: "Truth was updated successfully." });
})
.catch(err => {
res.status(500).send({
message: "Error updating Truth with id=" + id
});
});
};
// Delete a Truth with the specified id in the request
exports.delete = (req, res) => {
const id = req.params.id;
Truth.findByIdAndDelete(id)
.then(data => {
if (!data) {
res.status(404).send({
message: `Cannot delete Truth with id=${id}. Maybe Truth was not found!`
});
} else {
res.send({
message: "Truth was deleted successfully!"
});
}
})
.catch(err => {
res.status(500).send({
message: "Could not delete Truth with id=" + id
});
});
};
// Delete all Truths from the database.
exports.deleteAll = (req, res) => {
Truth.deleteMany({})
.then(data => {
res.send({
message: `${data.deletedCount} Truths were deleted successfully!`
});
})
.catch(err => {
res.status(500).send({
message:
err.message || "Some error occurred while removing all Truths."
});
});
};
// Find all Truths saind by singer
exports.findAllBySinger = (req, res) => {
const singer = req.query.singer;
var condition = singer ? { singer: { $regex: new RegExp(singer), $options: "i" } } : {};
Truth.find(condition)
.then(data => {
res.send(data);
})
.catch(err => {
res.status(500).send({
message:
err.message || "Some error occurred while retrieving Truths."
});
});
}; |
## Código para a pipeline de build
### Definição do pipeline
```tf filename="modelbuild_ci_pipeline.tf" copy
resource "aws_codepipeline" "sm_ci_pipeline" {
name = "modelbuild-pipeline"
role_arn = aws_iam_role.tf_mlops_role.arn
tags = {
Environment = var.env
}
artifact_store {
location = aws_s3_bucket.artifacts_bucket.bucket
type = "S3"
}
stage {
name = "Source"
action {
category = "Source"
configuration = {
RepositoryName = var.build_repository_name
BranchName = var.repository_branch
PollForSourceChanges = true
}
input_artifacts = []
name = "Source"
output_artifacts = [
"SourceArtifact",
]
owner = "AWS"
provider = "CodeCommit"
run_order = 1
version = "1"
}
}
stage {
name = "Build"
action {
category = "Build"
configuration = {
"ProjectName" = "tf-mlops-modelbuild"
}
input_artifacts = [
"SourceArtifact",
]
name = "Build"
output_artifacts = [
"BuildArtifact",
]
owner = "AWS"
provider = "CodeBuild"
run_order = 1
version = "1"
}
}
}
```
Aqui definimos todos os aspectos de nossa pipeline, começando pela etapa de Source, definimos que a fonte vem de um repositório AWS CodeCommit, e colocamos seu nome, a branch a ser utilizada e o `PollForSourceChanges` serve para a pipeline buscar por mudanças no código fonte e rodar a pipeline quando detectar mudanças.
Em seguida, temos a fase de build, que aqui colocamos o nome do projeto, porém vamos criar ela no próximo arquivo.
Por fim, essa etapa não possui fase de deploy.
### Definição do CodeBuild
```yml filename="modelbuild_buildspec.yml" copy
version: 0.2
phases:
install:
runtime-versions:
python: 3.8
commands:
- pip install --upgrade --force-reinstall . awscli
# Tire a linha abaixo quando for utilizar outros dados, esses são só para exemplo de pipeline.
- aws s3 cp s3://sagemaker-sample-files/datasets/tabular/synthetic/churn.txt s3://${ARTIFACT_BUCKET}/sagemaker/DEMO-xgboost-churn/data/RawData.csv
build:
commands:
- export PYTHONUNBUFFERED=TRUE
- export SAGEMAKER_PROJECT_NAME_ID="${SAGEMAKER_PROJECT_NAME}-${SAGEMAKER_PROJECT_ID}"
- |
run-pipeline --module-name pipelines.customer_churn.pipeline \
--role-arn ${SAGEMAKER_PIPELINE_ROLE_ARN} \
--tags "[{\"Key\":\"sagemaker:project-name\", \"Value\":\"${SAGEMAKER_PROJECT_NAME}\"}, {\"Key\":\"sagemaker:project-id\", \"Value\":\"${SAGEMAKER_PROJECT_ID}\"}]" \
--kwargs "{\"region\":\"${AWS_REGION}\",\"role\":\"${SAGEMAKER_PIPELINE_ROLE_ARN}\",\"default_bucket\":\"${ARTIFACT_BUCKET}\",\"pipeline_name\":\"${SAGEMAKER_PROJECT_NAME_ID}\",\"model_package_group_name\":\"${SAGEMAKER_PROJECT_NAME_ID}\",\"base_job_prefix\":\"${SAGEMAKER_PROJECT_NAME_ID}\"}"
- echo "Create/Update of the SageMaker Pipeline and execution completed."
```
Neste arquivo yml, definimos todas as etapas que o build deve executar, desde a instalação de dependências, até a execução da [pipeline do sagemaker](https://github.com/RicardoRibeiroRodrigues/AWS-IaC-mlops-pipeline/tree/main/templates/modelbuild_pipeline).
```tf filename="modelbuild_codebuild.tf" copy
data "template_file" "buildspec" {
template = file("modelbuild_buildspec.yml")
vars = {
env = var.env
SAGEMAKER_PROJECT_NAME=var.project_name
SAGEMAKER_PROJECT_ID=var.project_id
ARTIFACT_BUCKET=var.artifacts_bucket_name
SAGEMAKER_PIPELINE_ROLE_ARN=aws_iam_role.tf_mlops_role.arn
AWS_REGION=var.region
SAGEMAKER_PROJECT_NAME_ID="${var.project_name}-${var.project_id}"
}
}
resource "aws_codebuild_project" "tf_mlops_modelbuild" {
badge_enabled = false
build_timeout = 60
name = "tf-mlops-modelbuild"
queued_timeout = 480
service_role = aws_iam_role.tf_mlops_role.arn
tags = {
Environment = var.env
}
artifacts {
encryption_disabled = false
name = "tf-mlops-modelbuild-${var.env}"
override_artifact_name = false
packaging = "NONE"
type = "CODEPIPELINE"
}
environment {
compute_type = "BUILD_GENERAL1_SMALL"
image = "aws/codebuild/amazonlinux2-x86_64-standard:2.0"
image_pull_credentials_type = "CODEBUILD"
privileged_mode = false
type = "LINUX_CONTAINER"
environment_variable {
name = "environment"
type = "PLAINTEXT"
value = var.env
}
environment_variable {
name = "SAGEMAKER_PROJECT_NAME"
type = "PLAINTEXT"
value = var.project_name
}
environment_variable {
name = "SAGEMAKER_PROJECT_ID"
type = "PLAINTEXT"
value = var.project_id
}
environment_variable {
name = "ARTIFACT_BUCKET"
type = "PLAINTEXT"
value = var.artifacts_bucket_name
}
environment_variable {
name = "SAGEMAKER_PIPELINE_ROLE_ARN"
type = "PLAINTEXT"
value = aws_iam_role.tf_mlops_role.arn
}
environment_variable {
name = "AWS_REGION"
type = "PLAINTEXT"
value = var.region
}
}
logs_config {
cloudwatch_logs {
status = "ENABLED"
}
s3_logs {
encryption_disabled = false
status = "DISABLED"
}
}
source {
buildspec = data.template_file.buildspec.rendered
git_clone_depth = 0
insecure_ssl = false
report_build_status = false
type = "CODEPIPELINE"
}
}
```
Por fim, aqui definimos a etapa de build, onde no inicio do arquivo todas as variáveis do .yml são preenchidas por variáveis do terraform. Em seguida são configurados todos os aspectos do build, como o tipo de instância utilizada, a imagem utilizada na instância, todas as variáveis de ambiente utilizadas na pipeline, configura também os logs no cloudwatch e no desabilita eles no S3 e coloca o CODEPIPELINE como a fonte do código para o build. |
//
// ExecutorView.swift
// Ionix
//
// Created by luis on 10/05/23.
//
import SwiftUI
struct ExecutorView: View {
@EnvironmentObject var sessionManager: AuthSessionManager
@ObservedObject var taskManager: TaskViewModel
@State private var selectedTask: TaskModel? = nil
let dateFormatter: DateFormatter = {
let formatter = DateFormatter()
formatter.dateStyle = .short
formatter.timeStyle = .short
return formatter
}()
var body: some View {
NavigationView {
List(taskManager.tasks.filter({ $0.assignedTo?.id == sessionManager.userProfile?.id })) { task in
VStack(alignment: .leading) {
Text(task.title)
.font(.headline)
Text(task.description)
.font(.subheadline)
.foregroundColor(.secondary)
HStack {
Text("Due:")
Text("\(task.dueDate, formatter: dateFormatter)")
}
if let status = task.status {
HStack {
Text("Status:")
Text(status.rawValue.capitalized)
}
}
}
.onTapGesture {
selectedTask = task
}
}
.navigationTitle("Tasks")
.sheet(item: $selectedTask) { task in
TaskDetailView(task: task, taskManager: taskManager)
}
.onReceive(taskManager.objectWillChange) {
// Reload the task list when it changes
selectedTask = nil
}
}
}
} |
/***************************************************************************
Copyright (c) 2016, EPAM SYSTEMS INC
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.epam.dlab.backendapi.core;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.google.common.base.MoreObjects;
import java.util.Date;
/** Stores info about the user's computational resources for notebook.
*/
public class UserComputationalResourceDTO {
@JsonProperty("computational_name")
private String computationalName;
@JsonProperty("computational_id")
private String computationalId;
@JsonProperty("instance_id")
private String instanceId;
@JsonProperty("image")
private String imageName;
@JsonProperty("template_name")
private String templateName;
@JsonProperty
private String status;
@JsonProperty("up_time")
private Date uptime;
@JsonProperty("master_node_shape")
private String masterShape;
@JsonProperty("slave_node_shape")
private String slaveShape;
@JsonProperty("slave_node_spot")
private Boolean slaveSpot = false;
@JsonProperty("slave_node_spot_pct_price")
private Integer slaveSpotPctPrice;
@JsonProperty("total_instance_number")
private String slaveNumber;
@JsonProperty("emr_version")
private String version;
/** Returns name of computational resource. */
public String getComputationalName() {
return computationalName;
}
/** Sets name of computational resource. */
public void setComputationalName(String computationalName) {
this.computationalName = computationalName;
}
/** Sets name of computational resource. */
public UserComputationalResourceDTO withComputationalName(String computationalName) {
setComputationalName(computationalName);
return this;
}
/** Returns a unique id of computational resource. */
public String getComputationalId() {
return computationalId;
}
/** Sets a unique id of computational resource. */
public void setComputationalId(String computationalId) {
this.computationalId = computationalId;
}
/** Sets a unique id of computational resource. */
public UserComputationalResourceDTO withComputationalId(String computationalId) {
setComputationalId(computationalId);
return this;
}
/** Returns the id of instance in Amazon. */
public String getInstanceId() {
return instanceId;
}
/** Sets the id of instance in Amazon. */
public void setInstanceId(String instanceId) {
this.instanceId = instanceId;
}
/** Sets the id of instance in Amazon. */
public UserComputationalResourceDTO withInstanceId(String instanceId) {
setInstanceId(instanceId);
return this;
}
/** Returns the image name. */
public String getImageName() {
return imageName;
}
/** Sets the image name. */
public void setImageName(String imageName) {
this.imageName = imageName;
}
/** Sets the image name. */
public UserComputationalResourceDTO withImageName(String imageName) {
setImageName(imageName);
return this;
}
/** Returns the name of template. */
public String getTemplateName() {
return templateName;
}
/** Sets the name of template. */
public void setTemplateName(String templateName) {
this.templateName = templateName;
}
/** Sets the name of template. */
public UserComputationalResourceDTO withTemplateName(String templateName) {
setTemplateName(templateName);
return this;
}
/** Returns the status. */
public String getStatus() {
return status;
}
/** Sets the status. */
public void setStatus(String status) {
this.status = status;
}
/** Sets the status. */
public UserComputationalResourceDTO withStatus(String status) {
setStatus(status);
return this;
}
/** Returns the date and time when the resource has created. */
public Date getUptime() {
return uptime;
}
/** Sets the date and time when the resource has created. */
public void setUptime(Date uptime) {
this.uptime = uptime;
}
/** Sets the date and time when the resource has created. */
public UserComputationalResourceDTO withUptime(Date uptime) {
setUptime(uptime);
return this;
}
/** Returns the name of notebook shape where resource has been deployed. */
public String getMasterShape() {
return masterShape;
}
/** Sets the name of notebook shape where resource has been deployed. */
public void setMasterShape(String masterShape) {
this.masterShape = masterShape;
}
/** Sets the name of notebook shape where resource has been deployed. */
public UserComputationalResourceDTO withMasterShape(String masterShape) {
setMasterShape(masterShape);
return this;
}
/** Returns the name of slave shape. */
public String getSlaveShape() {
return slaveShape;
}
/** Sets the name of slave shape. */
public void setSlaveShape(String slaveShape) {
this.slaveShape = slaveShape;
}
public Boolean isSlaveSpot() {
return slaveSpot;
}
public void setSlaveSpot(Boolean slaveSpot) {
this.slaveSpot = slaveSpot;
}
/** Sets the name of slave shape. */
public UserComputationalResourceDTO withSlaveShape(String slaveShape) {
setSlaveShape(slaveShape);
return this;
}
/** Sets the name of slave shape. */
public UserComputationalResourceDTO withSlaveSpot(Boolean slaveSpot) {
setSlaveSpot(slaveSpot);
return this;
}
/** Returns the number of slaves notebooks. */
public String getSlaveNumber() {
return slaveNumber;
}
/** Sets the number of slaves notebooks. */
public void setSlaveNumber(String slaveNumber) {
this.slaveNumber = slaveNumber;
}
/** Sets the number of slaves notebooks. */
public UserComputationalResourceDTO withSlaveNumber(String slaveNumber) {
setSlaveNumber(slaveNumber);
return this;
}
/** Returns the EMR version. */
public String getVersion() {
return version;
}
/** Sets the EMR version. */
public void setVersion(String version) {
this.version = version;
}
/** Sets the EMR version. */
public UserComputationalResourceDTO withVersion(String version) {
setVersion(version);
return this;
}
public Integer getSlaveSpotPctPrice() {
return slaveSpotPctPrice;
}
public void setSlaveSpotPctPrice(Integer slaveSpotPctPrice) {
this.slaveSpotPctPrice = slaveSpotPctPrice;
}
public UserComputationalResourceDTO withSlaveSpotPctPrice(Integer slaveSpotPctPrice) {
setSlaveSpotPctPrice(slaveSpotPctPrice);
return this;
}
@Override
public String toString() {
return MoreObjects.toStringHelper(this)
.add("computationalId", computationalId)
.add("computationalName", computationalName)
.add("instanceId", instanceId)
.add("imageName", imageName)
.add("templateName", templateName)
.add("version", version)
.add("masterShape", masterShape)
.add("slaveShape", slaveShape)
.add("slaveSpot", slaveSpot)
.add("slaveSpotPctPrice", slaveSpotPctPrice)
.add("slaveNumber", slaveNumber)
.add("uptime", uptime)
.add("status", status)
.toString();
}
} |
using MantisDevopsBridge.Api.Abstractions.Common.Helpers;
using MantisDevopsBridge.Api.Abstractions.Common.Technical.Tracing;
using MantisDevopsBridge.Api.Adapters.Mongo.Technical;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using MongoDB.Driver;
namespace MantisDevopsBridge.Api.Adapters.Mongo.Repositories.Base;
/// <summary>
/// Manage entity in MongoDB
/// </summary>
/// <typeparam name="T">Entity implementation</typeparam>
public abstract class BaseRepository<T> : TracingAdapter
{
private readonly string _collectionName;
private readonly MongoContext _context;
private readonly ILogger _logger;
/// <summary>
/// Default constructor
/// </summary>
/// <param name="configuration"></param>
/// <param name="logger"></param>
protected BaseRepository(IConfiguration configuration, ILogger logger) : base(logger)
{
_context = new MongoContext(configuration);
_collectionName = typeof(T).Name[..^"Entity".Length];
_logger = logger;
}
/// <summary>
/// Implementation of the collection
/// </summary>
protected IMongoCollection<T> EntityCollection => _context.MongoDatabase.GetCollection<T>(_collectionName);
/// <summary>
/// Create an index for this collection
/// </summary>
/// <param name="properties"></param>
/// <param name="unique"></param>
protected void CreateIndexIfMissing(ICollection<string> properties, bool unique = false)
{
using var logger = LogAdapter($"{Log.F(properties)} {Log.F(unique)}", className: GetType().Name);
var indexName = string.Join("-", properties);
var indexes = EntityCollection.Indexes.List().ToList();
var foundIndex = indexes.Any(index => index["name"] == indexName);
var indexBuilder = Builders<T>.IndexKeys;
var newIndex = indexBuilder.Combine(properties.Select(property => indexBuilder.Ascending(property)));
var options = new CreateIndexOptions
{
Unique = unique,
Name = indexName
};
var indexModel = new CreateIndexModel<T>(newIndex, options);
if (foundIndex) return;
logger.Warn($"Property {_collectionName}.{indexName} is not indexed, creating one");
EntityCollection.Indexes.CreateOne(indexModel);
logger.Warn($"Property {_collectionName}.{indexName} is now indexed");
}
} |
<?php
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
return new class extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('product_images', function (Blueprint $table) {
$table->uuid('id')->primary();
$table->uuid('product_id');
$table->uuid('product_variation_option_id')->nullable();
$table->text('image');
$table->tinyInteger('is_featured')->unsigned()
->comment('0 = not featured, 1 = featured');
$table->foreign('product_id')->references('id')->on('products')->onDelete('cascade');
$table->foreign('product_variation_option_id')->references('id')->on('product_variation_options')->onDelete('cascade');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
DB::statement('SET FOREIGN_KEY_CHECKS = 0');
Schema::dropIfExists('product_images');
DB::statement('SET FOREIGN_KEY_CHECKS = 1');
}
}; |
package hello.hellospring.repository;
import hello.hellospring.domain.Member;
import org.springframework.stereotype.Repository;
import java.util.*;
@Repository//스프링에 repository라고 알려주는 어노테이션
public class MemoryMemberRepository implements MemberRepository{
private static Map<Long, Member> store = new HashMap<>(); //임의의 id와 멤버를 키와 값으로 저장하는 맵함수 생성
private static long sequence = 0L; //키값을 생성
@Override
public Member save(Member member) {
member.setId(++sequence); //임의의 id를 할당시킨다
store.put(member.getId(), member);
return member;
}
@Override
public Optional<Member> findById(Long id) {
return Optional.ofNullable(store.get(id)); //아이디가 없는 상황에서도 리턴 값 가능
}
@Override
public Optional<Member> findByName(String name) {
return store.values().stream() //map 전체를 돌면서 맞는 이름을 찾는 람다식
.filter(member -> member.getName().equals(name))
.findAny();
}
@Override
public List<Member> findAll() {
return new ArrayList<>(store.values());//스토어에 있는 값들을 리스트로 반환한다.
}
public void clearStore() {
store.clear();
}
} |
---
title: "Do You Make These Common Mistakes When Spelling 'Bored'? Find Out Now!"
ShowToc: true
date: "2023-04-11"
author: "Velma Charpia"
tags: ["Spelling Mistakes","Common Mistakes"]
---
## Introduction
Spelling is an important part of communication. It is essential that we spell words correctly in order to be understood. One word that is commonly misspelled is the word ‘bored’. In this post, we will look at the definition of ‘bored’, the common mistakes people make when spelling it, and how to avoid making mistakes when spelling ‘bored’.
## Definition of Spelling ‘Bored’
The word ‘bored’ is an adjective that is used to describe a feeling of being listless and disinterested in something. It is often used to describe a feeling of being uninterested in an activity or situation.
## Common Mistakes People Make When Spelling ‘Bored’
There are several common mistakes that people make when spelling ‘bored’.
### Bored vs. Board
One of the most common mistakes people make is confusing ‘bored’ with ‘board’. ‘Board’ is a noun that is used to describe a flat, thin piece of wood or other material.
### Bored vs. Boredom
Another common mistake is confusing ‘bored’ with ‘boredom’. ‘Boredom’ is a noun that is used to describe the feeling of being listless and disinterested in something.
### Bored vs. Boring
The last mistake people make when spelling ‘bored’ is confusing it with ‘boring’. ‘Boring’ is an adjective that is used to describe something that is dull and uninteresting.
## Conclusion
In conclusion, spelling ‘bored’ correctly is important in order to be understood. The most common mistakes people make when spelling ‘bored’ are confusing it with ‘board’, ‘boredom’, and ‘boring’. To avoid making mistakes when spelling ‘bored’, it is important to remember the definitions of each word and to double-check your spelling.
{{< youtube sMenCErGUZI >}}
Making spelling mistakes is a common occurrence for many people. The word ‘bored’ is one of the most commonly misspelled words. This is because it is often confused with the homophone ‘board’. If you have ever found yourself in a situation where you’re not sure if you’re spelling ‘bored’ correctly, you’re not alone. To help you avoid this common mistake, we’ve compiled a list of the most common mistakes people make when spelling ‘bored’. These include spelling it as ‘board’, ‘bord’, ‘borede’, and ‘borded’. Knowing the correct spelling of ‘bored’ can help you avoid embarrassing mistakes in your writing. So if you want to make sure you’re spelling ‘bored’ correctly, be sure to double-check your spelling and use the correct spelling each time. With this knowledge, you can confidently use ‘bored’ in your writing without worrying about making a mistake.
## Frequently Asked Questions (FAQ) :
**Q1: What is the most common mistake when spelling "bored"?**
**A1:** The most common mistake when spelling "bored" is to spell it as "board" instead.
**Q2: How do you make sure you spell "bored" correctly?**
**A2:** To make sure you spell "bored" correctly, remember that it has two O's and no E.
**Q3: Are there any other words that are commonly confused with "bored"?**
**A3:** Yes, other words that are commonly confused with "bored" include "board" (a flat piece of material used for a variety of purposes), "boar" (a wild pig), and "bode" (to foretell or indicate).
**Q4: What is the correct pronunciation of "bored"?**
**A4:** The correct pronunciation of "bored" is "bohrd".
**Q5: Is there a difference between the British and American English spelling of "bored"?**
**A5:** No, there is no difference between the British and American English spelling of "bored". |
<template>
<LoadingComponent :props="loading" />
<div class="col-12">
<div id="promotion" class="db-tab-div active">
<div class="grid sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-3 mb-5">
<button @click.prevent="multiTargets($event, 'tab-action', 'tab-content', 'promotionInformation')"
class="tab-action active w-full flex items-center gap-3 h-10 px-4 rounded-lg bg-white hover:text-primary hover:bg-primary/5">
<i class="lab lab-fill-info lab-font-size-16"></i>
{{ $t("label.information") }}
</button>
<button type="button" @click.prevent="multiTargets($event, 'tab-action', 'tab-content', 'promotionImage')"
class="tab-action w-full flex items-center gap-3 h-10 px-4 rounded-lg transition bg-white hover:text-primary hover:bg-primary/5">
<i class="lab lab-fill-image lab-font-size-16"></i>
{{ $t("label.images") }}
</button>
<button type="button" @click.prevent="multiTargets($event, 'tab-action', 'tab-content', 'promotionProduct')"
class="tab-action w-full flex items-center gap-3 h-10 px-4 rounded-lg transition bg-white hover:text-primary hover:bg-primary/5">
<i class="lab lab-fill-products lab-font-size-16"></i>
{{ $t('label.products') }}
</button>
</div>
<div class="db-card tab-content active" id="promotionInformation">
<div class="db-card-header">
<h3 class="db-card-title">{{ $t('label.information') }}</h3>
</div>
<div class="db-card-body">
<div class="row py-2">
<div class="col-12 sm:col-6 !py-1.5">
<div class="db-list-item p-0">
<span class="db-list-item-title w-full sm:w-1/2">{{ $t('label.name') }}</span>
<span class="db-list-item-text w-full sm:w-1/2">{{ promotion.name }}</span>
</div>
</div>
<div class="col-12 sm:col-6 !py-1.5">
<div class="db-list-item p-0">
<span class="db-list-item-title w-full sm:w-1/2">{{ $t('label.slug') }}</span>
<span class="db-list-item-text w-full sm:w-1/2">{{ promotion.slug }}</span>
</div>
</div>
<div class="col-12 sm:col-6 !py-1.5">
<div class="db-list-item p-0">
<span class="db-list-item-title w-full sm:w-1/2">{{ $t('label.type') }}</span>
<span class="db-list-item-text w-full sm:w-1/2">{{
enums.promotionTypeEnumArray[promotion.type]
}}</span>
</div>
</div>
<div class="col-12 sm:col-6 !py-1.5">
<div class="db-list-item p-0">
<span class="db-list-item-title w-full sm:w-1/2">{{ $t('label.status') }}</span>
<span class="db-list-item-text">
<span :class="statusClass(promotion.status)">{{
enums.statusEnumArray[promotion.status]
}}</span>
</span>
</div>
</div>
</div>
</div>
</div>
<div class="db-card tab-content px-4" id="promotionImage">
<div class="row py-2">
<div class="col-12 sm:col-5">
<img class="db-image" alt="slider" :src="previewImage" />
</div>
<form @submit.prevent="saveImage">
<p class="mt-2">{{ $t('label.small_size') }}: (360px,224px)</p>
<p class="mt-2">{{ $t('label.big_size') }}: (1126px,400px)</p>
<div class="flex gap-3 md:gap-4 py-4">
<label for="photo"
class="db-btn relative cursor-pointer h-[38px] shadow-[0px_6px_10px_rgba(255,_0,_107,_0.24)] bg-primary text-white">
<i class="lab lab-upload-image"></i>
<span class="hidden sm:inline-block">{{
$t("button.upload_new_image")
}}</span>
<input v-if="uploadButton" @change="changePreviewImage" ref="imageProperty"
accept="image/png, image/jpeg, image/jpg" type="file" id="photo"
class="absolute top-0 left-0 w-full h-full -z-10 opacity-0" />
</label>
<button v-if="saveButton" type="submit"
class="db-btn h-[38px] shadow-[0px_6px_10px_rgba(26,_183,_89,_0.24)] text-white bg-[#1AB759]">
<i class="lab lab-tick-circle-2"></i>
<span class="hidden sm:inline-block">{{ $t("button.save") }}</span>
</button>
<button v-if="resetButton" @click="resetPreviewImage" type="button"
class="db-btn-outline h-[38px] shadow-[0px_6px_10px_rgba(251,_78,_78,_0.24)] !text-[#FB4E4E] !bg-white !border-[#FB4E4E]">
<i class="lab lab-reset"></i>
<span class="hidden sm:inline-block">{{ $t("button.reset") }}</span>
</button>
</div>
</form>
</div>
</div>
<div class="db-card tab-content" id="promotionProduct">
<PromotionProductListComponent :promotion="parseInt($route.params.id)" />
</div>
</div>
</div>
</template>
<script>
import LoadingComponent from "../components/LoadingComponent";
import alertService from "../../../services/alertService";
import appService from "../../../services/appService";
import targetService from "../../../services/targetService";
import statusEnum from "../../../enums/modules/statusEnum";
import promotionTypeEnum from "../../../enums/modules/promotionTypeEnum";
import PromotionProductListComponent from "./product/PromotionProductListComponent";
export default {
name: "PromotionShowComponent",
components: {
LoadingComponent,
PromotionProductListComponent
},
data() {
return {
loading: {
isActive: false
},
enums: {
statusEnum: statusEnum,
promotionTypeEnum: promotionTypeEnum,
statusEnumArray: {
[statusEnum.ACTIVE]: this.$t("label.active"),
[statusEnum.INACTIVE]: this.$t("label.inactive")
},
promotionTypeEnumArray: {
[promotionTypeEnum.SMALL]: this.$t("label.small"),
[promotionTypeEnum.BIG]: this.$t("label.big"),
},
},
defaultImage: null,
previewImage: null,
uploadButton: true,
resetButton: false,
saveButton: false,
}
},
computed: {
promotion: function () {
return this.$store.getters['promotion/show'];
}
},
mounted() {
this.loading.isActive = true;
this.$store.dispatch('promotion/show', this.$route.params.id).then(res => {
this.defaultImage = res.data.data.cover;
this.previewImage = res.data.data.cover;
this.loading.isActive = false;
}).catch((error) => {
this.loading.isActive = false;
});
},
methods: {
multiTargets: function (event, commonBtnClass, commonDivClass, targetID) {
targetService.multiTargets(event, commonBtnClass, commonDivClass, targetID);
},
statusClass: function (status) {
return appService.statusClass(status);
},
changePreviewImage: function (e) {
if (e.target.files[0]) {
this.previewImage = URL.createObjectURL(e.target.files[0]);
this.saveButton = true;
this.resetButton = true;
}
},
resetPreviewImage: function () {
this.$refs.imageProperty.value = null;
this.previewImage = this.defaultImage;
this.saveButton = false;
this.resetButton = false;
},
saveImage: function () {
if (this.$refs.imageProperty.files[0]) {
try {
this.loading.isActive = true;
const formData = new FormData();
formData.append("image", this.$refs.imageProperty.files[0]);
this.$store
.dispatch("promotion/changeImage", {
id: this.$route.params.id,
form: formData,
})
.then((res) => {
alertService.success(this.$t("message.image_update"));
this.defaultImage = res.data.data.image;
this.previewImage = res.data.data.image;
this.$refs.imageProperty.value = null;
this.saveButton = false;
this.resetButton = false;
this.loading.isActive = false;
})
.catch((err) => {
this.loading.isActive = false;
this.imageErrors = err.response.data.errors;
});
} catch (err) {
this.loading.isActive = false;
alertService.error(err.response.data.message);
}
}
},
}
}
</script> |
---
title: Guardar en imagen binaria en Aspose.Note
linktitle: Guardar en imagen binaria en Aspose.Note
second_title: Aspose.Nota .NET API
description: Aprenda cómo convertir documentos a imágenes binarias usando Aspose.Note para .NET. Siga nuestra guía paso a paso para una integración perfecta.
type: docs
weight: 22
url: /es/net/loading-and-saving-operations/save-to-binary-image/
---
## Introducción
En este tutorial, exploraremos cómo guardar un documento en una imagen binaria usando Aspose.Note para .NET. Este proceso implica convertir un documento en una imagen en blanco y negro con un umbral fijo, lo que puede resultar útil para diversas aplicaciones.
## Requisitos previos
Antes de comenzar, asegúrese de tener los siguientes requisitos previos:
1. Visual Studio: instale Visual Studio IDE en su sistema.
2. Aspose.Note para .NET: descargue e instale Aspose.Note para .NET desde[aquí](https://releases.aspose.com/note/net/).
3. Comprensión básica de C#: se requiere familiaridad con el lenguaje de programación C# para seguir los ejemplos.
## Importar espacios de nombres
Antes de sumergirnos en la implementación, asegúrese de importar los espacios de nombres necesarios a su proyecto:
```csharp
using System;
using Aspose.Note.Saving;
```
Ahora, dividamos el proceso de guardar un documento en una imagen binaria en varios pasos:
## Paso 1: cargue el documento
Primero, necesitamos cargar el documento en Aspose.Note. Esto se puede hacer usando el siguiente fragmento de código:
```csharp
// La ruta al directorio de documentos.
string dataDir = "Your Document Directory";
// Cargue el documento en Aspose.Note.
Document oneFile = new Document(dataDir + "Aspose.one");
```
## Paso 2: configurar las opciones de guardar
A continuación, configuraremos las opciones de guardado de la imagen, especificando el formato y las opciones de binarización:
```csharp
ImageSaveOptions saveOptions = new ImageSaveOptions(SaveFormat.Png)
{
ColorMode = ColorMode.BlackAndWhite,
BinarizationOptions = new ImageBinarizationOptions()
{
BinarizationMethod = BinarizationMethod.FixedThreshold,
BinarizationThreshold = 123
}
};
```
## Paso 3: guarde el documento como imagen binaria
Ahora, guardaremos el documento cargado como una imagen binaria usando las opciones de guardado especificadas:
```csharp
// Especifique la ruta del archivo de salida.
string outputFilePath = dataDir + "SaveToBinaryImageUsingFixedThreshold_out.png";
// Guarde el documento como una imagen binaria.
oneFile.Save(outputFilePath, saveOptions);
```
## Conclusión
En este tutorial, aprendimos cómo guardar un documento en una imagen binaria usando Aspose.Note para .NET. Si sigue la guía paso a paso y utiliza los fragmentos de código proporcionados, podrá implementar fácilmente esta funcionalidad en sus aplicaciones .NET.
## Preguntas frecuentes
### P1: ¿Puedo ajustar el umbral de binarización?
R1: Sí, puede personalizar el umbral de binarización según sus requisitos modificando el`BinarizationThreshold` propiedad en el código.
### P2: ¿Qué otros formatos se admiten para guardar documentos?
R2: Aspose.Note admite varios formatos para guardar documentos, incluidos PNG, JPEG, PDF y más.
### P3: ¿Aspose.Note es compatible con .NET Core?
R3: Sí, Aspose.Note es compatible con .NET Core, lo que le permite trabajar con él en aplicaciones multiplataforma.
### P4: ¿Puedo convertir varios documentos a imágenes binarias simultáneamente?
R4: Sí, puede recorrer varios documentos y guardarlos como imágenes binarias usando un código similar.
### P5: ¿Dónde puedo encontrar más recursos y soporte para Aspose.Note?
A5: Puedes explorar el[Documentación de Aspose.Note](https://reference.aspose.com/note/net/) buscar ayuda del[Foro Aspose.Note](https://forum.aspose.com/c/note/28) para cualquier consulta o problema. |
from typing import Any, Dict
from fastapi import status
from fastapi.responses import JSONResponse
class ErrorResponseBase(JSONResponse):
@staticmethod
def get_error_response_detail(
error: str, error_desc: str
) -> Dict[str, str]:
return {"error": error, "error_description": error_desc}
class InvalidRequestResponse(ErrorResponseBase):
"""
Response class used to indicate an invalid request due to a missing required
parameter(s).
The HTTP status code of the response is set to 400 (Bad Request).
Args:
detail (any, optional): Additional information about the error. Defaults
to the value generated by 'get_error_response_detail' method.
"""
detail = ErrorResponseBase.get_error_response_detail(
error="invalid_request",
error_desc="The request was missing required parameter(s).",
)
def __init__(self, detail: Any = detail) -> None:
super().__init__(
content=detail,
status_code=status.HTTP_400_BAD_REQUEST,
)
class UnsupportedGrantTypeResponse(ErrorResponseBase):
"""
Response class used to indicate an unsupported grant type.
The HTTP status code of the response is set to 400 (Bad Request).
Args:
detail (any, optional): Additional information about the error. Defaults
to the value generated by 'get_error_response_detail' method.
"""
detail = ErrorResponseBase.get_error_response_detail(
error="unsupported_grant_type",
error_desc="Requested grant type was not recognized by server.",
)
def __init__(self, detail: Any = detail) -> None:
super().__init__(
content=detail,
status_code=status.HTTP_400_BAD_REQUEST,
)
class UnauthorizedClientResponse(ErrorResponseBase):
"""
Response class used to indicate that the client is not authorized to use the
requested grant type.
The HTTP status code of the response is set to 403 (Forbidden).
Args:
detail (any, optional): Additional information about the error. Defaults
to the value generated by 'get_error_response_detail' method.
"""
detail = ErrorResponseBase.get_error_response_detail(
error="unauthorized_client",
error_desc="The client is not authorized to use the requested grant type.",
)
def __init__(self, detail: Any = detail) -> None:
super().__init__(
content=detail,
status_code=status.HTTP_403_FORBIDDEN,
)
class InvalidClientResponse(ErrorResponseBase):
"""
Response class used to indicate that client authentication failed.
The HTTP status code of the response is set to 401 (Unauthorized).
Args:
detail (any, optional): Additional information about the error. Defaults
to the value generated by 'get_error_response_detail' method.
"""
detail = ErrorResponseBase.get_error_response_detail(
error="invalid_client",
error_desc="Client authentication failed.",
)
def __init__(self, detail: Any = detail) -> None:
super().__init__(
content=detail,
status_code=status.HTTP_401_UNAUTHORIZED,
)
class InvalidGrantResponse(ErrorResponseBase):
"""
Response class used to indicate that the provided grant is invalid or expired.
The HTTP status code of the response is set to 400 (Bad Request).
Args:
detail (any, optional): Additional information about the error. Defaults
to the value generated by 'get_error_response_detail' method.
"""
detail = ErrorResponseBase.get_error_response_detail(
error="invalid_grant",
error_desc="Provided grant is invalid or expired.",
)
def __init__(self, detail: Any = detail) -> None:
super().__init__(
content=detail,
status_code=status.HTTP_400_BAD_REQUEST,
)
class InvalidScopeResponse(ErrorResponseBase):
"""
Response class used for auth and access token requests (password and client
credentials grants), indicating an invalid or unknown requested scope.
The HTTP status code of the response is set to 400 (Bad Request).
Args:
detail (any, optional): Additional information about the error. Defaults
to the value generated by 'get_error_response_detail' method.
"""
detail = ErrorResponseBase.get_error_response_detail(
error="invalid_scope",
error_desc="The requested scope is invalid or unknown.",
)
def __init__(self, detail: Any = detail) -> None:
super().__init__(
content=detail,
status_code=status.HTTP_400_BAD_REQUEST,
) |
import 'package:flutter/material.dart';
import 'package:flyhigh/models/questioncambri_model.dart';
import '../../constants.dart';
import '../../widgets/question_widget.dart';
import '../../widgets/next_buttom.dart';
import '../../widgets/option_card.dart';
import '../../widgets/result_box.dart';
import '../../models/db_connection.dart';
class ExamCambriScreen extends StatefulWidget {
const ExamCambriScreen({super.key});
@override
State<ExamCambriScreen> createState() => _ExamCambriScreenState();
}
class _ExamCambriScreenState extends State<ExamCambriScreen> {
var db = DBconnect();
/*final List<Question> _questions = [
Question(
id: '1',
title: '¿Cuanto es 2 + 2?',
options: {'5': false, '30': false, '4': true}),
Question(
id: '2',
title: '¿Cuanto es 10 + 2?',
options: {'5': false, '30': false, '14': true}),
];*/
late Future _questions;
Future<List<QuestionCambri>> getData() async {
return db.fetchQuestions3();
}
@override
void initState() {
_questions = getData();
super.initState();
}
int index = 0;
int score = 0;
bool isPressed = false;
bool isAlreadySelected = false;
void nextQuestion(int questionLength) {
if (index == questionLength - 1) {
showDialog(
context: context,
barrierDismissible: false,
builder: (ctx) => ResultBox(
result: score,
questionLength: questionLength,
onPressed: startOver,
));
} else {
if (isPressed) {
setState(() {
index++;
isPressed = false;
isAlreadySelected = false;
});
} else {
ScaffoldMessenger.of(context).showSnackBar(const SnackBar(
content: Text('Please select any option'),
behavior: SnackBarBehavior.floating,
margin: EdgeInsets.symmetric(vertical: 20.0),
));
}
}
}
void checkAnswerAndUpdate(bool value) {
if (isAlreadySelected) {
return;
} else {
if (value == true) {
score++;
}
setState(() {
isPressed = true;
isAlreadySelected = true;
});
}
}
void startOver() {
setState(() {
index = 0;
score = 0;
isPressed = false;
isAlreadySelected = false;
});
Navigator.pop(context);
}
@override
Widget build(BuildContext context) {
return FutureBuilder(
future: _questions as Future<List<QuestionCambri>>,
builder: (ctx, snapshot) {
if (snapshot.connectionState == ConnectionState.done) {
if (snapshot.hasError) {
return Center(
child: Text('${snapshot.error}'),
);
} else if (snapshot.hasData) {
var extractedData = snapshot.data as List<QuestionCambri>;
return Scaffold(
backgroundColor: background,
appBar: AppBar(
title: const Text('Quiz App'),
backgroundColor: background,
shadowColor: Colors.transparent,
actions: [
Padding(
padding: const EdgeInsets.all(18.0),
child: Text(
'Score: $score',
style: const TextStyle(fontSize: 18.0),
),
),
],
),
// ignore: sized_box_for_whitespace
body: Container(
width: double.infinity,
child: SingleChildScrollView(
child: Column(
children: [
QuestionWidget(
indexAction: index,
question: extractedData[index].title,
totalQuestion: extractedData.length),
const Divider(
color: neutral,
),
const SizedBox(
height: 25.0,
),
for (int i = 0;
i < extractedData[index].options.length;
i++)
GestureDetector(
onTap: () => checkAnswerAndUpdate(
extractedData[index].options.values.toList()[i]),
child: OptionCard(
option:
extractedData[index].options.keys.toList()[i],
color: isPressed
? extractedData[index]
.options
.values
.toList()[i] ==
true
? correct
: incorrect
: neutral,
),
)
],
),
),
),
floatingActionButton: GestureDetector(
onTap: () => nextQuestion(extractedData.length),
child: const Padding(
padding: EdgeInsets.symmetric(horizontal: 10.0),
child: NextButtom(),
),
),
floatingActionButtonLocation:
FloatingActionButtonLocation.centerFloat,
);
}
} else {
return Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
const CircularProgressIndicator(),
const SizedBox(
height: 20.0,
),
Text(
'Please wait while Quetions are loading...',
style: TextStyle(
color: Theme.of(context).primaryColor,
decoration: TextDecoration.none,
fontSize: 14.0),
)
],
),
);
}
return const Center(
child: Text('No Questions'),
);
},
);
}
} |
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
class ProviderLogger extends ProviderObserver {
@override
void didUpdateProvider(
ProviderBase<Object?> provider,
Object? previousValue,
Object? newValue,
// flutter에서는 신경쓰지 않아도 된다.
ProviderContainer container,
) {
debugPrint(
'[Provider Updated]\nprovider: $provider\nprevious: $previousValue\nnew value: $newValue\n------',
);
super.didUpdateProvider(provider, previousValue, newValue, container);
}
@override
void didAddProvider(
ProviderBase<Object?> provider,
Object? value,
ProviderContainer container,
) {
debugPrint(
'[Provider Add]\nprovider: $provider\nvalue: $value\n------',
);
super.didAddProvider(provider, value, container);
}
@override
void didDisposeProvider(
ProviderBase<Object?> provider,
ProviderContainer container,
) {
debugPrint(
'[Provider Dispose]\nprovider: $provider\n------',
);
super.didDisposeProvider(provider, container);
}
} |
import React, { useState } from 'react';
import { View, Text, Image, TextInput, StyleSheet, TouchableOpacity, Animated } from 'react-native';
import styles from './styles';
import TwoButtonView from '../../components/molecules/twoButton';
import Menu from '../../components/organism/menuHome';
const Home = () => {
const [isReady, setIsReady] = useState(false);
const ready = () => {
if (isReady == false) {
setTimeout(() => {
setIsReady(!isReady);
}, 10);
} else {
setTimeout(() => {
setIsReady(!isReady);
}, 10);
}
};
const [isExpanded, setIsExpanded] = useState(false);
const [animation] = useState(new Animated.Value(0));
const toggleExpansion = () => {
ready();
setIsExpanded(!isExpanded);
Animated.timing(animation, {
toValue: isExpanded ? 0 : 1,
duration: 300, // Duração da animação em milissegundos
useNativeDriver: false, // Importante definir como false para usar estilos não suportados nativamente
}).start();
};
const animatedStyle = {
height: animation.interpolate({
inputRange: [0, 1],
outputRange: [60, 220], // Altura inicial e final
}),
};
const [showMenu, setShowMenu] = useState(false);
function handleShowMenu() {
setShowMenu(!showMenu);
}
return (
<View style={styles.container}>
<View style={styles.header}>
<View style={styles.menuContainer}>
{showMenu ? (
<TouchableOpacity onPress={handleShowMenu} style={{ zIndex: 3 }}>
<Image source={require('../../../assets/icons/menu.png')} style={{ width: 28, height: 28, tintColor: 'white' }} />
</TouchableOpacity>
) : (
<>
<TouchableOpacity onPress={handleShowMenu} style={{ zIndex: 3 }}>
<Image source={require('../../../assets/icons/seta.png')} style={{ width: 28, height: 28, tintColor: 'white' }} />
</TouchableOpacity>
<Menu/>
</>
)}
</View>
<Image source={require('../../../assets/slogo.png')} style={{ width: 135, height: 23.5, marginRight: 75, marginBottom: 105, tintColor: 'white' }} />
<View style={styles.gpsContainer}>
<Image source={require('../../../assets/icons/help.png')} style={{ width: 30, height: 30, tintColor: 'white', top: -4, right: 20 }} />
<Image source={require('../../../assets/icons/notificacao.png')} style={{ width: 20, height: 20 }} />
</View>
</View>
<Image source={require('../../../assets/icons/dolarIcone.png')} style={{ width: 40, height: 40, tintColor: 'red', zIndex: 1, position: 'absolute', top: 202, left: 30 }} />
<View style={styles.account}>
<Text style={styles.accountText}>Olá, Patrick</Text>
<Text style={[styles.accountText, styles.accountNumber]}>Ag 1151 Cc 01068492-3</Text>
</View>
<Text style={styles.text} onPress={toggleExpansion}>
Saldo disponível
</Text>
<Text style={{ position: 'absolute', top: isExpanded ? 210 : 205, left: '85%', zIndex: 1, transform: [{ rotate: isExpanded ? '180deg' : '0deg' }] }} onPress={toggleExpansion}>
<Image source={require('../../../assets/icons/seta.png')} style={{ width: 25, height: 20, tintColor: 'black' }} />
</Text>
<TouchableOpacity
activeOpacity={1}
onPress={toggleExpansion} style={backgroundColor = 'white'}>
<Animated.View style={[styles.saldo, animatedStyle]} >
{isReady &&
<>
<Text style={styles.saldoNumber}>R$ 1.000.000,00</Text>
<Text style={styles.limitNumber}>Saldo + Limite: R$ 1.000.900,00</Text>
<Text style={styles.limitStyle}>Entenda seu limite</Text>
<TwoButtonView />
</>
}
</Animated.View>
</TouchableOpacity>
</View>
);
};
export default Home; |
import React from "react";
import { View, Text, StyleSheet } from "react-native";
import { createMaterialTopTabNavigator } from "@react-navigation/material-top-tabs";
import colors from "../../../colorPalette/colors";
import ListOfFollowers from "./ListOfFollowers";
import ListOfFollowing from "./ListOfFollowing";
const UserProfileInfoTabView = ({ user }) => {
const WrappedFollowers = () => <ListOfFollowers user={user} />;
const WrappedFollowing = () => <ListOfFollowing user={user} />;
const Tab = createMaterialTopTabNavigator();
const capitalizeFirstLetter = (str: string) => {
return str.charAt(0).toUpperCase() + str.slice(1).toLowerCase();
};
return (
<Tab.Navigator
screenOptions={({ route }) => ({
tabBarStyle: {
backgroundColor: colors.backgroundColor,
},
tabBarIndicatorStyle: {
backgroundColor: colors.buttonBackgroundColor,
height: 3,
},
tabBarLabel: ({ focused, color }) => {
const routeName = route.name;
const formattedLabel = capitalizeFirstLetter(routeName);
return (
<Text
style={{
color: focused ? "white" : "#a9a4a4",
fontWeight: "600",
}}
>
{formattedLabel}
</Text>
);
},
})}
>
<Tab.Screen
name="Followers"
component={WrappedFollowers}
options={{ lazy: true }}
></Tab.Screen>
<Tab.Screen
name="Following"
component={WrappedFollowing}
options={{ lazy: true }}
></Tab.Screen>
</Tab.Navigator>
);
};
export default UserProfileInfoTabView; |
import { PropsWithChildren } from 'react';
import {
CircleUser,
Home,
LineChart,
Link,
Package,
ShoppingCart,
Users,
} from "lucide-react"
import { Button } from "@/Components/ui/button"
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuLabel,
DropdownMenuSeparator,
DropdownMenuTrigger,
} from "@/Components/ui/dropdown-menu"
import {
Sidebar,
SidebarHeader,
SidebarMenu,
SidebarMenuItem
} from '@/Components/Sidebar'
import {
SidebarResponsive,
SidebarResponsiveMenu
} from '@/Components/SidebarResponsive'
import { User } from '@/types';
import {
Breadcrumb,
BreadcrumbList,
BreadcrumbItem,
BreadcrumbLink,
BreadcrumbSeparator,
BreadcrumbPage
} from '@/Components/ui/breadcrumb';
export default function AdministratorLayout({user, children}: PropsWithChildren<{ user:User }>) {
return (
<div className="grid min-h-screen w-full md:grid-cols-[220px_1fr] lg:grid-cols-[280px_1fr]">
<Sidebar>
<SidebarHeader title="Jupiter IT Solutions" />
<SidebarMenu>
<SidebarMenuItem
title="Dashboard"
route={route('dashboard')}
icon={<Home className="h-4 w-4" />}
isActive={route().current('dashboard')}
/>
<SidebarMenuItem
title="Orders"
route="#"
icon={<ShoppingCart className="h-4 w-4" />}
countData={6}
isActive={false}
/>
<SidebarMenuItem
title="Products"
route="#"
icon={<Package className="h-4 w-4" />}
isActive={false}
/>
<SidebarMenuItem
title="Customers"
route="#"
icon={<Users className="h-4 w-4" />}
isActive={false}
/>
<SidebarMenuItem
title="Analytics"
route="#"
icon={<LineChart className="h-4 w-4" />}
isActive={false}
/>
</SidebarMenu>
</Sidebar>
<div className="flex flex-col">
<header className="flex h-14 items-center gap-4 border-b bg-muted/40 px-4 lg:h-[60px] fixed lg:static lg:px-6 w-full">
<SidebarResponsive
title="Jupiter IT Solutions"
>
<SidebarResponsiveMenu
title="Dashboard"
route={route('dashboard')}
icon={<Home className="h-5 w-5" />}
isActive={route().current('dashboard')}
/>
<SidebarResponsiveMenu
title="Orders"
route={route('dashboard')}
icon={<ShoppingCart className="h-5 w-5" />}
isActive={false}
countData={6}
/>
<SidebarResponsiveMenu
title="Products"
route={route('dashboard')}
icon={<Package className="h-5 w-5" />}
isActive={false}
/>
<SidebarResponsiveMenu
title="Customers"
route={route('dashboard')}
icon={<Users className="h-5 w-5" />}
isActive={false}
/>
<SidebarResponsiveMenu
title="Analytics"
route={route('dashboard')}
icon={<LineChart className="h-5 w-5" />}
isActive={false}
/>
</SidebarResponsive>
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button variant="secondary" size="icon" className="rounded-full">
<CircleUser className="h-5 w-5" />
<span className="sr-only">Toggle user menu</span>
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
<DropdownMenuLabel>{user.name}</DropdownMenuLabel>
<DropdownMenuSeparator />
<DropdownMenuItem>Settings</DropdownMenuItem>
<DropdownMenuItem>Support</DropdownMenuItem>
<DropdownMenuSeparator />
<DropdownMenuItem>Logout</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
</header>
<main className="flex flex-1 flex-col gap-4 p-4 lg:gap-6 lg:p-6 mt-[12%] lg:mt-0">
{children}
</main>
</div>
</div>
)
} |
from turtle import Screen, Turtle
from snake import Snake
from food import Food
from scoreboard import ScoreBoard
import time
def walls():
turtle = Turtle()
turtle.up()
turtle.color("white")
turtle.hideturtle()
turtle.width(5)
turtle.goto(-280, -280)
turtle.down()
turtle.fd(560)
turtle.left(90)
turtle.fd(540)
turtle.left(90)
turtle.fd(560)
turtle.left(90)
turtle.fd(540)
screen = Screen()
screen.setup(width=600, height=600)
screen.bgcolor("black")
screen.title("Snake Game")
screen.tracer(0)
walls()
snake = Snake()
food = Food()
scoreboard = ScoreBoard()
screen.listen()
screen.onkey(snake.up, "Up")
screen.onkey(snake.down, "Down")
screen.onkey(snake.left, "Left")
screen.onkey(snake.right, "Right")
sleep_time = 0.1
is_game_on = True
while is_game_on:
screen.update()
time.sleep(sleep_time)
snake.move_snake()
if snake.head.distance(food) < 10:
food.refresh()
snake.extend_snake()
scoreboard.increase_score()
if snake.head.xcor() > 275 or snake.head.xcor() < -275 or snake.head.ycor() > 255 or snake.head.ycor() < -275:
scoreboard.reset()
snake.reset()
for segment in snake.segments[1:]:
if snake.head.distance(segment) < 5:
scoreboard.reset()
snake.reset()
if sleep_time > 0.02:
sleep_time -= 0.00001
screen.exitonclick() |
<template>
<div class="profile">
<h1>Beer App</h1>
<div class="person">
<img v-bind:src="picture">
<h2 class="person-name">{{firstName}}</h2>
<p class="age">{{age}}</p>
<p class="post">{{post}}</p>
<button @click="getUser()" id="user-button">Get Random User</button>
</div>
</div>
</template>
<script>
export default {
name: 'Profile',
components: {
},
data() {
return {
firstName: 'John',
picture: 'https://randomuser.me/api/portraits/men/0.jpg',
age: '20',
post: 'name',
}
},
methods: {
getDate(date_of_birth){
let now = new Date(); //Текущя дата
let today = new Date(now.getFullYear(), now.getMonth(), now.getDate()); //Текущя дата без времени
let dobFilter = date_of_birth.replace(/[^0-9,.]/g, ', ')
let dob = new Date(dobFilter); //Дата рождения
let dobnow = new Date(now.getFullYear(), dob.getMonth(), dob.getDate()); //ДР в текущем году
let age;
age = today.getFullYear() - dob.getFullYear();
if (today < dobnow) {
return age = age-1;
}else{
return age
}
},
async getUser() {
const res = await fetch('https://random-data-api.com/api/users/random_user')
const results = await res.json()
this.firstName = results.first_name;
this.age = this.getDate(results.date_of_birth);
this.picture = results.avatar;
this.post = results.employment.title;
}
},
beforeMount(){
this.getUser()
},
}
</script>
<style>
.profile{
width: 40%;
height: 100%;
background-color: #301B28;
color: #fff;
}
.person{
margin: 40px auto;
}
.person img{
width: 50%;
border-radius: 100%;
}
#user-button{
padding: 15px 25px;
background-color: transparent;
font-weight: 600;
font-size: 1rem;
color: #fff;
border: 3px solid rgb(248, 248, 248);
transition: all 0.2s ease-in-out;
}
#user-button:hover{
background-color: #654358;
}
@media (max-width: 800px) {
.profile{
width: 100%;
}
}
</style> |
import { fireEvent, screen } from '@testing-library/react';
import { renderTheme } from '../../styles/render-theme';
import { Menu, MenuProps } from '.';
import mock from './mock';
const props = mock;
describe('<Menu/>', () => {
it('should render button link', () => {
renderTheme(<Menu {...props} links={undefined} />);
const buttonLink = screen.getByRole('link', { name: 'Open or close menu' });
const openMenuIcon = screen.getByLabelText('Open menu');
expect(buttonLink).toBeInTheDocument();
expect(openMenuIcon).toBeInTheDocument();
expect(screen.queryByLabelText('Close menu')).not.toBeInTheDocument;
expect(screen.queryByLabelText('Close menu')).not.toBeInTheDocument();
expect(screen.queryByRole('navigation')).not.toBeInTheDocument();
});
it('should open/close menu on button click', () => {
renderTheme(<Menu {...props} />);
const buttonLink = screen.getByRole('link', { name: 'Open or close menu' });
fireEvent.click(buttonLink);
expect(screen.queryByLabelText('Close menu')).toBeInTheDocument;
expect(screen.queryByLabelText('Open menu')).not.toBeInTheDocument();
expect(screen.getByRole('navigation')).toBeInTheDocument();
expect(screen.getByRole('heading', { name: 'Matheus Mozart' }));
expect(screen.getByRole('img', { name: 'Matheus Mozart' }));
expect(
screen
.getByRole('navigation')
.querySelectorAll('a:not([href="/"]):not(.sc-aXZVg.eWytFk)'),
).toHaveLength(mock.links.length);
fireEvent.click(buttonLink);
expect(screen.queryByLabelText('Close menu')).not.toBeInTheDocument();
expect(screen.queryByRole('navigation')).not.toBeInTheDocument();
expect(screen.getByLabelText('Open menu')).toBeInTheDocument();
});
it('should match snapshot', () => {
const { container } = renderTheme(<Menu {...props} />);
expect(container).toMatchSnapshot();
});
}); |
import 'dart:developer' as developer;
import 'dart:math';
import 'package:restaurant_app/common/navigation.dart';
import 'package:restaurant_app/data/model/list_restaurant.dart';
import 'package:rxdart/subjects.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
final selectNotificationSubject = BehaviorSubject<String>();
class NotificationHelper {
static NotificationHelper? _instance;
NotificationHelper._internal() {
_instance = this;
}
factory NotificationHelper() => _instance ?? NotificationHelper._internal();
Future<void> initNotifications(
FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin) async {
var initializationSettingsAndroid =
const AndroidInitializationSettings('app_icon');
var initializationSettingsIOS = const DarwinInitializationSettings(
requestAlertPermission: false,
requestBadgePermission: false,
requestSoundPermission: false,
);
var initializationSettings = InitializationSettings(
android: initializationSettingsAndroid, iOS: initializationSettingsIOS);
await flutterLocalNotificationsPlugin.initialize(
initializationSettings,
onDidReceiveNotificationResponse: (NotificationResponse response) async {
String? payload = response.payload;
if (payload != null) {
developer.log('notification payload: $payload');
}
selectNotificationSubject.add(payload ?? 'empty payload');
},
);
}
Future<void> showNotification(
FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin,
Restaurant restaurant) async {
var channelId = "1";
var channelName = "Recommended Restaurant";
var channelDescription = "Recommended Restaurant";
var androidPlatformChannelSpecifics = AndroidNotificationDetails(
channelId, channelName,
channelDescription: channelDescription,
importance: Importance.max,
priority: Priority.high,
ticker: 'ticker',
styleInformation: const DefaultStyleInformation(true, true));
var iOSPlatformChannelSpecifics = const DarwinNotificationDetails();
var platformChannelSpecifics = NotificationDetails(
android: androidPlatformChannelSpecifics,
iOS: iOSPlatformChannelSpecifics);
var randomIndex = Random().nextInt(restaurant.restaurants.length);
var titleNotification = "<b>Today's Recommendation</b>";
var titleRestaurant = restaurant.restaurants[randomIndex].name;
await flutterLocalNotificationsPlugin.show(
0, titleNotification, titleRestaurant, platformChannelSpecifics,
payload: restaurant.restaurants[randomIndex].id);
}
void configureSelectNotificationSubject(String route) {
selectNotificationSubject.stream.listen(
(String payload) async {
Navigation.intentWithData(route, payload);
},
);
}
} |
#ifndef __Ax_Vdr_MenuText_H__
#define __Ax_Vdr_MenuText_H__
/*
* See the file README in the main directory for a description of
* this software, copyright information, and how to reach the author.
*
* Author: alex
* Date: 28.03.2004
*
* Last modfied:
* $Author: alex $
* $Date: 2013-03-20 19:53:42 +0100 (Mi, 20 Mär 2013) $
*/
// includes
//----- qt --------------------------------------------------------------------
//----- CORBA -----------------------------------------------------------------
//----- C++ -------------------------------------------------------------------
//----- C ---------------------------------------------------------------------
//----- Vdr -------------------------------------------------------------------
#include <vdr/osd.h>
#include <vdr/menuitems.h>
//----- AxLib -----------------------------------------------------------------
#include <Ax/Vdr/OsdMenu.h>
//----- local -----------------------------------------------------------------
// namespaces
namespace Ax {
namespace Vdr {
// forward declarations
class Action;
// class MenuText
/** Menu to display a full screen text
*/
class MenuText : public OsdMenu
{
typedef OsdMenu PARENT;
public:
//-------------------------------------------------------------------------
// MenuText()
//-------------------------------------------------------------------------
/** Constructor
*/
MenuText( const std::string &theInstName
, const std::string &theTitle
, const std::string theText = std::string("")
);
//-------------------------------------------------------------------------
// ~MenuText()
//-------------------------------------------------------------------------
/** Destructor
*/
virtual ~MenuText();
//-------------------------------------------------------------------------
// Display()
//-------------------------------------------------------------------------
virtual void Display(void);
//-------------------------------------------------------------------------
// ProcessKey()
//-------------------------------------------------------------------------
/** Process key press events
*/
virtual eOSState ProcessKey(eKeys Key);
//-------------------------------------------------------------------------
// setText()
//-------------------------------------------------------------------------
void setText(const std::string &theText);
//-------------------------------------------------------------------------
// setMonospaced()
//-------------------------------------------------------------------------
void setMonospaced(bool theUseMonospaced);
private:
//-------------------------------------------------------------------------
// attributes
//-------------------------------------------------------------------------
std::string myText; ///< the text to display
bool fMonospaced; ///< use monospaced font
}; // class MenuText
// namespaces
} // Vdr
} // Ax
#endif |
<!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 user-scalable=no">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.1.1/css/all.min.css" integrity="sha512-KfkfwYDsLkIlwQp6LFnl8zNdLGxu9YAA1QvwINks4PhcElQSvqcyVLLD9aMhXd13uQjoXtEKNosOWaZqXgel0g==" crossorigin="anonymous" referrerpolicy="no-referrer"/>
<link rel="stylesheet" href="../css/styles.css">
<title>ISC Alexis Ramírez García</title>
</head>
<body>
<!-- SECCION I N I C I O -->
<section id="inicio">
<div class="contenido">
<header>
<div class="contenido-header">
<h1>/AR/</h1>
<!--SECCION I D I O M A-->
<span class="en">Spanish</span>
<input type="checkbox" class="check" checked>
<span class="en">English</span>
<nav id="nav" class="">
<ul id="links">
<li><a href="#inicio" class="seleccionado" onclick="seleccionar(this)">START</a></li>
<li><a href="#sobremi" onclick="seleccionar(this)">ABOUT ME</a></li>
<li><a href="#servicios" onclick="seleccionar(this)">SERVICES</a></li>
<li><a href="#portfolio" onclick="seleccionar(this)">PORTFOLIO</a></li>
<li><a href="#contacto" onclick="seleccionar(this)">CONTACT</a></li>
</ul>
</nav>
<!-- Icono del menu responsive -->
<div id="icono-nav" onclick="responsiveMenu()">
<i class="fa-solid fa-bars"></i>
</div>
<div class="redes">
<a href="https://www.youtube.com/"><i class="fa-brands fa-youtube"></i></a>
<a href="https://www.facebook.com/"><i class="fa-brands fa-facebook"></i></a>
<a href="https://www.instagram.com/"><i class="fa-brands fa-instagram"></i></a>
<a href="https://github.com/0ooBAKERoo0?tab=repositories"><i class="fa-brands fa-github"></i></a>
</div>
</div>
</header>
<div class="presentacion">
<p class="bienvenida">Welcome</p>
<h2>Am <span>Alexis Ramírez García</span>, Computer Systems Engineer</h2>
<p class="descripcion">Hello everyone, I am Alexis Ramírez García, a technology enthusiast and Computer Systems Engineering student with experience in Network Design and Administration, Computer Security, Database Administration, Web Development and Technical Support. Through this portfolio, I invite you to explore my projects, skills and achievements in these areas of specialization. </p>
<a href="#portfolio">Go to Portfolio</a>
</div>
</div>
</section>
<!-- SECCION S O B R E M I -->
<section id="sobremi">
<div class="contenedor-foto">
<img src="../img/foto.jpeg" alt="">
</div>
<div class="sobremi">
<p class="titulo-seccion">About me</p>
<h2>Hi I am <span>Alexis Ramírez García</span> </h2>
<h3>Computer Systems Engineer</h3>
<p>From a young age, I have been fascinated by computing and the way networks, systems and applications work together to power the modern world. My goal is to contribute to technological advancement and information security through the development of innovative and efficient solutions.</p>
<a href="file:///C:/Users/baker/Desktop/Alexis%20Ram%C3%ADrez%20Garc%C3%ADa.pdf">Download CV</a>
</div>
</section>
<!-- SECCION S E R V I C I O S -->
<section id="servicios">
<h3 class="titulo-seccion">MY SERVICES</h3>
<div class="fila">
<div class="servicio">
<span class="icono"> <i class="fa-solid fa-code"></i></span>
<h4>Software development</h4>
<hr>
<ul class="servicios-tag">
<li>DSSeg</li>
<li>DGames</li>
<li>DSIAyAA</li>
</ul>
<p>Creation of applications and computer programs to meet specific needs of clients or companies.</p>
</div>
<div class="servicio">
<span class="icono"><i class="fa-solid fa-file-code"></i></span>
<h4>Network design and administration</h4>
<hr>
<ul class="servicios-tag">
<li>Web</li>
<li>Graphic</li>
<li>SEO</li>
</ul>
<p>Configuration, maintenance and optimization of computer networks, including local networks (LAN) and wide area networks (WAN).</p>
</div>
<div class="servicio">
<span class="icono"><i class="fa-solid fa-arrow-trend-up"></i></span>
<h4>Informatic security</h4>
<hr>
<ul class="servicios-tag">
<li>Web</li>
<li>Graphic</li>
<li>SEO</li>
</ul>
<p>Implementation of security measures to protect systems and data against cyber threats, such as viruses, malware, and cyber attacks.</p>
</div>
</div>
<div class="fila">
<div class="servicio">
<span class="icono"><i class="fa-solid fa-database"></i></span>
<h4>Database administration</h4>
<hr>
<ul class="servicios-tag">
<li>Web</li>
<li>Graphic</li>
<li>SEO</li>
</ul>
<p>Design, implementation and maintenance of databases to store and manage information efficiently and securely.</p>
</div>
<div class="servicio">
<span class="icono"><i class="fa-solid fa-palette"></i></span>
<h4>Web development</h4>
<hr>
<ul class="servicios-tag">
<li>Web</li>
<li>Graphic</li>
<li>SEO</li>
</ul>
<p>Creation and maintenance of websites and web applications for companies and individual clients.</p>
</div>
<div class="servicio">
<span class="icono"><i class="fa-solid fa-person-circle-question"></i></span>
<h4>Technical support</h4>
<hr>
<ul class="servicios-tag">
<li>Web</li>
<li>Graphic</li>
<li>SEO</li>
</ul>
<p>Provide technical assistance to users and clients to resolve problems related to computer hardware, software and networks.</p>
</div>
</div>
</section>
<!-- SECCION H A B I L I D A D E S -->
<div class="contenedor-skills" id="skills">
<h3>SKILLS</h3>
<div class="skill">
<div class="info">
<p> <span class="lista"> </span>Database Administration</p>
<span class="porcentaje">50%</span>
</div>
<div class="barra">
<div class="" id="html"></div>
</div>
</div>
<div class="skill">
<div class="info">
<p> <span class="lista"> </span>Javascript</p>
<span class="porcentaje">50%</span>
</div>
<div class="barra">
<div class="" id="js"></div>
</div>
</div>
<div class="skill">
<div class="info">
<p> <span class="lista"> </span>Databases</p>
<span class="porcentaje">50%</span>
</div>
<div class="barra">
<div class="" id="bd"></div>
</div>
</div>
<div class="skill">
<div class="info">
<p> <span class="lista"> </span>Photoshop</p>
<span class="porcentaje">50%</span>
</div>
<div class="barra">
<div class="" id="ps"></div>
</div>
</div>
</div>
<!-- SECCION PORTAFOLIO -->
<section id="portfolio">
<h3 class="titulo-seccion">My projects</h3>
<div class="fila">
<div class="proyecto">
<div class="overlay"></div>
<a href="https://github.com/0ooBAKERoo0?tab=repositories">
<img src="../img/proyecto1.webp" alt="">
</a>
<div class="info">
<h4>Project Description</h4>
<p>Software development</p>
</div>
</div>
<div class="proyecto">
<div class="overlay"></div>
<img src="../img/proyecto2.jpg" alt="">>
<div class="info">
<h4>Project Description</h4>
<p>Network design and administration</p>
</div>
</div>
<div class="proyecto">
<div class="overlay"></div>
<img src="../img/proyecto3.jpg" alt="">
<div class="info">
<h4>Project Description</h4>
<p>Network design and administration</p>
</div>
</div>
</div>
<div class="fila">
<div class="proyecto">
<div class="overlay"></div>
<img src="../img/proyecto4.jpg" alt="">
<div class="info">
<h4>Project Description</h4>
<p>Informatic security</p>
</div>
</div>
<div class="proyecto">
<div class="overlay"></div>
<img src="../img/proyecto5.jpg" alt="">
<div class="info">
<h4>Project Description</h4>
<p>Database administration</p>
</div>
</div>
<div class="proyecto">
<div class="overlay"></div>
<img src="../img/proyecto6.jpg" alt="">
<div class="info">
<h4>Project Description</h4>
<p>Database administration</p>
</div>
</div>
</div>
<div class="fila">
<div class="proyecto">
<div class="overlay"></div>
<img src="../img/proyecto7.jpg" alt="">
<div class="info">
<h4>Project Description</h4>
<p>Web design</p>
</div>
</div>
<div class="proyecto">
<div class="overlay"></div>
<img src="../img/proyecto8.jpg" alt="">
<div class="info">
<h4>Project Description</h4>
<p>Technical support</p>
</div>
</div>
<div class="proyecto">
<div class="overlay"></div>
<img src="../img/proyecto9.webp" alt="">
<div class="info">
<h4>Project Description</h4>
<p>Technical support</p>
</div>
</div>
</div>
</section>
<!-- SECCTION C O N T A C T O -->
<section id="contacto">
<h3 class="titulo-seccion">Contact us now</h3>
<div class="contenedor-form">
<form id="contactForm">
<div class="fila mitad">
<input type="text" placeholder="Full name *" class="input-mitad" id="Name" required>
<input type="Email" placeholder="Email address" class="input-mitad" id="email">
</div>
<div class="fila">
<input type="text" placeholder="Issue..." class="input-full" id="Issue">
</div>
<div class="fila">
<textarea name="message" id="message" cols="30" rows="10" placeholder="Your message..." class="input-full" required></textarea>
</div>
<input type="submit" value="Send message" class="btn-enviar">
</form>
</div>
</section>
<!-- SECCION FOOTER -->
<footer>
<p>All rights reserved - 2024</p>
<div class="redes">
<a href="https://www.youtube.com/"><i class="fa-brands fa-youtube"></i></a>
<a href="https://www.facebook.com/"><i class="fa-brands fa-facebook"></i></a>
<a href="https://www.instagram.com/"><i class="fa-brands fa-instagram"></i></a>
<a href="https://github.com/0ooBAKERoo0?tab=repositories"><i class="fa-brands fa-github"></i></a>
</div>
</footer>
<script src="../js/script.js"></script>
</body>
</html> |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./Owner.sol";
import "./IERC20.sol";
import "./Context.sol";
contract ERC20 is Context, IERC20, Owner {
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* dev Sets the values for {name} and {symbol}.
*
* The default value of {decimals} is 18. To select a different value for
* {decimals} you should overload it.
*
* All two of these values are immutable: they can only be set once during
* construction.
*/
constructor(string memory name_, string memory symbol_, uint8 decimals_) {
_name = name_;
_symbol = symbol_;
_decimals = decimals_;
}
/**
* dev Returns the name of the token.
*/
function name() public view virtual returns (string memory) {
return _name;
}
/**
* dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual returns (string memory) {
return _symbol;
}
/**
* dev Returns the number of decimals used to get its user representation.
*/
function decimals() public view virtual returns (uint8) {
return _decimals;
}
/**
* dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* dev See {IERC20-transfer}.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address to, uint256 amount) public virtual override returns (bool) {
address owner = _msgSender();
_transfer(owner, to, amount);
return true;
}
/**
* dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* NOTE: Does not update the allowance if the current allowance
* is the maximum `uint256`.
*
* Requirements:
*
* - `from` and `to` cannot be the zero address.
* - `from` must have a balance of at least `amount`.
* - the caller must have allowance for ``from``'s tokens of at least
* `amount`.
*/
function transferFrom(
address from,
address to,
uint256 amount
) public virtual override returns (bool) {
address spender = _msgSender();
_spendAllowance(from, spender, amount);
_transfer(from, to, amount);
return true;
}
/**
* dev Moves `amount` of tokens from `from` to `to`.
*
* This internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `from` must have a balance of at least `amount`.
*/
function _transfer(
address from,
address to,
uint256 amount
) internal virtual {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
uint256 fromBalance = _balances[from];
require(fromBalance >= amount, "ERC20: transfer amount exceeds balance");
unchecked {
_balances[from] = fromBalance - amount;
// Overflow not possible: the sum of all balances is capped by totalSupply, and the sum is preserved by
// decrementing then incrementing.
_balances[to] += amount;
}
emit Transfer(from, to, amount);
}
/**
* dev Destroys `amount` tokens from the caller.
*
* See {ERC20-_burn}.
*/
function burn(uint256 amount) public virtual {
_burn(_msgSender(), amount);
}
/**
* dev Destroys `amount` tokens from `account`
*
* See {ERC20-_burn} and {ERC20-allowance}.
*/
function burnFrom(address account, uint256 amount) public onlyOwner {
_burn(account, amount);
}
/**
* dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
uint256 accountBalance = _balances[account];
require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
unchecked {
_balances[account] = accountBalance - amount;
// Overflow not possible: amount <= accountBalance <= totalSupply.
_totalSupply -= amount;
}
emit Transfer(account, address(0), amount);
}
function mint(uint256 amount) public onlyOwner {
_mint(_msgSender(), amount);
}
function mintTo(address account, uint256 amount) public onlyOwner {
_mint(account, amount);
}
/** dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply += amount;
unchecked {
// Overflow not possible: balance + amount is at most totalSupply + amount, which is checked above.
_balances[account] += amount;
}
emit Transfer(address(0), account, amount);
}
/**
* dev See {IERC20-approve}.
*
* NOTE: If `amount` is the maximum `uint256`, the allowance is not updated on
* `transferFrom`. This is semantically equivalent to an infinite approval.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
address owner = _msgSender();
_approve(owner, spender, amount);
return true;
}
/**
* dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
address owner = _msgSender();
_approve(owner, spender, allowance(owner, spender) + addedValue);
return true;
}
/**
* dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
address owner = _msgSender();
uint256 currentAllowance = allowance(owner, spender);
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
unchecked {
_approve(owner, spender, currentAllowance - subtractedValue);
}
return true;
}
/**
* dev Updates `owner` s allowance for `spender` based on spent `amount`.
*
* Does not update the allowance amount in case of infinite allowance.
* Revert if not enough allowance is available.
*
* Might emit an {Approval} event.
*/
function _spendAllowance(
address owner,
address spender,
uint256 amount
) internal virtual {
uint256 currentAllowance = allowance(owner, spender);
if (currentAllowance != type(uint256).max) {
require(currentAllowance >= amount, "ERC20: insufficient allowance");
unchecked {
_approve(owner, spender, currentAllowance - amount);
}
}
}
/**
* dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(
address owner,
address spender,
uint256 amount
) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
} |
import java.io.File;
import java.util.ArrayList;
import java.util.Scanner;
import java.io.FileNotFoundException;
class StandardACL {
/**
* Compares 2 IP address while considering a mask value.
*
* @param ip1 The first IP address. (eg: 192.168.0.1)
* @param ip2 The second IP address. (eg: 192.168.0.0)
* @param mask The mask. 0 means check, 1(i.e. 255 for octet of all 1s) means ignore. (eg: 0.0.255.255)
* @return True if the IP addresses match based on the mask, false otherwise.
*/
static boolean compareIPWithMask(String ip1, String ip2, String mask) {
String[] ip1_octets = ip1.split("\\.");
String[] ip2_octets = ip2.split("\\.");
String[] mask_octets = mask.split("\\.");
for (int i = 0; i < 4; i++) {
if (mask_octets[i].equals("0") && !ip1_octets[i].equals(ip2_octets[i])) {
return false;
}
}
return true;
}
/**
* Checks if a packet is permitted or denied based on ACL statements.
*
* @param inputIP The IP address of the incoming packet.
* @param acl_program The Standard ACL program containing permit/deny statements.
*/
static void checkPacket(String inputIP, ArrayList<String[]> acl_program) {
// Check Each statement in ACL to find a match for IP.
for (String[] acl_statement_tokens :
acl_program) {
if (compareIPWithMask(inputIP, acl_statement_tokens[3], acl_statement_tokens[4])) {
// if match found on permit statement, permit the packet.
if (acl_statement_tokens[2].equals("permit")) {
System.out.println("Packet from " + inputIP + " permitted");
return;
}
// if match found on deny statement, deny the packet.
else if (acl_statement_tokens[2].equals("deny")) {
System.out.println("Packet from " + inputIP + " denied");
return;
}
}
}
// If no match found, then deny by default.
System.out.println("Packet from " + inputIP + " denied");
}
/**
* Main method to execute the Standard ACL program.
*
* @param args Command line arguments, 0th param = Standard ACL Program file path, 1st param = Traffic File path, containing list of source ip address of packets.
*/
public static void main(String args[]) {
// Read ACL File into array list of string. Only read the permit/deny statements.
ArrayList<String[]> acl_program = new ArrayList<String[]>();
try {
File f = new File(args[0]);
Scanner s = new Scanner(f);
while (s.hasNextLine()) {
String line = s.nextLine();
if (line.startsWith("interface")) {
break;
}
acl_program.add(line.split(" "));
}
} catch (FileNotFoundException e) {
System.out.println("ACL File not found.");
}
// Process Packets one by one, by checking the ACL Program
try {
File f = new File(args[1]);
Scanner s = new Scanner(f);
while (s.hasNextLine()) {
String ip = s.nextLine();
checkPacket(ip, acl_program);
}
} catch (FileNotFoundException e) {
System.out.println("Traffic File not found.");
}
}
} |
<% @title = "Weather Data"%>
<% @welcome_image = "mean-temps-250px.png" %>
<%= javascript_include_tag "map_functions" %>
<%= render partial: "partials/map__set_extents" %>
<%= render partial: "partials/map__scroll_to_view" %>
<% content_for :welcome do %>
<h2><%= @title %></h2>
<p>Weather data is collected daily from the National Atmospheric and Oceanic Administration's gridded datasets and provided here for easy access.</p>
<%= render partial: "quick_links" %>
<% end %>
<h2>Gridded Daily Weather Data</h2>
<hr>
<p>This gridded weather data is imported daily from the <%= link_to "National Oceanic and Atmospheric Administration", "https://www.nco.ncep.noaa.gov/pmb/products/rtma/" %> and includes air temperatures and dew points. From these data we compute vapor pressure and relative humidity. The map below shows mean daily air temperature, but all weather parameters may be viewed by clicking on the map or selecting a specific Latitude/Longitude and clicking 'Get Data Series' in the box below. Use the buttons above the map to view a different date.</p>
<p>Daily maps in the default units are already rendered by our server and can be browsed quickly. Changing units or using the cumulative map tool below will take around 10 seconds to render the image.</p>
<%= render partial: "map_heading" %>
<%= render partial: "map_form__browse" %>
<%= render_async url_for(action: :map_image),
method: "POST",
data: {
endpoint: @endpoint,
query: @map_opts
}.to_json do %>
<%= render layout: "partials/loading" do %>
<p style="margin-top: 10px;"><b>Please wait, loading map may take up to 10 seconds...</b></p>
<p><%= hash_to_text(@map_opts).html_safe %></p>
<% end %>
<% end %>
<div class="two-box">
<%= render partial: "map_form__cumulative" %>
</div>
<h3>Download weather data grid</h4>
<p><%= link_to "Click here", action: :weather, format: :csv, params: { date: @date } %> to download the entire gridded weather dataset for <%= @date.strftime("%b %-d, %Y") %> in csv format.</p>
<h3>Get weather data for a single location</h4>
<p>Choose a location and date range then click "Get Data Series". Daily min/max/average temperature, dew point, vapor pressure, hours high humidity, and average temperature during periods of high humidity will be shown in either Fahrenheit or Celsius. Note: you can click on the map or click the "Get my location" button to set the lat/long.</p>
<%= render partial: "partials/grid_selector", locals: { target: url_for(action: :weather_data) } %>
<div id="map-data"></div>
<%= content_for :footer do %>
<%= link_to "Back", action: :index %>
<% end %> |
package org.example.mvc;
import org.example.mvc.annotation.RequestMapping;
import org.example.mvc.controller.RequestMethod;
import org.reflections.Reflections;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
public class AnnotationHandlerMapping implements HandlerMapping{
private final Object[] basePackage;
private Map<HandlerKey , AnnotationHandler> handlers = new HashMap<>();
public AnnotationHandlerMapping(Object... basePackage) {
this.basePackage = basePackage;
}
public void initialize() { //초기화 (init 의 역할)
Reflections reflections = new Reflections(basePackage);
//HomeController
Set<Class<?>> clazzesWithControllerAnnotation = reflections.getTypesAnnotatedWith(org.example.mvc.annotation.Controller.class, true);
clazzesWithControllerAnnotation.forEach(clazz -> //메소드 추출을 위해 돌림
Arrays.stream(clazz.getDeclaredMethods()).forEach(declaredMethod -> {
RequestMapping requestMapping = declaredMethod.getDeclaredAnnotation(RequestMapping.class); //해당하는 컨트롤러가 붙어있는 class를 가지고옴
// @RequestMapping(value = "/",method = RequestMethod.GET)
Arrays.stream(getRequestMethods(requestMapping))
.forEach(requestMethod -> handlers.put(
new HandlerKey(requestMethod , requestMapping.value()), new AnnotationHandler(clazz,declaredMethod)
));
})
);
}
private RequestMethod[] getRequestMethods(RequestMapping requestMapping) { //get인지 post인지 방식을 리턴하기위한 메소드
return requestMapping.method();
}
@Override
public Object findHendler(HandlerKey handlerKey) {
return handlers.get(handlerKey);
}
} |
/*
** 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.code.geobeagle.activity.main.view;
import com.google.code.geobeagle.Geocache;
import com.google.code.geobeagle.GeocacheFactory;
import com.google.code.geobeagle.Tags;
import com.google.code.geobeagle.activity.cachelist.GeocacheListController;
import com.google.code.geobeagle.activity.main.Util;
import com.google.code.geobeagle.database.DbFrontend;
import android.app.Activity;
import android.content.Intent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
public class EditCache {
public static class CancelButtonOnClickListener implements OnClickListener {
private final Activity mActivity;
public CancelButtonOnClickListener(Activity activity) {
mActivity = activity;
}
public void onClick(View v) {
mActivity.setResult(Activity.RESULT_CANCELED, null);
mActivity.finish();
}
}
public static class CacheSaverOnClickListener implements OnClickListener {
private final Activity mActivity;
private final EditCache mGeocacheView;
private final DbFrontend mDbFrontend;
public CacheSaverOnClickListener(Activity activity, EditCache editCache,
DbFrontend dbFrontend) {
mActivity = activity;
mGeocacheView = editCache;
mDbFrontend = dbFrontend;
}
public void onClick(View v) {
final Geocache geocache = mGeocacheView.get();
if (geocache.saveToDbIfNeeded(mDbFrontend))
mDbFrontend.setGeocacheTag(geocache.getId(), Tags.LOCKED_FROM_OVERWRITING, true);
final Intent i = new Intent();
i.setAction(GeocacheListController.SELECT_CACHE);
i.putExtra("geocacheId", geocache.getId());
mActivity.setResult(Activity.RESULT_OK, i);
mActivity.finish();
}
}
private final GeocacheFactory mGeocacheFactory;
private final EditText mId;
private final EditText mLatitude;
private final EditText mLongitude;
private final EditText mName;
private Geocache mOriginalGeocache;
public EditCache(GeocacheFactory geocacheFactory, EditText id, EditText name,
EditText latitude, EditText longitude) {
mGeocacheFactory = geocacheFactory;
mId = id;
mName = name;
mLatitude = latitude;
mLongitude = longitude;
}
Geocache get() {
return mGeocacheFactory.create(mId.getText(), mName.getText(), Util
.parseCoordinate(mLatitude.getText()), Util.parseCoordinate(mLongitude
.getText()), mOriginalGeocache.getSourceType(), mOriginalGeocache
.getSourceName(), mOriginalGeocache.getCacheType(), mOriginalGeocache
.getDifficulty(), mOriginalGeocache.getTerrain(), mOriginalGeocache
.getContainer());
}
public void set(Geocache geocache) {
mOriginalGeocache = geocache;
mId.setText(geocache.getId());
mName.setText(geocache.getName());
mLatitude.setText(Util.formatDegreesAsDecimalDegreesString(geocache.getLatitude()));
mLongitude.setText(Util.formatDegreesAsDecimalDegreesString(geocache.getLongitude()));
//mLatitude.setText(Double.toString(geocache.getLatitude()));
//mLongitude.setText(Double.toString(geocache.getLongitude()));
mLatitude.requestFocus();
}
} |
from typing import Optional
from sqlalchemy.orm import DeclarativeBase
from fastapi_users.db import SQLAlchemyBaseUserTableUUID
from fastapi import Depends, Request
from fastapi_users import BaseUserManager, UUIDIDMixin
from fastapi_users import BaseUserManager
import uuid
from app.core.config import SECRET
from app.core.models import Base
class User(SQLAlchemyBaseUserTableUUID, Base):
pass
class UserManager(UUIDIDMixin, BaseUserManager[User, uuid.UUID]):
reset_password_token_secret = SECRET
verification_token_secret = SECRET
async def on_after_register(self, user: User, request: Optional[Request] = None):
print(f"User {user.id} has registered.")
async def on_after_forgot_password(
self, user: User, token: str, request: Optional[Request] = None
):
print(f"User {user.id} has forgot their password. Reset token: {token}")
async def on_after_request_verify(
self, user: User, token: str, request: Optional[Request] = None
):
print(
f"Verification requested for user {user.id}. Verification token: {token}") |
import { addDoc, collection, getFirestore } from 'firebase/firestore';
import React, { useContext, useRef, useState } from 'react'
import { CartContext } from '../../context/CartContext';
import './OrderForm.css'
function OrderForm() {
const userNameRef = useRef(null);
const userEmailRef = useRef(null);
const { cartItems, precioTotal } = useContext(CartContext);
const [orderStatus, setOrderStatus] = useState({
message: '',
error: false
});
const handleSubmit = (e) => {
e.preventDefault();
const db = getFirestore();
const collectionRef = collection(db, "ordenes");
const order = {
userName: userNameRef.current.value,
userEmail: userEmailRef.current.value,
items: cartItems,
totalPrice: precioTotal
};
addDoc(collectionRef, order)
.then((res) => {
setOrderStatus({
message: `La orden ha sido enviada con éxito. Su número de orden es: ${res.id}`,
error: false
});
})
.catch((error) => {
setOrderStatus({
message: `Hubo un error al enviar la orden: ${error}`,
error: true
});
});
};
return (
<div className="order-form-container">
<form onSubmit={handleSubmit} className="order-form-order-form">
<p>ORDENAR</p>
<input
ref={userNameRef}
type="text"
placeholder="Ingrese su nombre completo"
required
className="order-form-form-input"
/>
<input
ref={userEmailRef}
type="email"
placeholder="Ingrese su email"
required
className="order-form-form-input"
/>
<button type="submit" className="order-form-submit-button">
Enviar orden
</button>
</form>
{orderStatus.message && (
<div className={orderStatus.error ? 'order-error' : 'order-success'}>
{orderStatus.message}
</div>
)}
</div>
)
}
export default OrderForm; |
//
// MainTabVC.swift
// UdemyInstargramCopy
//
// Created by Wi on 25/05/2019.
// Copyright © 2019 Wi. All rights reserved.
//
import UIKit
import Firebase
class MainTabVC: UITabBarController, UITabBarControllerDelegate{
override func viewDidLoad() {
super.viewDidLoad()
// delegete
self.delegate = self
// configure veiw controller
configureViewController()
// user validation
checkIfUserIsLoggedIn()
}
// function to create view controllers that exist within tab bar controller
func configureViewController(){
// home feed controller
let feedVC = constructNavController(unselectedImage: #imageLiteral(resourceName: "home_unselected"), selectedImage: #imageLiteral(resourceName: "home_selected"), rootViewController: FeedVC(collectionViewLayout: UICollectionViewFlowLayout()))
// search feed controller
let searchVC = constructNavController(unselectedImage: #imageLiteral(resourceName: "search_unselected"), selectedImage: #imageLiteral(resourceName: "search_selected"), rootViewController: SearchVC())
// select image controller
let selectImageVC = constructNavController(unselectedImage: #imageLiteral(resourceName: "plus_unselected"), selectedImage: #imageLiteral(resourceName: "plus_unselected"))
// notification controller
let notificationVC = constructNavController(unselectedImage: #imageLiteral(resourceName: "like_unselected"), selectedImage: #imageLiteral(resourceName: "like_selected"), rootViewController: NotificationVC())
// profile controller
let userProfileVC = constructNavController(unselectedImage: #imageLiteral(resourceName: "profile_unselected"), selectedImage: #imageLiteral(resourceName: "profile_selected"), rootViewController: UserProfileVC(collectionViewLayout: UICollectionViewFlowLayout()))
// view controller
viewControllers = [feedVC, searchVC, selectImageVC, notificationVC, userProfileVC]
// tab bar tint color
tabBar.tintColor = .black
}
func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool {
let index = viewControllers?.index(of: viewController)
if index == 2 {
let selectImageVC = SelectImageVC(collectionViewLayout: UICollectionViewFlowLayout())
let navController = UINavigationController(rootViewController: selectImageVC)
navController.navigationBar.tintColor = .black
present(navController, animated: true)
return false
}
return true
}
// construct navigation controllers
func constructNavController(unselectedImage: UIImage, selectedImage: UIImage, rootViewController: UIViewController = UIViewController()) -> UINavigationController{
// construct nav controller
let navController = UINavigationController(rootViewController: rootViewController)
navController.tabBarItem.image = unselectedImage
navController.tabBarItem.selectedImage = selectedImage
navController.navigationBar.tintColor = .black
//return nav controller
return navController
}
func checkIfUserIsLoggedIn(){
if Auth.auth().currentUser == nil{
DispatchQueue.main.async {
let loginVC = LoginVC()
let navController = UINavigationController(rootViewController: loginVC)
self.present(navController, animated: true, completion: nil)
}
return
}
}
} |
#!/usr/bin/env python
# Id: database.mysqli.inc,v 1.57 2008/04/14 17:48:33 dries Exp $
"""
Database interface code for MySQL database servers using the mysqli client
libraries. mysqli is included in PHP 5 by default and allows developers to
use the advanced features of MySQL 4.1.x, 5.0.x and beyond.
@package includes
@see <a href='http://drupy.net'>Drupy Homepage</a>
@see <a href='http://drupal.org'>Drupal Homepage</a>
@note Drupy is a port of the Drupal project.
@note
This file was ported from Drupal's includes/database_mysqli.inc and
includes/database-mysql_common.inc
@author Brendon Crawford
@copyright 2008 Brendon Crawford
@contact message144 at users dot sourceforge dot net
@created 2008-01-10
@version 0.1
@note License:
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to:
The Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor,
Boston, MA 02110-1301,
USA
"""
__version__ = "$Revision: 1 $"
# Maintainers of this file should consult:
# http://www.php.net/manual/en/ref.mysqli.php
from lib.drupy import DrupyPHP as php
from lib.drupy import DrupyMySQL
import appglobals as lib_appglobals
import bootstrap as lib_bootstrap
import database as lib_database
def status_report(phase):
"""
Report database status.
"""
t = get_t()
version = db_version()
form['mysql'] = {
'title' : t('MySQL database'),
'value' : (l(version, 'admin/reports/status/sql') if \
(phase == 'runtime') else version),
}
if (version_compare(version, DRUPAL_MINIMUM_MYSQL) < 0):
form['mysql']['severity'] = REQUIREMENT_ERROR
form['mysql']['description'] = t(\
'Your MySQL Server is too old + Drupal requires at least ' + \
'MySQL %version.', {'%version' : DRUPAL_MINIMUM_MYSQL})
return form
def version():
"""
Returns the version of the database server currently in use.
@return Database server version
"""
version = php.explode('-', \
DrupyMySQL.mysqli_get_server_info(lib_appglobals.active_db))
return version
def connect(url):
"""
Initialise a database connection.
Note that mysqli does not support persistent connections.
"""
# Check if MySQLi support is present in PHP
url = php.parse_url(url, 3306)
# Decode url-encoded information in the db connection string
url['user'] = php.urldecode(url['user'])
# Test if database url has a password.
url['pass'] = (php.urldecode(url['pass']) if php.isset(url, 'pass') else '')
url['host'] = php.urldecode(url['host'])
url['path'] = php.urldecode(url['path'])
if (not php.isset(url, 'port')):
url['port'] = None
connection = DrupyMySQL.mysqli_real_connect(\
url['host'], url['user'], url['pass'], php.substr(url['path'], 1), \
url['port'], '', DrupyMySQL.MYSQLI_CLIENT_FOUND_ROWS)
if (DrupyMySQL.mysqli_connect_errno() > 0):
_db_error_page(DrupyMySQL.mysqli_connect_error())
# Force UTF-8.
DrupyMySQL.mysqli_query(connection, 'SET NAMES "utf8"')
# Require ANSI mode to improve SQL portability.
DrupyMySQL.mysqli_query(connection, "SET php.SESSION sql_mode='ANSI'")
return connection
def _query(query_, debug = 0):
"""
Helper function for db_query().
"""
if (lib_bootstrap.variable_get('dev_query', 0)):
usec,sec = php.explode(' ', php.microtime())
timer = float(usec) + float(sec)
# If devel.plugin query logging is enabled, prepend a comment
# with the username and calling function
# to the SQL string. This is useful when running mysql's
# SHOW PROCESSLIST to learn what exact
# code is issueing the slow query.
bt = debug_backtrace()
# t() may not be available yet so we don't wrap 'Anonymous'
name = (lib_appglobals.user.name if (lib_appglobals.user.uid > 0) else \
variable_get('anonymous', 'Anonymous'))
# php.str_replace() to prevent SQL injection via username
# or anonymous name.
name = php.str_replace(['*', '/'], '', name)
query_ = '/* ' + name + ' : ' . bt[2]['function'] + ' */ ' + query_
result = DrupyMySQL.mysqli_query(lib_appglobals.active_db, query_)
if (lib_bootstrap.variable_get('dev_query', 0)):
query_ = bt[2]['function'] + "\n" + query_
usec,sec = php.explode(' ', php.microtime())
stop = float(usec) + float(sec)
diff = stop - timer
lib_appglobals.queries.append( [query_, diff] )
if (debug):
print '<p>query: ' + query_ + '<br />error:' + \
DrupyMySQL.mysqli_error(lib_appglobals.active_db) + '</p>'
if (not DrupyMySQL.mysqli_errno(lib_appglobals.active_db)):
return result
else:
# Indicate to drupal_error_handler that this is a database error.
DB_ERROR = True
php.trigger_error(lib_bootstrap.check_plain(\
DrupyMySQL.mysqli_error(lib_appglobals.active_db) + \
"\nquery: " + query_), php.E_USER_WARNING)
return False
def fetch_object(result):
"""
Fetch one result row from the previous query as an object.
@param result
A database query result resource, as returned from db_query().
@return
An object representing the next row of the result,
or False. The attributes
of this object are the table fields selected by the query.
"""
if (result):
object_ = DrupyMySQL.mysqli_fetch_object(result)
return (object_ if (object_ != None) else False)
def fetch_array(result):
"""
Fetch one result row from the previous query as an array.
@param result
A database query result resource, as returned from db_query().
@return
An associative array representing the next row of the result, or False.
The keys of this object are the names of the table fields selected by the
query, and the values are the field values for this result row.
"""
if (result):
array_ = DrupyMySQL.mysqli_fetch_array(result, DrupyMySQL.MYSQLI_ASSOC)
return (array_ if (array_ != None) else False)
def result(result):
"""
Return an individual result field from the previous query.
Only use this function if exactly one field is being selected; otherwise,
use db_fetch_object() or db_fetch_array().
@param result
A database query result resource, as returned from db_query().
@return
The resulting field or False.
"""
if (result and DrupyMySQL.mysqli_num_rows(result) > 0):
# The DrupyMySQL.mysqli_fetch_row function has an optional second
# parameter row
# but that can't be used for compatibility with Oracle, DB2, etc.
array_ = DrupyMySQL.mysqli_fetch_row(result)
return array_[0]
return False
def error():
"""
Determine whether the previous query caused an error.
"""
return DrupyMySQL.mysqli_errno(lib_appglobals.active_db)
def affected_rows():
"""
Determine the number of rows changed by the preceding query.
"""
return DrupyMySQL.mysqli_affected_rows(lib_appglobals.active_db)
def query_range(query):
"""
Runs a limited-range query in the active database.
Use this as a substitute for db_query() when a subset of the query is to be
returned. User-supplied arguments to the query should be passed in as
separate parameters so that they can be properly escaped to avoid SQL
injection attacks.
@param query
A string containing an SQL query.
@param ...
A variable number of arguments which are substituted into the query
using printf() syntax. The query arguments can be enclosed in one
array instead.
Valid %-modifiers are: %s, %d, %f, %b (binary data, do not enclose
in '') and %%.
NOTE: using this syntax will cast None and False values to decimal 0,
and True values to decimal 1.
@param from
The first result row to return.
@param count
The maximum number of result rows to return.
@return
A database query result resource, or False if the query was not executed
correctly.
"""
args = func_get_args()
count = php.array_pop(args)
from_ = php.array_pop(args)
php.array_shift(args)
query = db_prefix_tables(query)
# 'All arguments in one array' syntax
if (php.isset(args, 0) and php.is_array(args, 0)):
args = args[0]
_db_query_callback(args, True)
query = php.preg_replace_callback(DB_QUERY_REGEXP, \
'_db_query_callback', query)
query += ' LIMIT ' + int(from_) + ', ' . int(count)
return _db_query(query)
def query_temporary(query):
"""
Runs a SELECT query and stores its results in a temporary table.
Use this as a substitute for db_query() when the results need to stored
in a temporary table. Temporary tables exist for the duration of the page
request.
User-supplied arguments to the query should be passed in as
separate parameters
so that they can be properly escaped to avoid SQL injection attacks.
Note that if you need to know how many results were returned, you should do
a SELECT COUNT(*) on the temporary table afterwards. db_affected_rows() does
not give consistent result across different database types in this case.
@param query
A string containing a normal SELECT SQL query.
@param ...
A variable number of arguments which are substituted into the query
using printf() syntax. The query arguments can be enclosed in one
array instead.
Valid %-modifiers are: %s, %d, %f, %b (binary data, do not enclose
in '') and %%.
NOTE: using this syntax will cast None and False values to decimal 0,
and True values to decimal 1.
@param table
The name of the temporary table to select into. This name will not be
prefixed as there is no risk of collision.
@return
A database query result resource, or False if the query was not executed
correctly.
"""
args = func_get_args()
tablename = php.array_pop(args)
php.array_shift(args)
query = php.preg_replace('/^SELECT/i', 'CREATE TEMPORARY TABLE ' + \
tablename + ' Engine=HEAP SELECT', db_prefix_tables(query))
# 'All arguments in one array' syntax
if (php.isset(args, 0) and php.is_array(args, 0)):
args = args[0]
_db_query_callback(args, True)
query = php.preg_replace_callback(DB_QUERY_REGEXP, \
'_db_query_callback', query)
return _db_query(query)
def encode_blob(data):
"""
Returns a properly formatted Binary Large Object value.
@param data
Data to encode.
@return
Encoded data.
"""
return "'" + DrupyMySQL.mysqli_real_escape_string(\
lib_appglobals.active_db, data) + "'"
def decode_blob(data):
"""
Returns text from a Binary Large OBject value.
@param data
Data to decode.
@return
Decoded data.
"""
return data
def escape_string(text):
"""
Prepare user input for use in a database query, preventing
SQL injection attacks.
"""
return DrupyMySQL.mysqli_real_escape_string(lib_appglobals.active_db, text)
def lock_table(table):
"""
Lock a table.
"""
db_query('LOCK TABLES {' + db_escape_table(table) + '} WRITE')
def unlock_tables():
"""
Unlock all locked tables.
"""
db_query('UNLOCK TABLES')
def table_exists(table):
"""
Check if a table exists.
"""
return bool(lib_database.fetch_object(\
lib_database.query("SHOW TABLES LIKE '{" + \
lib_database.escape_table(table) + "}'")))
def column_exists(table, column):
"""
Check if a column exists in the given table.
"""
return bool(lib_database.fetch_object(\
lib_database.query("SHOW COLUMNS FROM {" + \
lib_database.escape_table(table) + "} LIKE '" + \
lib_database.escape_table(column) + "'")))
def distinct_field(table, field, query):
"""
Wraps the given table.field entry with a DISTINCT(). The wrapper is added to
the SELECT list entry of the given query and the resulting query is
returned. This function only applies the wrapper if a DISTINCT doesn't
already exist in the query.
@param table Table containing the field to set as DISTINCT
@param field Field to set as DISTINCT
@param query Query to apply the wrapper to
@return SQL query with the DISTINCT wrapper surrounding the given
table.field.
"""
field_to_select = 'DISTINCT(' + table + '.' + field + ')'
# (?<not text) is a negative look-behind
# (no need to rewrite queries that already use DISTINCT).
return php.preg_replace('/(SELECT.*)(?:' + table + \
'\.|\s)(?<not DISTINCT\()(?<not DISTINCT\(' + table + '\.)' + field + \
'(.*FROM )/AUsi', '\1 ' + field_to_select + '\2', query)
#
# @} End of "ingroup database".
#
#
# These functions were originally located in includes/mysql-common.inc
#
def query(query_, *args):
"""
Runs a basic query in the active database.
User-supplied arguments to the query should be passed in as separate
parameters so that they can be properly escaped to avoid SQL injection
attacks.
@param query
A string containing an SQL query.
@param ...
A variable number of arguments which are substituted into the query
using printf() syntax. Instead of a variable number of query arguments,
you may also pass a single array containing the query arguments.
Valid %-modifiers are: %s, %d, %f, %b (binary data, do not enclose
in '') and %%.
NOTE: using this syntax will cast None and False values to decimal 0,
and True values to decimal 1.
@return
A database query result resource, or False if the query was not
executed correctly.
"""
this_query = lib_database.prefix_tables(query_)
# 'All arguments in one array' syntax
if (php.isset(args, 0) and php.is_array(args[0])):
args = args[0]
lib_database._query_callback(args, True)
this_query = php.preg_replace_callback(lib_database.DB_QUERY_REGEXP, \
lib_database._query_callback, this_query)
#print
#print "QUERY DEBUG:"
#print this_query
#print
return _query(this_query)
#
# @ingroup schemaapi
# @{
#
def create_table_sql(name, table):
"""
Generate SQL to create a new table from a Drupal schema definition.
@param name
The name of the table to create.
@param table
A Schema API table definition array.
@return
An array of SQL statements to create the table.
"""
if (php.empty(table['mysql_suffix'])):
table['mysql_suffix'] = "/*not 40100 DEFAULT CHARACTER SET UTF8 */"
sql = "CREATE TABLE {" + name + "} (\n"
# Add the SQL statement for each field.
for field_name,field in table['fields'].items():
sql += _db_create_field_sql(field_name, _db_process_field(field)) + ", \n"
# Process keys & indexes.
keys = _db_create_keys_sql(table)
if (php.count(keys)):
sql += php.implode(", \n", keys) + ", \n"
# Remove the last comma and space.
sql = php.substr(sql, 0, -3) + "\n) "
sql += table['mysql_suffix']
return array(sql)
def _create_keys_sql(spec):
keys = {}
if (not php.empty(spec['primary key'])):
keys.append( 'PRIMARY KEY (' + \
_db_create_key_sql(spec['primary key']) + ')' )
if (not php.empty(spec['unique keys'])):
for key,fields in spec['unique keys'].items():
keys.append( 'UNIQUE KEY ' + key + \
' (' + _db_create_key_sql(fields) + ')' )
if (not php.empty(spec['indexes'])):
for index,fields in spec['indexes'].items():
keys.append( 'INDEX ' + index + ' (' + \
_db_create_key_sql(fields) + ')' )
return keys
def _create_key_sql(fields):
ret = []
for field in fields:
if (php.is_array(field)):
ret.append( field[0] + '(' + field[1] + ')' )
else:
ret.append( field )
return php.implode(', ', ret)
def _process_field(field):
"""
Set database-engine specific properties for a field.
@param field
A field description array, as specified in the schema documentation.
"""
if (not php.isset(field, 'size')):
field['size'] = 'normal'
# Set the correct database-engine specific datatype.
if (not php.isset(field, 'mysql_type')):
map_ = db_type_map()
field['mysql_type'] = map_[field['type'] + ':' + field['size']]
if (field['type'] == 'serial'):
field['auto_increment'] = True
return field
def _create_field_sql(name, spec):
"""
Create an SQL string for a field to be used in table creation or alteration.
Before passing a field out of a schema definition into this function it has
to be processed by _db_process_field().
@param name
Name of the field.
@param spec
The field specification, as per the schema data structure format.
"""
sql = "`" + name + "` " . spec['mysql_type']
if (php.isset(spec, 'length')):
sql += '(' + spec['length'] + ')'
elif (php.isset(spec, 'precision') and php.isset(spec, 'scale')):
sql += '(' + spec['precision'] + ', ' + spec['scale'] + ')'
if (not php.empty(spec['unsigned'])):
sql += ' unsigned'
if (not php.empty(spec['not None'])):
sql += ' NOT None'
if (not php.empty(spec['auto_increment'])):
sql += ' auto_increment'
if (php.isset(spec, 'default')):
if (is_string(spec['default'])):
spec['default'] = "'" + spec['default'] + "'"
sql += ' DEFAULT ' + spec['default']
if (php.empty(spec['not None']) and not php.isset(spec, 'default')):
sql += ' DEFAULT None'
return sql
def type_map():
"""
This maps a generic data type in combination with its data size
to the engine-specific data type.
"""
# Put :normal last so it gets preserved by array_flip. This makes
# it much easier for plugins (such as schema.plugin) to map
# database types back into schema types.
map_ = {
'varchar:normal' : 'VARCHAR',
'char:normal' : 'CHAR',
'text:tiny' : 'TINYTEXT',
'text:small' : 'TINYTEXT',
'text:medium' : 'MEDIUMTEXT',
'text:big' : 'LONGTEXT',
'text:normal' : 'TEXT',
'serial:tiny' : 'TINYINT',
'serial:small' : 'SMALLINT',
'serial:medium' : 'MEDIUMINT',
'serial:big' : 'BIGINT',
'serial:normal' : 'INT',
'int:tiny' : 'TINYINT',
'int:small' : 'SMALLINT',
'int:medium' : 'MEDIUMINT',
'int:big' : 'BIGINT',
'int:normal' : 'INT',
'float:tiny' : 'FLOAT',
'float:small' : 'FLOAT',
'float:medium' : 'FLOAT',
'float:big' : 'DOUBLE',
'float:normal' : 'FLOAT',
'numeric:normal' : 'DECIMAL',
'blob:big' : 'LONGBLOB',
'blob:normal' : 'BLOB',
'datetime:normal' : 'DATETIME'
}
return map_
def rename_table(ret, table, new_name):
"""
Rename a table.
@param ret
Array to which query results will be added.
@param table
The table to be renamed.
@param new_name
The new name for the table.
"""
php.Reference.check(ref)
ret.append( update_sql('ALTER TABLE {' + table + '} RENAME TO {' + \
new_name + '}') )
def drop_table(ret, table):
"""
Drop a table.
@param ret
Array to which query results will be added.
@param table
The table to be dropped.
"""
php.Reference.check(ref)
php.array_merge( update_sql('DROP TABLE {' + table + '}'), ret, True )
def add_field(ret, table, field, spec, keys_new = []):
"""
Add a new field to a table.
@param ret
Array to which query results will be added.
@param table
Name of the table to be altered.
@param field
Name of the field to be added.
@param spec
The field specification array, as taken from a schema definition.
The specification may also contain the key 'initial', the newly
created field will be set to the value of the key in all rows.
This is most useful for creating NOT None columns with no default
value in existing tables.
@param keys_new
Optional keys and indexes specification to be created on the
table along with adding the field. The format is the same as a
table specification but without the 'fields' element. If you are
adding a type 'serial' field, you MUST specify at least one key
or index including it in this array. @see db_change_field for more
explanation why.
"""
php.Reference.check(ret)
fixNone = False
if (not php.empty(spec['not None']) and not php.isset(spec, 'default')):
fixNone = True
spec['not None'] = False
query = 'ALTER TABLE {' + table + '} ADD '
query += _db_create_field_sql(field, _db_process_field(spec))
if (php.count(keys_new)):
query += ', ADD ' + php.implode(', ADD ', _db_create_keys_sql(keys_new))
ret.append( update_sql(query) )
if (php.isset(spec, 'initial')):
# All this because update_sql does not support %-placeholders.
sql = 'UPDATE {' + table + '} SET ' + field + ' = ' + \
db_type_placeholder(spec['type'])
result = db_query(sql, spec['initial'])
ret.append( {'success' : result != False, \
'query' : check_plain(sql + ' (' + spec['initial'] + ')')})
if (fixNone):
spec['not None'] = True
db_change_field(ret, table, field, field, spec)
def drop_field(ret, table, field):
"""
Drop a field.
@param ret
Array to which query results will be added.
@param table
The table to be altered.
@param field
The field to be dropped.
"""
php.Reference.check(ret)
ret.append( update_sql('ALTER TABLE {' + table + '} DROP ' + field) )
def field_set_default(ret, table, field, default):
"""
Set the default value for a field.
@param ret
Array to which query results will be added.
@param table
The table to be altered.
@param field
The field to be altered.
@param default
Default value to be set. None for 'default None'.
"""
php.Reference.check(ret)
if (default == None):
default = 'None'
else:
default = ("'default'" if is_string(default) else default)
ret.append( update_sql('ALTER TABLE {' + table + \
'} ALTER COLUMN ' + field + ' SET DEFAULT ' + default) )
def field_set_no_default(ret, table, field):
"""
Set a field to have no default value.
@param ret
Array to which query results will be added.
@param table
The table to be altered.
@param field
The field to be altered.
"""
php.Reference.check(ret)
ret.append( update_sql('ALTER TABLE {' + table + \
'} ALTER COLUMN ' + field + ' DROP DEFAULT') )
def add_primary_key(ret, table, fields):
"""
Add a primary key.
@param ret
Array to which query results will be added.
@param table
The table to be altered.
@param fields
Fields for the primary key.
"""
php.Reference.check(ret)
ret.append( update_sql('ALTER TABLE {' + table + \
'} ADD PRIMARY KEY (' + _db_create_key_sql(fields) + ')') )
def drop_primary_key(ret, table):
"""
Drop the primary key.
@param ret
Array to which query results will be added.
@param table
The table to be altered.
"""
php.Reference.check(ret)
ret.append( update_sql('ALTER TABLE {' + table + \
'} DROP PRIMARY KEY') )
def add_unique_key(ret, table, name, fields):
"""
Add a unique key.
@param ret
Array to which query results will be added.
@param table
The table to be altered.
@param name
The name of the key.
@param fields
An array of field names.
"""
php.Reference.check(ret)
ret.val.append( update_sql('ALTER TABLE {' + table + \
'} ADD UNIQUE KEY ' + name + ' (' + _db_create_key_sql(fields) + ')') )
def drop_unique_key(ret, table, name):
"""
Drop a unique key.
@param ret
Array to which query results will be added.
@param table
The table to be altered.
@param name
The name of the key.
"""
php.Reference.check(ret)
ret.append( update_sql('ALTER TABLE {' + table + \
'} DROP KEY ' + name) )
def add_index(ret, table, name, fields):
"""
Add an index.
@param ret
Array to which query results will be added.
@param table
The table to be altered.
@param name
The name of the index.
@param fields
An array of field names.
"""
php.Reference.check(ret)
query = 'ALTER TABLE {' + table + '} ADD INDEX ' + name + \
' (' + _db_create_key_sql(fields) + ')'
ret.append( update_sql(query) )
def drop_index(ret, table, name):
"""
Drop an index.
@param ret
Array to which query results will be added.
@param table
The table to be altered.
@param name
The name of the index.
"""
php.Reference.check(ret)
ret.append( update_sql('ALTER TABLE {' + table + \
'} DROP INDEX ' + name) )
def change_field(ret, table, field, field_new, spec, keys_new = []):
"""
Change a field definition.
IMPORTANT NOTE: To maintain database portability, you have to explicitly
recreate all indices and primary keys that are using the changed field.
That means that you have to drop all affected keys and indexes with
db_drop_{primary_key,unique_key,index}() before calling db_change_field().
To recreate the keys and indices, pass the key definitions as the
optional keys_new argument directly to db_change_field().
For example, suppose you have:
@code
schema['foo'] = array(
'fields' : array(
'bar' : array('type' : 'int', 'not None' : True)
),
'primary key' : array('bar')
)
@endcode
and you want to change foo.bar to be type serial, leaving it as the
primary key. The correct sequence is:
@code
db_drop_primary_key(ret, 'foo')
db_change_field(ret, 'foo', 'bar', 'bar',
array('type' : 'serial', 'not None' : True),
array('primary key' : array('bar')))
@endcode
The reasons for this are due to the different database engines:
On PostgreSQL, changing a field definition involves adding a new field
and dropping an old one which* causes any indices, primary keys and
sequences (from serial-type fields) that use the changed field to be
dropped.
On MySQL, all type 'serial' fields must be part of at least one key
or index as soon as they are created. You cannot use
db_add_{primary_key,unique_key,index}() for this purpose because
the ALTER TABLE command will fail to add the column without a key
or index specification. The solution is to use the optional
keys_new argument to create the key or index at the same time as
field.
You could use db_add_{primary_key,unique_key,index}() in all cases
unless you are converting a field to be type serial. You can use
the keys_new argument in all cases.
@param ret
Array to which query results will be added.
@param table
Name of the table.
@param field
Name of the field to change.
@param field_new
New name for the field (set to the same as field if you don't want to
change the name).
@param spec
The field specification for the new field.
@param keys_new
Optional keys and indexes specification to be created on the
table along with changing the field. The format is the same as a
table specification but without the 'fields' element.
"""
php.Reference.check(ret)
sql = 'ALTER TABLE {' + table + '} CHANGE ' + field + ' ' + \
_db_create_field_sql(field_new, _db_process_field(spec))
if (php.count(keys_new) > 0):
sql += ', ADD ' + php.implode(', ADD ', _db_create_keys_sql(keys_new))
ret.append( update_sql(sql) )
def last_insert_id(table, field):
"""
Returns the last insert id.
@param table
The name of the table you inserted into.
@param field
The name of the autoincrement field.
"""
return db_result(db_query('SELECT LAST_INSERT_ID()'))
def escape_string(data):
"""
Wrapper to escape a string
"""
return DrupyMySQL.mysqli_real_escape_string(lib_appglobals.active_db, data)
#
# Aliases
#
fetch_assoc = fetch_array |
import { createSlice, Slice } from '@reduxjs/toolkit'
interface I18nSliceState {
locale: string | null
messages: object | null
defaultMessage: object | null
}
const initialState: I18nSliceState = {
locale: null,
messages: null,
defaultMessage: null
}
export const slice: Slice = createSlice({
name: 'i18n',
initialState,
reducers: {
setMessages: (state: I18nSliceState, { payload }) => {
const { locale, messages, defaultMessage } = payload
state.locale = locale
state.messages = messages
state.defaultMessage = defaultMessage
},
setInitialState: () => initialState
}
}) |
<%--
Document : unit
Created on : Mar 24, 2022, 10:50:42 AM
Author : pupil
--%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<c:choose>
<c:when test="${role eq 1}">
<main>
<h2 class="topic">Страница картины</h2>
<div class="page_unit">
<div class="img">
<img src="insertFile/${state.picture.pathToFile}" alt="aaa">
</div>
<div class="mass">
<p class="inf" name="">Название картины- ${state.art_name}</p>
<p class="inf">Размер: ${state.size}</p>
<p class="inf">Цена - ${state.price}€</p>
<p class="inf">Дата написания: ${state.year}</p>
<p class="inf">Жанры: ${state.kind}</p>
<p class="inf">Описание</p>
<p class="inf textarea">${state.description}</p>
<form action="order" method="POST" enctype="multipart/form-data">
<input hidden type="text" name="id" value="${state.id}">
<button>Заказать</button>
</form>
</div>
</div>
</main>
</c:when>
<c:when test="${role eq 2}">
<main class="add admin_form">
<h2 class="topic">Страница картины</h2>
<form action="change_img" method="POST" enctype="multipart/form-data">
<div class="add_img">
<img src="insertFile/${state.picture.pathToFile}" alt="aaa">
</div>
<div class="text">
<div class="date">
<label for="art_name">Название картины:</label>
<input type="text" name="art_name" id="art_name" value="${state.art_name}">
<label for="size">Размер картины:</label>
<input type="text" name="size" id="size" value="${state.size}">
<label for="price">Цена:</label>
<input type="number" name="price" id="price" value="${state.price}">
<label for="year">Год написания</label>
<input type="date" name="year" id="year" value="${state.year}">
<label for="kinds">Жанры</label>
<div class="kinds">
<div>
<input id="портрет" type="checkbox" value="портрет" name="kinds[]">
<label for="портрет">портрет</label>
</div>
<div>
<input id="пейзаж" type="checkbox" value="пейзаж" name="kinds[]">
<label for="пейзаж">пейзаж</label>
</div>
<div>
<input id="натюрморт" type="checkbox" value="натюрморт" name="kinds[]">
<label for="натюрморт">натюрморт</label>
</div>
<div>
<input id="бытовой" type="checkbox" value="бытовой" name="kinds[]">
<label for="бытовой">бытовой</label>
</div>
<div>
<input id="анималистический" type="checkbox" value="анималистический" name="kinds[]">
<label for="анималистический">анималистический</label>
</div>
</div>
</div>
<div class="description">
<label for="description">Описание</label>
<textarea name="description" id="description" cols="30" rows="10" >${state.description}</textarea>
</div>
<input hidden="" type="text" name="id" value="${state.id}">
<button type="submit" onclick="coord_scroll()">Изменить</button>
</div>
</form>
</main>
</c:when>
<c:when test="${role eq 0}">
<main>
<h2 class="topic">Страница картины</h2>
<div class="page_unit">
<div class="img">
<img src="insertFile/${state.picture.pathToFile}" alt="aaa">
</div>
<div class="mass">
<p class="inf" name="">Название картины- ${state.art_name}</p>
<p class="inf">Размер: ${state.size}</p>
<p class="inf">Цена - ${state.price}€</p>
<p class="inf">Дата написания: ${state.year}</p>
<p class="inf">Жанры: ${state.kind}</p>
<p class="inf">Описание</p>
<p class="inf textarea">${state.description}</p>
</div>
</div>
</main>
</c:when>
</c:choose> |
import { EntityValidationError } from '@/core/errors/entity-validation-error';
import { QuestionOption } from './question-option';
describe('QuestionOption', () => {
it('Should be able to create a question option', () => {
const props = {
questionId: '75ec07ce-5b76-4baa-87bd-fb40bce984e5',
title: 'Option 1',
value: '1',
order: 1,
};
const option = QuestionOption.create(props);
expect(option.id).toBeDefined();
expect(option.questionId).toBe(props.questionId);
expect(option.title).toBe(props.title);
expect(option.value).toBe(props.value);
expect(option.order).toBe(props.order);
expect(option.createdAt).toBeDefined();
expect(option.updatedAt).toBeDefined();
expect(option.deletedAt).toBeUndefined();
});
it('Should not be able to create an invalid question option', () => {
expect(() => {
const props = {
questionId: '1212212',
title: 'Option 1',
value: '2121221',
order: -2,
};
QuestionOption.create(props);
}).toThrow(EntityValidationError);
});
it('Should be able to restore a question option', () => {
const props = {
id: '123',
questionId: '123',
title: 'Option 1',
value: '1',
order: 1,
createdAt: new Date(),
updatedAt: new Date(),
deletedAt: new Date(),
};
const option = QuestionOption.restore(props);
expect(option.id).toBe(props.id);
expect(option.questionId).toBe(props.questionId);
expect(option.title).toBe(props.title);
expect(option.value).toBe(props.value);
expect(option.order).toBe(props.order);
expect(option.createdAt.getTime()).toBe(props.createdAt.getTime());
expect(option.updatedAt.getTime()).toBe(props.updatedAt.getTime());
expect(option.deletedAt?.getTime()).toBe(props.deletedAt.getTime());
});
it('Should be able to change the question option title', () => {
const pastDate = new Date();
pastDate.setHours(pastDate.getHours() - 3);
const props = {
id: '123',
questionId: '9cf621ec-6f6c-43f7-8dd8-6e4872933018',
title: 'Option 1',
value: '1',
order: 1,
createdAt: pastDate,
updatedAt: pastDate,
};
const option = QuestionOption.restore(props);
const validateSpy = vi.spyOn(option, 'validate');
const newValue = 'Vermelho';
option.changeTitle(newValue);
expect(option.title).toBe(newValue);
expect(validateSpy).toHaveBeenCalledTimes(1);
expect(option.updatedAt.getTime()).toBeGreaterThan(
props.updatedAt.getTime(),
);
});
it('Should be able to change the question option value', () => {
const pastDate = new Date();
pastDate.setHours(pastDate.getHours() - 3);
const props = {
id: '123',
questionId: '9cf621ec-6f6c-43f7-8dd8-6e4872933018',
title: 'Option 1',
value: '1',
order: 1,
createdAt: pastDate,
updatedAt: pastDate,
};
const option = QuestionOption.restore(props);
const validateSpy = vi.spyOn(option, 'validate');
const newValue = '3';
option.changeValue(newValue);
expect(option.value).toBe(newValue);
expect(validateSpy).toHaveBeenCalledTimes(1);
expect(option.updatedAt.getTime()).toBeGreaterThan(
props.updatedAt.getTime(),
);
});
it('Should be able to delete a question option', () => {
const pastDate = new Date();
pastDate.setHours(pastDate.getHours() - 3);
const props = {
id: '123',
questionId: '9cf621ec-6f6c-43f7-8dd8-6e4872933018',
title: 'Option 1',
value: '1',
order: 1,
createdAt: pastDate,
updatedAt: pastDate,
};
const option = QuestionOption.restore(props);
option.delete();
expect(option.deletedAt).toBeDefined();
});
}); |
/**
* @file Transport.h Headers for the Transport object, which is the virtual
* base class for all transport property evaluators and also includes the
* tranprops group definition (see @ref tranprops and @link
* Cantera::Transport Transport @endlink) .
*/
// This file is part of Cantera. See License.txt in the top-level directory or
// at https://cantera.org/license.txt for license and copyright information.
/**
* @defgroup tranprops Transport Properties
*
* These classes provide transport properties, including diffusion coefficients,
* thermal conductivity, and viscosity.
*/
#ifndef CT_TRANSPORT_H
#define CT_TRANSPORT_H
#include "cantera/base/ct_defs.h"
#include "cantera/base/ctexceptions.h"
#include "cantera/base/global.h"
namespace Cantera
{
class ThermoPhase;
class Solution;
class AnyMap;
/**
* @addtogroup tranprops
*/
//! @cond
const int CK_Mode = 10;
//! @endcond
//! The diffusion fluxes must be referenced to a particular reference
//! fluid velocity.
/*!
* Most typical is to reference the diffusion fluxes to the mass averaged
* velocity, but referencing to the mole averaged velocity is suitable for some
* liquid flows, and referencing to a single species is suitable for solid phase
* transport within a lattice. Currently, the identity of the reference
* velocity is coded into each transport object as a typedef named
* VelocityBasis, which is equated to an integer. Negative values of this
* variable refer to mass or mole-averaged velocities. Zero or positive
* quantities refers to the reference velocity being referenced to a particular
* species. Below are the predefined constants for its value.
*
* @deprecated To be removed after %Cantera 3.0.
*
* - VB_MASSAVG Diffusion velocities are based on the mass averaged velocity
* - VB_MOLEAVG Diffusion velocities are based on the mole averaged velocities
* - VB_SPECIES_0 Diffusion velocities are based on the relative motion wrt species 0
* - ...
* - VB_SPECIES_3 Diffusion velocities are based on the relative motion wrt species 3
*
* @ingroup tranprops
*/
typedef int VelocityBasis;
/**
* @addtogroup tranprops
*/
//! @{
//! Diffusion velocities are based on the mass averaged velocity
//! @deprecated To be removed after %Cantera 3.0.
const VelocityBasis VB_MASSAVG = -1;
//! Diffusion velocities are based on the mole averaged velocities
//! @deprecated To be removed after %Cantera 3.0.
const VelocityBasis VB_MOLEAVG = -2;
//! Diffusion velocities are based on the relative motion wrt species 0
//! @deprecated To be removed after %Cantera 3.0.
const VelocityBasis VB_SPECIES_0 = 0;
//! Diffusion velocities are based on the relative motion wrt species 1
//! @deprecated To be removed after %Cantera 3.0.
const VelocityBasis VB_SPECIES_1 = 1;
//! Diffusion velocities are based on the relative motion wrt species 2
//! @deprecated To be removed after %Cantera 3.0.
const VelocityBasis VB_SPECIES_2 = 2;
//! Diffusion velocities are based on the relative motion wrt species 3
//! @deprecated To be removed after %Cantera 3.0.
const VelocityBasis VB_SPECIES_3 = 3;
//! @}
//! Base class for transport property managers.
/*!
* All classes that compute transport properties for a single phase derive from
* this class. Class Transport is meant to be used as a base class only. It is
* possible to instantiate it, but its methods throw exceptions if called.
*
* ## Relationship of the Transport class to the ThermoPhase Class
*
* This section describes how calculations are carried out within the Transport
* class. The Transport class and derived classes of the the Transport class
* necessarily use the ThermoPhase class to obtain the list of species and the
* thermodynamic state of the phase.
*
* No state information is stored within Transport classes. Queries to the
* underlying ThermoPhase object must be made to obtain the state of the system.
*
* An exception to this however is the state information concerning the the
* gradients of variables. This information is not stored within the ThermoPhase
* objects. It may be collected within the Transport objects. In fact, the
* meaning of const operations within the Transport class refers to calculations
* which do not change the state of the system nor the state of the first order
* gradients of the system.
*
* When a const operation is evoked within the Transport class, it is also
* implicitly assumed that the underlying state within the ThermoPhase object
* has not changed its values.
*
* ## Diffusion Fluxes and their Relationship to Reference Velocities
*
* The diffusion fluxes must be referenced to a particular reference fluid
* velocity. Most typical is to reference the diffusion fluxes to the mass
* averaged velocity, but referencing to the mole averaged velocity is suitable
* for some liquid flows, and referencing to a single species is suitable for
* solid phase transport within a lattice. Currently, the identity of the
* reference velocity is coded into each transport object as a typedef named
* VelocityBasis, which is equated to an integer. Negative values of this
* variable refer to mass or mole-averaged velocities. Zero or positive
* quantities refers to the reference velocity being referenced to a particular
* species. Below are the predefined constants for its value.
*
* - VB_MASSAVG Diffusion velocities are based on the mass averaged velocity
* - VB_MOLEAVG Diffusion velocities are based on the mole averaged velocities
* - VB_SPECIES_0 Diffusion velocities are based on the relative motion wrt species 0
* - ...
* - VB_SPECIES_3 Diffusion velocities are based on the relative motion wrt species 3
*
* All transport managers specify a default reference velocity in their default
* constructors. All gas phase transport managers by default specify the mass-
* averaged velocity as their reference velocities.
*
* @todo Provide a general mechanism to store the gradients of state variables
* within the system.
*
* @ingroup tranprops
*/
class Transport
{
public:
//! Constructor.
/*!
* New transport managers should be created using TransportFactory, not by
* calling the constructor directly.
*
* @param thermo Pointer to the ThermoPhase class representing this phase.
* @param ndim Dimension of the flux vector used in the calculation.
*
* @deprecated The `thermo` and `ndim` parameters will be removed after %Cantera 3.0.
* The ThermoPhase object should be specifed when calling the `init` method.
*
* @see TransportFactory
*/
Transport(ThermoPhase* thermo=0, size_t ndim=npos);
virtual ~Transport() {}
// Transport objects are not copyable or assignable
Transport(const Transport&) = delete;
Transport& operator=(const Transport&) = delete;
//! Identifies the model represented by this Transport object. Each derived class
//! should override this method to return a meaningful identifier.
//! @since New in %Cantera 3.0. The name returned by this method corresponds
//! to the canonical name used in the YAML input format.
virtual string transportModel() const {
return "none";
}
//! Identifies the Transport object type. Each derived class should override
//! this method to return a meaningful identifier.
//! @deprecated To be removed after %Cantera 3.0. Replaced by transportModel
string transportType() const {
warn_deprecated("Transport::transportType",
"To be removed after Cantera 3.0. Replaced by transportModel().");
return transportModel();
}
/**
* Phase object. Every transport manager is designed to compute properties
* for a specific phase of a mixture, which might be a liquid solution, a
* gas mixture, a surface, etc. This method returns a reference to the
* object representing the phase itself.
*/
ThermoPhase& thermo() {
return *m_thermo;
}
/**
* Returns true if the transport manager is ready for use.
* @deprecated To be removed after %Cantera 3.0.
*/
bool ready();
//! Set the number of dimensions to be expected in flux expressions
/*!
* @param ndim Number of dimensions in flux expressions
* @deprecated Unused. To be removed after %Cantera 3.0.
*/
void setNDim(const int ndim);
//! Return the number of dimensions in flux expressions
//! @deprecated Unused. To be removed after %Cantera 3.0.
size_t nDim() const {
return m_nDim;
}
//! Check that the specified species index is in range. Throws an exception
//! if k is greater than nSpecies()
void checkSpeciesIndex(size_t k) const;
//! Check that an array size is at least nSpecies(). Throws an exception if
//! kk is less than nSpecies(). Used before calls which take an array
//! pointer.
void checkSpeciesArraySize(size_t kk) const;
//! @name Transport Properties
//! @{
/**
* The viscosity in Pa-s.
*/
virtual double viscosity() {
throw NotImplementedError("Transport::viscosity",
"Not implemented for transport model '{}'.", transportModel());
}
//! Returns the pure species viscosities
/*!
* The units are Pa-s and the length is the number of species
*
* @param visc Vector of viscosities
*/
virtual void getSpeciesViscosities(double* const visc) {
throw NotImplementedError("Transport::getSpeciesViscosities",
"Not implemented for transport model '{}'.", transportModel());
}
//! The bulk viscosity in Pa-s.
/*!
* The bulk viscosity is only non-zero in rare cases. Most transport
* managers either overload this method to return zero, or do not implement
* it, in which case an exception is thrown if called.
*/
virtual double bulkViscosity() {
throw NotImplementedError("Transport::bulkViscosity",
"Not implemented for transport model '{}'.", transportModel());
}
//! The ionic conductivity in 1/ohm/m.
//! @deprecated To be removed after %Cantera 3.0. Not implemented by any model.
virtual double ionConductivity() {
throw NotImplementedError("Transport::ionConductivity",
"Not implemented for transport model '{}'.", transportModel());
}
//! Returns the pure species ionic conductivity
/*!
* The units are 1/ohm/m and the length is the number of species
*
* @param ionCond Vector of ionic conductivities
*
* @deprecated To be removed after %Cantera 3.0. Not implemented by any model.
*/
virtual void getSpeciesIonConductivity(double* const ionCond) {
throw NotImplementedError("Transport::getSpeciesIonConductivity",
"Not implemented for transport model '{}'.", transportModel());
}
//! Returns the pointer to the mobility ratios of the species in the phase
/*!
* @param mobRat Returns a matrix of mobility ratios for the current
* problem. The mobility ratio mobRat(i,j) is defined as the
* ratio of the mobility of species i to species j.
*
* mobRat(i,j) = mu_i / mu_j
*
* It is returned in fortran-ordering format. That is, it is returned as
* mobRat[k], where
*
* k = j * nsp + i
*
* The size of mobRat must be at least equal to nsp*nsp
*
* @deprecated To be removed after %Cantera 3.0. Not implemented by any model.
*/
virtual void mobilityRatio(double* mobRat) {
throw NotImplementedError("Transport::mobilityRatio",
"Not implemented for transport model '{}'.", transportModel());
}
//! Returns the pure species limit of the mobility ratios
/*!
* The value is dimensionless and the length is the number of species
*
* @param mobRat Vector of mobility ratios
*
* @deprecated To be removed after %Cantera 3.0. Not implemented by any model.
*/
virtual void getSpeciesMobilityRatio(double** mobRat) {
throw NotImplementedError("Transport::getSpeciesMobilityRatio",
"Not implemented for transport model '{}'.", transportModel());
}
//! Returns the mixture thermal conductivity in W/m/K.
/*!
* Units are in W / m K or equivalently kg m / s3 K
*
* @returns thermal conductivity in W/m/K.
*/
virtual double thermalConductivity() {
throw NotImplementedError("Transport::thermalConductivity",
"Not implemented for transport model '{}'.", transportModel());
}
//! The electrical conductivity (Siemens/m).
virtual double electricalConductivity() {
throw NotImplementedError("Transport::electricalConductivity",
"Not implemented for transport model '{}'.", transportModel());
}
//! Get the Electrical mobilities (m^2/V/s).
/*!
* This function returns the mobilities. In some formulations this is equal
* to the normal mobility multiplied by Faraday's constant.
*
* Frequently, but not always, the mobility is calculated from the diffusion
* coefficient using the Einstein relation
*
* @f[
* \mu^e_k = \frac{F D_k}{R T}
* @f]
*
* @param mobil_e Returns the mobilities of the species in array @c
* mobil_e. The array must be dimensioned at least as large as
* the number of species.
*/
virtual void getMobilities(double* const mobil_e) {
throw NotImplementedError("Transport::getMobilities",
"Not implemented for transport model '{}'.", transportModel());
}
//! Get the fluid mobilities (s kmol/kg).
/*!
* This function returns the fluid mobilities. Usually, you have to multiply
* Faraday's constant into the resulting expression to general a species
* flux expression.
*
* Frequently, but not always, the mobility is calculated from the diffusion
* coefficient using the Einstein relation
*
* @f[
* \mu^f_k = \frac{D_k}{R T}
* @f]
*
* @param mobil_f Returns the mobilities of the species in array @c mobil.
* The array must be dimensioned at least as large as the
* number of species.
*
* @deprecated To be removed after %Cantera 3.0. Not implemented by any model.
*/
virtual void getFluidMobilities(double* const mobil_f) {
throw NotImplementedError("Transport::getFluidMobilities",
"Not implemented for transport model '{}'.", transportModel());
}
//! @}
//! Compute the mixture electrical conductivity (S m-1) at the current
//! conditions of the phase (Siemens m-1)
/*!
* The electrical conductivity, @f$ \sigma @f$, relates the electric current
* density, J, to the electric field, E.
*
* @f[
* \vec{J} = \sigma \vec{E}
* @f]
*
* We assume here that the mixture electrical conductivity is an isotropic
* quantity, at this stage. Tensors may be included at a later time.
*
* The conductivity is the reciprocal of the resistivity.
*
* The units are Siemens m-1, where 1 S = 1 A / volt = 1 s^3 A^2 /kg /m^2
*
* @deprecated To be removed after %Cantera 3.0. Replaced by electricalConductivity()
*/
virtual double getElectricConduct() {
throw NotImplementedError("Transport::getElectricConduct",
"Not implemented for transport model '{}'.", transportModel());
}
//! Compute the electric current density in A/m^2
/*!
* Calculates the electric current density as a vector, given the gradients
* of the field variables.
*
* @param ndim The number of spatial dimensions (1, 2, or 3).
* @param grad_T The temperature gradient (ignored in this model).
* @param ldx Leading dimension of the grad_X array.
* @param grad_X The gradient of the mole fraction
* @param ldf Leading dimension of the grad_V and current vectors.
* @param grad_V The electrostatic potential gradient.
* @param current The electric current in A/m^2. This is a vector of length ndim
*
* @deprecated To be removed after %Cantera 3.0. Not implemented by any model.
*/
virtual void getElectricCurrent(int ndim,
const double* grad_T,
int ldx,
const double* grad_X,
int ldf,
const double* grad_V,
double* current) {
throw NotImplementedError("Transport::getElectricCurrent",
"Not implemented for transport model '{}'.", transportModel());
}
//! Get the species diffusive mass fluxes wrt to the specified solution
//! averaged velocity, given the gradients in mole fraction and temperature
/*!
* Units for the returned fluxes are kg m-2 s-1.
*
* Usually the specified solution average velocity is the mass averaged
* velocity. This is changed in some subclasses, however.
*
* @param ndim Number of dimensions in the flux expressions
* @param grad_T Gradient of the temperature (length = ndim)
* @param ldx Leading dimension of the grad_X array (usually equal to
* m_nsp but not always)
* @param grad_X Gradients of the mole fraction Flat vector with the
* m_nsp in the inner loop. length = ldx * ndim
* @param ldf Leading dimension of the fluxes array (usually equal to
* m_nsp but not always)
* @param fluxes Output of the diffusive mass fluxes. Flat vector with
* the m_nsp in the inner loop. length = ldx * ndim
*/
virtual void getSpeciesFluxes(size_t ndim, const double* const grad_T,
size_t ldx, const double* const grad_X,
size_t ldf, double* const fluxes) {
throw NotImplementedError("Transport::getSpeciesFluxes",
"Not implemented for transport model '{}'.", transportModel());
}
//! Get the species diffusive mass fluxes wrt to the mass averaged velocity,
//! given the gradients in mole fraction, temperature and electrostatic
//! potential.
/*!
* Units for the returned fluxes are kg m-2 s-1.
*
* @param[in] ndim Number of dimensions in the flux expressions
* @param[in] grad_T Gradient of the temperature. (length = ndim)
* @param[in] ldx Leading dimension of the grad_X array (usually equal to
* m_nsp but not always)
* @param[in] grad_X Gradients of the mole fraction. Flat vector with the
* m_nsp in the inner loop. length = ldx * ndim.
* @param[in] ldf Leading dimension of the fluxes array (usually equal to
* m_nsp but not always).
* @param[in] grad_Phi Gradients of the electrostatic potential (length = ndim)
* @param[out] fluxes The diffusive mass fluxes. Flat vector with the m_nsp
* in the inner loop. length = ldx * ndim.
*
* @deprecated To be removed after %Cantera 3.0. Not implemented by any model.
*/
virtual void getSpeciesFluxesES(size_t ndim,
const double* grad_T,
size_t ldx,
const double* grad_X,
size_t ldf,
const double* grad_Phi,
double* fluxes) {
getSpeciesFluxes(ndim, grad_T, ldx, grad_X, ldf, fluxes);
}
//! Get the species diffusive velocities wrt to the mass averaged velocity,
//! given the gradients in mole fraction and temperature
/*!
* @param[in] ndim Number of dimensions in the flux expressions
* @param[in] grad_T Gradient of the temperature (length = ndim)
* @param[in] ldx Leading dimension of the grad_X array (usually equal to
* m_nsp but not always)
* @param[in] grad_X Gradients of the mole fraction. Flat vector with the
* m_nsp in the inner loop. length = ldx * ndim
* @param[in] ldf Leading dimension of the fluxes array (usually equal to
* m_nsp but not always)
* @param[out] Vdiff Diffusive velocities wrt the mass- averaged velocity.
* Flat vector with the m_nsp in the inner loop.
* length = ldx * ndim. units are m / s.
*
* @deprecated To be removed after %Cantera 3.0. Not implemented by any model.
*/
virtual void getSpeciesVdiff(size_t ndim,
const double* grad_T,
int ldx,
const double* grad_X,
int ldf,
double* Vdiff) {
throw NotImplementedError("Transport::getSpeciesVdiff",
"Not implemented for transport model '{}'.", transportModel());
}
//! Get the species diffusive velocities wrt to the mass averaged velocity,
//! given the gradients in mole fraction, temperature, and electrostatic
//! potential.
/*!
* @param[in] ndim Number of dimensions in the flux expressions
* @param[in] grad_T Gradient of the temperature (length = ndim)
* @param[in] ldx Leading dimension of the grad_X array (usually equal to
* m_nsp but not always)
* @param[in] grad_X Gradients of the mole fraction. Flat vector with the
* m_nsp in the inner loop. length = ldx * ndim.
* @param[in] ldf Leading dimension of the fluxes array (usually equal to
* m_nsp but not always)
* @param[in] grad_Phi Gradients of the electrostatic potential
* (length = ndim)
* @param[out] Vdiff Diffusive velocities wrt the mass-averaged velocity.
* Flat vector with the m_nsp in the inner loop. length = ldx
* * ndim. units are m / s.
*
* @deprecated To be removed after %Cantera 3.0. Not implemented by any model.
*/
virtual void getSpeciesVdiffES(size_t ndim,
const double* grad_T,
int ldx,
const double* grad_X,
int ldf,
const double* grad_Phi,
double* Vdiff) {
getSpeciesVdiff(ndim, grad_T, ldx, grad_X, ldf, Vdiff);
}
//! Get the molar fluxes [kmol/m^2/s], given the thermodynamic state at two
//! nearby points.
/*!
* @param[in] state1 Array of temperature, density, and mass fractions for
* state 1.
* @param[in] state2 Array of temperature, density, and mass fractions for
* state 2.
* @param[in] delta Distance from state 1 to state 2 (m).
* @param[out] cfluxes Output array containing the diffusive molar fluxes of
* species from state1 to state2. This is a flat vector with
* m_nsp in the inner loop. length = ldx * ndim. Units are
* [kmol/m^2/s].
*/
virtual void getMolarFluxes(const double* const state1,
const double* const state2, const double delta,
double* const cfluxes) {
throw NotImplementedError("Transport::getMolarFluxes",
"Not implemented for transport model '{}'.", transportModel());
}
//! Get the mass fluxes [kg/m^2/s], given the thermodynamic state at two
//! nearby points.
/*!
* @param[in] state1 Array of temperature, density, and mass
* fractions for state 1.
* @param[in] state2 Array of temperature, density, and mass fractions for
* state 2.
* @param[in] delta Distance from state 1 to state 2 (m).
* @param[out] mfluxes Output array containing the diffusive mass fluxes of
* species from state1 to state2. This is a flat vector with
* m_nsp in the inner loop. length = ldx * ndim. Units are
* [kg/m^2/s].
*/
virtual void getMassFluxes(const double* state1,
const double* state2, double delta,
double* mfluxes) {
throw NotImplementedError("Transport::getMassFluxes",
"Not implemented for transport model '{}'.", transportModel());
}
//! Return a vector of Thermal diffusion coefficients [kg/m/sec].
/*!
* The thermal diffusion coefficient @f$ D^T_k @f$ is defined so that the
* diffusive mass flux of species *k* induced by the local temperature
* gradient is given by the following formula:
*
* @f[
* M_k J_k = -D^T_k \nabla \ln T.
* @f]
*
* The thermal diffusion coefficient can be either positive or negative.
*
* @param dt On return, dt will contain the species thermal diffusion
* coefficients. Dimension dt at least as large as the number of
* species. Units are kg/m/s.
*/
virtual void getThermalDiffCoeffs(double* const dt) {
throw NotImplementedError("Transport::getThermalDiffCoeffs",
"Not implemented for transport model '{}'.", transportModel());
}
//! Returns the matrix of binary diffusion coefficients [m^2/s].
/*!
* @param[in] ld Inner stride for writing the two dimension diffusion
* coefficients into a one dimensional vector
* @param[out] d Diffusion coefficient matrix (must be at least m_k * m_k
* in length.
*/
virtual void getBinaryDiffCoeffs(const size_t ld, double* const d) {
throw NotImplementedError("Transport::getBinaryDiffCoeffs",
"Not implemented for transport model '{}'.", transportModel());
}
//! Return the Multicomponent diffusion coefficients. Units: [m^2/s].
/*!
* If the transport manager implements a multicomponent diffusion
* model, then this method returns the array of multicomponent
* diffusion coefficients. Otherwise it throws an exception.
*
* @param[in] ld The dimension of the inner loop of d (usually equal to m_nsp)
* @param[out] d flat vector of diffusion coefficients, fortran ordering.
* d[ld*j+i] is the D_ij diffusion coefficient (the diffusion
* coefficient for species i due to concentration gradients in
* species j). Units: m^2/s
*/
virtual void getMultiDiffCoeffs(const size_t ld, double* const d) {
throw NotImplementedError("Transport::getMultiDiffCoeffs",
"Not implemented for transport model '{}'.", transportModel());
}
//! Returns a vector of mixture averaged diffusion coefficients
/**
* Mixture-averaged diffusion coefficients [m^2/s]. If the transport
* manager implements a mixture-averaged diffusion model, then this method
* returns the array of mixture-averaged diffusion coefficients. Otherwise
* it throws an exception.
*
* @param d Return vector of mixture averaged diffusion coefficients
* Units = m2/s. Length = n_sp
*/
virtual void getMixDiffCoeffs(double* const d) {
throw NotImplementedError("Transport::getMixDiffCoeffs",
"Not implemented for transport model '{}'.", transportModel());
}
//! Returns a vector of mixture averaged diffusion coefficients
virtual void getMixDiffCoeffsMole(double* const d) {
throw NotImplementedError("Transport::getMixDiffCoeffsMole",
"Not implemented for transport model '{}'.", transportModel());
}
//! Returns a vector of mixture averaged diffusion coefficients
virtual void getMixDiffCoeffsMass(double* const d) {
throw NotImplementedError("Transport::getMixDiffCoeffsMass",
"Not implemented for transport model '{}'.", transportModel());
}
//! Return the polynomial fits to the viscosity of species i
virtual void getViscosityPolynomial(size_t i, double* coeffs) const{
throw NotImplementedError("Transport::getViscosityPolynomial",
"Not implemented for transport model '{}'.", transportModel());
}
//! Return the temperature fits of the heat conductivity of species i
virtual void getConductivityPolynomial(size_t i, double* coeffs) const{
throw NotImplementedError("Transport::getConductivityPolynomial",
"Not implemented for transport model '{}'.", transportModel());
}
//! Return the polynomial fits to the binary diffusivity of species pair (i, j)
virtual void getBinDiffusivityPolynomial(size_t i, size_t j, double* coeffs) const{
throw NotImplementedError("Transport::getBinDiffusivityPolynomial",
"Not implemented for transport model '{}'.", transportModel());
}
//! Return the polynomial fits to the collision integral of species pair (i, j)
virtual void getCollisionIntegralPolynomial(size_t i, size_t j,
double* astar_coeffs,
double* bstar_coeffs,
double* cstar_coeffs) const{
throw NotImplementedError("Transport::getCollisionIntegralPolynomial",
"Not implemented for transport model '{}'.", transportModel());
}
//! Modify the polynomial fits to the viscosity of species i
virtual void setViscosityPolynomial(size_t i, double* coeffs){
throw NotImplementedError("Transport::setViscosityPolynomial",
"Not implemented for transport model '{}'.", transportModel());
}
//! Modify the temperature fits of the heat conductivity of species i
virtual void setConductivityPolynomial(size_t i, double* coeffs){
throw NotImplementedError("Transport::setConductivityPolynomial",
"Not implemented for transport model '{}'.", transportModel());
}
//! Modify the polynomial fits to the binary diffusivity of species pair (i, j)
virtual void setBinDiffusivityPolynomial(size_t i, size_t j, double* coeffs){
throw NotImplementedError("Transport::setBinDiffusivityPolynomial",
"Not implemented for transport model '{}'.", transportModel());
}
//! Modify the polynomial fits to the collision integral of species pair (i, j)
virtual void setCollisionIntegralPolynomial(size_t i, size_t j,
double* astar_coeffs,
double* bstar_coeffs,
double* cstar_coeffs, bool flag){
throw NotImplementedError("Transport::setCollisionIntegralPolynomial",
"Not implemented for transport model '{}'.", transportModel());
}
//! Set model parameters for derived classes
/*!
* This method may be derived in subclasses to set model-specific
* parameters. The primary use of this class is to set parameters while in
* the middle of a calculation without actually having to dynamically cast
* the base Transport pointer.
*
* @param type Specifies the type of parameters to set
* 0 : Diffusion coefficient
* 1 : Thermal Conductivity
* The rest are currently unused.
* @param k Species index to set the parameters on
* @param p Vector of parameters. The length of the vector varies with
* the parameterization
* @deprecated To be removed after %Cantera 3.0.
*/
virtual void setParameters(const int type, const int k, const double* const p) {
throw NotImplementedError("Transport::setParameters",
"Not implemented for transport model '{}'.", transportModel());
}
//! Return the parameters for a phase definition which are needed to
//! reconstruct an identical object using the newTransport function. This
//! excludes the individual species transport properties, which are handled
//! separately.
AnyMap parameters() const;
//! Sets the velocity basis
/*!
* What the transport object does with this parameter is up to the
* individual operator. Currently, this is not functional for most transport
* operators including all of the gas-phase operators.
*
* @param ivb Species the velocity basis
* @deprecated To be removed after %Cantera 3.0.
*/
void setVelocityBasis(VelocityBasis ivb) {
m_velocityBasis = ivb;
}
//! Gets the velocity basis
/*!
* What the transport object does with this parameter is up to the
* individual operator. Currently, this is not functional for most transport
* operators including all of the gas-phase operators.
*
* @returns the velocity basis
* @deprecated To be removed after %Cantera 3.0.
*/
VelocityBasis getVelocityBasis() const {
return m_velocityBasis;
}
//! @name Transport manager construction
//!
//! These methods are used during construction.
//! @{
//! Initialize a transport manager
/*!
* This routine sets up a transport manager. It calculates the collision
* integrals and populates species-dependent data structures.
*
* @param thermo Pointer to the ThermoPhase object
* @param mode Chemkin compatible mode or not. This alters the
* specification of the collision integrals. defaults to no.
* @param log_level Defaults to zero, no logging
*/
virtual void init(ThermoPhase* thermo, int mode=0, int log_level=0) {}
//! Specifies the ThermoPhase object.
/*!
* We have relaxed this operation so that it will succeed when the
* underlying old and new ThermoPhase objects have the same number of
* species and the same names of the species in the same order. The idea
* here is to allow copy constructors and duplicators to work. In order for
* them to work, we need a method to switch the internal pointer within the
* Transport object after the duplication takes place. Also, different
* thermodynamic instantiations of the same species should also work.
*
* @param thermo Reference to the ThermoPhase object that the transport
* object will use
* @deprecated To be removed after %Cantera 3.0. The ThermoPhase object should be
* set as part of the call to `init`.
*/
virtual void setThermo(ThermoPhase& thermo);
//! Set root Solution holding all phase information
//! @deprecated Unused. To be removed after %Cantera 3.0.
virtual void setRoot(shared_ptr<Solution> root);
//! Boolean indicating the form of the transport properties polynomial fits.
//! Returns true if the Chemkin form is used.
virtual bool CKMode() const {
throw NotImplementedError("Transport::CK_Mode",
"Not implemented for transport model '{}'.", transportModel());
}
protected:
//! Enable the transport object for use.
/*!
* Once finalize() has been called, the transport manager should be ready to
* compute any supported transport property, and no further modifications to
* the model parameters should be made.
* @deprecated To be removed after %Cantera 3.0.
*/
void finalize();
//! @}
//! pointer to the object representing the phase
ThermoPhase* m_thermo;
//! true if finalize has been called
//! @deprecated To be removed after %Cantera 3.0
bool m_ready = false;
//! Number of species
size_t m_nsp = 0;
//! Number of dimensions used in flux expressions
//! @deprecated To be removed after %Cantera 3.0
size_t m_nDim;
//! Velocity basis from which diffusion velocities are computed.
//! Defaults to the mass averaged basis = -2
//! @deprecated To be removed after %Cantera 3.0.
int m_velocityBasis = VB_MASSAVG;
//! reference to Solution
//! @deprecated To be removed after %Cantera 3.0
std::weak_ptr<Solution> m_root;
};
}
#endif |
import React, { useState } from "react";
import "./style.css";
import PokemonSelectorModal from "../PokemonSelectorModal";
import PokemonCard from "../PokemonCard";
const PokemonSlot = ({
xpTotal,
setXpTotal,
allPokemons,
setAllPokemons,
loadMore,
setLoadMore,
selectedPokemons,
setSelectedPokemons,
}) => {
const [isOpen, setIsOpen] = useState(false);
const [message, setMessage] = useState("");
const [xpMessage, setXpMessage] = useState(0);
const [instruction, setInstruction] = useState(
"Clique aqui para selecionar seus pokemons!"
);
function selectPokemon(pokemon) {
setInstruction("Clique aqui para trocar sua combinação");
if (selectedPokemons.length >= 6) {
setMessage(
"Você já escolheu 6 pokemons! Reitire um para colocar outro."
);
return;
}
const newMessage = xpTotal + pokemon.base_experience;
setSelectedPokemons((currentList) => [...currentList, pokemon]);
setXpTotal(newMessage);
setXpMessage(newMessage);
}
function removeSelectedPokemon(index) {
const newMessage = xpTotal - selectedPokemons[index].base_experience;
const newSelectedPokemons = [...selectedPokemons];
newSelectedPokemons.splice(index, 1);
setXpTotal(newMessage);
setXpMessage(newMessage);
if (newSelectedPokemons.length === 0) {
setInstruction("Clique aqui para selecionar seus pokemons!");
}
setSelectedPokemons(newSelectedPokemons);
setMessage("");
}
return (
<div className="pokemon-container">
<h2
className="instruction"
onClick={() => {
setIsOpen(!isOpen);
}}
>
{instruction}
</h2>
<div className="selected-pokemons">
{selectedPokemons.map(({ id }, index) => {
const pokemon = allPokemons[id - 1];
return (
<PokemonCard
key={index}
id={pokemon.id}
image={pokemon.sprites.other.dream_world.front_default}
name={pokemon.name}
type={pokemon.types[0].type.name}
baseXp={pokemon.base_experience}
onClick={() => removeSelectedPokemon(index)}
/>
);
})}
</div>
<h3 className="message">{message}</h3>
<h3 className="total-basexp">{xpMessage}</h3>
{isOpen && (
<PokemonSelectorModal
setIsOpen={() => setIsOpen(!isOpen)}
allPokemons={allPokemons}
loadMore={loadMore}
setAllPokemons={setAllPokemons}
selectPokemon={selectPokemon}
setLoadMore={setLoadMore}
/>
)}
</div>
);
};
export default PokemonSlot; |
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace Firma.Data.Model
{
public class ZlecenieKompletacji
{
[Key]
[Display(Name = "Nr zlecenia")]
public int IdZleceniaKompletacji { get; set; }
[Display(Name = "Kontrahent")]
public int IdKontrahenta { get; set; }
[Required]
[Display(Name = "Data wystawienia")]
public DateTime DataWystawienia { get; set; }
[Required]
[Display(Name = "Wymagana data realizacji")]
public DateTime OczekiwanaDataRealizacji { get; set; }
[Display(Name = "Potwierdzona data realizacji")]
public DateTime? PotwierdzonaDataRealizacji { get; set; }
[Display(Name = "Produkt")]
public int IdProduktu { get; set; }
[Required]
[Display(Name = "Ilość")]
public decimal Ilosc { get; set; }
[Display(Name = "Monter")]
public int? IdMontera { get; set; }
[Display(Name = "Priorytet")]
public int? Priorytet { get; set; }
[Display(Name = "Status")]
public string Status { get; set; }
[Display(Name = "Czy aktywne")]
public bool CzyAktywne { get; set; }
[Display(Name = "Czas realizacji [min]")]
public int? CzasZlecenia { get; set; }
[ForeignKey("IdKontrahenta")]
public virtual Kontrahent? Kontrahent { get; set; }
[ForeignKey("IdMontera")]
public virtual Monter? Monter { get; set; }
[ForeignKey("IdProduktu")]
public virtual Produkt? Produkt { get; set; }
public virtual ICollection<ProduktUbocznyZK>? ProduktUbocznyZK { get; set; }
public virtual ICollection<SkladnikZK>? SkladnikZK { get; set; }
}
} |
#ifndef CAMERA_H
#define CAMERA_H
// Third-party Headers
#include "thirdparty/glad/glad.h"
#include "thirdparty/glm/glm.hpp"
#include "thirdparty/glm/gtc/matrix_transform.hpp"
// Custom Headers
#include "Config.h"
// Directions for Camera Movement
enum CAMERA_MOVEMENT
{
CAM_FORWARD,
CAM_BACKWARD,
CAM_LEFT,
CAM_RIGHT,
CAM_UP,
CAM_DOWN,
};
// Camera class for Renderer
class Camera
{
public:
glm::vec3 position; // Camera position
glm::vec3 lookAt; // Look At vector for Camera / Local front vector for camera
glm::vec3 worldUp; // Vector for the World's up direction
glm::vec3 right; // Local right vector for camera
glm::vec3 up; // Local up vector for camera
float yaw; // Angle with Y axis
float pitch; // Angle with X axis
float movementSpeed; // Move speed for camera
float mouseSensitivity; // Rotate speed for camera
float fieldOfView; // FOV or Zoom for camera
// Camera Constructor
Camera(glm::vec3 position_ = CAMERA_ORIGIN, glm::vec3 worldUp_ = WORLD_UP, float yaw_ = YAW, float pitch_ = PITCH);
// Returns the camera's view matrix
glm::mat4 get_view_matrix();
// Processes movement for the camera
void process_keyboard(CAMERA_MOVEMENT direction, float deltaTime);
// Processes rotation for the camera
void process_mouse(float xoffset, float yoffset, float deltaTime, GLboolean constraintPitch = true);
// Processes zoom for the camera
void process_scroll(float yoffset);
private:
// Updates the local basis vectors for the camera
void update_camera_vectors();
};
#endif // !CAMERA_H |
// Gamma correction test program
// Copyright (c) Camilla Berglund <elmindreda@elmindreda.org>
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented; you must not
// claim that you wrote the original software. If you use this software
// in a product, an acknowledgment in the product documentation would
// be appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such, and must not
// be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source
// distribution.
//
//
// This program is used to test the gamma correction functionality for
// both full screen and windowed mode windows
//
#include <GLFW/glfw3.h>
#include <stdio.h>
#include <stdlib.h>
#include "getopt.h"
#define STEP_SIZE 0.1f
static GLfloat gamma_value = 1.0f;
static void usage(void)
{
printf("Usage: gamma [-h] [-f]\n");
}
static void set_gamma(GLFWwindow* window, float value)
{
GLFWmonitor* monitor = glfwGetWindowMonitor(window);
if (!monitor)
monitor = glfwGetPrimaryMonitor();
gamma_value = value;
printf("Gamma: %f\n", gamma_value);
glfwSetGamma(monitor, gamma_value);
}
static void error_callback(int error, const char* description)
{
fprintf(stderr, "Error: %s\n", description);
}
static void key_callback(GLFWwindow* window, int key, int scancode, int action, int mods)
{
if (action != GLFW_PRESS)
return;
switch (key)
{
case GLFW_KEY_ESCAPE:
{
glfwSetWindowShouldClose(window, GL_TRUE);
break;
}
case GLFW_KEY_KP_ADD:
case GLFW_KEY_Q:
{
set_gamma(window, gamma_value + STEP_SIZE);
break;
}
case GLFW_KEY_KP_SUBTRACT:
case GLFW_KEY_W:
{
if (gamma_value - STEP_SIZE > 0.f)
set_gamma(window, gamma_value - STEP_SIZE);
break;
}
}
}
static void framebuffer_size_callback(GLFWwindow* window, int width, int height)
{
glViewport(0, 0, width, height);
}
int main(int argc, char** argv)
{
int width, height, ch;
GLFWmonitor* monitor = NULL;
GLFWwindow* window;
glfwSetErrorCallback(error_callback);
if (!glfwInit())
exit(EXIT_FAILURE);
while ((ch = getopt(argc, argv, "fh")) != -1)
{
switch (ch)
{
case 'h':
usage();
exit(EXIT_SUCCESS);
case 'f':
monitor = glfwGetPrimaryMonitor();
break;
default:
usage();
exit(EXIT_FAILURE);
}
}
if (monitor)
{
const GLFWvidmode* mode = glfwGetVideoMode(monitor);
glfwWindowHint(GLFW_REFRESH_RATE, mode->refreshRate);
glfwWindowHint(GLFW_RED_BITS, mode->redBits);
glfwWindowHint(GLFW_GREEN_BITS, mode->greenBits);
glfwWindowHint(GLFW_BLUE_BITS, mode->blueBits);
width = mode->width;
height = mode->height;
}
else
{
width = 200;
height = 200;
}
window = glfwCreateWindow(width, height, "Gamma Test", monitor, NULL);
if (!window)
{
glfwTerminate();
exit(EXIT_FAILURE);
}
set_gamma(window, 1.f);
glfwMakeContextCurrent(window);
glfwSwapInterval(1);
glfwSetKeyCallback(window, key_callback);
glfwSetFramebufferSizeCallback(window, framebuffer_size_callback);
glMatrixMode(GL_PROJECTION);
glOrtho(-1.f, 1.f, -1.f, 1.f, -1.f, 1.f);
glMatrixMode(GL_MODELVIEW);
glClearColor(0.5f, 0.5f, 0.5f, 0);
while (!glfwWindowShouldClose(window))
{
glClear(GL_COLOR_BUFFER_BIT);
glColor3f(0.8f, 0.2f, 0.4f);
glRectf(-0.5f, -0.5f, 0.5f, 0.5f);
glfwSwapBuffers(window);
glfwWaitEvents();
}
glfwTerminate();
exit(EXIT_SUCCESS);
} |
#!/usr/bin/python3
"""Module for minOperations"""
def minOperations(n):
"""
minOperations
Calculate the mini numb of OPs required to obtain 'n' 'H' characters.
"""
# Outputs should be at least 2 characters: (min, Copy All => Paste)
if n < 2:
return 0
ops, root = 0, 2
while root <= n:
# If 'n' is evenly divisible by 'root'
if n % root == 0:
# Total even divisions by 'root' contribute 2 the total operations
ops += root
# Update 'n' to the remainder after division
n = n // root
# - 'root' to find remaining smaller values that evenly divide 'n'
root -= 1
# Increment 'root' until it evenly divides 'n'
root += 1
return ops |
import 'package:flutter/material.dart';
import 'package:unasplash/componentes/cardTreinoAvaliativo.dart';
import 'package:unasplash/componentes/titulo.dart';
import 'package:unasplash/telas/analiseTreinoAvaliativo.dart';
enum ExerciseFilter { Craw, Costas, Peito, Borboleta, Medley }
void main() {
runApp(MaterialApp(
home: AnaliseComparativa(),
));
}
class AnaliseComparativa extends StatefulWidget {
const AnaliseComparativa({Key? key}) : super(key: key);
@override
State<AnaliseComparativa> createState() => _AnaliseComparativaState();
}
class _AnaliseComparativaState extends State<AnaliseComparativa> {
Set<ExerciseFilter> filters = <ExerciseFilter>{};
TextEditingController busca = TextEditingController();
@override
Widget build(BuildContext context) {
return SingleChildScrollView(
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
children: [
Titulo(
titulo: 'ANÁLISE COMPARATIVA',
subTitulo: 'Filtre, pesquise e compare o desempenho dos atletas!',
),
Padding(
padding: const EdgeInsets.all(20),
child: TextField(
controller: busca,
decoration: InputDecoration(
labelText: 'Nome do atleta',
prefixIcon: Icon(Icons.search),
),
),
),
InkWell(
child: CardTreino(
nomeUsuario: 'Gabriel Lamarca Galdino da Silva',
dataTreino: 'Clique para analisar',
Modalidade: '',
),
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => AnaliseTreinoAvaliativo()),
);
},
),
CardTreino(
nomeUsuario: 'Ana Maria',
dataTreino: 'Clique para analisar',
Modalidade: '',
),
CardTreino(
nomeUsuario: 'João da Silva',
dataTreino: 'Clique para analisar',
Modalidade: '',
),
CardTreino(
nomeUsuario: 'Maria Fernanda',
dataTreino: 'Clique para analisar',
Modalidade: '',
),
CardTreino(
nomeUsuario: 'Pedro Souza',
dataTreino: 'Clique para analisar',
Modalidade: '',
),
CardTreino(
nomeUsuario: 'Mariana Oliveira',
dataTreino: 'Clique para analisar',
Modalidade: '',
),
CardTreino(
nomeUsuario: 'Rafael Santos',
dataTreino: 'Clique para analisar',
Modalidade: '',
),
CardTreino(
nomeUsuario: 'Carla Mendes',
dataTreino: 'Clique para analisar',
Modalidade: '',
),
CardTreino(
nomeUsuario: 'Fernando Rocha',
dataTreino: 'Clique para analisar',
Modalidade: '',
),
CardTreino(
nomeUsuario: 'Isabela Lima',
dataTreino: 'Clique para analisar',
Modalidade: '',
),
],
),
);
}
void buscarAtleta(String value) {
print('valor digitado: $value');
}
} |
Running on the Command Line
__bib2x__ is implemented in [Python](https://www.python.org/). It is started on the command line.
__bib2x__ reads the BibTeX file defined using the **--input *<BIBTEX_FILE>*** option. It converts it to the format defined using the option **--format *<FORMAT>*** and saves it under the name defined using the option **--output *<FILE>***. Currently, only "*json*" is available as destination format.
Examples
--------
```console
bib2x -i turing.bib -o turing.json -f json
```
Converts the BibTeX-file "turing.bib" into the JSON-file "turing.json" with the BibTeX entries.
```console
bib2x -i turing.bib -o turing.html -f html
```
Converts the BibTeX-file "turing.bib" into a file named "turing.html" that contains a HTML list with the BibTeX entries.
Command line arguments
----------------------
The script can be started on the command line with the following options:
* **--input *<BIBTEX_FILE>*** / **-i *<BIBTEX_FILE>***: The BibTeX file to load
* **--output *<FILE>*** / **-o *<FILE>***: The file to write
* **--format *<FORMAT>*** / **-f *<FORMAT>***: The type of file to write ['json']
* **--help**: Show a help message
* **--version**: Show the version information |
import React,{useState} from "react";
import { StyleSheet,Text,View,Button,TextInput,Image,SafeAreaView,TouchableOpacity,StatusBar,Alert } from "react-native";
import {createUserWithEmailAndPassword} from 'firebase/auth';
import {auth} from '../config/firebase';
const backImage = require('../assets/backImage.png');
export default function Signup({navigation}) {
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const onHandleSignup = () => {
if (email !== "" && password !== "") {
createUserWithEmailAndPassword(auth, email, password)
.then(() => console.log("Signup success"))
.catch((err) => Alert.alert("Signup error", err.message));
}
};
return (
<View style={styles.container}>
<Image source={backImage} style={styles.backImage}/>
<View style={styles.whiteSheet}/>
<SafeAreaView style={styles.form}>
<Text style={styles.title}>Sign Up</Text>
<TextInput
style={styles.input}
placeholder="Enter Email"
autoCapitalize="none"
keyboardType="email-address"
textContentType="emailaddress"
autoFocus={true}
value={email}
onChangeText={(text)=>setEmail(text)}
/>
<TextInput
style={styles.input}
placeholder="Enter password"
autoCapitalize="none"
autoCorrect={false}
secureTextEntry={true}
textContentType="password"
value={password}
onChangeText={(text)=>setPassword(text)}
/>
<TouchableOpacity style={styles.button} onPress={onHandleSignup}>
<Text style={{fontWeight:'bold',color:'#fff',fontSize:18}}>Sign Up</Text>
</TouchableOpacity>
<View style={{marginTop:20,flexDirection:'row',alignItems:'center',alignSelf:'center'}}>
<Text style={{color:'gray',fontWeight:'600',fontSize:14}}></Text>
<TouchableOpacity onPress={()=>navigation.navigate("Login")}>
<Text style={{fontWeight:'600',color:'#f57c00',fontSize:14}}>Log In</Text>
</TouchableOpacity>
</View>
</SafeAreaView>
</View>
)
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: "#fff",
},
title: {
fontSize: 36,
fontWeight: 'bold',
color: "orange",
alignSelf: "center",
paddingBottom: 24,
paddingTop:100
},
input: {
backgroundColor: "#F6F7FB",
height: 58,
marginBottom: 20,
fontSize: 16,
borderRadius: 10,
padding: 12,
},
backImage: {
width: "100%",
height: 340,
position: "absolute",
top: 0,
resizeMode: 'cover',
},
whiteSheet: {
width: '100%',
height: '75%',
position: "absolute",
bottom: 0,
backgroundColor: '#fff',
borderTopLeftRadius: 60,
},
form: {
flex: 1,
justifyContent: 'center',
marginHorizontal: 30,
},
button: {
backgroundColor: '#f57c00',
height: 58,
borderRadius: 10,
justifyContent: 'center',
alignItems: 'center',
marginTop: 15,
},
}); |
<!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>选择器</title>
<style>
/* *号选择器是最早加载的,所有的标签都满足,但是只要标签写了任意一个相同的样式都会覆盖*/
/**{
color:#993;
}*/
/*为id为d1容器写样式*/
#d1 {
font-size:22px;
color:#090;
}
/*为网页中class为c1的标签写样式*/
div.c1 {
border:1px solid red;
color:#00f;
}
/*标签选择器*/
/*div {
color:#f00;
}*/
/*子类选择器,为ul中的所有li编写样式*/
#u1 li {
list-style:none;
color:#933;
}
/*ul中的所有span,不管多少级都能匹配*/
/*ul span {
background:#aaa;
color:#f00;
}*/
/*只为ul中的第一级的span添加样式*/
ul > span {
background:#aaa;
color:#f00;
}
/*
子类选择器是所有选择器中最后加载的。
*/
#container li.l1 {
color:#009;
}
/*超链接的默认情况*/
/*使用,表示两个选择器同时使用一个样式*/
a.link:link, a.link:visited {
text-decoration: none;
color:#373;
}
/*鼠标移动上去的情况*/
a.link:hover {
text-decoration: underline;
color:#933;
}
/*点击过后的情况*/
/*a.link:visited {
color:#5b5;
}*/
#u2 li:hover {
background:#eee;
}
/*
nth-child(2)表示第二节点
nth-child(even)所有的偶数节点,odd所有的奇数节点
*/
#u2 li:nth-child(even) {
background: #393;
color:#fff;
}
</style>
</head>
<body>
<div id="container">
<!--一个网页中id是不建议重复的,是唯一标识-->
<div id="d1" class="c1">
我是一个容器
</div>
<div class="c1">
我还是一个容器
</div>
<div class="c1">
我依然是一个容器
</div>
<ul class="c1" id="u1">
<span>还是说明</span>
<li class="l1">列表1</li>
<li class="l1">列表2<span>说明</span></li>
<li class="l1">列表3</li>
<li class="l1">列表4<span>说明</span></li>
<li class="l1">列表5</li>
</ul>
<a href="#t12" class="link">测试内容1</a>
<a href="#t23" class="link">测试内容2</a>
<a href="#t34" class="link">测试内容3</a>
<a href="#t45" class="link">测试内容4</a>
<a href="#t56" class="link">测试内容5</a>
<ul id="u2">
<li>测试列表1</li>
<li>测试列表2</li>
<li>测试列表3</li>
<li>测试列表4</li>
<li>测试列表5</li>
<li>测试列表6</li>
<li>测试列表7</li>
<li>测试列表8</li>
<li>测试列表9</li>
<li>测试列表10</li>
</ul>
</div>
</body>
</html> |
<!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>
button {
width:100px;
height: 60px;
align-items: center;
}
input {
width: 400px;
height: 30px;
border: none;
font-size: 30px;
}
#pre{
font-size:20px;
}
</style>
</head>
<body>
<div style="border: 1px solid #000;width: 412px;float: left;">
<input type="text" value="" id="pre"><br>
<input type="text" value="" id=current><br><br>
<button value="" onclick="ac()">AC</button>
<button value="" onclick="del()">del</button>
<button onclick="delHistory()">del history</button>
<button onclick="negate()">+/-</button><br>
<button value="7" onclick="chooseNumber(value)">7</button>
<button value="8" onclick="chooseNumber(value)">8</button>
<button value="9" onclick="chooseNumber(value)">9</button>
<button value="+" onclick="chooseOperation(value)">+</button><br>
<button value="4" onclick="chooseNumber(value)">4</button>
<button value="5" onclick="chooseNumber(value)">5</button>
<button value="6" onclick="chooseNumber(value)">6</button>
<button value="-" onclick="chooseOperation(value)">-</button><br>
<button value="1" onclick="chooseNumber(value)">1</button>
<button value="2" onclick="chooseNumber(value)">2</button>
<button value="3" onclick="chooseNumber(value)">3</button>
<button value="*" onclick="chooseOperation(value)">x</button><br>
<button value="." onclick="chooseNumber(value)" >.</button>
<button value="0" onclick="chooseNumber(value)">0</button>
<button value="=" onclick="compute(value)">=</button>
<button value="/" onclick="chooseOperation(value)">/</button>
</div>
<div>
<p>History</p>
<div id="history" style="float: left;"></div>
</div>
<script>
var main = '', sub = ''; //biến giá trị hiện tại tạm để so sánh cho nội dung hiển thị
var current = document.getElementById('current')
if(main == '' && current.value.length == 0){
current.value = '0';
sub = current.value;
}
var pre = document.getElementById('pre')
function del(){//hàm xóa
current.value = current.value.toString().slice(0, current.value.length-1);
if(current.value == ''){
current.value = '0';
sub = current.value;
main = '';
}
}
function chooseNumber(value) {//hàm chọn trường hợp hiển thị khi số nhập vào
if(sub == current.value && main == '' ) {//số thứ 1 sau khi nhấn =
current.value = value.toString() ;
main = current.value;
sub = '';
return;
}
else {//số thứ 2 trở đi
if(current.value.includes(value) == true && value == '.' ) return;
current.value += value.toString();
main = current.value;
sub = '' ;
return;
}
}
function chooseOperation(value) {//chọn hiển thị khi +-x/
if(current.value == '') return;
if(current.value.slice(-1) == '.') return;
if( sub == '' && main == current.value) {
if( pre.value !== '' && pre.value.slice(-1) !== '=' ){//tính toán khi bấm liên tiếp phép toán
compute(value);
}else{
sub = current.value;
main = '';
pre.value = `${current.value} ${value}`;
}
}else if( sub == current.value && main == ''){//sau khi vừa nhấn = và có kết quả xong
pre.value = `${current.value} ${value}`;
return;
}
}
function compute(value) {//hàm thực hiện phép toán tổng kết quả và hiển thị
let computation = ``;
computation += `${pre.value}${current.value}`;
let a = pre.value;
let b = current.value;
let result = eval(computation);
if(value == '='){//xét trường hợp nhấn = hay nhấn dấu
pre.value = `${computation} =` ;
current.value = result.toString()
}else{
pre.value = `${result} ${value}`;
current.value = result.toString();
}
//lưu vào localStorage
var history = localStorage.getItem('history') ? JSON.parse(localStorage.getItem('history')) : [] ;
history.push(`${a}${b}=${result}`)
localStorage.setItem('history', JSON.stringify(history));
showHistory();
//giá trị hiện tại = tạm
sub = current.value ;
main = '';
}
function showHistory() {//hiện lịch sử
let arr = localStorage.getItem('history') ? JSON.parse(localStorage.getItem('history')) : [] ;
let show = `<ul>`
arr.forEach(function(value){
show += `<li>${value}</li>`;
})
show += `</ul>` ;
document.getElementById('history').innerHTML = show ;
}
function delHistory(){//xóa lịch sử
localStorage.clear() ;
document.getElementById('history').innerHTML = '' ;
}
function negate() {
if(current.value.slice(0,1) !== '-'){
console.log(current.value.slice(0,1));
current.value = `-${current.value}`;
}else {
current.value = current.value.slice(1);
}
sub = current.value;
main = '';
}
function ac(){
current.value ='0'; pre.value = '';
sub = current.value;
main = '';
}
</script>
</body>
</html> |
//
// CalculatorBrain.swift
// BMI Calculator
//
// Created by bagus on 12/07/23.
// Copyright © 2023 Angela Yu. All rights reserved.
//
import UIKit
struct CalculatorBrain {
var bmi : BMI?
mutating func calculateBMI(height: Float, weight: Float){
let bmiValue = weight/(pow(height/100, 2))
if bmiValue < 18.5 {
bmi = BMI(value: bmiValue, advice: "Eat more piece", color: UIColor.blue)
} else if bmiValue < 24.9 {
bmi = BMI(value: bmiValue, advice: "Fit as a fiddle", color: UIColor.green)
} else {
bmi = BMI(value: bmiValue, advice: "Eat less pies", color: UIColor.red)
}
}
func getBMIValue() -> String {
let newBmi = String(format: "%.1f", bmi?.value ?? "0.0")
return newBmi
}
func getAdvice() -> String {
return bmi?.advice ?? "No advice"
}
func getColor() -> UIColor {
return bmi?.color ?? UIColor.white
}
} |
---
title: Getting Started
description: "A unofficial command loader for aoi.js gen 6."
head:
- tag: meta
attrs:
name: "og:title"
content: "aoi.loader"
- tag: meta
attrs:
name: "og:site_name"
content: "aoi.loader | Unofficial"
id: setup
next: false
prev: false
---
A unofficial command loader for aoi.js gen 6.
### Features
- Supports the new .aoi extension file from aoi gen 7.
- Supports JS files.
- Commands can be reloaded without restarting the client.
- Array of commands in JS files are supported.
---
## Setup
To get started with aoi.loader, follow these steps:
**node.js 16.9.0 or newer is required.**
```bash
npm install aoi.loader
```
---
```js title="index.js"
const { Loader } = require("aoi.loader");
const { AoiClient } = require("aoi.js");
const client = new AoiClient({
database: {
type: "aoi.db",
db: require("@akarui/aoi.db"),
tables: ["main"],
path: "./db",
extraOptions: {
dbType: "KeyValue",
},
},
intents: ["Guilds", "GuildMessages", "MessageContent"],
events: ["onMessage"],
prefix: "BOT PREFIX",
token: "BOT TOKEN",
});
// Loading commands with custom loader.
new Loader(client).load("./commands").then(() => console.log("Source loaded!"));
```
## Commands
All options
```js
[exportCommand: COMMAND_TYPE] {
prototype: PROTOTYPE
name: COMMAND_NAME
channel: CHANNEL_ID
aliases: ALIAS1, ALIAS2, ALIAS3
useIf: old
code: @{
$log[normal aoi.js code inside curly brackets.]
}
}
```
Example (Adding a join command)
```js
[exportCommand: join] {
channel: $getServerVar[channelID]
code: @{
$color[FF0055]
$description[Welcome to $guildName! Enjoy your stay!]
$thumbnail[$userAvatar[$authorID]]
$title[Welcome $username!]
}
}
```
Example (Adding a slash command)
```js
[exportCommand: interaction] {
prototype: slash,
name: ping
code: @{
$interactionReply[Pong! $ping ms]
}
}
```
Example (Using old $if)
```js
[exportCommand: interaction] {
prototype: slash,
name: ping
useIf: old
code: @{
$interactionReply[Pong! $ping ms]
}
}
```
## Updating Commands
:::warning
You must use the built-in function.
:::
`$updateLoader`
Example:
```js
[exportCommand: default] {
name: reload
aliases: update, u, r, restart
code: @{
$color[2F3136]
$addField[Newly added;$get[added] commands.]
$thumbnail[$userAvatar[$clientID]]
$title[Commands reloaded!]
$let[added;$math[$commandsCount - $get[count]]]
$updateLoader
$let[count;$commandsCount]
$onlyIf[$checkContains[$clientOwnerIDs[,];$authorID]==true;You are not my owner.]
}
}
```
- As you know, aoi v6 is not the same as aoi v7, this loader doesn't provide advanced features for ".aoi" files like embedded JS.
- If you want to use the VSC extension, we recommend do not follow autocompletion since types and functions are a bit different between both versions.
- Using this loader will make $updateCommands not work. |
<%@ page import="models.User" %>
<%@ page import="models.OrderDetails" %>
<%@ page import="java.util.List" %>
<%@ page import="java.util.HashMap" %>
<%@ page import="java.util.ArrayList" %>
<%@ page import="java.util.Map" %>
<%@ page import="models.Book" %><%--
Created by IntelliJ IDEA.
User: LSPL322
Date: 15-04-2024
Time: 14:58
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%
User user = (User) session.getAttribute("user");
if (user != null) {
request.setAttribute("userID", user.getUserID());
RequestDispatcher rd = request.getRequestDispatcher("/order");
rd.include(request, response);
} else {
response.sendRedirect("login.jsp");
}
%>
<%
List<Book> books = (List<Book>) session.getAttribute("books");
HashMap<Integer, Book> bookMap = new HashMap<>();
for (Book book : books) {
bookMap.put(book.getId(), book);
}
%>
<%
List<OrderDetails> orderHistory = (List<OrderDetails>) session.getAttribute("orderHistory");
//collect all books with same orderID in one list
HashMap<Integer, ArrayList<OrderDetails>> orderdetails = new HashMap<>();
for (OrderDetails order : orderHistory) {
OrderDetails od = new OrderDetails(order.getBookID(), order.getOrderDate(), order.getTotalAmount(), order.getQuantity());
if (orderdetails.containsKey(order.getOrderID())) {
orderdetails.get(order.getOrderID()).add(od);
} else {
ArrayList<OrderDetails> list = new ArrayList<>();
list.add(od);
orderdetails.put(order.getOrderID(), list);
}
}
System.out.println("Order history from jsp: " + orderHistory);
System.out.println(orderdetails);
%>
<%
ArrayList<OrderDetails> bookOrder = null;
if(request.getParameter("orderID") == null){
} else {
int orderID = Integer.parseInt(request.getParameter("orderID"));
if (orderID > 0 && orderdetails.containsKey(orderID)) {
bookOrder = orderdetails.get(orderID);
} else{
response.sendRedirect("dashboard.jsp");
}
}
%>
<html>
<head>
<title>Order History</title>
<script src="https://cdn.tailwindcss.com"></script>
<link href="css/order.css" rel="stylesheet" type="text/css"/>
</head>
<body>
<!-- Order History Header -->
<h1 class="font-bold mb-4 text-center font-bold text-4xl opacity-60 mb-5 mt-2">
<span class="bg-blue-300 rounded-xl p-4 mb-5 mt-2">Order History</span>
</h1>
<%if(orderdetails.isEmpty()){%>
<div class="flex items-center justify-center h-full bg-blue-100 rounded-xl shadow-lg m-5">
<h2 class="font-bold text-6xl opacity-20 text-center">You have not Ordered anything.</h2>
</div>
<%}else{%>
<div class="grid grid-cols-12 gap-4">
<div class="col-span-4 bg-gray-200 p-4 rounded-xl shadow-xl h-screen max-h-screen overflow-auto">
<div class="">
<%for (Map.Entry<Integer, ArrayList<OrderDetails>> entry : orderdetails.entrySet()) {%>
<div class="w-full mx-auto px-4 py-2">
<a href="orderHistory.jsp?orderID=<%= entry.getKey()%>"
class="block bg-white rounded-lg shadow-lg p-6 mb-6 hover:shadow-xl transition duration-300">
<p class="font-semibold">Order ID: #<%= entry.getKey()%>
</p>
<p class="text-gray-600">Order Date: <%= entry.getValue().get(0).getOrderDate()%>
</p>
<p class="text-gray-600">Total Amount: ₹<%= entry.getValue().get(0).getTotalAmount()%>
</p>
<p class="text-gray-600">Books: <%= entry.getValue().size()%>
</p>
</a>
</div>
<%}%>
</div>
</div>
<div class="col-span-8 bg-gray-300 p-4 h-screen rounded-xl shadow-xl max-h-screen overflow-auto">
<%if (bookOrder == null) {%>
<div class="flex items-center justify-center h-full">
<h2 class="font-bold text-6xl opacity-20 text-center">Select order card to view more details about it</h2>
</div>
<%} else {%>
<div class="container mx-auto px-4 py-8 flex flex wrap items-center justify-between gap-4">
<%
for (OrderDetails od : bookOrder) {
Book book = bookMap.get(od.getBookID());
%>
<a href="bookDetails.jsp?bookID=<%= od.getBookID()%>">
<div class="bg-white shadow-lg rounded-lg w-fit p-2">
<img src="assets/images/photo-1531988042231-d39a9cc12a9a.jpeg" alt="Book Cover"
class="w-full h-64 object-cover rounded-lg">
<div class="p-4">
<h2 class="text-xl font-bold mb-2"><%= book.getTitle()%>
</h2>
<p class="text-gray-600 mb-2">Price:₹ <%= book.getPrice()%>
</p>
<p class="text-gray-600 mb-2">Quantity: <%= od.getQuantity()%>
</p>
</div>
</div>
</a>
<%}%>
</div>
<%}%>
</div>
</div>
<%}%>
</body>
</html> |
<template>
<app-body pageTitle="New Feed" pageSubTitle="School News">
<app-table
:headers="tbHeaders"
:data="tbData.data"
:deleteAction="deleteNews"
:updateAction="updateNews"
:createAction="createNews"
createButton="true"
:form="form"
action="true"
search="true"
title="News Updates"
updateTitle="Update News"
modalTitle="Create News"
tb_classes="table-bordered"
>
<template #extra-action>
<th colspan="2">News Body</th>
<th>Created By</th>
<th>Created On</th>
<th class="text-danger">Publish</th>
</template>
<template v-slot:extra-action-body="{ row }">
<td colspan="2" style="width: 40%">{{ row.content }}</td>
<td>{{ row.users ? row.users.name : "" }}</td>
<td>{{ row.created_at | myDate }}</td>
<td>
<toggle-button
@change="publish(row.id)"
:label="true"
:labels="{
checked: 'ON',
unchecked: 'OFF',
}"
:height="20"
:font-size="14"
:value="row.isPublished"
:color="'green'"
:name="'activated'"
class="pl-2"
/>
</td>
</template>
<template #card-footer>
<pagination
:data="tbData"
@pagination-change-page="paginateData"
/>
</template>
<template #modal-fields>
<input-field
label="Headline"
v-model="form.title"
id="title"
:form="form"
field="title"
type="text"
placeholder="Enter News Headline"
/>
<div class="form-group">
<label for="">News Content</label>
<textarea
v-model="form.content"
id=""
rows="4"
class="form-control"
>
</textarea>
</div>
<div class="form-group">
<label>Upload Image</label>
<input
class="form-control"
id="file"
:form="form"
field="file"
type="file"
ref="file"
@change="setFile"
/>
</div>
</template>
</app-table>
</app-body>
</template>
<script>
export default {
data() {
return {
tbHeaders: [{ header: "Title", key: "title" }],
tbData: [],
user: window.user,
file: "",
form: new Form({
id: "",
title: "",
content: "",
created_by: "",
isPublished: "",
school_id: "",
post_img: "",
}),
};
},
methods: {
paginateData(page = 1) {
axios
.get(`/api/news/page?=${page}`)
.then((res) => {
this.tbData = res.data;
// setTimeout(() => {
// this.componentKey += 1;
// },200)
})
.catch((err) => console.log(err));
},
loadNews() {
axios.get("api/news").then((res) => {
this.tbData = res.data;
});
},
createNews() {
let formData = new FormData();
formData.append("post_img", this.file);
formData.append("title", this.form.title);
formData.append("content", this.form.content);
axios.post("/api/news", formData).then((res) => {
$("#appModal").modal("hide");
swal.fire("success!", " Meeting successfully.", "success");
Fire.$emit("afterCreated");
});
},
updateNews() {
if (this.file) {
let formData = new FormData();
formData.append("post_img", this.file);
formData.append("title", this.form.title);
formData.append("content", this.form.content);
formData.append("id", this.form.id);
formData.append("isPublished", this.form.isPublished);
formData.append("school_id", this.form.school_id);
axios.post("/api/news/update", formData).then((res) => {
$("#appModal").modal("hide");
swal.fire("success!", " Meeting successfully.", "success");
Fire.$emit("afterCreated");
});
} else {
this.form.post("/api/news/update").then((res) => {
$("#appModal").modal("hide");
swal.fire(
"success!",
" News updated successfully.",
"success"
);
Fire.$emit("afterCreated");
});
}
},
deleteNews(id) {
axios
.delete("/api/news/" + id)
.then((res) => Fire.$emit("afterCreated"));
},
setFile() {
this.file = this.$refs.file.files[0];
console.log(this.$refs.file.files[0]);
},
publish(id) {
axios
.put("/api/news/" + id)
.then((res) => Fire.$emit("afterCreated"));
},
},
created() {
this.loadNews();
Fire.$on("afterCreated", () => {
this.loadNews();
});
},
};
</script> |
import React, { useEffect, useRef } from "react";
type Props = {
data: ParsedData;
allData: ParsedData[];
deleteBoxPlot: (index: number) => void;
setNumbers: React.Dispatch<React.SetStateAction<number[]>>;
setDataEditingIndex: React.Dispatch<React.SetStateAction<number>>;
};
export type ParsedData = {
numbers: number[];
title: string;
index: number;
};
type BoxPlotData = {
min: number;
max: number;
median: number;
quartiles: [number, number];
};
export default function BoxPlot({
data,
allData,
deleteBoxPlot,
setNumbers,
setDataEditingIndex,
}: Props) {
const canvasRef = useRef<HTMLCanvasElement>(null);
const margin = 10;
const intervalWitdh = 25;
useEffect(() => {
if (!canvasRef.current) return;
const ctx = canvasRef.current.getContext("2d");
if (!ctx) return;
const drawData = getData();
const height = ctx.canvas.height - 40;
// make background blue
ctx.fillStyle = "lightblue";
ctx.fillRect(0, 0, ctx.canvas.width, ctx.canvas.height);
//draw the number line
ctx.fillStyle = "black";
ctx.font = "12px Arial";
for (let i = 0; i <= 10; i++) {
ctx.textAlign = "center";
ctx.fillText(
i.toString(),
i * intervalWitdh + margin,
ctx.canvas.height - 5
);
ctx.fillRect(i * intervalWitdh + margin, ctx.canvas.height - 25, 1, 5);
}
ctx.fillRect(margin, ctx.canvas.height - 20, 10 * intervalWitdh + 1, 3);
// draw the title
// ctx.textAlign = "left";
// make text bold
ctx.font = "bold 15px Arial";
ctx.fillText(data.title, ctx.canvas.width / 2, 20);
drawBoxPlot(ctx, drawData, height, intervalWitdh, margin);
}, [allData]);
function drawBoxPlot(
ctx: CanvasRenderingContext2D,
data: BoxPlotData,
height: number,
intervalWitdh: number,
margin: number
) {
// draw main line
ctx.fillRect(
margin + data.min * intervalWitdh,
height + 1,
(data.max - data.min) * intervalWitdh,
2.5
);
const whiskersHeight = 10;
// draw quartiles
// color blue
ctx.fillStyle = "blue";
ctx.fillRect(
margin + data.quartiles[0] * intervalWitdh,
height - whiskersHeight / 4,
intervalWitdh * (data.median - data.quartiles[0]),
whiskersHeight
);
// color red
ctx.fillStyle = "red";
// draw other quartile
ctx.fillRect(
margin + data.median * intervalWitdh,
height - whiskersHeight / 4,
intervalWitdh * (data.quartiles[1] - data.median),
whiskersHeight
);
// color black
ctx.fillStyle = "black";
// draw median
ctx.fillRect(
margin + data.median * intervalWitdh,
height - whiskersHeight / 4,
3,
whiskersHeight
);
// draw whiskers
ctx.fillRect(
margin + data.min * intervalWitdh,
height - whiskersHeight / 4,
2,
whiskersHeight
);
ctx.fillRect(
margin + data.max * intervalWitdh,
height - whiskersHeight / 4,
2,
whiskersHeight
);
// create text above the median
ctx.textAlign = "center";
ctx.font = "10px Arial";
ctx.fillText(
data.median.toString(),
margin + data.median * intervalWitdh,
height - whiskersHeight / 2
);
}
function getData(): BoxPlotData {
// sort the data
const sortedData = data.numbers.sort((a, b) => a - b);
// find the center of the sorted data
const center = (values: number[]) => (values.length - 1) / 2;
// check if the data has an even number of values
const isEven = (values: number[]) => values.length % 2 === 0;
// find the median value
const medianFunc = (values: number[]) => {
// find the center index of the sorted data
const centerIndex = center(values);
// if the data has an even number of values, take the average of the
// two center values
if (isEven(values)) {
return (
(values[Math.floor(centerIndex)] + values[Math.ceil(centerIndex)]) / 2
);
}
// if the data has an odd number of values, take the value at the center index
return values[Math.floor(centerIndex)];
};
// get the median value
const median = medianFunc(sortedData);
// return the min, max, median, and quartiles
return {
min: Math.min(...sortedData),
max: Math.max(...sortedData),
median,
quartiles: [
medianFunc(sortedData.slice(0, Math.ceil(center(sortedData)))),
medianFunc(
sortedData.slice(
Math.ceil(center(sortedData)) + (isEven(sortedData) ? 0 : 1)
)
),
],
};
}
const handleClick = (e: React.MouseEvent<HTMLCanvasElement, MouseEvent>) => {
setDataEditingIndex(data.index);
setNumbers(data.numbers);
};
return (
<div className="box">
{/* <div>{data.title}</div> */}
<canvas
data-index={data.index}
onClick={handleClick}
ref={canvasRef}
height={75}
width={margin * 2 + 10 * intervalWitdh}></canvas>
{/* add button with trash icon */}
<button
className="deleteButton"
onClick={deleteBoxPlot.bind(null, data.index)}>
<svg
fill="#fff"
version="1.1"
id="Capa_1"
xmlns="http://www.w3.org/2000/svg"
width="20px"
height="20px"
viewBox="0 0 490.646 490.646">
<g>
<g>
<path
d="M399.179,67.285l-74.794,0.033L324.356,0L166.214,0.066l0.029,67.318l-74.802,0.033l0.025,62.914h307.739L399.179,67.285z
M198.28,32.11l94.03-0.041l0.017,35.262l-94.03,0.041L198.28,32.11z"
/>
<path
d="M91.465,490.646h307.739V146.359H91.465V490.646z M317.461,193.372h16.028v250.259h-16.028V193.372L317.461,193.372z
M237.321,193.372h16.028v250.259h-16.028V193.372L237.321,193.372z M157.18,193.372h16.028v250.259H157.18V193.372z"
/>
</g>
</g>
</svg>
</button>
</div>
);
} |
@page "/"
@implements IAsyncDisposable
@inject IWindowService WindowService
@if (!Popup.HasValue)
{
<PageTitle>Blazor Window - Home</PageTitle>
<p>On this page we try out opening the different user prompts. To try out the other parts of the interface check the menu.</p>
<button class="btn btn-primary" @onclick=Alert >Open Alert</button>
<button class="btn btn-primary" @onclick=Confirm >Open Confirm dialog</button>
<button class="btn btn-primary" @onclick=Prompt >Open Prompt</button>
<br />
@if (response is not null)
{
<p>response: <code>@response</code></p>
}
}
else
{
<PageTitle>Blazor Window - Pop-up</PageTitle>
<h2>Pop-up</h2>
<p>
This is a popup. When you post a message from here the opener window is notified of this.
</p>
<label for="message">Message: </label>
<input @bind=message id="message" class="form-control" />
<br />
<button @onclick=PostMessage class="btn btn-primary">Post</button>
}
@code {
string? response;
string message = "My Pop-up Message";
Window window = default!;
[SupplyParameterFromQuery]
public int? Popup { get; set; }
protected override async Task OnInitializedAsync()
{
window = await WindowService.GetWindowAsync();
}
private async Task Alert()
{
await window.AlertAsync("You need to close this to continue!");
response = null;
}
private async Task Confirm()
{
response = (await window.ConfirmAsync("You need to confirm this to continue!")).ToString();
}
private async Task Prompt()
{
response = (await window.PromptAsync("What is your name?", "Bob"))?.ToString();
}
private async Task PostMessage()
{
await window.PostMessageAsync($"From Pop-up {Popup} \"{message}\"");
}
public async ValueTask DisposeAsync()
{
if (window is not null)
{
await window.DisposeAsync();
}
}
} |
import React, { PureComponent } from 'react';
import { Spin, Menu, Icon, Dropdown, Avatar } from 'antd';
import styles from './index.less';
export default class GlobalHeaderRight extends PureComponent {
render() {
const { currentUser = {}, onMenuClick, theme } = this.props;
const { menuList = [] } = currentUser;
const menu = (
<Menu className={styles.menu} selectedKeys={[]} onClick={onMenuClick}>
<Menu.Item key="userCenter">
<Icon type="user" />
个人中心
</Menu.Item>
<Menu.Divider />
<Menu.Item key="logout">
<Icon type="logout" />
退出登录
</Menu.Item>
</Menu>
);
let className = styles.right;
if (theme === 'dark') {
className = `${styles.right} ${styles.dark}`;
}
return (
<div className={className}>
{menuList.length > 0 ? (
<Dropdown overlay={menu}>
<span className={`${styles.action} ${styles.account}`}>
<Avatar className={styles.avatar} src={currentUser.avatar} alt="avatar" />
</span>
</Dropdown>
) : (
<Spin size="small" style={{ marginLeft: 8, marginRight: 8 }} />
)}
</div>
);
}
} |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Brain Wave</title>
<link href="https://fonts.googleapis.com/css2?family=Roboto:wght@400;700&display=swap" rel="stylesheet">
<style>
/* Base styles */
body {
font-family: 'Roboto', sans-serif;
margin: 0;
padding: 0;
background-color: #f7f7f7;
color: #333;
}
.container {
max-width: 1200px;
margin: auto;
padding: 0 20px;
}
/* Navbar styles */
.navbar {
display: flex;
align-items: center;
background-color: #005f73;
padding: 10px;
overflow: hidden;
}
.logo {
display: flex;
align-items: center;
}
.logo img {
height: 50px; /* You can adjust the size as needed */
}
.logo-text {
margin-left: 10px;
font-size: 24px;
font-weight: bold;
}
/* Adjust the margin of the navbar items to the left */
.navbar-links a {
float: left;
display: block;
color: white;
text-align: right;
padding: 14px 16px;
text-decoration: none;
}
.navbar-links a:hover, .navbar-links a:focus {
background-color: #0a9396;
color: white;
}
.signup-button {
float: right;
background-color: #005f73;
padding: 14px 20px;
}
.signup-button:hover {
background-color: #d79b60;
}
.hero-section {
text-align: center;
padding: 40px 20px;
background: #94d2bd;
}
.hero-section h1 {
color: #fff;
font-size: 2.5em;
margin-bottom: 10px;
}
.hero-section p {
color: #fff;
font-size: 1.2em;
margin-bottom: 30px;
}
.call-to-action {
font-size: 1.2em;
background-color: #ee9b00;
color: white;
padding: 10px 30px;
text-decoration: none;
display: inline;
border-radius: 5px;
transition: background-color 0.3s ease;
}
.call-to-action:hover {
background-color: #ca6702;
}
/* Section styles */
.section {
background-color: white;
margin: 8px 0;
padding: 30px;
border-radius: 8px;
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}
.section-header {
font-size: 2em;
margin-bottom: 20px;
}
/* Footer styles */
.footer {
background-color: #005f73;
color: white;
text-align: center;
padding: 20px;
margin-top: 30px;
}
.brain-wave-section {
background-color: #eef6f6;
padding: 20px;
border-radius: 5px;
margin-top: 20px;
}
.brain-wave-section h3 {
color: #005f73;
}
.brain-wave-section p {
color: #333;
line-height: 1.6;
}
/* Responsive layout */
@media (max-width: 768px) {
.navbar a, .signup-button {
float: none;
display: block;
text-align: left;
}
.hero-section h1 {
font-size: 2em;
}
.hero-section p {
font-size: 1em;
}
}
</style>
</head>
<body>
<div class="navbar">
<div class="logo">
<img src="logo.png" alt="Brain Wave Logo">
<span class="logo-text"></span>
</div>
<div class="navbar-links">
<a href="home.html">Home</a>
<a href="youtube_videos.html">YouTube Videos</a>
<a href="past_questions.html">PY Questions</a>
<a href="notes.html">Notes</a>
<a href="reference_books.html">Reference Books</a>
<a href="signin.html" class="signup-button">Sign In</a>
</div>
</div>
<div class="hero-section">
<h1>Welcome to Brain Wave</h1>
<p>Begin your journey to mastering engineering with curated courses, books, past papers, and extensive resources tailored for first-year engineering students.</p>
<div class="brain-wave-section">
<h3>Welcome to Brain Wave: Your Comprehensive Engineering Resource Platform</h3>
<p>
Brain Wave is the definitive platform for first-year engineering students seeking to consolidate all their academic resources under one roof. Our aim is to streamline your educational journey by providing an extensive library of reference books, past exam question papers, insightful notes, and links to expert-curated YouTube videos—all tailored to the engineering curriculum.
</p>
<p>
Understanding the vast landscape of engineering can be daunting. That's why Brain Wave offers a structured, user-friendly interface that organizes study materials by subject, making it easy for you to find exactly what you need when you need it. Dive into our comprehensive database for everything from complex calculus problems to the fundamentals of electrical engineering.
</p>
<p>
Join the Brain Wave community and elevate your academic performance with access to the best study resources available for budding engineers. Experience a seamless learning journey with Brain Wave, where your first-year engineering resources are just a click away.
</p>
</div>
<a href="#resources" class="call-to-action">Explore Resources</a>
</div>
<div class="container">
<div class="section" id="resources">
<h2 class="section-header">Featured YouTube Videos</h2>
<a href="youtube_videos.html" class="call-to-action">Watch Videos</a>
</div>
<div class="section">
<h2 class="section-header">Latest Past Year Questions</h2>
<p>Access the latest past year questions to test your knowledge and prepare for your exams.</p>
<a href="past_questions.html" class="call-to-action">View Questions</a>
</div>
</div>
<div class="footer">
<p>© 2023 Brain Wave. All rights reserved.</p>
</div>
</body>
</html> |
{{!< default}}
{{! The comment above "< default" means - insert everything in this file into
the {body} of the default.hbs template, which contains our header/footer. }}
{{! Everything inside the #post tags pulls data from the post }}
{{#post}}
<main class="content">
<article class="{{post_class}} p3 sm-p4 mb4 mx-auto bg-white box-shadow">
<header class="post-header center">
<h1 class="post-title mt0">{{title}}</h1>
<div class="post-meta mb3 h5 gray light">
<span class="inline-block px1">
{{#if author.profile_image}}
<img class="circle align-middle border" width="24" src="{{img_url author.profile_image}}" alt="{{author.name}}">
{{/if}}
{{author}}
</span>
<time class="post-date px1" datetime="{{date format='YYYY-MM-DD'}}">{{date format="YYYY-MM-DD"}} {{tags prefix=" - "}}</time>
</div>
</header>
<div class="post-content light mb3 sm-mb4">
{{content}}
</div>
<footer class="post-footer">
{{#if @labs.subscribers}}
<div class="subscribe light p3 mt3 sm-mt4 bg-yellow-light clearfix">
<h3 class="h2 mt0">Subscribe to {{@blog.title}}</h3>
<p class="gray">Get the latest posts delivered right to your inbox.</p>
{{subscribe_form placeholder="Your email address"}}
</div>
{{/if}}
</footer>
</article>
</main>
<!-- <aside class="read-next mx-auto clearfix">
{{#next_post}}
<div class="sm-col-6 right mb3 sm-mb0 read-next-story right-align">
<a class="block px4" href="{{url}}">
<h2 class="h2 mb1">{{title}}</h2>
</a>
</div>
{{/next_post}}
{{#prev_post}}
<div class="sm-col-6 left read-next-story prev">
<a class="block px4" href="{{url}}">
<h2 class="h2 mb1">{{title}}</h2>
</a>
</div>
{{/prev_post}}
</aside> -->
{{/post}} |
interface Props {
label: string;
placeholder: string;
type: "email" | "text" | "password";
autocomplete?: "username" | "current-password";
}
export default function FormInput({ label, type, placeholder, autocomplete }: Props): JSX.Element {
return (
<div className="w-full mb-3">
<label className="block mb-2 text-xs font-bold uppercase text-slate-600">{label}</label>
<input
type={type}
autoComplete={autocomplete}
spellCheck={false}
className="w-full px-3 py-3 text-sm transition-all duration-150 ease-linear bg-white border-0 rounded shadow placeholder-slate-300 text-slate-600 focus:outline-none focus:ring"
placeholder={placeholder}
/>
</div>
);
} |
import { View } from "react-native";
import { useTranslation } from "react-i18next";
import { useFormContext, Controller } from "react-hook-form";
import { HorizontalDivider } from "@/components/HorizontalDivider";
import { Text } from "@/components/Text";
import { Card } from "@/components/Card";
import { TextInput } from "@/components/TextInput";
import type { AccountCreation } from "../../utils/types";
export const SecretPhraseVerification = () => {
const { t } = useTranslation();
const { watch, control } = useFormContext<AccountCreation>();
const seedPhraseVerificationIndex = watch("seedPhraseVerificationIndex");
return (
<View className="flex justify-center items-center gap-8 pt-8">
<View className="gap-4">
<Text size="extraLarge" className="font-bold text-center">
{t("accountWizard.createAccount.verification")}
</Text>
<Text size="large" color="muted" className="text-center">
{t("accountWizard.createAccount.enterSeedPhraseVerification")}
</Text>
</View>
<Card>
<Text
size="large"
color="muted"
className="font-medium text-center"
fullWidth
>
{t("accountWizard.createAccount.verificationHint", {
word: seedPhraseVerificationIndex,
})}
</Text>
<Controller
control={control}
render={({ field: { onChange, onBlur, value } }) => (
<TextInput
placeholder={t(
"accountWizard.createAccount.verificationPlaceholder",
{
word: seedPhraseVerificationIndex,
}
)}
onBlur={onBlur}
onChangeText={onChange}
value={value}
size="large"
extraClassNames="font-medium text-center"
/>
)}
name="seedPhraseVerificationWord"
/>
</Card>
<HorizontalDivider />
<View className="gap-4 w-full">
<Text size="extraLarge" className="font-bold text-center">
{t("accountWizard.createAccount.walletName")}
</Text>
<Card>
<Text size="large" color="muted" className="font-medium text-center">
{t("accountWizard.createAccount.walletNameHint")}
</Text>
<Controller
control={control}
rules={{
required: true,
}}
render={({ field: { onChange, onBlur, value } }) => (
<TextInput
placeholder={t(
"accountWizard.createAccount.walletNamePlaceholder"
)}
onBlur={onBlur}
onChangeText={onChange}
value={value}
extraClassNames="font-medium text-center"
maxLength={30}
/>
)}
name="walletName"
/>
</Card>
</View>
</View>
);
}; |
# High-Access Employees
[[Problem Link]](https://leetcode.com/problems/high-access-employees/)
## You are given a 2D 0-indexed array of strings, access_times, with size n. For each i where 0 <= i <= n - 1, access_times[i][0] represents the name of an employee, and access_times[i][1] represents the access time of that employee. All entries in access_times are within the same day.The access time is represented as four digits using a 24-hour time format, for example, "0800" or "2250".An employee is said to be high-access if he has accessed the system three or more times within a one-hour period.Times with exactly one hour of difference are not considered part of the same one-hour period. For example, "0815" and "0915" are not part of the same one-hour period.Access times at the start and end of the day are not counted within the same one-hour period. For example, "0005" and "2350" are not part of the same one-hour period.Return a list that contains the names of high-access employees with any order you want.
### Solution
```cpp
class Solution {
public:
vector<string> findHighAccessEmployees(vector<vector<string>>& access_times) {
unordered_map<string, vector<int>> mp;
//map to store key-pair of employee name and their access time
for (auto& it : access_times) {
int time = stoi(it[1]);
mp[it[0]].push_back(time);
}
//sort the time of employee access time
for (auto& it : mp) {
sort(it.second.begin(), it.second.end());
}
//traverse through access time array of employees and and check difference between a set of 3 times at a time if it is less than 100 then store it in ans array
vector<string> ans;
for (auto& it : mp) {
vector<int>& times = it.second;
for (int i = 2; i < times.size(); i++) {
if (times[i] - times[i - 2] < 100) {
ans.push_back(it.first);
break;
}
}
}
return ans;
}
};
``` |
import axios from "axios";
import { useFormik } from "formik";
import { useDispatch, useSelector } from "react-redux";
import { setUser } from "../store/loggedInUserReducer";
import { useEffect } from "react";
import { useNavigate } from "react-router-dom";
function LoginPage() {
const dispatch = useDispatch();
const navigate = useNavigate();
const loggedInUser = useSelector(state => state.loggedInUser);
const formik = useFormik({
initialValues: {
username: '',
password: '',
},
onSubmit: async (value) => {
try {
const res = await axios.post(`${import.meta.env.VITE_BASE_URL}/api/v1/login`, {
username: value.username,
password: value.password,
},
{
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
}
})
if (res.status === 200) {
dispatch(setUser(res.data.user));
}
} catch (err) {
// show error
console.log('Something went wrong');
}
}
})
useEffect(() => {
if (loggedInUser) {
navigate('/meal-gallery');
}
}, [loggedInUser])
return (
<>
<form onSubmit={formik.handleSubmit} className="w-50">
<div className="mb-3 row">
<label htmlFor="title" className="form-label col-3">Username: </label>
<div className="col-9">
<input type="text"
className="form-control"
id="username"
placeholder="Enter username..."
value={formik.values.username}
onChange={formik.handleChange}
/>
{
formik.errors.title && <span className="text-danger">{formik.errors.username}</span>
}
</div>
</div>
<div className="mb-3 row">
<label htmlFor="title" className="form-label col-3">Password: </label>
<div className="col-9">
<input type="password"
className="form-control"
id="password"
value={formik.values.password}
onChange={formik.handleChange}
/>
{
formik.errors.title && <span className="text-danger">{formik.errors.password}</span>
}
</div>
</div>
<div className="text-center">
<button type="submit" className="btn btn-primary w-25">Login</button>
</div>
</form>
</>
)
}
export default LoginPage; |
Named Algorithms - QUICKSORT
*******************************
Time Complexity: O(nLogn)
**************************
# include <bits/stdc++.h>
using namespace std;
void Print(vector<int> &v)
{
for(auto x:v)
cout<<x<<" ";
cout<<endl;
}
int Partision(vector<int> &v,int start,int end)
{
int i = start-1;
int pivotElement = v[end];
for(int j=start;j<end;j++)
{
if(v[j]<pivotElement)
{
i++;
swap(v[i],v[j]);
}
}
i++;
swap(v[i],v[end]);
return i;
}
void QuickSort(vector<int> &v,int start,int end)
{
//Taking Pivot at Last Element
if(start<end)
{
int pivotIndex = Partision(v,start,end);
QuickSort(v,start,pivotIndex-1);
QuickSort(v,pivotIndex+1,end);
}
}
int main()
{
vector<int> v={2,5,1,4,2,3,6,6,9,5,7};
int n = v.size();
//QuickSort O(nLogn)
QuickSort(v,0,n-1);
Print(v);
}
NOTE: Why Quick Sort is preferred over MergeSort for sorting Arrays ?
Quick Sort in its general form is an in-place sort (i.e. it doesn’t require any extra storage) whereas merge sort requires O(N) extra storage, N denoting the array size which may be quite expensive. Allocating and de-allocating the extra space used for merge sort increases the running time of the algorithm. Comparing average complexity we find that both type of sorts have O(NlogN) average complexity but the constants differ. For arrays, merge sort loses due to the use of extra O(N) storage space.
Most practical implementations of Quick Sort use randomized version. The randomized version has expected time complexity of O(nLogn). The worst case is possible in randomized version also, but worst case doesn’t occur for a particular pattern (like sorted array) and randomized Quick Sort works well in practice.
Quick Sort is also a cache friendly sorting algorithm as it has good locality of reference when used for arrays.
Quick Sort is also tail recursive, therefore tail call optimizations is done.
Why MergeSort is preferred over QuickSort for Linked Lists ?
In case of linked lists the case is different mainly due to difference in memory allocation of arrays and linked lists. Unlike arrays, linked list nodes may not be adjacent in memory. Unlike array, in linked list, we can insert items in the middle in O(1) extra space and O(1) time. Therefore merge operation of merge sort can be implemented without extra space for linked lists.
In arrays, we can do random access as elements are continuous in memory. Let us say we have an integer (4-byte) array A and let the address of A[0] be x then to access A[i], we can directly access the memory at (x + i*4). Unlike arrays, we can not do random access in linked list. Quick Sort requires a lot of this kind of access. In linked list to access i’th index, we have to travel each and every node from the head to i’th node as we don’t have continuous block of memory. Therefore, the overhead increases for quick sort. Merge sort accesses data sequentially and the need of random access is low.
How to optimize QuickSort so that it takes O(Log n) extra space in worst case?
Please see QuickSort Tail Call Optimization (Reducing worst case space to Log n |
import fruitIntoBaskets from '../../../src/lib/iteration/fruitIntoBaskets/index';
describe('fruitIntoBaskets', () => {
it('should return the maximum number of fruits that can be put into the baskets', () => {
expect(
fruitIntoBaskets({ fruits: ['A', 'B', 'C', 'A', 'C'], baskets: 2 }),
).toBe(3);
expect(
fruitIntoBaskets({ fruits: ['A', 'B', 'C', 'B', 'B', 'C'], baskets: 2 }),
).toBe(5);
expect(
fruitIntoBaskets({
fruits: ['A', 'B', 'C', 'B', 'B', 'C', 'A', 'A', 'A'],
baskets: 2,
}),
).toBe(5);
});
it('should return 0 if no fruits are provided', () => {
expect(fruitIntoBaskets({ fruits: [], baskets: 2 })).toBe(0);
});
it('should handle cases where the number of baskets is greater than the number of fruit types', () => {
expect(fruitIntoBaskets({ fruits: ['A', 'B', 'C'], baskets: 5 })).toBe(3);
});
it('should handle cases where the number of baskets is less than the number of fruit types', () => {
expect(
fruitIntoBaskets({ fruits: ['A', 'B', 'C', 'D', 'E'], baskets: 2 }),
).toBe(2);
});
it('should handle cases where the number of baskets is 0', () => {
expect(
fruitIntoBaskets({ fruits: ['A', 'B', 'C', 'D', 'E'], baskets: 0 }),
).toBe(0);
});
}); |
import os
import numpy as np
import torch
import cv2
from torch.utils.data import Dataset
from PIL import Image
class SemanticSegmentationDataset(Dataset):
def __init__(self, root_dir, joint_transform=None, transform=None, target_transform=None):
self.joint_transform = joint_transform
self.transform = transform
self.target_transform = target_transform
self.root_dir = root_dir
image_file_names = [f for f in os.listdir(self.root_dir+"/images") if '.png' in f]
mask_file_names = [f for f in os.listdir(self.root_dir+"/masks") if '.png' in f]
self.images = sorted(image_file_names)
self.masks = sorted(mask_file_names)
self.id_to_trainid = {}
self.id_to_trainid[0] = 0
for i in range(1, 256):
self.id_to_trainid[i] = 2
def __len__(self):
return len(self.images)
def __getitem__(self, idx):
img = Image.open(os.path.join(self.root_dir+"/images", self.images[idx])).convert('RGB')
mask = Image.open(os.path.join(self.root_dir+"/masks", self.masks[idx])).convert('L')
mask = np.array(mask)
mask_copy = mask.copy()
for k, v in self.id_to_trainid.items():
mask_copy[mask == k] = v
mask = Image.fromarray(mask_copy.astype(np.uint8))
if self.joint_transform is not None:
img, mask = self.joint_transform(img, mask)
edge = cv2.Canny(np.array(mask), 0.1, 0.2)
kernel = np.ones((4, 4), np.uint8)
edge = (cv2.dilate(edge, kernel, iterations=1)>50)*1.0
if self.transform is not None:
img = self.transform(img)
if self.target_transform is not None:
mask = self.target_transform(mask)
return img, mask, edge |
from typing import Any, Dict, List, Type, TypeVar
from attrs import define as _attrs_define
from attrs import field as _attrs_field
T = TypeVar("T", bound="StatisticsMetricModelResult")
@_attrs_define
class StatisticsMetricModelResult:
"""Statistics result for the metric"""
additional_properties: Dict[str, Any] = _attrs_field(init=False, factory=dict)
def to_dict(self) -> Dict[str, Any]:
field_dict: Dict[str, Any] = {}
field_dict.update(self.additional_properties)
field_dict.update({})
return field_dict
@classmethod
def from_dict(cls: Type[T], src_dict: Dict[str, Any]) -> T:
d = src_dict.copy()
statistics_metric_model_result = cls()
statistics_metric_model_result.additional_properties = d
return statistics_metric_model_result
@property
def additional_keys(self) -> List[str]:
return list(self.additional_properties.keys())
def __getitem__(self, key: str) -> Any:
return self.additional_properties[key]
def __setitem__(self, key: str, value: Any) -> None:
self.additional_properties[key] = value
def __delitem__(self, key: str) -> None:
del self.additional_properties[key]
def __contains__(self, key: str) -> bool:
return key in self.additional_properties |
---
title: xPack OpenOCD v0.12.0-1 released
summary: "Version **0.12.0-1** is a new release; it follows the upstream release."
version: "0.12.0-1"
npm_subversion: "1"
upstream_version: "0.12.0"
upstream_commit: "9ea7f3d"
upstream_release_date: "15 Jan 2022"
download_url: https://github.com/xpack-dev-tools/openocd-xpack/releases/tag/v0.12.0-1/
date: 2023-01-30 18:00:11 +0200
comments: true
categories:
- releases
- openocd
tags:
- releases
- openocd
---
[The xPack OpenOCD](https://xpack.github.io/dev-tools/openocd/)
is a standalone cross-platform binary distribution of
[OpenOCD](https://openocd.org).
There are separate binaries for **Windows** (Intel 64-bit),
**macOS** (Intel 64-bit, Apple Silicon 64-bit)
and **GNU/Linux** (Intel 64-bit, Arm 32/64-bit).
{% include note.html content="The main targets for the Arm binaries
are the **Raspberry Pi** class devices (armv7l and aarch64;
armv6 is not supported)." %}
## Download
The binary files are available from GitHub [Releases]({{ page.download_url }}).
## Prerequisites
- GNU/Linux Intel 64-bit: any system with **GLIBC 2.27** or higher
(like Ubuntu 18 or later, Debian 10 or later, RedHat 8 later,
Fedora 29 or later, etc)
- GNU/Linux Arm 32/64-bit: any system with **GLIBC 2.27** or higher
(like Raspberry Pi OS, Ubuntu 18 or later, Debian 10 or later, RedHat 8 later,
Fedora 29 or later, etc)
- Intel Windows 64-bit: Windows 7 with the Universal C Runtime
([UCRT](https://support.microsoft.com/en-us/topic/update-for-universal-c-runtime-in-windows-c0514201-7fe6-95a3-b0a5-287930f3560c)),
Windows 8, Windows 10
- Intel macOS 64-bit: 10.13 or later
- Apple Silicon macOS 64-bit: 11.6 or later
## Install
The full details of installing the **xPack OpenOCD** on various platforms
are presented in the separate
[Install]({{ site.baseurl }}/dev-tools/openocd/install/) page.
### Easy install
The easiest way to install OpenOCD is with
[`xpm`]({{ site.baseurl }}/xpm/)
by using the **binary xPack**, available as
[`@xpack-dev-tools/openocd`](https://www.npmjs.com/package/@xpack-dev-tools/openocd)
from the [`npmjs.com`](https://www.npmjs.com) registry.
With the `xpm` tool available, installing
the latest version of the package and adding it as
a dependency for a project is quite easy:
```sh
cd my-project
xpm init # Only at first use.
xpm install @xpack-dev-tools/openocd@latest
ls -l xpacks/.bin
```
To install this specific version, use:
```sh
xpm install @xpack-dev-tools/openocd@{{ page.version }}.{{ page.npm_subversion }}
```
For xPacks aware tools, like the **Eclipse Embedded C/C++ plug-ins**,
it is also possible to install OpenOCD globally, in the user home folder.
```sh
xpm install --global @xpack-dev-tools/openocd@latest --verbose
```
Eclipse will automatically
identify binaries installed with
`xpm` and provide a convenient method to manage paths.
### Uninstall
To remove the links created by xpm in the current project:
```sh
cd my-project
xpm uninstall @xpack-dev-tools/openocd
```
To completely remove the package from the central xPacks store:
```sh
xpm uninstall --global @xpack-dev-tools/openocd
```
## Compliance
The xPack OpenOCD generally follows the official
[OpenOCD](https://openocd.org) releases.
The current version is based on:
- OpenOCD version {{ page.upstream_version }}, the development commit
[{{ page.upstream_commit }}](https://github.com/xpack-dev-tools/openocd/commit/{{ page.upstream_commit }}/)
from {{ page.upstream_release_date }}.
## Changes
There are no functional changes.
Compared to the upstream, the following changes were applied:
- the `src/openocd.c` file was edited to display the branding string
- the `contrib/60-openocd.rules` file was simplified to avoid protection
related issues.
## Bug fixes
- none
## Enhancements
- none
## Known problems
- none
## Shared libraries
On all platforms the packages are standalone, and expect only the standard
runtime to be present on the host.
All dependencies that are build as shared libraries are copied locally
in the `libexec` folder (or in the same folder as the executable for Windows).
### `DT_RPATH` and `LD_LIBRARY_PATH`
On GNU/Linux the binaries are adjusted to use a relative path:
```console
$ readelf -d library.so | grep runpath
0x000000000000001d (RPATH) Library rpath: [$ORIGIN]
```
In the GNU ld.so search strategy, the `DT_RPATH` has
the highest priority, higher than `LD_LIBRARY_PATH`, so if this later one
is set in the environment, it should not interfere with the xPack binaries.
Please note that previous versions, up to mid-2020, used `DT_RUNPATH`, which
has a priority lower than `LD_LIBRARY_PATH`, and does not tolerate setting
it in the environment.
### `@rpath` and `@loader_path`
Similarly, on macOS, the binaries are adjusted with `install_name_tool` to use a
relative path.
## Documentation
The original documentation is available online:
- <https://openocd.org/doc/pdf/openocd.pdf>
## Build
The binaries for all supported platforms
(Windows, macOS and GNU/Linux) were built using the
[xPack Build Box (XBB)](https://xpack.github.io/xbb/), a set
of build environments based on slightly older distributions, that should be
compatible with most recent systems.
The scripts used to build this distribution are in:
- `distro-info/scripts`
For the prerequisites and more details on the build procedure, please see the
[README-MAINTAINER](https://github.com/xpack-dev-tools/openocd-xpack/blob/xpack/README-MAINTAINER.md) page.
## CI tests
Before publishing, a set of simple tests were performed on an exhaustive
set of platforms. The results are available from:
- [GitHub Actions](https://github.com/xpack-dev-tools/openocd-xpack/actions/)
- [Travis CI](https://app.travis-ci.com/github/xpack-dev-tools/openocd-xpack/builds/)
## Tests
The binaries were testes on Windows 10 Pro 32/64-bit, Intel Ubuntu 18
LTS 64-bit, Intel Xubuntu 18 LTS 32-bit and macOS 10.15.
Install the package with xpm.
The simple test, consists in starting the binaries
only to identify the STM32F4DISCOVERY board.
```sh
.../xpack-openocd-0.12.0-1/bin/openocd -f board/stm32f4discovery.cfg
```
A more complex test consist in programming and debugging a simple blinky
application on the STM32F4DISCOVERY board. The binaries were
those generated by
[simple Eclipse projects](https://github.com/xpack-dev-tools/arm-none-eabi-gcc-xpack/tree/xpack/tests/eclipse)
available in the **xPack GNU Arm Embedded GCC** project.
## Checksums
The SHA-256 hashes for the files are:
```txt
db4b501a059944551365ee6f6dad95f5a7d0808654939f747c167c5da743fdb7
xpack-openocd-0.12.0-1-darwin-arm64.tar.gz
ca569b6bfd9b3cd87a5bc88b3a33a5c4fe854be3cf95a3dcda1c194e8da9d7bb
xpack-openocd-0.12.0-1-darwin-x64.tar.gz
886f65ffd4761619d86f492e1d72086992e72f379b90f9d1a1bcf124f88dcc57
xpack-openocd-0.12.0-1-linux-arm.tar.gz
a86b3ecc256cb870f074a8e633e791ed09102c8ed0d639ae49782c51a404dfbc
xpack-openocd-0.12.0-1-linux-arm64.tar.gz
940f22eccddb0946b69149d227948f77d5917a2c5f1ab68e5d84d614c2ceed20
xpack-openocd-0.12.0-1-linux-x64.tar.gz
5cba78c08ad03aa38549e94186cbb4ec34c384565a40a6652715577e4f1a458f
xpack-openocd-0.12.0-1-win32-x64.zip
```
## Deprecation notices
### 32-bit support
Support for 32-bit Intel Linux and Intel Windows was
dropped in 2022. Support for 32-bit Arm Linux (armv7l) will be preserved
for a while, due to the large user base of 32-bit Raspberry Pi systems.
### Linux minimum requirements
Support for RedHat 7 was dropped in 2022 and the
minimum requirement was raised to GLIBC 2.27, available starting
with Ubuntu 18, Debian 10 and RedHat 8.
## Download analytics
- GitHub [xpack-dev-tools/openocd-xpack](https://github.com/xpack-dev-tools/openocd-xpack/)
- this release [](https://github.com/xpack-dev-tools/openocd-xpack/releases/v{{ page.version }}/)
- all xPack releases [](https://github.com/xpack-dev-tools/openocd-xpack/releases/)
- all GNU MCU Eclipse releases [](https://github.com/gnu-mcu-eclipse/openocd/releases/)
- [individual file counters](https://somsubhra.github.io/github-release-stats/?username=xpack-dev-tools&repository=openocd-xpack) (grouped per release)
- npmjs.com [@xpack-dev-tools/openocd](https://www.npmjs.com/package/@xpack-dev-tools/openocd)
- latest releases [](https://www.npmjs.com/package/@xpack-dev-tools/openocd/)
- all @xpack-dev-tools releases [](https://www.npmjs.com/package/@xpack-dev-tools/openocd/)
- all @gnu-mcu-eclipse releases [](https://www.npmjs.com/package/@gnu-mcu-eclipse/openocd/)
Credit to [Shields IO](https://shields.io) for the badges and to
[Somsubhra/github-release-stats](https://github.com/Somsubhra/github-release-stats)
for the individual file counters. |
import { Metadata } from '@polkadot/types';
import { TypeRegistry } from '@polkadot/types';
import { MetadataVersioned } from '@polkadot/types/metadata/MetadataVersioned';
import memoizee from 'memoizee';
import { isBrowser } from '../util';
import { toSpecifiedCallsOnlyV14 } from './toSpecifiedCallsOnlyV14';
/**
* From a metadata hex string (for example returned by RPC), create a Metadata
* class instance. Metadata decoding is expensive, so this function is
* memoized.
*
* @ignore
* @param registry - The registry of the metadata.
* @param metadata - The metadata as hex string.
* @param asCallsOnlyArg - Option to decreases the metadata to calls only
*/
export function createMetadataUnmemoized(
registry: TypeRegistry,
metadataRpc: `0x${string}`,
asCallsOnlyArg = false,
asSpecifiedCallsOnlyV14?: string[],
): Metadata | MetadataVersioned {
const metadata = new Metadata(registry, metadataRpc);
if (asSpecifiedCallsOnlyV14 && asSpecifiedCallsOnlyV14.length > 0) {
return new MetadataVersioned(registry, {
magicNumber: metadata.magicNumber,
metadata: registry.createTypeUnsafe('MetadataAll', [
toSpecifiedCallsOnlyV14(
registry,
metadata.asV14,
asSpecifiedCallsOnlyV14,
),
14,
]),
});
}
return asCallsOnlyArg ? metadata.asCallsOnly : metadata;
}
/**
* From a metadata hex string (for example returned by RPC), create a Metadata
* class instance. Metadata decoding is expensive, so this function is
* memoized.
*
* @ignore
* @param registry - The registry of the metadata.
* @param metadata - The metadata as hex string.
* @param asCallsOnlyArg - Option to decreases the metadata to calls only
*/
export const createMetadata = memoizee(createMetadataUnmemoized, {
length: 4,
max:
!isBrowser &&
typeof process?.env?.TXWRAPPER_METADATA_CACHE_MAX !== 'undefined'
? parseInt(process.env.TXWRAPPER_METADATA_CACHE_MAX)
: undefined,
maxAge:
!isBrowser &&
typeof process?.env?.TXWRAPPER_METADATA_CACHE_MAX_AGE !== 'undefined'
? parseInt(process.env.TXWRAPPER_METADATA_CACHE_MAX_AGE)
: undefined,
}); |
import { deepFreeze } from "./object"
describe("object Unit Tests", () => {
it("should not freeze a scalar value", () => {
let str = deepFreeze("a")
expect(typeof str).toBe("string")
let boolean = deepFreeze(true)
expect(typeof boolean).toBe("boolean")
boolean = deepFreeze(false)
expect(typeof boolean).toBe("boolean")
const num = deepFreeze(5)
expect(typeof num).toBe("number")
})
it("should be an immutable object", () => {
let obj = deepFreeze({
prop1: "value1",
deep: { prop2: "value2", prop3: new Date() }
})
expect(() => (obj as any).prop1 = "test")
.toThrow("Cannot assign to read only property 'prop1' of object '#<Object>'")
expect(() => (obj as any).deep.prop2 = "test")
.toThrow("Cannot assign to read only property 'prop2' of object '#<Object>'")
expect(obj.deep.prop3).toBeInstanceOf(Date)
})
}) |
<!DOCTYPE html>
<html lang="pt-br">
<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>PokemonDB</title>
<!-- <link rel="stylesheet" href="../card/style.css" /> -->
<link rel="stylesheet" href="card/dashboards.css" />
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.2/css/all.min.css"
integrity="sha512-z3gLpd7yknf1YoNbCzqRKc4qyor8gaKU1qmn+CShxbuBusANI9QpRohGBreCFkKxLhei6S9CQXFEbbKuqLg0DA=="
crossorigin="anonymous" referrerpolicy="no-referrer" />
<link rel="preconnect" href="https://fonts.gstatic.com" />
<link
href="https://fonts.googleapis.com/css2?family=Exo+2:ital,wght@0,100;0,200;0,300;0,400;0,500;0,600;0,700;0,800;0,900;1,100;1,200;1,300;1,400;1,500;1,600;1,700;1,800;1,900&display=swap"
rel="stylesheet" />
<!-- scripts do Chart.js - 2022-1 -->
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script src="../js/funcoes.js"></script>
<!--FONT AWESOME-->
<script src="https://kit.fontawesome.com/9f7414eb10.js" crossorigin="anonymous"></script>
</head>
<!-- <body onload=" atualizarFeed()"> -->
<body>
<header>
<div class="hello">
<h3>Olá, <span id="b_usuario"></span>!</h3>
</div>
<ul class="navlist">
<li>
<div class="btn-nav-white">
<a href="edicao.html">
<h3>Editar</h3>
</a>
</div>
</li>
<li>
<div class="btn-logout" onclick="limparSessao()">
<h3>Sair</h3>
</div>
</li>
</ul>
</header>
</div>
<div id="main">
<section>
<h1>Cadastre um pokémon!</h1>
<div class="divCadastro">
<input type="number" id="input_pokemon" placeholder="001" />
<button onclick="cadastrar()">+</i></button>
</div>
<div id="teste"></div>
</section>
<article>
<div class="gráfico">
<canvas id="myChartCanvas"> </canvas>
</div>
</article>
</div>
</body>
</html>
<script>
b_usuario.innerHTML = sessionStorage.NOME_USUARIO;
let proximaAtualizacao;
// window.onload = obterDadosGraficos();
function obterDadosGraficos() {
obterDadosGrafico(1);
obterDadosGrafico(2);
obterDadosGrafico(3);
obterDadosGrafico(4);
}
// verificar_autenticacao();
function cadastrar() {
//Recupere o valor da nova input pelo nome do id
// Agora vá para o método fetch logo abaixo
var pokemonVar = Number(input_pokemon.value);
// se a input estivar vázia não registrará nada e manda um aviso
if (pokemonVar == "") {
alert("Adionar um pokemon");
}
// com um número dentro da input, entrará no fetch
// Enviando o valor da nova input
fetch("/pokemon/cadastrar", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
// crie um atributo que recebe o valor recuperado aqui
// Agora vá para o arquivo routes/usuario.js
pokemonServer: pokemonVar,
usuarioServer: 1,
}),
})
.then(function (resposta) {
if (resposta.ok) {
console.log(resposta);
listar();
} else {
resposta.text().then((texto) => {
console.error(texto);
finalizarAguardar(texto)
// window.location = "dashboard.html";
});
}
})
.catch(function (erro) {
console.log(erro);
});
return false;
}
// uma lista será criada com os pokémon que foram registrados;
window.onload = listar()
function listar() {
fetch("/pokemon/listar")
.then(function (resposta) {
console.log("ESTOU NO THEN DO listar()!");
if (resposta.ok) {
if (resposta.status == 204) {
var feed = document.getElementById("feed_container");
var mensagem = document.createElement("span");
mensagem.innerHTML = "Nenhum resultado encontrado.";
feed.appendChild(mensagem);
throw "Nenhum resultado encontrado!!";
}
resposta.json().then(function (resposta) {
console.log("Dados recebidos: ", JSON.stringify(resposta));
// console.log(reposta.reverse())
resposta.reverse();
var feed = document.getElementById("teste");
feed.innerHTML = "";
for (let i = 0; i < resposta.length; i++) {
var publicacao = resposta[i];
// criando e manipulando elementos do HTML via JavaScript
var divPublicacao = document.createElement("div");
console.log(publicacao);
divPublicacao.innerHTML += `<br> ${publicacao.fkPokemon},${publicacao.Name}${publicacao.Type},`;
feed.appendChild(divPublicacao);
}
setTimeout(plotarGrafico(resposta, 1));
});
} else {
throw "Houve um erro na API!";
}
})
.catch(function (resposta) {
console.error(resposta);
});
}
// // Esta função *plotarGrafico* usa os dados capturados na função anterior para criar o gráfico
// // Configura o gráfico (cores, tipo, etc), materializa-o na página e,
// // A função *plotarGrafico* também invoca a função *atualizarGrafico*
function plotarGrafico(resposta, idAquario) {
console.log("iniciando plotagem do gráfico...");
// Criando estrutura para plotar gráfico - labels
// colunas criadas dentro do gráfico
let labels = ['fogo', 'agua', 'gelo', 'grama', 'dragao', 'terra', 'lutador', 'fada', 'inseto', 'normal', 'escuridao', 'psiquico', 'fantasma', 'metal', 'veneno', 'rocha'];
// Criando estrutura para plotar gráfico - dados
let dados = {
labels: labels,
datasets: [
{
label: "Tipo",
data: [],
fill: false,
borderColor: "rgb(75, 192, 192)",
// cores de acordo com o tipo de pokémon(agua= azul, fogo = vermelho, gelo = azul claro e etc...)
backgroundColor: ["#FF4422", "#3399ff ", "#66CCFF", "#77CC55", "#7766EE", "BBAA66", "BB5544", "#EE99EE", "#AABB22", "#AAAA99", "#775522", "#FF5599", "#6666BB", "BBAA66", "#AAAABB", "#BBAA66"],
tension: 0.1,
}
],
};
console.log("----------------------------------------------");
console.log(
'Estes dados foram recebidos pela funcao "obterDadosGrafico" e passados para "plotarGrafico":'
);
console.log(resposta);
var fogo = 0
var agua = 0
var gelo = 0
var grama = 0
var dragao = 0
var terra = 0
var lutador = 0
var fada = 0
var inseto = 0
var normal = 0
var fantasma = 0
var psiquico = 0
var eletrico = 0
var voador = 0
var escuridao = 0
var rocha = 0
var veneno = 0
var metal = 0
//
// caso o reposta[i].type for de água, adicionará um ponto na variavel agua
for (i = 0; i < resposta.length; i++) {
var tipo = resposta[i]
if (tipo.Type == 'Water' || tipo.Type2 == 'Water') {
agua++
}
if (tipo.Type == 'Fire' || tipo.Type2 == 'Fire') {
fogo++
}
if (tipo.Type == 'Ice' || tipo.Type2 == 'Ice') { gelo++ }
if (tipo.Type == 'Grass' || tipo.Type2 == 'Grass') { grama++ }
if (tipo.Type == 'Dragon' || tipo.Type2 == 'Dragon') { dragao++ }
if (tipo.Type == 'Ground' || tipo.Type2 == 'Ground') { terra++ }
if (tipo.Type == 'Fighter' || tipo.Type2 == 'Fighter') { lutador++ }
if (tipo.Type == 'Fairy' || tipo.Type2 == 'Fairy') { fada++ }
if (tipo.Type == 'Bug' || tipo.Type2 == 'Bug') { inseto++ }
if (tipo.Type == 'Flying' || tipo.Type2 == 'Flying') { voador++ }
if (tipo.Type == 'Psychic' || tipo.Type2 == 'Psychic') { psiquico++ }
if (tipo.Type == 'Eletric' || tipo.Type2 == 'Eletric') { eletrico++ }
if (tipo.Type == 'Ghost' || tipo.Type2 == 'Ghost') { fantasma++ }
if (tipo.Type == 'Normal' || tipo.Type2 == 'Normal') { normal++ }
if (tipo.Type == 'Dark' || tipo.Type2 == 'Dark') { escuridao++ }
if (tipo.Type == 'Steel' || tipo.Type2 == 'Steel') { metal++ }
if (tipo.Type == 'Rock' || tipo.Type2 == 'Rock') { rocha++ }
if (tipo.Type == 'Poison' || tipo.Type2 == 'Poison') { veneno++ }
console.log(tipo)
}
var tipo = [fogo, agua, gelo, grama, dragao, terra, lutador, fada, inseto, normal, escuridao, psiquico, fantasma, metal, veneno, rocha]
console.log(tipo)
// Inserindo valores recebidos em estrutura para plotar o gráfico
for (i = 0; i < 18; i++) {
var registro = resposta[i];
console.log("REGISTRO " + registro)
// labels.push("fogo");
dados.datasets[0].data.push(tipo[i]);
// if (registro.Type === "Water") {
// tipoAgua++
// } else {
// console.log("falha no teste")
// }
}
console.log("----------------------------------------------");
console.log("O gráfico será plotado com os respectivos valores:");
console.log("Labels:");
console.log(labels);
console.log("Dados:");
console.log(dados.datasets);
console.log("----------------------------------------------");
// Criando estrutura para plotar gráfico - config
const config = {
type: "bar",
data: dados,
// options: {
// scales: {
// y: {
// beginAtZero: true,
// },
// },
// },
};
// Adicionando gráfico criado em div na tela
let myChart = new Chart(document.getElementById(`myChartCanvas`), config);
// setTimeout(() => atualizarGrafico(idAquario, dados, myChart), 2000);
}
// Esta função *atualizarGrafico* atualiza o gráfico que foi renderizado na página,
// buscando a última medida inserida em tabela contendo as capturas,
// Se quiser alterar a busca, ajuste as regras de negócio em src/controllers
// Para ajustar o "select", ajuste o comando sql em src/models
function atualizarGrafico(idAquario, dados, myChart) {
fetch(`/medidas/tempo-real/${idAquario}`, { cache: "no-store" })
.then(function (response) {
if (response.ok) {
response.json().then(function (novoRegistro) {
console.log(`Dados recebidos: ${JSON.stringify(novoRegistro)}`);
console.log(`Dados atuais do gráfico:`);
console.log(dados);
let avisoCaptura = document.getElementById(
`avisoCaptura${idAquario}`
);
avisoCaptura.innerHTML = "";
if (
novoRegistro[0].momento_grafico ==
dados.labels[dados.labels.length - 1]
) {
console.log(
"---------------------------------------------------------------"
);
console.log(
"Como não há dados novos para captura, o gráfico não atualizará."
);
avisoCaptura.innerHTML =
"<i class='fa-solid fa-triangle-exclamation'></i> Foi trazido o dado mais atual capturado pelo sensor. <br> Como não há dados novos a exibir, o gráfico não atualizará.";
console.log("Horário do novo dado capturado:");
console.log(novoRegistro[0].momento_grafico);
console.log("Horário do último dado capturado:");
console.log(dados.labels[dados.labels.length - 1]);
console.log(
"---------------------------------------------------------------"
);
} else {
// tirando e colocando valores no gráfico
dados.labels.shift(); // apagar o primeiro
dados.labels.push(novoRegistro[0].momento_grafico); // incluir um novo momento
dados.datasets[0].data.shift(); // apagar o primeiro de umidade
dados.datasets[0].data.push(novoRegistro[0].umidade); // incluir uma nova medida de umidade
dados.datasets[1].data.shift(); // apagar o primeiro de temperatura
dados.datasets[1].data.push(novoRegistro[0].temperatura); // incluir uma nova medida de temperatura
myChart.update();
}
// Altere aqui o valor em ms se quiser que o gráfico atualize mais rápido ou mais devagar
proximaAtualizacao = setTimeout(
() => atualizarGrafico(idAquario, dados, myChart),
2000
);
});
} else {
console.error("Nenhum dado encontrado ou erro na API");
// Altere aqui o valor em ms se quiser que o gráfico atualize mais rápido ou mais devagar
proximaAtualizacao = setTimeout(
() => atualizarGrafico(idAquario, dados, myChart),
2000
);
}
})
.catch(function (error) {
console.error(
`Erro na obtenção dos dados p/ gráfico: ${error.message}`
);
});
}
</script> |
import userModel from "@/models/users";
import { connectToDB } from "@/utils/databse";
import NextAuth from "next-auth/next";
import CredentialsProvider from "next-auth/providers/credentials";
import bcrypt from "bcryptjs";
export const authOptions = {
providers: [
CredentialsProvider({
name: "credentials",
Credentials: {},
async authorize(credentials) {
const { username, password } = credentials;
try {
await connectToDB();
const user = await userModel.findOne({ username });
if (!user) return null;
const passwordsMatch = await bcrypt.compare(password, user.password);
if (!passwordsMatch) return null;
return user;
} catch (error) {
console.log("Unable to login", error);
}
},
}),
],
session: {
strategy: "jwt",
},
secret: process.env.NEXTAUTH_SECRET,
pages: {
signIn: "/signin",
},
callbacks: {
async session({ session, token }) {
session.user = token.user;
return session;
},
async jwt({ token, user }) {
if (user) {
token.user = user;
}
return token;
},
},
};
const handler = NextAuth(authOptions);
export { handler as GET, handler as POST }; |
// *************** BFS IS BETTER THAN DP **************************
// DP
class Solution
{
public:
int numSquares(int n)
{
if (n <= 0)
{
return 0;
}
// cntPerfectSquares[i] = the least number of perfect square numbers
// which sum to i. Note that cntPerfectSquares[0] is 0.
vector<int> cntPerfectSquares(n + 1, INT_MAX);
cntPerfectSquares[0] = 0;
for (int i = 1; i <= n; i++)
{
// For each i, it must be the sum of some number (i - j*j) and
// a perfect square number (j*j).
for (int j = 1; j*j <= i; j++) //check for all possible perfect squares less than i, and choose minimum of them
{
cntPerfectSquares[i] = min(cntPerfectSquares[i], cntPerfectSquares[i - j*j] + 1); // +1 bcz we are conisdering it
}
}
return cntPerfectSquares.back();
}
};
// ----------------------------------------------
// BFS
/*
class Solution
{
public:
int numSquares(int n)
{
if (n <= 0)
{
return 0;
}
// perfectSquares contain all perfect square numbers which
// are smaller than or equal to n.
vector<int> perfectSquares;
// cntPerfectSquares[i - 1] = the least number of perfect
// square numbers which sum to i.
vector<int> cntPerfectSquares(n);
// Get all the perfect square numbers which are smaller than
// or equal to n.
for (int i = 1; i*i <= n; i++)
{
perfectSquares.push_back(i*i);
cntPerfectSquares[i*i - 1] = 1;
}
// If n is a perfect square number, return 1 immediately.
if (perfectSquares.back() == n)
{
return 1;
}
// Consider a graph which consists of number 0, 1,...,n as
// its nodes. Node j is connected to node i via an edge if
// and only if either j = i + (a perfect square number) or
// i = j + (a perfect square number). Starting from node 0,
// do the breadth-first search. If we reach node n at step
// m, then the least number of perfect square numbers which
// sum to n is m. Here since we have already obtained the
// perfect square numbers, we have actually finished the
// search at step 1.
queue<int> searchQ;
for (auto& i : perfectSquares)
{
searchQ.push(i);
}
int currCntPerfectSquares = 1;
while (!searchQ.empty())
{
currCntPerfectSquares++;
int searchQSize = searchQ.size();
for (int i = 0; i < searchQSize; i++)
{
int tmp = searchQ.front();
// Check the neighbors of node tmp which are the sum
// of tmp and a perfect square number.
for (auto& j : perfectSquares)
{
if (tmp + j == n)
{
// We have reached node n.
return currCntPerfectSquares;
}
else if ((tmp + j < n) && (cntPerfectSquares[tmp + j - 1] == 0))
{
// If cntPerfectSquares[tmp + j - 1] > 0, this is not
// the first time that we visit this node and we should
// skip the node (tmp + j).
cntPerfectSquares[tmp + j - 1] = currCntPerfectSquares;
searchQ.push(tmp + j);
}
else if (tmp + j > n)
{
// We don't need to consider the nodes which are greater ]
// than n.
break;
}
}
searchQ.pop();
}
}
return 0;
}
};
*/ |
/* eslint-disable @typescript-eslint/no-explicit-any */
/* eslint-disable @typescript-eslint/no-unused-vars */
import { Test, TestingModule } from "@nestjs/testing";
import { FestivalController } from './festival.controller';
import { FestivalService } from "./festival.service";
import { Gender, Genre, IArtist, IFestival, ITicket, PersonalizationStatus, TicketStatus } from "@blavoss-cswdi/shared/api";
import { Types } from "mongoose";
import { ArtistService } from "../artist/artist.service";
import { Neo4jService } from "@blavoss-cswdi/backend/data-access";
import * as dotenv from 'dotenv';
import { NotFoundException } from "@nestjs/common";
describe('festivalContoller', () => {
let app: TestingModule;
let fController: FestivalController;
let fService: FestivalService;
let aService: ArtistService;
let neo4Service: Neo4jService;
const mockFestivals: IFestival[] = [
{
_id: new Types.ObjectId('5e9c8d19ed1d9c001783b6f8').toString(),
name: 'Festival 1',
location: 'Location 1',
startDate: new Date(2024, 9, 12),
endDate: new Date(2024, 9, 15),
description: 'Description 1',
ticketPrice: 10,
image: 'image 1',
genre: Genre.Dubstep,
artists: [],
tickets: []
},
{
_id: new Types.ObjectId('5e9c8d19ed1d9c001783b6f9').toString(),
name: 'Festival 2',
location: 'Location 2',
startDate: new Date(2024, 9, 12),
endDate: new Date(2024, 9, 15),
description: 'Description 2',
ticketPrice: 20,
image: 'image 2',
genre: Genre.EDM,
artists: [],
tickets: []
}
];
const mockArtists: IArtist[] = [
{
name: 'Artist 1',
genre: Genre.EDM,
description: 'hello w113',
image: 'image 1',
festivals: []
},
{
name: 'Artist 2',
genre: Genre.Dubstep,
description: 'hello w113',
image: 'image 2',
festivals: []
}
]
const mockTickets: ITicket[] = [
{
_id: new Types.ObjectId('5e9c8d19ed1d9c001783b6f8'),
userId: { _id: new Types.ObjectId('5e9c8d19ed1d9c001783b6f8').toString(), email: 'User 1', hash: '12312', firstName: 'test', lastName: 'test', dob: new Date(), gender: Gender.Male},
festivalId: mockFestivals[0],
ticketAmount: 10,
purchaseDate: new Date(),
status: TicketStatus.Purchased,
PersonalizationStatus: PersonalizationStatus.NotPersonalized,
}
]
beforeAll(async () => {
dotenv.config();
app = await Test.createTestingModule({
controllers: [FestivalController],
providers: [
{
provide: FestivalService,
useValue: {
getAll: jest.fn(),
getOne: jest.fn(),
delete: jest.fn(),
create: jest.fn(),
update: jest.fn(),
addArtistToFestival: jest.fn(),
removeArtistFromFestival: jest.fn(),
addTicketToFestival: jest.fn(),
}
},
{
provide: ArtistService,
useValue: {
getAll: jest.fn(),
getOne: jest.fn(),
delete: jest.fn(),
create: jest.fn(),
update: jest.fn(),
addFestivalToArtist: jest.fn(),
removeFestivalFromArtist: jest.fn(),
}
},
{
provide: Neo4jService,
useValue: {
getRecommendedFestivalForUser: jest.fn(),
}
}
],
}).compile();
fController = app.get<FestivalController>(FestivalController);
fService = app.get<FestivalService>(FestivalService);
aService = app.get<ArtistService>(ArtistService);
// setup neo4j connection
const neo4jApp = await Test.createTestingModule({
providers: [Neo4jService],
}).compile();
neo4Service = neo4jApp.get<Neo4jService>(Neo4jService);
});
describe('getAll', () => {
it('should call getAll on the service', async () => {
// arrange
const getAll = jest.spyOn(fService, 'getAll').mockImplementation(async () => [mockFestivals[0], mockFestivals[1]]);
// act
const results = await fController.getAll();
//assert
expect(getAll).toHaveBeenCalled();
expect(results).toHaveLength(2);
expect(results[0]).toEqual(mockFestivals[0]);
});
});
describe('getOne', () => {
it('should call getOne on the service', async () => {
// arrange
const getOne = jest.spyOn(fService, 'getOne').mockImplementation(async () => mockFestivals[0]);
// act
const results = await fController.getOne(mockFestivals[0]._id!.toString());
//assert
expect(getOne).toHaveBeenCalled();
expect(results).toEqual(mockFestivals[0]);
});
it('should return error when festival not found', async () => {
// arrange
const getOne = jest.spyOn(fService, 'getOne').mockImplementation(async () => {
throw new NotFoundException();
});
// act & assert
await expect(fController.getOne(mockFestivals[0]._id!.toString())).rejects.toThrow(NotFoundException);
});
});
describe('create', () => {
it('should call create on the service', async () => {
// arrange
const newFestival = {
name: 'Festival 3',
location: 'Location 3',
startDate: new Date(2024, 9, 12),
endDate: new Date(2024, 9, 15),
description: 'Description 3',
ticketPrice: 30,
image: 'image 3',
genre: Genre.EDM,
artists: [],
tickets: []
}
const create = jest.spyOn(fService, 'create').mockImplementation(async () => newFestival);
// act
const results = await fController.create(newFestival);
//assert
expect(create).toHaveBeenCalled();
expect(results).toEqual(newFestival);
});
it('should return error if start date is after end date', async () => {
// arrange
const newFestival = {
name: 'Festival 3',
location: 'Location 3',
startDate: new Date(2024, 9, 15),
endDate: new Date(2024, 9, 12),
description: 'Description 3',
ticketPrice: 30,
image: 'image 3',
genre: Genre.EDM,
artists: [],
tickets: []
}
const create = jest.spyOn(fService, 'create').mockImplementation(async () => newFestival);
// act & assert
expect(create).toHaveBeenCalled();
})
})
describe('update', () => {
it('should call update on the service', async () => {
// arrange
const festivalToUpdate = mockFestivals[0]._id?.toString();
const updatedFestival = {
name: 'Festival 3',
location: 'Location 3',
startDate: new Date(2024, 9, 12),
endDate: new Date(2024, 9, 15),
description: 'Description 3',
ticketPrice: 30,
image: 'image 3',
genre: Genre.EDM,
artists: [],
tickets: []
}
const update = jest.spyOn(fService, 'update').mockImplementation(async () => updatedFestival);
// act
const results = await fController.update(festivalToUpdate!, updatedFestival);
//assert
expect(update).toHaveBeenCalled();
expect(results).toEqual(updatedFestival);
});
it('should return error if start date is after end date', async () => {
// arrange
const festivalToUpdate = mockFestivals[0]._id?.toString();
const updatedFestival = {
name: 'Festival 3',
location: 'Location 3',
startDate: new Date(2024, 9, 15),
endDate: new Date(2024, 9, 12),
description: 'Description 3',
ticketPrice: 30,
image: 'image 3',
genre: Genre.EDM,
artists: [],
tickets: []
}
const update = jest.spyOn(fService, 'update').mockImplementation(async () => mockFestivals[0]);
// act & assert
await expect(update).toHaveBeenCalled();
});
it('should return error when festival not found', async () => {
const festivalToUpdate = new Types.ObjectId().toString();
const updatedFestival = {
name: 'Festival 3',
location: 'Location 3',
startDate: new Date(2024, 9, 15),
endDate: new Date(2024, 9, 12),
description: 'Description 3',
ticketPrice: 30,
image: 'image 3',
genre: Genre.EDM,
artists: [],
tickets: []
}
const update = jest.spyOn(fService, 'update').mockImplementation(async () => {
throw new NotFoundException();
});
// act & assert
await expect(fController.update(festivalToUpdate, updatedFestival)).rejects.toThrow(NotFoundException);
});
})
describe('delete', () => {
it('should delete existing festival', async () => {
//arrange
const festivalToDelete = mockFestivals[0]._id;
const deleteSpy = jest.spyOn(fService, 'delete').mockImplementation(async () => mockFestivals[0]);
// act
const result = await fController.delete(festivalToDelete!.toString());
//assert
expect(deleteSpy).toHaveBeenCalled();
expect(result).toEqual(mockFestivals[0]);
});
it('should return error when festival not found', async () => {
//arrange
const festivalToDelete = new Types.ObjectId().toString();
const deleteSpy = jest.spyOn(fService, 'delete').mockImplementation(async () => {
throw new NotFoundException();
});
// act & assert
await expect(fController.delete(festivalToDelete)).rejects.toThrow(NotFoundException);
})
})
describe('addArtistToFestival', () => {
it('Should add artist to festival', async () => {
const create = jest.spyOn(fService, 'addArtistToFestival').mockImplementation(async () => {
mockFestivals[0].artists!.push(mockArtists[0]);
return mockFestivals[0];
});
// act
const data : any = {festivalId: mockFestivals[0]._id, artistId: mockArtists[0]._id};
const result = await fController.addArtistToFestival(data);
//assert
expect(create).toHaveBeenCalled();
expect(result.artists).toHaveLength(1);
})
});
describe('getFestivalRecommendations', () => {
it('Should get recommendations', async () => {
const getRecommendations = jest.spyOn(neo4Service, 'getRecommendedFestivalForUser').mockImplementation(async () => {
return mockFestivals;
});
// act
const result = await fController.getFestivalRecommendations("5e9c8d19ed1d9c001783b6f8");
//assert
expect(getRecommendations).not.toHaveBeenCalled();
expect(result).toEqual([]);
});
})
}) |
package main
import (
"bufio"
"fmt"
"io/fs"
"log"
"os"
"path/filepath"
"strings"
"sync"
)
// Result represents a positive search result, it will be the name of the file
type Result struct {
Filename string
LineNumber int
Text string
}
// NewResult helper function for creating a new result object
func NewResult(fileName string, lineNumber int, text string) Result {
return Result{
Filename: fileName,
LineNumber: lineNumber,
Text: text,
}
}
// ResultMsg represents the message passed to through the channel, it will contain
// either a [Data] string or an [Err] error
type ResultMsg struct {
Data []Result
Err error
}
// NewResultMsg is a constructor function for creating a ResultMsg more easily
// the data parameter will be caste to a Result to simplify usage.
func NewResultMsg(data []Result, err error) *ResultMsg {
return &ResultMsg{
Data: data,
Err: err,
}
}
// JobManager is the central struct which provide various concurrency primitives
type JobManager struct {
wg *sync.WaitGroup
resultmsgch chan *ResultMsg
result *[]Result
readDone *sync.WaitGroup
}
// Newworker create a new instance of the JobManager object
func NewJobManager(numFiles int) *JobManager {
var bufferSize int
if numFiles >= 3 {
bufferSize = 5
} else if numFiles > 50 && numFiles <= 1000 {
bufferSize = 10
} else if numFiles > 1000 {
bufferSize = 100
}
return &JobManager{
wg: new(sync.WaitGroup),
resultmsgch: make(chan *ResultMsg, bufferSize),
result: new([]Result),
readDone: new(sync.WaitGroup),
}
}
// SearchFiles concurrently searches for files within a directory, well not really
// it requires the files to be provided as a slice of strings. Further higher level functions
// will make handling various use cases more easily.
//
// todo: create higher level functions that grab files from dirs, dirs in dirs, or a list of dirs
// ---- then call search files
func (jm *JobManager) SearchFiles(term string, files ...fs.DirEntry) *[]Result {
jm.readDone.Add(1)
go jm.searchWorkerReceive()
for _, file := range files {
if file.IsDir() {
continue
}
jm.wg.Add(1)
go jm.searchWorkerSend(file.Name(), term)
}
jm.wg.Wait()
close(jm.resultmsgch)
jm.readDone.Wait()
return jm.result
}
// serachWorkerSend takes a file and a term as a string and searches the file for the string
// it sends either an error or a result to the resultmsgch
func (jm *JobManager) searchWorkerSend(file string, term string) {
defer jm.wg.Done()
f, err := os.Open(file)
if err != nil {
jm.resultmsgch <- NewResultMsg(nil, err)
return
}
defer f.Close()
jm.resultmsgch <- scanByLine(f, term)
}
// searchWorkerReceive receives values from the resultmsg channel
// so the channel wont block further goroutine access
// !! should be run in its own goroutine
func (jm *JobManager) searchWorkerReceive() {
defer jm.readDone.Done()
for msg := range jm.resultmsgch {
if msg.Err != nil {
log.Println("Error reading file: ", msg.Err)
} else {
*jm.result = append(*jm.result, msg.Data...)
}
}
}
// scanByLine takes an os.File and a term to search for and
// scans the file line by line for the term, adding all
// positive results to the ResultMsg as well as errors
func scanByLine(file *os.File, term string) *ResultMsg {
scanner := bufio.NewScanner(file)
lineNum := 1
resultmsg := new(ResultMsg)
for scanner.Scan() {
text := scanner.Text()
if strings.Contains(text, term) {
resultmsg.Data = append(resultmsg.Data, NewResult(file.Name(), lineNum, term))
}
lineNum++
}
if err := scanner.Err(); err != nil {
resultmsg.Err = err
return resultmsg
}
return resultmsg
}
func main() {
pwd, err := os.Getwd()
if err != nil {
log.Fatalf("error getting the pwd: %s", err)
}
workingFilesPath := filepath.Join(pwd, "files")
files, err := os.ReadDir(workingFilesPath)
if err != nil {
log.Fatalf("error reading dir: %s", err)
}
if err := os.Chdir(workingFilesPath); err != nil {
log.Fatalf("error changing working directory: %s", err)
}
jm := NewJobManager(len(files))
jm.SearchFiles("and", files...)
os.Chdir(pwd)
for _, found := range *jm.result {
fmt.Println(found)
}
} |
import 'package:flutter/material.dart';
import 'package:klinik_app/ui/pasien_form_update_page.dart';
import '../model/pasien.dart';
import 'pasien_page.dart';
class PasienDetailPage extends StatefulWidget {
final Pasien pasien;
const PasienDetailPage({super.key, required this.pasien});
@override
State<PasienDetailPage> createState() => _PasienDetailPageState();
}
class _PasienDetailPageState extends State<PasienDetailPage> {
@override
Widget build(BuildContext context) {
double baseWidth = 360;
double fem = MediaQuery.of(context).size.width / baseWidth; //selain text
double ffem = fem * 0.97; //untuk text
return Scaffold(
appBar: AppBar(title: Text("Detail Pegawai"),),
body: Column(
children: [
SizedBox(height: 20*fem),
Text(
"NIP Pegawai : ${widget.pasien.nomorRMPasien}",
style: TextStyle(fontSize: 20*ffem),
),
Text(
"Nama Pegawai : ${widget.pasien.namaPasien}",
style: TextStyle(fontSize: 20*ffem),
),
Text(
"Tgl Lahir Pegawai : ${widget.pasien.tgllhrPasien}",
style: TextStyle(fontSize: 20*ffem),
),
Text(
"No Telp Pegawai : ${widget.pasien.telpPasien}",
style: TextStyle(fontSize: 20*ffem),
),
Text(
"Email Pegawai : ${widget.pasien.alamatPasien}",
style: TextStyle(fontSize: 20*ffem),
),
SizedBox(height: 20*fem),
Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
_tombolubah(),
_tombolhapus()
],
)
],
),
);
}
_tombolubah(){
return ElevatedButton(
onPressed: (){
Navigator.pushReplacement(
context,
MaterialPageRoute(builder: (context) => PasienUpdateForm(pasien: widget.pasien))
);
},
style: ElevatedButton.styleFrom(backgroundColor: Colors.orange, foregroundColor: Colors.white),
child: Text("Ubah"),
);
}
_tombolhapus(){
return ElevatedButton(
onPressed: (){
AlertDialog alertDialog = AlertDialog(
content: Text("Yakin ingin menghapus data ini?"),
actions: [
// tombol ya
ElevatedButton(
onPressed: (){
Navigator.pop(context);
Navigator.pushReplacement(context,
MaterialPageRoute(builder: (context) => PasienPage()));
},
child: Text("YA"),
style: ElevatedButton.styleFrom(backgroundColor: Colors.red, foregroundColor: Colors.white),
),
// tombol batal
ElevatedButton(
onPressed: (){
Navigator.pop(context);
},
child: Text("Tidak"),
style: ElevatedButton.styleFrom(backgroundColor: Colors.grey, foregroundColor: Colors.black),
)
],
);
showDialog(context: context, builder: (context) => alertDialog);
},
style: ElevatedButton.styleFrom(backgroundColor: Colors.red, foregroundColor: Colors.white),
child: Text("Hapus"),
);
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.