text
stringlengths 184
4.48M
|
---|
import { createRouter, createWebHistory } from 'vue-router'
import { useAuthStore } from '../stores/auth';
import Home from '../views/Home.vue'
import Login from "../views/Login.vue";
import Register from "../views/Register.vue";
import DefaultLayout from "../layouts/DefaultLayout.vue";
import GuestLayout from "../layouts/GueastLayout.vue";
import Calculation from "../pages/Calculation.vue"
const routes = [
{
path: "/",
component: DefaultLayout,
children: [
{
path: "/",
name: "home",
component: Home,
meta: { requiresAuth: true }
},
{
path: "/calculate",
name: "calculation",
component: Calculation,
},
],
},
{
path: "/guest",
component: GuestLayout,
children: [
{
path: "/login",
name: "login",
component: Login,
},
{
path: "/register",
name: "register",
component: Register,
},
],
},
];
const router = createRouter({
history: createWebHistory(),
routes,
});
// router.beforeEach((to, from, next) => {
// const authStore = useAuthStore();
// if (to.matched.some(record => record.meta.requiresAuth) && !authStore.accessToken) {
// next('/login');
// } else {
// next();
// }
// });
export default router |
////Handles the movements for our character "Harry" based on the keycodes generated from the USB PIO
//-------------------------------------------------------------------------
// Ball.sv --
// Viral Mehta --
// Spring 2005 --
// --
// Modified by Stephen Kempf 03-01-2006 --
// 03-12-2007 --
// Translated by Joe Meng 07-07-2013 --
// Fall 2014 Distribution --
// --
// For use with ECE 298 Lab 7 --
// UIUC ECE Department --
//-------------------------------------------------------------------------
module harry ( input Reset, frame_clk, harry_death,
input [7:0] keycode,
output [9:0] HarryX, HarryY, HarryS_X, HarryS_Y, output logic new_level);
logic [9:0] Ball_X_Pos, Ball_X_Motion, Ball_Y_Pos, Ball_Y_Motion, Ball_Size_Y, Ball_Size_X;
parameter [9:0] Ball_X_Center=20; // Center position on the X axis
parameter [9:0] Ball_Y_Center=280; // Center position on the Y axis
parameter [9:0] Ball_X_Min=0; // Leftmost point on the X axis
parameter [9:0] Ball_X_Max=639; // Rightmost point on the X axis
parameter [9:0] Ball_Y_Min=0; // Topmost point on the Y axis
parameter [9:0] Ball_Y_Max=479; // Bottommost point on the Y axis
parameter [9:0] Ball_X_Step=1; // Step size on the X axis
parameter [9:0] Ball_Y_Step=1; // Step size on the Y axis
assign Ball_Size_Y = 32; // assigns the value 4 as a 10-digit binary number, ie "0000000100"
assign Ball_Size_X = 16;
logic jump_en = 1'b0;
// logic[] count = x'b0;
// logic jump_up = 1'b0;
// logic jump_down = 1'b0;
always_ff @ (posedge Reset or posedge frame_clk )
begin: Move_Ball
if (Reset) // Asynchronous Reset
begin
Ball_Y_Motion <= 10'd0; //Ball_Y_Step;
Ball_X_Motion <= 10'd0; //Ball_X_Step;
Ball_Y_Pos <= Ball_Y_Center;
Ball_X_Pos <= Ball_X_Center;
end
else if(new_level)
begin
Ball_Y_Pos <= Ball_Y_Center;
Ball_X_Pos <= Ball_X_Center;
new_level <= 1'b0;
end
else if(harry_death)
begin
Ball_Y_Pos <= Ball_Y_Center;
Ball_X_Pos <= Ball_X_Center;
end
else
begin
if ( (Ball_Y_Pos + Ball_Size_Y) >= Ball_Y_Max ) // Ball is at the bottom edge, BOUNCE!
Ball_Y_Motion <= (~ (Ball_Y_Step) + 1'b1); // 2's complement.
else if ( (Ball_Y_Pos - Ball_Size_Y) <= Ball_Y_Min ) // Ball is at the top edge, BOUNCE!
Ball_Y_Motion <= Ball_Y_Step;
else if ( (Ball_X_Pos + Ball_Size_X) >= Ball_X_Max ) // Ball is at the Right edge, GENERATE NEW LEVEL AND RESET POSITION
begin
new_level <= 1'b1;
end
else if ( (Ball_X_Pos - Ball_Size_X) <= Ball_X_Min ) // Ball is at the Left edge, BOUNCE!
Ball_X_Motion <= Ball_X_Step;
else
Ball_Y_Motion <= Ball_Y_Motion; // Ball is somewhere in the middle, don't bounce, just keep moving
case (keycode)
8'h00 :
begin
Ball_Y_Motion <= 0;
Ball_X_Motion <= 0;
end
8'h04 : begin
Ball_X_Motion <= -1;//A
Ball_Y_Motion<= 0;
end
8'h07 : begin
Ball_X_Motion <= 1;//D
Ball_Y_Motion <= 0;
end
8'h16 : begin
Ball_Y_Motion <= 1;//S
Ball_X_Motion <= 0;
end
8'h1A : begin
Ball_Y_Motion <= -1;//W
Ball_X_Motion <= 0;
end
8'h2C: begin //space bar
jump_en <= 1'b1;
end
default: ;
endcase
Ball_Y_Pos <= (Ball_Y_Pos + Ball_Y_Motion); // Update ball position
Ball_X_Pos <= (Ball_X_Pos + Ball_X_Motion);
end
end
assign HarryX = Ball_X_Pos;
assign HarryY = Ball_Y_Pos;
assign HarryS_Y = Ball_Size_Y;
assign HarryS_X = Ball_Size_X;
endmodule |
//
// ServiceCell.swift
// Intervk
//
// Created by Andrei Kovryzhenko on 28.03.2024.
//
import UIKit
class ServiceCell: UITableViewCell {
let titleServiceLabel = UILabel()
let descriptionServiceLabel = UILabel()
let imageService = UIImageView()
let chevronImage = UIImageView(image: UIImage(systemName: "chevron.right"))
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
setupCell()
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - Networking
func configure(with service: Service) {
titleServiceLabel.text = service.name
descriptionServiceLabel.text = service.description
DispatchQueue.global().async {
let stringUrl = service.iconURL
guard let imageURL = URL(string: stringUrl) else { return }
if let imageData = try? Data(contentsOf: imageURL) {
DispatchQueue.main.async {
self.imageService.image = UIImage(data: imageData)
}
}
}
}
// MARK: - Setup UI
private func setupCell() {
backgroundColor = .clear
setupImage()
setupChevron()
setupTitle()
setupDescription()
}
private func setupImage() {
addSubview(imageService)
imageService.contentMode = .scaleToFill
imageService.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
imageService.leadingAnchor.constraint(equalTo: self.leadingAnchor, constant: 6),
imageService.centerYAnchor.constraint(equalTo: self.centerYAnchor),
imageService.widthAnchor.constraint(equalToConstant: self.frame.width / 5),
imageService.heightAnchor.constraint(equalToConstant: self.frame.width / 5)
])
}
private func setupChevron() {
addSubview(chevronImage)
chevronImage.tintColor = .darkGray
chevronImage.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
chevronImage.centerYAnchor.constraint(equalTo: imageService.centerYAnchor),
chevronImage.trailingAnchor.constraint(equalTo: self.trailingAnchor, constant: -10)
])
}
private func setupTitle() {
addSubview(titleServiceLabel)
titleServiceLabel.textColor = .white
titleServiceLabel.font = .boldSystemFont(ofSize: 18)
titleServiceLabel.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
titleServiceLabel.topAnchor.constraint(equalTo: self.topAnchor, constant: 6),
titleServiceLabel.leadingAnchor.constraint(equalTo: imageService.trailingAnchor, constant: 20),
])
}
private func setupDescription() {
addSubview(descriptionServiceLabel)
descriptionServiceLabel.textColor = .white
descriptionServiceLabel.numberOfLines = 0
descriptionServiceLabel.font = .systemFont(ofSize: 14)
descriptionServiceLabel.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
descriptionServiceLabel.topAnchor.constraint(equalTo: titleServiceLabel.bottomAnchor),
descriptionServiceLabel.leadingAnchor.constraint(equalTo: imageService.trailingAnchor, constant: 20),
descriptionServiceLabel.trailingAnchor.constraint(equalTo: self.trailingAnchor, constant: -20)
])
}
}
#Preview{
ViewController()
} |
const {
is,
data: { bson: BSON }
} = ateos;
const {BinaryParser} = require("./binary_parser");
const ObjectId = BSON.ObjectId;
const Binary = BSON.Binary;
const BSONRegExp = BSON.BSONRegExp;
describe("Full BSON", () => {
/**
* @ignore
*/
it("Should Correctly Deserialize object", (done) => {
const bytes = [
95,
0,
0,
0,
2,
110,
115,
0,
42,
0,
0,
0,
105,
110,
116,
101,
103,
114,
97,
116,
105,
111,
110,
95,
116,
101,
115,
116,
115,
95,
46,
116,
101,
115,
116,
95,
105,
110,
100,
101,
120,
95,
105,
110,
102,
111,
114,
109,
97,
116,
105,
111,
110,
0,
8,
117,
110,
105,
113,
117,
101,
0,
0,
3,
107,
101,
121,
0,
12,
0,
0,
0,
16,
97,
0,
1,
0,
0,
0,
0,
2,
110,
97,
109,
101,
0,
4,
0,
0,
0,
97,
95,
49,
0,
0
];
let serialized_data = "";
// Convert to chars
for (let i = 0; i < bytes.length; i++) {
serialized_data = serialized_data + BinaryParser.fromByte(bytes[i]);
}
const object = BSON.deserialize(Buffer.from(serialized_data, "binary"));
expect("a_1").to.equal(object.name);
expect(false).to.equal(object.unique);
expect(1).to.equal(object.key.a);
done();
});
/**
* @ignore
*/
it("Should Correctly Deserialize object with all types", (done) => {
const bytes = [
26,
1,
0,
0,
7,
95,
105,
100,
0,
161,
190,
98,
75,
118,
169,
3,
0,
0,
3,
0,
0,
4,
97,
114,
114,
97,
121,
0,
26,
0,
0,
0,
16,
48,
0,
1,
0,
0,
0,
16,
49,
0,
2,
0,
0,
0,
16,
50,
0,
3,
0,
0,
0,
0,
2,
115,
116,
114,
105,
110,
103,
0,
6,
0,
0,
0,
104,
101,
108,
108,
111,
0,
3,
104,
97,
115,
104,
0,
19,
0,
0,
0,
16,
97,
0,
1,
0,
0,
0,
16,
98,
0,
2,
0,
0,
0,
0,
9,
100,
97,
116,
101,
0,
161,
190,
98,
75,
0,
0,
0,
0,
7,
111,
105,
100,
0,
161,
190,
98,
75,
90,
217,
18,
0,
0,
1,
0,
0,
5,
98,
105,
110,
97,
114,
121,
0,
7,
0,
0,
0,
2,
3,
0,
0,
0,
49,
50,
51,
16,
105,
110,
116,
0,
42,
0,
0,
0,
1,
102,
108,
111,
97,
116,
0,
223,
224,
11,
147,
169,
170,
64,
64,
11,
114,
101,
103,
101,
120,
112,
0,
102,
111,
111,
98,
97,
114,
0,
105,
0,
8,
98,
111,
111,
108,
101,
97,
110,
0,
1,
15,
119,
104,
101,
114,
101,
0,
25,
0,
0,
0,
12,
0,
0,
0,
116,
104,
105,
115,
46,
120,
32,
61,
61,
32,
51,
0,
5,
0,
0,
0,
0,
3,
100,
98,
114,
101,
102,
0,
37,
0,
0,
0,
2,
36,
114,
101,
102,
0,
5,
0,
0,
0,
116,
101,
115,
116,
0,
7,
36,
105,
100,
0,
161,
190,
98,
75,
2,
180,
1,
0,
0,
2,
0,
0,
0,
10,
110,
117,
108,
108,
0,
0
];
let serialized_data = "";
// Convert to chars
for (let i = 0; i < bytes.length; i++) {
serialized_data = serialized_data + BinaryParser.fromByte(bytes[i]);
}
const object = BSON.deserialize(Buffer.from(serialized_data, "binary"));
expect("hello").to.equal(object.string);
expect([1, 2, 3]).to.deep.equal(object.array);
expect(1).to.equal(object.hash.a);
expect(2).to.equal(object.hash.b);
expect(!ateos.isNil(object.date)).to.be.ok;
expect(!ateos.isNil(object.oid)).to.be.ok;
expect(!ateos.isNil(object.binary)).to.be.ok;
expect(42).to.equal(object.int);
expect(33.3333).to.equal(object.float);
expect(!ateos.isNil(object.regexp)).to.be.ok;
expect(true).to.equal(object.boolean);
expect(!ateos.isNil(object.where)).to.be.ok;
expect(!ateos.isNil(object.dbref)).to.be.ok;
expect(ateos.isNil(object.null)).to.be.ok;
done();
});
/**
* @ignore
*/
it("Should Serialize and Deserialize String", (done) => {
const test_string = { hello: "world" };
const serialized_data = BSON.serialize(test_string);
expect(test_string).to.deep.equal(BSON.deserialize(serialized_data));
done();
});
/**
* @ignore
*/
it("Should Correctly Serialize and Deserialize Integer", (done) => {
const test_number = { doc: 5 };
const serialized_data = BSON.serialize(test_number);
expect(test_number).to.deep.equal(BSON.deserialize(serialized_data));
done();
});
/**
* @ignore
*/
it("Should Correctly Serialize and Deserialize null value", (done) => {
const test_null = { doc: null };
const serialized_data = BSON.serialize(test_null);
const object = BSON.deserialize(serialized_data);
expect(test_null).to.deep.equal(object);
done();
});
/**
* @ignore
*/
it("Should Correctly Serialize and Deserialize undefined value", (done) => {
const test_undefined = { doc: undefined };
const serialized_data = BSON.serialize(test_undefined);
const object = BSON.deserialize(Buffer.from(serialized_data, "binary"));
expect(undefined).to.equal(object.doc);
done();
});
/**
* @ignore
*/
it("Should Correctly Serialize and Deserialize Number 3", (done) => {
const test_number = { doc: 5.5 };
const serialized_data = BSON.serialize(test_number);
expect(test_number).to.deep.equal(BSON.deserialize(serialized_data));
done();
});
/**
* @ignore
*/
it("Should Correctly Serialize and Deserialize Integer", (done) => {
let test_int = { doc: 42 };
let serialized_data = BSON.serialize(test_int);
expect(test_int).to.deep.equal(BSON.deserialize(serialized_data));
test_int = { doc: -5600 };
serialized_data = BSON.serialize(test_int);
expect(test_int).to.deep.equal(BSON.deserialize(serialized_data));
test_int = { doc: 2147483647 };
serialized_data = BSON.serialize(test_int);
expect(test_int).to.deep.equal(BSON.deserialize(serialized_data));
test_int = { doc: -2147483648 };
serialized_data = BSON.serialize(test_int);
expect(test_int).to.deep.equal(BSON.deserialize(serialized_data));
done();
});
/**
* @ignore
*/
it("Should Correctly Serialize and Deserialize Object", (done) => {
const doc = { doc: { age: 42, name: "Spongebob", shoe_size: 9.5 } };
const serialized_data = BSON.serialize(doc);
expect(doc).to.deep.equal(BSON.deserialize(serialized_data));
done();
});
/**
* @ignore
*/
it("Should Correctly Serialize and Deserialize Array", (done) => {
const doc = { doc: [1, 2, "a", "b"] };
const serialized_data = BSON.serialize(doc);
expect(doc).to.deep.equal(BSON.deserialize(serialized_data));
done();
});
/**
* @ignore
*/
it("Should Correctly Serialize and Deserialize Array with added on functions", (done) => {
const doc = { doc: [1, 2, "a", "b"] };
const serialized_data = BSON.serialize(doc);
expect(doc).to.deep.equal(BSON.deserialize(serialized_data));
done();
});
/**
* @ignore
*/
it("Should Correctly Serialize and Deserialize A Boolean", (done) => {
const doc = { doc: true };
const serialized_data = BSON.serialize(doc);
expect(doc).to.deep.equal(BSON.deserialize(serialized_data));
done();
});
/**
* @ignore
*/
it("Should Correctly Serialize and Deserialize a Date", (done) => {
const date = new Date();
//(2009, 11, 12, 12, 00, 30)
date.setUTCDate(12);
date.setUTCFullYear(2009);
date.setUTCMonth(11 - 1);
date.setUTCHours(12);
date.setUTCMinutes(0);
date.setUTCSeconds(30);
const doc = { doc: date };
const serialized_data = BSON.serialize(doc);
expect(doc).to.deep.equal(BSON.deserialize(serialized_data));
done();
});
/**
* @ignore
*/
it("Should Correctly Serialize and Deserialize Oid", (done) => {
const doc = { doc: new ObjectId() };
const serialized_data = BSON.serialize(doc);
expect(doc.doc.toHexString()).to.deep.equal(
BSON.deserialize(serialized_data).doc.toHexString()
);
done();
});
/**
* @ignore
*/
it("Should Correctly Serialize and Deserialize Buffer", (done) => {
const doc = { doc: Buffer.from("123451234512345") };
const serialized_data = BSON.serialize(doc);
expect("123451234512345").to.equal(
BSON.deserialize(serialized_data).doc.buffer.toString("ascii")
);
done();
});
/**
* @ignore
*/
it("Should Correctly Serialize and Deserialize Buffer with promoteBuffers option", (done) => {
const doc = { doc: Buffer.from("123451234512345") };
const serialized_data = BSON.serialize(doc);
const options = { promoteBuffers: true };
expect("123451234512345").to.equal(
BSON.deserialize(serialized_data, options).doc.toString("ascii")
);
done();
});
/**
* @ignore
*/
it("Should Correctly encode Empty Hash", (done) => {
const test_code = {};
const serialized_data = BSON.serialize(test_code);
expect(test_code).to.deep.equal(BSON.deserialize(serialized_data));
done();
});
/**
* @ignore
*/
it("Should Correctly Serialize and Deserialize Ordered Hash", (done) => {
const doc = { doc: { b: 1, a: 2, c: 3, d: 4 } };
const serialized_data = BSON.serialize(doc);
const decoded_hash = BSON.deserialize(serialized_data).doc;
const keys = [];
for (const name in decoded_hash) {
keys.push(name);
}
expect(["b", "a", "c", "d"]).to.deep.equal(keys);
done();
});
/**
* @ignore
*/
it("Should Correctly Serialize and Deserialize Regular Expression", (done) => {
const doc = { doc: /foobar/im };
const serialized_data = BSON.serialize(doc);
const doc2 = BSON.deserialize(serialized_data);
expect(doc.doc.toString()).to.equal(doc2.doc.toString());
done();
});
/**
* @ignore
*/
it("Should Correctly Serialize and Deserialize a Binary object", (done) => {
const bin = new Binary();
const string = "binstring";
for (let index = 0; index < string.length; index++) {
bin.put(string.charAt(index));
}
const doc = { doc: bin };
const serialized_data = BSON.serialize(doc);
const deserialized_data = BSON.deserialize(serialized_data);
expect(doc.doc.value()).to.equal(deserialized_data.doc.value());
done();
});
it("Should Correctly fail due to attempting serialization of illegal key values", (done) => {
const k = Buffer.alloc(15);
for (var i = 0; i < 15; i++) {
k[i] = 0;
}
k.write("hello");
k[6] = 0x06;
k.write("world", 10);
const v = Buffer.alloc(65801);
for (i = 0; i < 65801; i++) {
v[i] = 1;
}
v[0] = 0x0a;
const doc = {};
doc[k.toString()] = v.toString();
// Should throw due to null character
try {
BSON.serialize(doc, {
checkKeys: true
});
expect(false).to.be.ok;
} catch (err) {
expect(true).to.be.ok;
}
done();
});
it("Should correctly fail to serialize regexp with null bytes", (done) => {
const doc = {};
doc.test = new RegExp("a\0b"); // eslint-disable-line no-control-regex
try {
BSON.serialize(doc, {
checkKeys: true
});
expect(false).to.be.ok;
} catch (err) {
expect(true).to.be.ok;
}
done();
});
it("Should correctly fail to serialize BSONRegExp with null bytes", (done) => {
const doc = {};
doc.test = new BSONRegExp("a\0b");
try {
BSON.serialize(doc, {
checkKeys: true
});
expect(false).to.be.ok;
} catch (err) {
expect(true).to.be.ok;
}
done();
});
}); |
### :sparkles: Message Queue Dashboard
This project was created w/ to learning more about React using the Next.JS framework.
### :eyes: __Overview__

### :hammer: Build w/






### :runner: Installing and Running
You can integrate this project with: [kmlyteixeira/message-queue](https://github.com/kmlyteixeira/message-queue)) - or create your own APIs
1. Clone this repo `https://github.com/kmlyteixeira/message-queue-dashboard.git`
4. Run `npm install` to install the dependencies
5. Run `npm run dev`
6. Open `http://localhost:3000` and be happy! :)
### Here you'll find:
```
message-queue-dashboard
|
├── src
│ ├── app
| | ├── layout.tsx
| | └── page.tsx
| ├── commons
| | └── hooks
| | ├── notification/useCustomNotification.ts
| | └── search-filter/useSearchFilter.tsx
| |
| ├── components
| | ├── card/MessageCard.tsx
| | ├── chart/MessageChart.tsx
| | ├── drawer
| | | ├── hooks/useSendMessage.ts
| | | └── MessageDrawer.tsx
| | ├── form/MessageForm.tsx
| | ├── grid/MessageGrid.tsx
| | ├── layouts
| | | ├── app
| | | | ├── hooks/useReceiveMessages.ts
| | | | └── AppPage.tsx
| | | ├── main-header
| | | | ├── main-toolbar/MainToolbar.tsx
| | | | ├── notification-popover/NotificationPopover.tsx
| | | | └── MainHeader.tsx
| | | ├── main-sidebar/MainSidebar.tsx
| | | └── MainLayout.tsx
| | ├── AppQueryClientProvider.tsx
| | └── StyledComponentsRegistry.tsx
| |
| ├── interfaces
| | └── message
| | ├── MessageBodyType.ts
| | └── MessageType.ts
│ └── services
| └── messages/messages-api.ts
|
├── .eslintrc.json
├── next.config.mjs
├── package-lock.json
├── package.json
├── postcss.config.mjs
├── tailwind.config.ts
├── tsconfig.json
└── README.md
```
---
## :books: __Learn more__
:one: [React Learn](https://react.dev/learn)
:two: [Learn Next.js: Getting Started | Next.js](nextjs.org)
:three: [Ant Design - Components Overview](https://ant.design/components/overview)
:four: [React for the Haters in 100 Seconds](https://www.youtube.com/watch?v=HyWYpM_S-2c)
:five: [The React Ecosystem in 2023](https://www.youtube.com/watch?v=6j9tnGMbm2c)
:six: [How A Small Team of Developers Created React at Facebook | React.js: The Documentary](https://www.youtube.com/watch?v=8pDqJVdNa44&list=PLtEPUaeDclku1ECmuN3IsUimHApukWIOf) |
//
// NetworkManager.swift
// Pixify
//
// Created by Rajwinder Singh on 12/4/23.
//
import Foundation
class NetworkManager : NSObject {
static let sharedInstance : NetworkManager = {
let instance = NetworkManager()
return instance
}()
private override init() {
super.init()
}
func searchPhotos(query: String, page: Int, completion: @escaping (PhotoResponse?) -> Void) {
let apiUrl = "\(baseImageURL)/search/photos?query=\(query)&page=\(page)&client_id=\(clientID)"
// 1. Get the url
guard let requestURL = URL(string: apiUrl) else {
print("Invalid URL")
completion(nil)
return
}
// 2. Get the URLRequest
var urlRequest = URLRequest(url: requestURL)
// Sets cache policy and timeout interval for the request
urlRequest.cachePolicy = .useProtocolCachePolicy
urlRequest.timeoutInterval = 30.0
urlRequest.httpMethod = "GET"
//3. Make API request
let task = URLSession.shared.dataTask(with: urlRequest) { (data, response, error) in
guard let data = data, error == nil else {
print("Error: \(error?.localizedDescription ?? "Unknown error")")
completion(nil)
return
}
// Decode JSON response
let photoResponse = apiManagerInstance.decodePhotoResponse(data: data)
completion(photoResponse)
}
task.resume()
}
func searchCollection(query: String, page: Int, completion: @escaping (CollectionResponse?) -> Void) {
let apiUrl = "\(baseImageURL)/search/collections?query=\(query)&page=\(page)&client_id=\(clientID)"
// 1. Get the url
guard let requestURL = URL(string: apiUrl) else {
print("Invalid URL")
completion(nil)
return
}
// 2. Get the URLRequest
var urlRequest = URLRequest(url: requestURL)
// Sets cache policy and timeout interval for the request
urlRequest.cachePolicy = .useProtocolCachePolicy
urlRequest.timeoutInterval = 30.0
urlRequest.httpMethod = "GET"
//3. Make API request
let task = URLSession.shared.dataTask(with: urlRequest) { (data, response, error) in
guard let data = data, error == nil else {
print("Error: \(error?.localizedDescription ?? "Unknown error")")
completion(nil)
return
}
// Decode JSON response
let collectionResponse = apiManagerInstance.decodeCollectionResponse(data: data)
completion(collectionResponse)
}
task.resume()
}
func CollectionPhotos(url: String, completion: @escaping ([Photo]?) -> Void) {
// 1. Get the url
guard let requestURL = URL(string: url) else {
print("Invalid URL")
completion(nil)
return
}
// 2. Get the URLRequest
var urlRequest = URLRequest(url: requestURL)
// Sets cache policy and timeout interval for the request
urlRequest.cachePolicy = .useProtocolCachePolicy
urlRequest.timeoutInterval = 30.0
urlRequest.httpMethod = "GET"
urlRequest.allHTTPHeaderFields = headers
//3. Make API request
let task = URLSession.shared.dataTask(with: urlRequest) { (data, response, error) in
guard let data = data, error == nil else {
print("Error: \(error?.localizedDescription ?? "Unknown error")")
completion(nil)
return
}
// Decode JSON response
let collectionPhotoResponse = apiManagerInstance.decodeCollectionPhotoResponse(data: data)
completion(collectionPhotoResponse)
}
task.resume()
}
//download images from a given URL
func downloadImage(from url: URL, completion: @escaping (Data?) -> Void) {
// Create a data task to download the image from the given URL
let task = URLSession.shared.dataTask(with: url) { data, response, error in
guard let data = data, error == nil else {
completion(nil)
return
}
// Pass data to the completion block
completion(data)
}
// Resume the data task to start the download
task.resume()
}
}
let networkManagerInstance = NetworkManager.sharedInstance |
<?php
namespace App\Mail;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\DB;
class NotifyService extends Mailable
{
use Queueable, SerializesModels;
/**
* Create a new message instance.
*
* @return void
*/
protected $value;
public function __construct($a1)
{
$this->value = $a1;
}
/**
* Build the message.
*
* @return $this
*/
public function build()
{
$table = DB::table('temp_data')->join('stock', 'temp_data.refer', '=', 'stock.item_code')
->where('temp_data.value', $this->value)->where('type', 'EMPSTCK')
->select('stock.item_code as item_code', 'stock.item_name as item_name', 'stock.qty as qty',
'stock.uom as uom', 'stock.minimum as minimum', 'stock.location as location', 'stock.remark as remark')->get();
$easter = DB::table('easter')->where('id', rand(1,450))->value('text');
return $this->from('notify.no_reply@mli.panasonic.co.id')
->subject('Reminder Zero Stock Item')
->view('mail_internal')
->with([
'data' => $table,
'easter' => $easter,
]);
}
} |
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/css/bootstrap.min.css"
rel="stylesheet"
integrity="sha384-GLhlTQ8iRABdZLl6O3oVMWSktQOp6b7In1Zl3/Jr59b6EGGoI1aFkw7cmDA6j6gD"
crossorigin="anonymous">
<title>QR Code Generator / Decoder</title>
<link href="../static/img/favicon.png" th:href="@{/img/favicon.png}"
rel="shortcut icon"/>
<style>
body {
background-image: url('https://i.pinimg.com/originals/45/d6/b5/45d6b57da9ee5b13a583918c64801807.jpg');
background-size: cover;
background-repeat: no-repeat;
background-position: center center;
background-attachment: fixed; /* Optional: Makes the background fixed while scrolling */
}
/* Set the background-color for the navbar and navbar-nav to your preferred color */
.navbar {
background-color: #333;
width: 100%; /* Set the desired width */
}
/* Adjust other styles as needed */
.navbar-brand {
/* Example: Set a max-width for the brand to avoid stretching */
max-width: 200px; /* Adjust as needed */
overflow: hidden;
text-overflow: ellipsis; /* Truncate if the text is too long */
}
/* Set the text color to white and make it bold for the menu items */
.navbar-nav .nav-link {
color: white;
font-weight: bold;
}
/* Set the background-color for the table to transparent */
tbody {
background-color: rgba(255, 255, 255, 0.5); /* Transparent white */
}
/* Set the text color to white for the table header */
.thead-dark {
color: white;
}
/* Set the background-color for the values in the table to transparent */
tbody td {
background-color: transparent;
color: black; /* Set text color to black for visibility */
}
.mb-4 {
color: white;
}
</style>
</head>
<body>
<header id="header">
<div class="container" style="max-width: 75%;">
<nav class="navbar navbar-expand-lg navbar-dark">
<a class="navbar-brand" href="/mostrarPartits">Inici</a>
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav1" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarNav1">
<div class="navbar-nav">
<li>
<a class="nav-link" href="/mostrarPartits">
<i class="fa-solid fa-trophy"></i> Partits
</a>
</li>
<li th:if="${session.userId != null}" class="nav-item active">
<form th:action="@{/subscription}" method="post">
<button type="submit" class="nav-link" style="border: none; background: none; cursor: pointer;">Soci</button>
</form>
</li>
<li class="nav-item">
<a class="nav-link" href="/decode">
<i class="fas fa-qrcode"></i> Scanner
</a>
</li>
</div>
<li th:if="${session.userId == null}" class="nav-item">
<a class="btn btn-outline-light ms-auto" th:href="@{/login}"><i class="fa-solid fa-right-to-bracket"></i> Iniciar sesión</a>
</li>
<li th:if="${session.userId != null}" class="nav-item">
<a class="btn btn-outline-light ms-auto" th:href="@{/logout}"><i class="fa-solid fa-right-to-bracket"></i>Cerrar sesión</a>
</li>
</div>
</nav>
</div>
</header>
<div class="container mt-4">
<h2 class="mb-4">Lista de Partidos</h2>
<table class="table">
<thead class="thead-dark">
<tr>
<th scope="col">ID</th>
<th scope="col">Nombre</th>
<th scope="col">Lugar</th>
<th scope="col">Hora</th>
<th scope="col">Fecha</th>
<th scope="col">Precio</th>
<th scope="col"></th>
</tr>
</thead>
<tbody>
<tr th:each="partit : ${partits}" class="table-light">
<td th:text="${partit.idPartit}"></td>
<td th:text="${partit.nomPartit}"></td>
<td th:text="${partit.llocPartit}"></td>
<td th:text="${partit.hora}"></td>
<td th:text="${#dates.format(partit.dataPartit, 'yyyy-MM-dd')}"></td>
<td th:text="${partit.preu/100} + ' €'"></td>
<td>
<a th:href="@{/tickets/{id}(id=${partit.idPartit})}" class="btn btn-info btn-sm" >Comprar Ticket</a>
</td>
</tr>
</tbody>
</table>
</div>
<!-- Agrega la referencia a Bootstrap JS y jQuery (asegúrate de tener estas bibliotecas disponibles) -->
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.5.2/dist/umd/popper.min.js" integrity="sha384-b3EEvhrC2vrvtLyJZ95de8RvZJoGKqqKSKnh84Kq1sFfUpF5G4Ogq4cezqO5eHP1" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js" integrity="sha384-B4gt1jrGC7Jh4AgTPSdUtOBvfO8sh+WyJq4CkRJkAg5A//KUpONtSt+IhvJSBqt" crossorigin="anonymous"></script>
</body>
</html> |
"use client";
import { CarProps } from "@/types";
import { calculateCarRent, generateCarImageUrl } from "@/utils";
import Image from "next/image";
import React, { useState } from "react";
import Button from "./Button";
import CarDetails from "./CarDetails";
interface CarCardProps {
car: CarProps;
}
const CarCard = ({ car }: CarCardProps) => {
const { city_mpg, year, make, model, transmission, drive } = car;
const [isOpen, setIsOpen] = useState(false)
const carRent = calculateCarRent(city_mpg, year);
return (
<div className="group cursor-pointer flex flex-col p-6 justify-center items-start text-black-100 bg-primary-blue-100 hover:bg-white hover:shadow-md rounded-3xl">
<div className="w-full flex justify-between items-start gap-2">
<h2 className="ext-[22px] leading-[26px] font-bold capitalize">
{make} {model}
</h2>
</div>
<p className="flex mt-6 text-[32px] leading-[38px] font-extrabold">
<span className="self-start text-[14px] leading-[17px] font-semibold">
₪
</span>
{carRent}
<span className="self-end text-[14px] leading-[17px] font-medium">
/יומי
</span>
</p>
<div className="relative w-full h-40 my-3 object-contain">
<Image
src={generateCarImageUrl(car)}
alt="car model"
fill
priority
className="object-contain"
/>
</div>
<div className="relative flex w-full mt-2">
<div className="flex group-hover:invisible w-full justify-between text-grey">
<div className="flex flex-col justify-center items-center gap-2">
<Image
src="/steering-wheel.svg"
height={20}
width={20}
alt="steering wheel"
/>
<p className="text-[14px]">
{transmission === "a" ? "אוטומטי" : "ידני"}
</p>
</div>
<div className="flex flex-col justify-center items-center gap-2">
<Image src="/tire.svg" height={20} width={20} alt="tire" />
<p className="text-[14px]">{drive.toUpperCase()}</p>
</div>
<div className="flex flex-col justify-center items-center gap-2">
<Image src="/gas.svg" height={20} width={20} alt="gas" />
<p className="text-[14px]">{city_mpg} MPG</p>
</div>
</div>
<div className="hidden group-hover:flex absolute bottom-0 w-full z-10">
<Button
title="לפרטים נוספים"
styles="w-full bg-primary-blue py-[16px] rounded-full text-white text-[14px] font-bold"
leftIcon="/left-arrow.svg"
handleClick={()=> setIsOpen(true)}
/>
</div>
</div>
<CarDetails isOpen={isOpen} closeModal={()=>setIsOpen(false)} car={car} />
</div>
);
};
export default CarCard; |
// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/renderer_host/offline_resource_handler.h"
#include <vector>
#include "base/logging.h"
#include "base/memory/singleton.h"
#include "base/metrics/histogram.h"
#include "base/string_util.h"
#include "chrome/browser/chromeos/offline/offline_load_page.h"
#include "chrome/browser/net/chrome_url_request_context.h"
#include "chrome/common/url_constants.h"
#include "content/browser/appcache/chrome_appcache_service.h"
#include "content/browser/browser_thread.h"
#include "content/browser/renderer_host/render_view_host.h"
#include "content/browser/renderer_host/resource_dispatcher_host.h"
#include "content/browser/renderer_host/resource_dispatcher_host_request_info.h"
#include "net/base/net_errors.h"
#include "net/base/network_change_notifier.h"
#include "net/url_request/url_request.h"
#include "net/url_request/url_request_context.h"
OfflineResourceHandler::OfflineResourceHandler(
ResourceHandler* handler,
int host_id,
int route_id,
ResourceDispatcherHost* rdh,
net::URLRequest* request,
ChromeAppCacheService* appcache_service)
: next_handler_(handler),
process_host_id_(host_id),
render_view_id_(route_id),
rdh_(rdh),
request_(request),
appcache_service_(appcache_service),
deferred_request_id_(-1) {
DCHECK(appcache_service_);
}
OfflineResourceHandler::~OfflineResourceHandler() {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
DCHECK(!appcache_completion_callback_.get());
}
bool OfflineResourceHandler::OnUploadProgress(int request_id,
uint64 position,
uint64 size) {
return next_handler_->OnUploadProgress(request_id, position, size);
}
bool OfflineResourceHandler::OnRequestRedirected(int request_id,
const GURL& new_url,
ResourceResponse* response,
bool* defer) {
return next_handler_->OnRequestRedirected(
request_id, new_url, response, defer);
}
bool OfflineResourceHandler::OnResponseStarted(int request_id,
ResourceResponse* response) {
return next_handler_->OnResponseStarted(request_id, response);
}
bool OfflineResourceHandler::OnResponseCompleted(
int request_id,
const net::URLRequestStatus& status,
const std::string& security_info) {
return next_handler_->OnResponseCompleted(request_id, status, security_info);
}
void OfflineResourceHandler::OnRequestClosed() {
if (appcache_completion_callback_) {
appcache_completion_callback_->Cancel();
appcache_completion_callback_.release();
Release(); // Balanced with OnWillStart
}
next_handler_->OnRequestClosed();
}
void OfflineResourceHandler::OnCanHandleOfflineComplete(int rv) {
CHECK(appcache_completion_callback_);
appcache_completion_callback_ = NULL;
if (deferred_request_id_ == -1) {
LOG(WARNING) << "OnCanHandleOfflineComplete called after completion: "
<< " this=" << this;
NOTREACHED();
return;
}
if (rv == net::OK) {
Resume();
Release(); // Balanced with OnWillStart
} else {
// Skipping AddRef/Release because they're redundant.
BrowserThread::PostTask(
BrowserThread::UI, FROM_HERE,
NewRunnableMethod(this, &OfflineResourceHandler::ShowOfflinePage));
}
}
bool OfflineResourceHandler::OnWillStart(int request_id,
const GURL& url,
bool* defer) {
if (ShouldShowOfflinePage(url)) {
deferred_request_id_ = request_id;
deferred_url_ = url;
DVLOG(1) << "OnWillStart: this=" << this << ", request id=" << request_id
<< ", url=" << url;
AddRef(); // Balanced with OnCanHandleOfflineComplete
DCHECK(!appcache_completion_callback_);
appcache_completion_callback_ =
new net::CancelableOldCompletionCallback<OfflineResourceHandler>(
this, &OfflineResourceHandler::OnCanHandleOfflineComplete);
appcache_service_->CanHandleMainResourceOffline(
url, request_->first_party_for_cookies(),
appcache_completion_callback_);
*defer = true;
return true;
}
return next_handler_->OnWillStart(request_id, url, defer);
}
// We'll let the original event handler provide a buffer, and reuse it for
// subsequent reads until we're done buffering.
bool OfflineResourceHandler::OnWillRead(int request_id, net::IOBuffer** buf,
int* buf_size, int min_size) {
return next_handler_->OnWillRead(request_id, buf, buf_size, min_size);
}
bool OfflineResourceHandler::OnReadCompleted(int request_id, int* bytes_read) {
return next_handler_->OnReadCompleted(request_id, bytes_read);
}
void OfflineResourceHandler::OnBlockingPageComplete(bool proceed) {
if (!BrowserThread::CurrentlyOn(BrowserThread::IO)) {
BrowserThread::PostTask(
BrowserThread::IO, FROM_HERE,
NewRunnableMethod(this,
&OfflineResourceHandler::OnBlockingPageComplete,
proceed));
return;
}
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
if (deferred_request_id_ == -1) {
LOG(WARNING) << "OnBlockingPageComplete called after completion: "
<< " this=" << this;
NOTREACHED();
return;
}
if (proceed) {
Resume();
} else {
int request_id = deferred_request_id_;
ClearRequestInfo();
rdh_->CancelRequest(process_host_id_, request_id, false);
}
Release(); // Balanced with OnWillStart
}
void OfflineResourceHandler::ClearRequestInfo() {
deferred_url_ = GURL();
deferred_request_id_ = -1;
}
bool OfflineResourceHandler::IsRemote(const GURL& url) const {
return url.SchemeIs(chrome::kFtpScheme) ||
url.SchemeIs(chrome::kHttpScheme) ||
url.SchemeIs(chrome::kHttpsScheme);
}
bool OfflineResourceHandler::ShouldShowOfflinePage(const GURL& url) const {
// Only check main frame. If the network is disconnected while
// loading other resources, we'll simply show broken link/images.
return IsRemote(url) &&
net::NetworkChangeNotifier::IsOffline() &&
ResourceDispatcherHost::InfoForRequest(request_)->resource_type()
== ResourceType::MAIN_FRAME;
}
void OfflineResourceHandler::Resume() {
const GURL url = deferred_url_;
int request_id = deferred_request_id_;
ClearRequestInfo();
bool defer = false;
DVLOG(1) << "Resume load: this=" << this << ", request id=" << request_id;
next_handler_->OnWillStart(request_id, url, &defer);
if (!defer)
rdh_->StartDeferredRequest(process_host_id_, request_id);
}
void OfflineResourceHandler::ShowOfflinePage() {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
if (!net::NetworkChangeNotifier::IsOffline()) {
// Check again on UI thread and proceed if it's connected.
OnBlockingPageComplete(true);
} else {
RenderViewHost* render_view_host =
RenderViewHost::FromID(process_host_id_, render_view_id_);
TabContents* tab_contents = render_view_host ?
render_view_host->delegate()->GetAsTabContents() : NULL;
// There is a chance that the tab closed after we decided to show
// the offline page on the IO thread and before we actually show the
// offline page here on the UI thread.
if (tab_contents)
(new chromeos::OfflineLoadPage(tab_contents, deferred_url_, this))->
Show();
}
} |
<template>
<div class="task-performance | d-flex justify-space-between pa-4 rounded">
<div v-if="task.startedBy">
<h4 v-if="task.started" class="sub-title | mb-1">
{{ $t('startedBy') }}
</h4>
<div v-if="task.started" class="task-performance_info">
<v-icon small color="green">mdi-account-hard-hat-outline</v-icon>
<span v-if="task.startedBy.fullName" class="sub-title">{{
task.startedBy.fullName
}}</span>
<br />
<span v-if="task.startedAt" class="fecha | info--text">
{{ $formatDate(task.startedAt, { relativeToNow: true }) }}</span
>
</div>
</div>
<div>
<h4 v-if="task.finished && task.finishedBy" class="sub-title | mb-1">
{{ $t('finishedBy') }}
</h4>
<div v-if="task.finished" class="task-performance_info">
<v-icon small color="primary"> mdi-account-hard-hat-outline</v-icon>
<span
v-if="task.finishedBy && task.finishedBy.fullName"
class="sub-title"
>{{ task.finishedBy.fullName }}
</span>
<br />
<span class="fecha | info--text">{{
$formatDate(task.finishedAt, { relativeToNow: true })
}}</span>
</div>
</div>
<div class="reloj">
<h4
v-if="(task.started || task.finished) && task.startedBy"
class="sub-title | mb-1"
>
{{ $t('performanceTime') }}
</h4>
<div v-if="task.startedBy" class="d-flex align-center">
<v-icon
v-if="task.started || task.finished"
size="20"
:color="task.finished ? 'primary' : 'success'"
class="mr-1"
>mdi-clock-outline</v-icon
>
<span v-if="task.started && !task.finished">
{{ elapsetTimeOnTask }}
</span>
<span v-else-if="task.finished">
{{ timeOnTaks }}
</span>
</div>
</div>
<div class="mb-2">
<h4 class="sub-title | mb-1">{{ $t('status') }}</h4>
<v-menu
left
min-width="170px"
max-width="190px"
rounded
offset-y
transition="slide-y-transition"
>
<!-- eslint-disable-next-line -->
<template v-slot:activator="{ on, attrs }">
<div class="status" v-bind="attrs" v-on="on">
<div v-if="!task.started && !task.finished" class="idle">
{{ $t('idle') }}
</div>
<div v-else-if="task.started && !task.finished" class="started">
{{ $t('performingWork') }}
</div>
<div v-else-if="task.finished" class="finished">
{{ $t('taskCompleted') }}
</div>
</div>
</template>
<div class="text-center">
<v-list>
<v-list-item
v-for="option in taskStatusOptions"
:key="option.title"
dense
:disabled="
(option.value === 'idle' && !task.started && !task.finished) ||
(option.value === 'started' &&
task.started &&
!task.finished) ||
(option.value === 'finished' && task.started && task.finished)
"
@click="handleTaskStatus(option.value)"
>
<v-list-item-title>
{{ option.title }}
</v-list-item-title>
</v-list-item>
</v-list>
</div>
</v-menu>
</div>
</div>
</template>
<script>
export default {
name: 'TaskPerformace',
props: {
task: { type: Object, default: () => ({}) },
orderId: { type: String, default: '' },
},
data() {
return {
elapsetTimeOnTask: '0:00:00',
elapsetTimeOnTaskInterval: null,
}
},
computed: {
taskStatusOptions() {
return [
{ value: 'idle', title: this.$t('Inactive') },
{ value: 'started', title: this.$t('performingWork') },
{ value: 'finished', title: this.$t('taskCompleted') },
]
},
timeOnTaks() {
let res = '0:00:00'
const initTime = this.task.startedAt.toDate().getTime()
const finishTime =
this.task.finishedAt && this.task.finishedAt.toDate()
? this.task.finishedAt.toDate().getTime()
: 0
const _elapsetTimeOnTask = Math.floor((finishTime - initTime) / 1000)
const sec = (_elapsetTimeOnTask % 60).toString().padStart(2, '0')
const min = (Math.floor(_elapsetTimeOnTask / 60) % 60)
.toString()
.padStart(2, '0')
const hour = Math.floor(_elapsetTimeOnTask / 60 / 60).toString()
res = `${hour}:${min}:${sec}`
return res
},
},
watch: {
task(newVal, oldVal) {
// if (newVal.started && !oldVal.started) {
this.setElapsetTimeOnTaskInterval()
// }
},
},
mounted() {
if (this.task.started && !this.task.finished) {
this.setElapsetTimeOnTaskInterval()
}
},
beforeDestroy() {
clearInterval(this.elapsetTimeOnTaskInterval)
},
destroyed() {
// eslint-disable-next-line
console.log('comp destroyed')
},
methods: {
setElapsetTimeOnTaskInterval() {
this.elapsetTimeOnTaskInterval = setInterval(() => {
if (this.task.finished) {
clearInterval(this.elapsetTimeOnTaskInterval)
}
if (!this.task.startedAt) {
return
}
const initTime = this.task.startedAt.seconds * 1000
const now = new Date().getTime()
const _elapsetTimeOnTask = Math.floor((now - initTime) / 1000)
const sec = (_elapsetTimeOnTask % 60).toString().padStart(2, '0')
const min = (Math.floor(_elapsetTimeOnTask / 60) % 60)
.toString()
.padStart(2, '0')
const hour = Math.floor(_elapsetTimeOnTask / 60 / 60).toString()
this.elapsetTimeOnTask = `${hour}:${min}:${sec}`
}, 1000)
},
// get_timeOnTaks() {
// const initTime = this.task.startedAt.toDate().getTime()
// const finishTime = this.task.finishedAt.toDate().getTime()
// const _elapsetTimeOnTask = Math.floor((finishTime - initTime) / 1000)
// const sec = (_elapsetTimeOnTask % 60).toString().padStart(2, '0')
// const min = (Math.floor(_elapsetTimeOnTask / 60) % 60)
// .toString()
// .padStart(2, '0')
// const hour = Math.floor(_elapsetTimeOnTask / 60 / 60).toString()
// return `${hour}:${min}:${sec}`
// },
async handleTaskStatus(typeStatus) {
try {
await this.$store.dispatch('oos/orders/handleTaskStatus', {
taskId: this.task.id,
orderId: this.orderId,
type: this.task.type,
typeStatus,
})
this.$mainAlertSuccess('Success! Updated task status')
} catch (error) {
// eslint-disable-next-line
console.log('error: ', error)
this.$mainAlertError(this.$t('oopsProblem'))
}
},
},
}
</script>
<style lang="scss" scoped>
.status {
& > div {
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 0.8rem;
font-weight: 600;
cursor: pointer;
border-radius: 5px;
padding: 4px 17px;
}
.idle {
color: #ffffff;
background-color: #585d5875;
}
.started {
color: #ffffff;
background-color: var(--v-success-base);
}
.finished {
color: #ffffff;
background-color: var(--v-primary-base);
}
}
.sub-title {
font-size: 0.72rem;
font-weight: bold;
white-space: normal;
}
.fecha {
font-size: 0.75rem;
}
.active-list {
font-size: 0.8rem;
}
.active-list:hover {
background-color: rgba(128, 128, 128, 0.081);
cursor: pointer;
}
</style> |
<?php
namespace frontend\models;
use yii\base\InvalidArgumentException;
use yii\base\Model;
use common\models\User;
/**
* Password reset form
*/
class ResetPasswordForm extends Model
{
public $password;
/**
* @var \common\models\User
*/
private $_user;
/**
* Creates a form model given a token.
*
* @param string $token
* @param array $config name-value pairs that will be used to initialize the object properties
* @throws InvalidArgumentException if token is empty or not valid
*/
public function __construct($token, $config = [])
{
if (empty($token) || !is_string($token)) {
throw new InvalidArgumentException('Password reset token cannot be blank.');
}
$this->_user = User::findByPasswordResetToken($token);
if (!$this->_user) {
throw new InvalidArgumentException('Wrong password reset token.');
}
parent::__construct($config);
}
/**
* {@inheritdoc}
*/
public function rules()
{
return [
['password', 'required'],
['password', 'string', 'min' => 6],
];
}
/**
* Resets password.
*
* @return bool if password was reset.
*/
public function resetPassword()
{
$user = $this->_user;
$user->setPassword($this->password);
$user->removePasswordResetToken();
return $user->save(false);
}
public function attributeLabels()
{
return [
'password' =>'Пароль',
];
}
} |
from django.views import generic as views
from .models import Accessories
from .forms import AccessoryCategoryForm
class AccessoriesListView(views.ListView):
model = Accessories
template_name = "accessories/accessories_list.html"
context_object_name = "accessories"
paginate_by = 6
def get_queryset(self):
queryset = super().get_queryset()
category = self.request.GET.get("category")
if category:
queryset = queryset.filter(category=category)
return queryset
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context["form"] = AccessoryCategoryForm(self.request.GET or None)
for accessory in context["accessories"]:
images = accessory.accessory_images.all()
if images:
accessory.first_image = images[0]
else:
accessory.first_image = None
return context
class AccessoryDetailView(views.DetailView):
model = Accessories
template_name = "accessories/accessory_detail.html"
context_object_name = "accessory"
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
accessory = self.get_object()
context["accessory_fields"] = [
{"name": field.name, "verbose_name": field.verbose_name, "value": getattr(accessory, field.name)}
for field in accessory._meta.fields if field.verbose_name not in ("ID", "quantity")
]
return context |
package leetcode_categories.stack;
import java.util.Arrays;
import java.util.Stack;
public class L_853_CarFleet {
public static int carFleet(int target, int[] position, int[] speed) {
Integer[] indices = new Integer[position.length];
for (int i = 0; i < indices.length; i++) {
indices[i] = i;
}
// Step 2: Sort the indices array based on the position array in reverse order
Arrays.sort(indices, (a, b) -> Integer.compare(position[b], position[a]));
// Step 3: Create a copy of the original position and speed arrays
int[] newPosition = Arrays.copyOf(position, position.length);
int[] newSpeed = Arrays.copyOf(speed, speed.length);
// Step 4: Update the position and speed arrays based on the sorted indices
for (int i = 0; i < indices.length; i++) {
position[i] = newPosition[indices[i]];
speed[i] = newSpeed[indices[i]];
}
Stack<Double> stk = new Stack<>();
stk.push(calc(target - position[0], speed[0]));
for (int i = 1; i < position.length; i++) {
Double currentTime = calc(target - position[i], speed[i]);
if (currentTime > stk.peek()) {
stk.push(currentTime);
}
}
return stk.size();
}
public static double calc(int dividend, int divisor) {
return (double) (dividend + divisor ) / divisor;
}
public static void main(String[] args) {
System.out.println(carFleet(12, new int[]{10,8,0,5,3}, new int[]{2,4,1,1,3}));
}
} |
package mini.chatting;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.util.Scanner;
public class TCPServerChatting {
public static void main(String[] args) {
// 서버용 프로그램
int port = 7000;
ServerSocket server = null;
try {
server = new ServerSocket(port);
while (true) { // 계속 대기상태로 만듦
clientAccess(server);
}
} catch (Exception e) {
e.printStackTrace();
}
} // main
private static void clientAccess(ServerSocket server) {
String serverIP = server.getInetAddress().getHostAddress(); // 서버가 구동되는 pc의 ip 주소 조회함
try {
// 클라이언트 접속 요청하면, 요청 수락하면서 클라이언트 정보 저장한 소켓을 만듦
Socket client = server.accept();
String clientIP = client.getInetAddress().getHostAddress(); // 접속 요청한 클라이언트 ip 주소 추출함
System.out.println(clientIP + " : connected!!!");
BufferedReader br = new BufferedReader(new InputStreamReader(client.getInputStream()));
PrintWriter pw = new PrintWriter(client.getOutputStream());
Scanner sc = new Scanner(System.in);
try {
// 메세지 주고 받기 : 서버가 먼저 받고(읽어들임) 답을 보내는 순서임
String receiveMessage;
while (!(receiveMessage = br.readLine()).equals("quit")) {
System.out.println(clientIP + " : " + receiveMessage);
System.out.print("응답할 메세지 입력 : ");
pw.println(serverIP + " : " + sc.nextLine());
pw.flush();
}
// quit 가 전송이 와서 정상적인 종료시
System.out.println(clientIP + " : disconnected....");
} catch (SocketException e) {
// quit 를 전송하지 않고 비정상적을 종료한 경우
System.out.println(clientIP + " : 클라이언트가 비정상적으로 종료하였습니다..");
pw.close();
br.close();
client.close();
} finally {
pw.close();
br.close();
client.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
} |
from pathlib import Path
from fpdf import FPDF
FILE_NAME_PDF = "feed.pdf"
class PDF(FPDF):
"""
Class that generates the PDF file
"""
def _get_item(self, news):
"""
the method that generates the news.
:param news: dict
"""
if news["title"]:
self.multi_cell(0, 5, f"Title: {news['title']}")
self.ln()
if news["pub_date"]:
self.multi_cell(0, 5, f"date of publication: {news['pub_date']}")
self.ln()
if news["link"]:
self.multi_cell(0, 5, f"Link: {news['link']}")
self.ln()
if news["author"]:
self.multi_cell(0, 5, f"Author: {news['author']}")
self.ln()
if news["category"]:
if self.is_list(news["category"]):
for category in news["category"]:
self.cell(0, 5, "Categories: ", ln=1)
self.multi_cell(0, 5, f"{' ' * 5}{category}")
else:
self.multi_cell(0, 5, f"Category: {news['category']}")
self.ln()
if news["description"]:
self.multi_cell(0, 5, f"Description: {news['description']}")
self.ln()
if news["more_description"]:
self.multi_cell(
0, 5, f"More description: {news['more_description']}"
)
self.ln()
if news["comments"]:
self.multi_cell(0, 5, f"Comments: {news['comments']}")
self.ln()
if news["media_objects"]:
if self.is_list(news["media_objects"]):
for media in news["media_objects"]:
self.cell(0, 5, "Media objects: ", ln=1)
self.multi_cell(0, 5, f"{' ' * 5}{media}")
else:
self.multi_cell(0, 5, f"Media object: {news['media_objects']}")
self.ln()
if news["extra_links"]:
if self.is_list(news["extra_links"]):
for extra_link in news["extra_links"]:
self.cell(0, 5, "Extra links: ", ln=1)
self.multi_cell(0, 5, f"{' ' * 5}{extra_link}")
else:
self.multi_cell(0, 5, f"Extra link: {news['extra_links']}")
self.ln()
if news["source_feed"]:
if self.is_list(news["source_feed"]):
for source in news["source_feed"]:
self.cell(0, 5, "Sources: ", ln=1)
self.multi_cell(0, 5, f"{' ' * 5}{source}")
else:
self.multi_cell(0, 5, f"Source: {news['source_feed']}")
def body(self, data):
"""
the method that generates the feeds
:param data: a list of dictionaries with news
"""
if not self.is_list(data[0]):
data = [data]
for feed in data:
self.cell(
0, 5, f'Channel title: {feed[0]["channel_title"]}',
align="C", ln=1
)
self.cell(0, 5, f'Source: {feed[0]["source"]}', align="C", ln=1)
for news in feed[1:]:
self.cell(0, 5, f"{'-' * 125}", align="C", ln=1)
self._get_item(news)
self.cell(0, 5, f"{'-' * 125}", align="C")
self.ln()
self.ln()
def footer(self):
"""
footer generation
"""
self.set_y(-10)
self.set_font("DejaVu", "", 15)
self.cell(0, 5, f"Page {str(self.page_no())}", 0, 0, "C")
@staticmethod
def is_list(obj):
"""
Check obj is list.
:param obj: object
:return: True or False
"""
return isinstance(obj, list)
@staticmethod
def make_dir(path):
"""
Creating a folder at the got path.
If the folder already exists does nothing.
:param path: the path where the folder should be created
"""
if not Path(path).exists():
p = Path(path)
p.mkdir(parents=True)
def convertor_to_pdf(data, path, error_message):
"""
Еhe function gets a list of dictionaries with
news, a path, and a verbose flag.
the function gets the path to TTF with fonts and
sets the resulting fonts to the PDF class,
generates PDF from the received data.
Saves the file to the received path.
:param data: a list of dictionaries with news
:param path: the path to save the file
:param error_message:
"""
pdf = PDF()
pdf.alias_nb_pages()
pdf.add_page()
path_to_ttf = Path(
Path(__file__).parent, "files_for_pdf", "DejaVuSansCondensed.ttf"
)
pdf.add_font("DejaVu", "", path_to_ttf, uni=True)
pdf.set_font("DejaVu", "", 14)
pdf.set_auto_page_break(True, 10)
pdf.body(data)
try:
pdf.make_dir(path)
path = Path(path, FILE_NAME_PDF)
pdf.output(path, "F")
except Exception:
error_message.append("Failed to create file") |
import { Router } from "express";
import { userModel } from "../daos/models/user.model.js";
const router = Router();
router.post("/register", async (req, res) => {
try {
const { first_name, last_name, email, password } = req.body;
console.log("Registrando usuario:");
console.log(req.body);
const exist = await userModel.findOne({ email });
if (exist) {
return res
.status(400)
.send({ status: "error", message: "Usuario ya existe!" });
}
let user = {
first_name,
last_name,
email,
password,
};
// Asignar el rol "admin" solo si las credenciales coinciden
if (user.email === "adminCoder@coder.com" && user.password === "Cod3r123") {
user.role = "admin";
} else {
user.role = "user"; // Asignar un rol predeterminado si no es un administrador
}
const result = await userModel.create(user);
res.send({
status: "success",
message: "Usuario creado con éxito con ID: " + result.id,
});
} catch (error) {
console.error("Error al registrar usuario:", error);
res.status(500).send("Error interno del servidor");
}
});
router.post("/login", async (req, res) => {
const { email, password } = req.body;
const user = await userModel.findOne({ email, password });
if (!user)
return res
.status(401)
.send({ status: "error", error: "Incorrect credentials" });
req.session.user = {
name: `${user.first_name} ${user.last_name}`,
email: user.email,
};
res.send({
status: "success",
payload: req.session.user,
message: "¡Primer logueo realizado! :)",
});
});
router.post("/logout", (req, res) => {
if (req.session.login || req.session.user) {
req.session.destroy((err) => {
if (err) {
console.error('Error al destruir la sesión:', err);
res.status(500).json({ status: "error", message: "Error al cerrar sesión" });
} else {
res.status(200).json({ status: "success", message: "Sesión cerrada exitosamente" });
}
});
} else {
res.status(400).json({ status: "error", message: "No hay sesión activa para cerrar" });
}
});
export default router; |
const mongoose = require('mongoose');
// Task schema
const taskSchema = mongoose.Schema({
id: {
type: String,
unique: true,
required: true
},
name: {
type: String,
required: true
},
description: {
type: String
},
createdAt: {
type: Date,
default: new Date()
},
updatedAt: {
type: Date,
default: new Date()
},
createdBy: {
type: String,
required: true
},
assignedTo: {
type: String,
default: null
},
status: {
type: String,
default: 'open' // Possible value are open|inprogress|closed
}
})
//Creating the collection Tasks
const tasks = mongoose.model('tasks', taskSchema);
module.exports = tasks; |
import { supabase } from "@/lib/supabase/browser-client"
import { TablesInsert, TablesUpdate } from "@/supabase/types"
export const getChatById = async (chatId: string) => {
const { data: chat } = await supabase
.from("chats")
.select("*")
.eq("id", chatId)
.maybeSingle()
return chat
}
export const getChatsByWorkspaceId = async (workspaceId: string) => {
const { data: chats, error } = await supabase
.from("chats")
.select("*")
.eq("workspace_id", workspaceId)
.order("created_at", { ascending: false })
if (!chats) {
throw new Error(error.message)
}
return chats
}
export const createChat = async (chat: TablesInsert<"chats">) => {
const { data: createdChat, error } = await supabase
.from("chats")
.insert([chat])
.select("*")
.single()
if (error) {
throw new Error(error.message)
}
return createdChat
}
export const createChats = async (chats: TablesInsert<"chats">[]) => {
const { data: createdChats, error } = await supabase
.from("chats")
.insert(chats)
.select("*")
if (error) {
throw new Error(error.message)
}
return createdChats
}
export const updateChat = async (
chatId: string,
chat: TablesUpdate<"chats">
) => {
const { data: updatedChat, error } = await supabase
.from("chats")
.update(chat)
.eq("id", chatId)
.select("*")
.single()
if (error) {
throw new Error(error.message)
}
return updatedChat
}
export const deleteChat = async (chatId: string) => {
const { error } = await supabase.from("chats").delete().eq("id", chatId)
if (error) {
throw new Error(error.message)
}
return true
}
export const deleteAllChats = async (userId: string) => {
const { error: chatDeleteError } = await supabase
.from("chats")
.delete()
.eq("user_id", userId)
if (chatDeleteError) {
throw new Error(chatDeleteError.message)
}
const { error: chatMessageDeleteError } = await supabase
.from("chat_files")
.delete()
.eq("user_id", userId)
if (chatMessageDeleteError) {
throw new Error(chatMessageDeleteError.message)
}
const { error: folders } = await supabase
.from("folders")
.delete()
.eq("user_id", userId)
if (folders) {
throw new Error(folders.message)
}
return true
} |
import {ColumnsType} from "antd/es/table";
import useSWR from "swr";
import {fetch, product} from "../services/Service";
import { Space, Table, Button, Typography } from 'antd';
import React, {useState} from "react";
import { PlusOutlined } from '@ant-design/icons';
import {AntDrawer} from "../components/AntDrawer";
export interface ProductData {
id: number | string;
description:string,
stock: number,
price: number,
categoryId: number,
category:number
}
export const Product: React.FC = () => {
const columns: ColumnsType<ProductData> = [
{
title: 'Código',
dataIndex: 'id',
key: 'id',
},
{
title: 'Description',
dataIndex: 'description',
key: 'description',
},
{
title: 'Stock',
dataIndex: 'stock',
key: 'stock',
},
{
title: 'Precio',
dataIndex: 'price',
key: 'price',
},
{
title: 'Categoría',
dataIndex: 'category',
key: 'category',
},
{
title: 'Acción',
key: 'action',
render: (_, record) => (
<Space size="middle">
<Typography.Link onClick={()=>fieldsEdit(record)} style={{ marginRight: 8 }}>
Editar
</Typography.Link>
<Typography.Link style={{ marginRight: 8 }}>
Eliminar
</Typography.Link>
</Space>
),
},
];
const [editingData, setEditingData] = useState<ProductData | undefined>(undefined);
const [open, setOpen] = useState(false);
const fieldsEdit = (field: ProductData) => {
setEditingData(field)
setOpen(true);
}
const showDrawer = () => {
setEditingData(undefined)
setOpen(true);
};
const { data } = useSWR<ProductData[]>(product, fetch, {
suspense: false,
});
return(
<>
<AntDrawer open={open} setOpen={setOpen} fields={editingData}></AntDrawer>
<Button type="primary" icon={<PlusOutlined />} onClick={showDrawer} >
Agregar
</Button>
<h2>Productos</h2>
<Table columns={columns} dataSource={data} ></Table>
</>
);
}; |
import express from "express";
import { QueryTypes } from "sequelize";
import User from "../Models/UserModels.js";
const router = express.Router();
router.post("/users", async (req, res) => {
try {
await User.create(req.body);
res.status(201).json({ msg: "Member ditambahkan" });
} catch (error) {
res.send(error.message);
}
});
//create new api for read / select data from database
router.get("/users/:name", async (req, res) => {
try {
const result = await User.sequelize.query('SELECT * FROM users u WHERE u.name = ?',
{
replacements: [req.params.name],
type: QueryTypes.SELECT
}
);
res.status(201).json({ msg: "Member ditemukan", result: result });
} catch (error) {
res.send(error.message);
}
});
//create new api for update data from database
router.put("/users/:name", async (req, res) => {
try {
const result = await User.sequelize.query('UPDATE users u SET u.email = ? WHERE name = ?',
{
replacements: [req.body.email, req.params.name],
type: QueryTypes.UPDATE
}
);
res.status(200).json({ msg: "Member berhasil diupdate!", result: result });
} catch (error) {
res.send(error.message);
}
});
//create new api for delete data from database
router.delete("/users/:name", async (req, res) => {
try {
const name = req.params.name;
const fetchedData = await User.findOne({ where: { name: name }});
await fetchedData.destroy({msg: 'Success Delete!'});
res.status(200).json();
} catch (error) {
res.send(error.message);
}
});
export default router; |
package flow;
import org.apache.hadoop.io.WritableComparable;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
/**
* @author TaoQingYang
* @date 2022/10/25
*/
public class FlowWritable implements WritableComparable<FlowWritable> {
private String phoneNum;
private Integer upFlow;
private Integer downFlow;
private Integer upCountFlow;
private Integer downCountFlow;
public FlowWritable() {
}
public FlowWritable(String phoneNum, Integer upFlow, Integer downFlow, Integer upCountFlow, Integer downCountFlow) {
this.phoneNum = phoneNum;
this.upFlow = upFlow;
this.downFlow = downFlow;
this.upCountFlow = upCountFlow;
this.downCountFlow = downCountFlow;
}
public String getPhoneNum() {
return phoneNum;
}
public void setPhoneNum(String phoneNum) {
this.phoneNum = phoneNum;
}
@Override
public int compareTo(FlowWritable o) {
return this.upCountFlow - o.getUpCountFlow();
}
@Override
public void write(DataOutput out) throws IOException {
out.writeInt(upFlow);
out.writeInt(downFlow);
out.writeInt(upCountFlow);
out.writeInt(downCountFlow);
}
@Override
public void readFields(DataInput in) throws IOException {
upFlow = in.readInt();
downFlow = in.readInt();
upCountFlow = in.readInt();
downCountFlow = in.readInt();
}
public Integer getUpFlow() {
return upFlow;
}
public void setUpFlow(Integer upFlow) {
this.upFlow = upFlow;
}
public Integer getDownFlow() {
return downFlow;
}
public void setDownFlow(Integer downFlow) {
this.downFlow = downFlow;
}
public Integer getUpCountFlow() {
return upCountFlow;
}
public void setUpCountFlow(Integer upCountFlow) {
this.upCountFlow = upCountFlow;
}
public Integer getDownCountFlow() {
return downCountFlow;
}
public void setDownCountFlow(Integer downCountFlow) {
this.downCountFlow = downCountFlow;
}
@Override
public String toString() {
return "FlowWritable{" +
"phoneNum='" + phoneNum + '\'' +
", upFlow=" + upFlow +
", downFlow=" + downFlow +
", upCountFlow=" + upCountFlow +
", downCountFlow=" + downCountFlow +
'}';
}
} |
import React from 'react';
import { Moon, Sun } from 'react-feather';
import { useDarkMode } from '../context/Dark';
import { useLocation, Link } from 'react-router-dom';
const Header: React.FC = () => {
const {isDarkMode, toggleMode} = useDarkMode();
const location = useLocation();
const activeClass = 'bg-primary text-text-dark';
const inactiveClass = 'bg-white dark:bg-dark-lighter';
const routes = [
{path: '/', title: 'Editor'},
{path: '/templates', title: 'Templates'},
];
const getClass = (index: number, desiredPath: string) => {
let cl = "px-6 py-2 rounded ";
if (index === 0)
cl += "rounded-tr-none rounded-br-none ";
else
cl += "rounded-tl-none rounded-bl-none ";
if (location.pathname === desiredPath)
cl += activeClass;
else
cl += inactiveClass;
return cl;
}
return (
<header className="flex justify-between mb-12">
<h1 className='text-3xl font-bold'>Markdown Generator</h1>
<div className="flex items-center">
<div className="mr-8 group">
{routes.map((route, index) => (
<Link key={index} to={route.path} className={getClass(index, route.path)}>
{route.title}
</Link>
))}
</div>
<button className="p-2 px-3 bg-white rounded dark:bg-primary" onClick={toggleMode}>
{isDarkMode ? <Sun width="1rem" /> : <Moon width="1rem" />}
</button>
</div>
</header>
);
}
export default Header; |
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org"
xmlns:sec="http://www.thymeleaf.org/extras/spring-security">
<head>
<div th:object="${list}" th:remove="tag">
<div th:replace="partials :: headFragment(*{name})"></div>
</div>
<link rel="stylesheet" th:href="@{/css/carousel.css}">
<link rel="stylesheet" th:href="@{/css/my-movies.css}">
</head>
<body>
<div hidden th:object="${list}">
<div id="list-id" th:text="*{id}"></div>
</div>
<!-- Page Wrapper Div to easily change full background-->
<div id="page-wrapper" class="normal-bg">
<!--Navbar -->
<div th:replace="partials :: siteBar" />
<nav class="navbar navbar-expand-lg navbar-dark bg-dark text-light fixed-bottom">
<div class="container-fluid d-flex justify-content-between py-1">
<!-- Add Button -->
<div class="nav-item ms-md-5 ms-2">
<button id="add-movie-btn" class="btn text-dark" data-bs-toggle="modal" data-bs-target="#add-movie-modal">Add Movie</button>
</div>
<!-- Randomize -->
<div class="nav-item">
<button id="random-movie-btn" class="btn text-dark">Suggest!</button>
</div>
<!-- Filters -->
<div class="nav-item">
<button id="filter-movie-btn" class="btn text-dark">Filters</button>
</div>
<!-- Sort Select Field -->
<div id="nav-sort-div" class="nav-item me-md-5 ms-2">
<select name="sort-select" id="sort-select" class="form-select border-dark" autocomplete="off">
<option value="1">Sort</option>
<option value="2">A - Z</option>
<option value="3">Z - A</option>
<option value="4">Newest</option>
<option value="5">Oldest</option>
</select>
</div>
</div>
</nav>
<!-- Main Wrapper Div for Loading Screen-->
<div id="main-wrapper">
<!-- Loading Screen Div-->
<div id="loading-div" class="d-flex justify-content-center normal-bg">
<img th:src="@{/javier.png}" id="loading-img" class="spin">
</div>
<!-- Add Movie Modal -->
<div class="modal fade" id="add-movie-modal" tabindex="-1">
<div class="modal-dialog modal-xl">
<div class="modal-content bg-dark">
<div class="modal-header">
<h5 class="modal-title text-light">Add Movie</h5>
</div>
<div class="modal-body text-center">
<input type="text" id="add-movie-text" list="movie-list" class="w-50" autocomplete="off">
<div class="container mt-3">
<div id="movie-list" class="row gy-3 d-flex justify-content-center"></div>
</div>
</div>
</div>
</div>
</div>
<!-- Single Movie Modal -->
<div class="modal fade" id="single-movie-modal" tabindex="-1">
<div class="modal-dialog">
<div class="modal-content bg-dark">
<div id="single-movie-modal-header" class="modal-header d-flex justify-content-center">
</div>
<div class="modal-body text-light">
<div class="container mt-3">
<div id="single-movie" class="row"></div>
</div>
</div>
</div>
</div>
</div>
<!-- Filters Modal -->
<div class="modal fade" id="filters-modal" tabindex="-1">
<div class="modal-dialog">
<div class="modal-content bg-dark">
<div id="filters-modal-header" class="modal-header">
<h3 class="text-light">Filters</h3>
</div>
<div id="filters-modal-body" class="modal-body text-light">
<div>
<h5>Genres: (select to add)</h5>
<div id="filters-modal-genres"></div>
</div>
<div>
<h5>Before Year:</h5>
<div id="filters-modal-before-year">
<select class="form-select form-select-md filters-year-select" name="before-year-select" id="before-year-select">
<option selected>Choose Year</option>
</select>
</div>
</div>
<div>
<h5>After Year:</h5>
<div id="filters-modal-after-year">
<select class="form-select form-select-md filters-year-select" name="after-year-select" id="after-year-select">
<option selected>Choose Year</option>
</select>
</div>
</div>
<div>
<div class="d-flex justify-content-between align-items-center">
<h5 class="my-0">Chosen Filters: (select to remove)</h5>
<button id="filters-modal-clear-all-button" class="btn btn-info">Clear All</button>
</div>
<div id="filters-modal-selections"></div>
</div>
</div>
</div>
</div>
</div>
<div id="all-movie-carousel" class="carousel-scene d-flex justify-content-center">
<div class="carousel"></div>
</div>
<nav id="carousel-buttons">
<div class="carousel-nav carousel-prev"><i class="bi bi-caret-left fs-5"></i></div>
<div class="carousel-nav carousel-next"><i class="bi bi-caret-right fs-5"></i></div>
</nav>
</div> <!-- Main Wrapper -->
</div> <!-- Page Wrapper -->
<!-- Scripts -->
<div th:replace="partials :: scripts" />
<script type="module" th:src="@{/js/my-movies.js}" />
<script type="module" src="../../../../static/js/my-movies.js"></script>
</body>
</html> |
import Title from "./Title";
import TextBox from "./TextBox";
import Pizza from "./Pizza";
import PizzaOven from "./PizzaOven";
// With props you can pass any data to them: Strings, numbers, booleans
// Functions, objects, arrays
// When this function is called, it will send a popup containing the passed in text
const alertFunc = (text) => {
alert(text);
}
// Create an array of objects to pass in
// [] - denotes an array
// {} - denotes an object
const pizzaArray = [
{
type: "Pepperoni",
size: 12,
stuffedCrust: true
},
{
type: "Hawiaan",
size: 11,
stuffedCrust: false
},
{
type: "Four Cheese",
size: 13,
stuffedCrust: true
}
]
const Manager = () => {
return (
// When passing props from a parent component, pass them in as if its HTML
// The name of the prop 'should' match the name of the prop it is replacing its value
<div>
<Title title="Value added as a prop" />
<TextBox text="this is new text added as a prop value.." />
<Title title="this is a new value"/>
<Title title="this is a third new value"/>
{/* If you're not passing in text (String) surround the value in {} converts to JS */}
<Pizza type="Pepperoni" size={12} stuffedCrust={true} funcProp={alertFunc}/>
{/* <br> line break, adds space between elements */}
<br></br>
<br></br>
<PizzaOven data={pizzaArray}/>
{/* Passing in our pizza array to our oven */}
</div>
);
};
export default Manager; |
<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\BookController;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::get('/welcome', function () {
return view('welcome');
});
Route::prefix('book')->group(function () {
Route::get('/', [BookController::class, 'index'])->name('books.index');
Route::get('/create', [BookController::class, 'create'])->name('books.create');
Route::post('/store', [BookController::class, 'store'])->name('books.store');
Route::get('/show/{id}', [BookController::class, 'show'])->name('books.show');
Route::get('/edit/{id}', [BookController::class, 'edit'])->name('books.edit');
Route::put('/update/{id}', [BookController::class, 'update'])->name('books.update');
Route::delete('/destroy/{id}', [BookController::class, 'destroy'])->name('books.destroy');
}); |
package net.minecraft.core;
import com.google.common.collect.Iterators;
import com.mojang.serialization.Codec;
import com.mojang.serialization.DataResult;
import java.util.Arrays;
import java.util.Collection;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import java.util.function.Predicate;
import java.util.stream.Stream;
import javax.annotation.Nullable;
import net.minecraft.Util;
import net.minecraft.util.ExtraCodecs;
import net.minecraft.util.Mth;
import net.minecraft.util.RandomSource;
import net.minecraft.util.StringRepresentable;
import net.minecraft.world.entity.Entity;
import org.joml.Matrix4f;
import org.joml.Quaternionf;
import org.joml.Vector3f;
import org.joml.Vector4f;
public enum Direction implements StringRepresentable {
DOWN(0, 1, -1, "down", Direction.AxisDirection.NEGATIVE, Direction.Axis.Y, new Vec3i(0, -1, 0)),
UP(1, 0, -1, "up", Direction.AxisDirection.POSITIVE, Direction.Axis.Y, new Vec3i(0, 1, 0)),
NORTH(2, 3, 2, "north", Direction.AxisDirection.NEGATIVE, Direction.Axis.Z, new Vec3i(0, 0, -1)),
SOUTH(3, 2, 0, "south", Direction.AxisDirection.POSITIVE, Direction.Axis.Z, new Vec3i(0, 0, 1)),
WEST(4, 5, 1, "west", Direction.AxisDirection.NEGATIVE, Direction.Axis.X, new Vec3i(-1, 0, 0)),
EAST(5, 4, 3, "east", Direction.AxisDirection.POSITIVE, Direction.Axis.X, new Vec3i(1, 0, 0));
public static final StringRepresentable.EnumCodec<Direction> CODEC = StringRepresentable.fromEnum(Direction::values);
public static final Codec<Direction> VERTICAL_CODEC = ExtraCodecs.validate(CODEC, Direction::verifyVertical);
private final int data3d;
private final int oppositeIndex;
private final int data2d;
private final String name;
private final Direction.Axis axis;
private final Direction.AxisDirection axisDirection;
private final Vec3i normal;
private static final Direction[] VALUES = values();
private static final Direction[] BY_3D_DATA = Arrays.stream(VALUES).sorted(Comparator.comparingInt((direction) -> {
return direction.data3d;
})).toArray((i) -> {
return new Direction[i];
});
private static final Direction[] BY_2D_DATA = Arrays.stream(VALUES).filter((direction) -> {
return direction.getAxis().isHorizontal();
}).sorted(Comparator.comparingInt((direction) -> {
return direction.data2d;
})).toArray((i) -> {
return new Direction[i];
});
// Paper start
private final int adjX;
private final int adjY;
private final int adjZ;
// Paper end
// Paper start - optimise collisions
private static final int RANDOM_OFFSET = 2017601568;
private Direction opposite;
static {
for (final Direction direction : VALUES) {
direction.opposite = from3DDataValue(direction.oppositeIndex);;
}
}
private final int id = it.unimi.dsi.fastutil.HashCommon.murmurHash3(it.unimi.dsi.fastutil.HashCommon.murmurHash3(this.ordinal() + RANDOM_OFFSET) + RANDOM_OFFSET);
public final int uniqueId() {
return this.id;
}
// Paper end - optimise collisions
private Direction(int id, int idOpposite, int idHorizontal, String name, Direction.AxisDirection direction, Direction.Axis axis, Vec3i vector) {
this.data3d = id;
this.data2d = idHorizontal;
this.oppositeIndex = idOpposite;
this.name = name;
this.axis = axis;
this.axisDirection = direction;
this.normal = vector;
// Paper start
this.adjX = vector.getX();
this.adjY = vector.getY();
this.adjZ = vector.getZ();
// Paper end
}
public static Direction[] orderedByNearest(Entity entity) {
float f = entity.getViewXRot(1.0F) * ((float)Math.PI / 180F);
float g = -entity.getViewYRot(1.0F) * ((float)Math.PI / 180F);
float h = Mth.sin(f);
float i = Mth.cos(f);
float j = Mth.sin(g);
float k = Mth.cos(g);
boolean bl = j > 0.0F;
boolean bl2 = h < 0.0F;
boolean bl3 = k > 0.0F;
float l = bl ? j : -j;
float m = bl2 ? -h : h;
float n = bl3 ? k : -k;
float o = l * i;
float p = n * i;
Direction direction = bl ? EAST : WEST;
Direction direction2 = bl2 ? UP : DOWN;
Direction direction3 = bl3 ? SOUTH : NORTH;
if (l > n) {
if (m > o) {
return makeDirectionArray(direction2, direction, direction3);
} else {
return p > m ? makeDirectionArray(direction, direction3, direction2) : makeDirectionArray(direction, direction2, direction3);
}
} else if (m > p) {
return makeDirectionArray(direction2, direction3, direction);
} else {
return o > m ? makeDirectionArray(direction3, direction, direction2) : makeDirectionArray(direction3, direction2, direction);
}
}
private static Direction[] makeDirectionArray(Direction first, Direction second, Direction third) {
return new Direction[]{first, second, third, third.getOpposite(), second.getOpposite(), first.getOpposite()};
}
public static Direction rotate(Matrix4f matrix, Direction direction) {
Vec3i vec3i = direction.getNormal();
Vector4f vector4f = matrix.transform(new Vector4f((float)vec3i.getX(), (float)vec3i.getY(), (float)vec3i.getZ(), 0.0F));
return getNearest(vector4f.x(), vector4f.y(), vector4f.z());
}
public static Collection<Direction> allShuffled(RandomSource random) {
return Util.shuffledCopy(values(), random);
}
public static Stream<Direction> stream() {
return Stream.of(VALUES);
}
public Quaternionf getRotation() {
Quaternionf var10000;
switch (this) {
case DOWN:
var10000 = (new Quaternionf()).rotationX((float)Math.PI);
break;
case UP:
var10000 = new Quaternionf();
break;
case NORTH:
var10000 = (new Quaternionf()).rotationXYZ(((float)Math.PI / 2F), 0.0F, (float)Math.PI);
break;
case SOUTH:
var10000 = (new Quaternionf()).rotationX(((float)Math.PI / 2F));
break;
case WEST:
var10000 = (new Quaternionf()).rotationXYZ(((float)Math.PI / 2F), 0.0F, ((float)Math.PI / 2F));
break;
case EAST:
var10000 = (new Quaternionf()).rotationXYZ(((float)Math.PI / 2F), 0.0F, (-(float)Math.PI / 2F));
break;
default:
throw new IncompatibleClassChangeError();
}
return var10000;
}
public int get3DDataValue() {
return this.data3d;
}
public int get2DDataValue() {
return this.data2d;
}
public Direction.AxisDirection getAxisDirection() {
return this.axisDirection;
}
public static Direction getFacingAxis(Entity entity, Direction.Axis axis) {
Direction var10000;
switch (axis) {
case X:
var10000 = EAST.isFacingAngle(entity.getViewYRot(1.0F)) ? EAST : WEST;
break;
case Z:
var10000 = SOUTH.isFacingAngle(entity.getViewYRot(1.0F)) ? SOUTH : NORTH;
break;
case Y:
var10000 = entity.getViewXRot(1.0F) < 0.0F ? UP : DOWN;
break;
default:
throw new IncompatibleClassChangeError();
}
return var10000;
}
public Direction getOpposite() {
return from3DDataValue(this.oppositeIndex);
}
public Direction getClockWise(Direction.Axis axis) {
Direction var10000;
switch (axis) {
case X:
var10000 = this != WEST && this != EAST ? this.getClockWiseX() : this;
break;
case Z:
var10000 = this != NORTH && this != SOUTH ? this.getClockWiseZ() : this;
break;
case Y:
var10000 = this != UP && this != DOWN ? this.getClockWise() : this;
break;
default:
throw new IncompatibleClassChangeError();
}
return var10000;
}
public Direction getCounterClockWise(Direction.Axis axis) {
Direction var10000;
switch (axis) {
case X:
var10000 = this != WEST && this != EAST ? this.getCounterClockWiseX() : this;
break;
case Z:
var10000 = this != NORTH && this != SOUTH ? this.getCounterClockWiseZ() : this;
break;
case Y:
var10000 = this != UP && this != DOWN ? this.getCounterClockWise() : this;
break;
default:
throw new IncompatibleClassChangeError();
}
return var10000;
}
public Direction getClockWise() {
Direction var10000;
switch (this) {
case NORTH:
var10000 = EAST;
break;
case SOUTH:
var10000 = WEST;
break;
case WEST:
var10000 = NORTH;
break;
case EAST:
var10000 = SOUTH;
break;
default:
throw new IllegalStateException("Unable to get Y-rotated facing of " + this);
}
return var10000;
}
private Direction getClockWiseX() {
Direction var10000;
switch (this) {
case DOWN:
var10000 = SOUTH;
break;
case UP:
var10000 = NORTH;
break;
case NORTH:
var10000 = DOWN;
break;
case SOUTH:
var10000 = UP;
break;
default:
throw new IllegalStateException("Unable to get X-rotated facing of " + this);
}
return var10000;
}
private Direction getCounterClockWiseX() {
Direction var10000;
switch (this) {
case DOWN:
var10000 = NORTH;
break;
case UP:
var10000 = SOUTH;
break;
case NORTH:
var10000 = UP;
break;
case SOUTH:
var10000 = DOWN;
break;
default:
throw new IllegalStateException("Unable to get X-rotated facing of " + this);
}
return var10000;
}
private Direction getClockWiseZ() {
Direction var10000;
switch (this) {
case DOWN:
var10000 = WEST;
break;
case UP:
var10000 = EAST;
break;
case NORTH:
case SOUTH:
default:
throw new IllegalStateException("Unable to get Z-rotated facing of " + this);
case WEST:
var10000 = UP;
break;
case EAST:
var10000 = DOWN;
}
return var10000;
}
private Direction getCounterClockWiseZ() {
Direction var10000;
switch (this) {
case DOWN:
var10000 = EAST;
break;
case UP:
var10000 = WEST;
break;
case NORTH:
case SOUTH:
default:
throw new IllegalStateException("Unable to get Z-rotated facing of " + this);
case WEST:
var10000 = DOWN;
break;
case EAST:
var10000 = UP;
}
return var10000;
}
public Direction getCounterClockWise() {
Direction var10000;
switch (this) {
case NORTH:
var10000 = WEST;
break;
case SOUTH:
var10000 = EAST;
break;
case WEST:
var10000 = SOUTH;
break;
case EAST:
var10000 = NORTH;
break;
default:
throw new IllegalStateException("Unable to get CCW facing of " + this);
}
return var10000;
}
public int getStepX() {
return this.adjX; // Paper
}
public int getStepY() {
return this.adjY; // Paper
}
public int getStepZ() {
return this.adjZ; // Paper
}
public Vector3f step() {
return new Vector3f((float)this.getStepX(), (float)this.getStepY(), (float)this.getStepZ());
}
public String getName() {
return this.name;
}
public Direction.Axis getAxis() {
return this.axis;
}
@Nullable
public static Direction byName(@Nullable String name) {
return CODEC.byName(name);
}
public static Direction from3DDataValue(int id) {
return BY_3D_DATA[Mth.abs(id % BY_3D_DATA.length)];
}
public static Direction from2DDataValue(int value) {
return BY_2D_DATA[Mth.abs(value % BY_2D_DATA.length)];
}
@Nullable
public static Direction fromDelta(int x, int y, int z) {
if (x == 0) {
if (y == 0) {
if (z > 0) {
return SOUTH;
}
if (z < 0) {
return NORTH;
}
} else if (z == 0) {
if (y > 0) {
return UP;
}
return DOWN;
}
} else if (y == 0 && z == 0) {
if (x > 0) {
return EAST;
}
return WEST;
}
return null;
}
public static Direction fromYRot(double rotation) {
return from2DDataValue(Mth.floor(rotation / 90.0D + 0.5D) & 3);
}
public static Direction fromAxisAndDirection(Direction.Axis axis, Direction.AxisDirection direction) {
Direction var10000;
switch (axis) {
case X:
var10000 = direction == Direction.AxisDirection.POSITIVE ? EAST : WEST;
break;
case Z:
var10000 = direction == Direction.AxisDirection.POSITIVE ? SOUTH : NORTH;
break;
case Y:
var10000 = direction == Direction.AxisDirection.POSITIVE ? UP : DOWN;
break;
default:
throw new IncompatibleClassChangeError();
}
return var10000;
}
public float toYRot() {
return (float)((this.data2d & 3) * 90);
}
public static Direction getRandom(RandomSource random) {
return Util.getRandom(VALUES, random);
}
public static Direction getNearest(double x, double y, double z) {
return getNearest((float)x, (float)y, (float)z);
}
public static Direction getNearest(float x, float y, float z) {
Direction direction = NORTH;
float f = Float.MIN_VALUE;
for(Direction direction2 : VALUES) {
float g = x * (float)direction2.normal.getX() + y * (float)direction2.normal.getY() + z * (float)direction2.normal.getZ();
if (g > f) {
f = g;
direction = direction2;
}
}
return direction;
}
@Override
public String toString() {
return this.name;
}
@Override
public String getSerializedName() {
return this.name;
}
private static DataResult<Direction> verifyVertical(Direction direction) {
return direction.getAxis().isVertical() ? DataResult.success(direction) : DataResult.error(() -> {
return "Expected a vertical direction";
});
}
public static Direction get(Direction.AxisDirection direction, Direction.Axis axis) {
for(Direction direction2 : VALUES) {
if (direction2.getAxisDirection() == direction && direction2.getAxis() == axis) {
return direction2;
}
}
throw new IllegalArgumentException("No such direction: " + direction + " " + axis);
}
public Vec3i getNormal() {
return this.normal;
}
public boolean isFacingAngle(float yaw) {
float f = yaw * ((float)Math.PI / 180F);
float g = -Mth.sin(f);
float h = Mth.cos(f);
return (float)this.normal.getX() * g + (float)this.normal.getZ() * h > 0.0F;
}
public static enum Axis implements StringRepresentable, Predicate<Direction> {
X("x") {
@Override
public int choose(int x, int y, int z) {
return x;
}
@Override
public double choose(double x, double y, double z) {
return x;
}
},
Y("y") {
@Override
public int choose(int x, int y, int z) {
return y;
}
@Override
public double choose(double x, double y, double z) {
return y;
}
},
Z("z") {
@Override
public int choose(int x, int y, int z) {
return z;
}
@Override
public double choose(double x, double y, double z) {
return z;
}
};
public static final Direction.Axis[] VALUES = values();
public static final StringRepresentable.EnumCodec<Direction.Axis> CODEC = StringRepresentable.fromEnum(Direction.Axis::values);
private final String name;
Axis(String name) {
this.name = name;
}
@Nullable
public static Direction.Axis byName(String name) {
return CODEC.byName(name);
}
public String getName() {
return this.name;
}
public boolean isVertical() {
return this == Y;
}
public boolean isHorizontal() {
return this == X || this == Z;
}
@Override
public String toString() {
return this.name;
}
public static Direction.Axis getRandom(RandomSource random) {
return Util.getRandom(VALUES, random);
}
@Override
public boolean test(@Nullable Direction direction) {
return direction != null && direction.getAxis() == this;
}
public Direction.Plane getPlane() {
Direction.Plane var10000;
switch (this) {
case X:
case Z:
var10000 = Direction.Plane.HORIZONTAL;
break;
case Y:
var10000 = Direction.Plane.VERTICAL;
break;
default:
throw new IncompatibleClassChangeError();
}
return var10000;
}
@Override
public String getSerializedName() {
return this.name;
}
public abstract int choose(int x, int y, int z);
public abstract double choose(double x, double y, double z);
}
public static enum AxisDirection {
POSITIVE(1, "Towards positive"),
NEGATIVE(-1, "Towards negative");
private final int step;
private final String name;
private AxisDirection(int offset, String description) {
this.step = offset;
this.name = description;
}
public int getStep() {
return this.step;
}
public String getName() {
return this.name;
}
@Override
public String toString() {
return this.name;
}
public Direction.AxisDirection opposite() {
return this == POSITIVE ? NEGATIVE : POSITIVE;
}
}
public static enum Plane implements Iterable<Direction>, Predicate<Direction> {
HORIZONTAL(new Direction[]{Direction.NORTH, Direction.EAST, Direction.SOUTH, Direction.WEST}, new Direction.Axis[]{Direction.Axis.X, Direction.Axis.Z}),
VERTICAL(new Direction[]{Direction.UP, Direction.DOWN}, new Direction.Axis[]{Direction.Axis.Y});
private final Direction[] faces;
private final Direction.Axis[] axis;
private Plane(Direction[] facingArray, Direction.Axis[] axisArray) {
this.faces = facingArray;
this.axis = axisArray;
}
public Direction getRandomDirection(RandomSource random) {
return Util.getRandom(this.faces, random);
}
public Direction.Axis getRandomAxis(RandomSource random) {
return Util.getRandom(this.axis, random);
}
@Override
public boolean test(@Nullable Direction direction) {
return direction != null && direction.getAxis().getPlane() == this;
}
@Override
public Iterator<Direction> iterator() {
return Iterators.forArray(this.faces);
}
public Stream<Direction> stream() {
return Arrays.stream(this.faces);
}
public List<Direction> shuffledCopy(RandomSource random) {
return Util.shuffledCopy(this.faces, random);
}
}
} |
package alan.pkg;
import java.util.ArrayList;
import java.util.Collection;
public class collec {
public static void main(String[] args) {
int [] a = new int[1000];
// Limitations of array
//1. Arrays are fixed in size
//2. Only homogenous data elements
//3. Does not provide any methods or APIs
Object [] obj = new Object[20];
Collection<String> collection = new ArrayList<>();
//add
collection.add("banana");
collection.add("apple");
collection.add("Orange");
System.out.println(collection);
//remove
collection.remove("banana");
System.out.println(collection);
//contains
System.out.println(collection.contains("apple"));
//for each
collection.forEach(System.out::println);
//or
collection.forEach((element)->{
System.out.println(element);
});
}
}
// collection - root interface extends iterable
// list, queue, set - sub-interfaces which extends the collection interface
// ............IMPLEMENTATIONS..............
// List implementations Set implementations Queue implementations
// Array List HashSet Priority Queue
// Linked-List LinkedHashSet Deque (extends Queue)
// Vector SortedSet ArrayDeque (Implements Deque)
// Stack (extends vector) TreeSet (implements Sortedset)
// Map
// HashMap (implements map)
// LinkedHashMap (implements map)
// HashTable (implements map)
// Sorted map (extends Map)
// TreeMap (implements Sorted Map) |
/*
Copyright (c) 2014 Ken Koch
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
'use strict'
/**
* The basis of the TRIE structure.
**/
function Trie (caseSensitive) {
this.dictionary = Object.create(null) // {}
this.$ = false
if (typeof caseSensitive === 'undefined') {
caseSensitive = true
}
this.cs = caseSensitive
}
/**
* Add a single string to the TRIE, returns true if the word was already in the
* trie.
**/
Trie.prototype.addString = function (string) {
if (this.cs === false) {
string = string.toLowerCase()
}
// If the string has only one letter, mark this as a word.
if (string.length === 0) {
const wasWord = this.$
this.$ = true
return wasWord
}
// Make sure theres a Trie node in our dictionary
let next = this.dictionary[string[0]]
if (!next) {
this.dictionary[string[0]] = new Trie(this.cs)
next = this.dictionary[string[0]]
}
// Continue adding the string
return next.addString(string.substring(1))
}
/**
* Add multiple strings to the TRIE
**/
Trie.prototype.addStrings = function (list) {
for (const i in list) {
this.addString(list[i])
}
}
/**
* A function to search the TRIE and return an array of
* words which have same prefix <prefix>
* for example if we had the following words in our database:
* a, ab, bc, cd, abc, abd
* and we search the string: a
* we will get :
* [a, ab, abc, abd]
**/
Trie.prototype.keysWithPrefix = function (prefix) {
if (this.caseSensitive === false) {
prefix = prefix.toLowerCase()
}
function isEmpty (object) {
for (const key in object) if (object[key]) return false
return true
}
function get (node, word) {
if (!node) return null
if (word.length === 0) return node
return get(node.dictionary[word[0]], word.substring(1))
}
function recurse (node, stringAgg, resultsAgg) {
if (!node) return
// Check if this is a word
if (node.$) {
resultsAgg.push(stringAgg)
}
if (isEmpty(node.dictionary)) {
return
}
for (const c in node.dictionary) {
recurse(node.dictionary[c], stringAgg + c, resultsAgg)
}
}
const results = []
recurse(get(this, prefix), prefix, results)
return results
}
/**
* A function to search the given string and return true if it lands
* on on a word. Essentially testing if the word exists in the database.
**/
Trie.prototype.contains = function (string) {
if (this.cs === false) {
string = string.toLowerCase()
}
if (string.length === 0) {
return this.$
}
// Otherwise, we need to continue searching
const firstLetter = string[0]
const next = this.dictionary[firstLetter]
// If we don't have a node, this isn't a word
if (!next) {
return false
}
// Otherwise continue the search at the next node
return next.contains(string.substring(1))
}
/**
* A function to search the TRIE and return an array of words which were encountered along the way.
* This will only return words with full prefix matches.
* for example if we had the following words in our database:
* a, ab, bc, cd, abc
* and we searched the string: abcd
* we would get only:
* [a, ab, abc]
**/
Trie.prototype.findMatchesOnPath = function (search) {
if (this.cs === false) {
search = search.toLowerCase()
}
function recurse (node, search, stringAgg, resultsAgg) {
// Check if this is a word.
if (node.$) {
resultsAgg.push(stringAgg)
}
// Check if the have completed the seearch
if (search.length === 0) {
return resultsAgg
}
// Otherwise, continue searching
const next = node.dictionary[search[0]]
if (!next) {
return resultsAgg
}
return recurse(next, search.substring(1), stringAgg + search[0], resultsAgg)
};
return recurse(this, search, '', [])
}
/**
* Returns the longest match and the remaining part that could not be matched.
* inspired by [NLTK containers.trie.find_prefix](http://nltk.googlecode.com/svn-/trunk/doc/api/nltk.containers.Trie-class.html).
**/
Trie.prototype.findPrefix = function (search) {
if (this.cs === false) {
search = search.toLowerCase()
}
function recurse (node, search, stringAgg, lastWord) {
// Check if this is a word
if (node.$) {
lastWord = stringAgg
}
// Check if we have no more to search
if (search.length === 0) {
return [lastWord, search]
}
// Continue searching
const next = node.dictionary[search[0]]
if (!next) {
return [lastWord, search]
}
return recurse(next, search.substring(1), stringAgg + search[0], lastWord)
};
return recurse(this, search, '', null)
}
/**
* Computes the number of actual nodes from this node to the end.
* Note: This involves traversing the entire structure and may not be
* good for frequent use.
**/
Trie.prototype.getSize = function () {
let total = 1
for (const c in this.dictionary) {
total += this.dictionary[c].getSize()
}
return total
}
/**
* EXPORT THE TRIE
**/
module.exports = Trie |
import { z } from 'zod'
// Definir el esquema para validar el tipo de valor
const stringSchema = z.string()
/**
* Checks if a value is a string.
*
* @param {unknown} value - The value to check.
* @returns {value is string} - True if the value is a string, false otherwise.
*
* @example
* // Example usage:
* const value1 = 'hello';
* const value2 = 42;
* isString(value1); // Returns: true
* isString(value2); // Returns: false
*
* @note value is string | something is a way of telling the compiler that the function acts as a guard type.
*/
export function isString (value: unknown): value is string {
return stringSchema.safeParse(value).success
} |
import re
import nltk
from nltk.corpus import stopwords as nltk_stopwords
from nltk.stem.porter import PorterStemmer
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.model_selection import train_test_split
class ModelTraining:
"""
A class used for training machine learning models for spam detection.
Attributes
----------
pattern : str
Regular expression pattern for text cleaning.
repl : str
Replacement string for text cleaning.
stopwords : set
Set of stopwords.
max_features : int
Maximum number of features for the vectorizer.
test_size : float
Proportion of the dataset to include in the test split.
random_state : int
Random seed for shuffling the data.
ps : PorterStemmer
Porter stemmer for stemming words.
cv : CountVectorizer
Vectorizer for transforming text data.
"""
download_stopwords = False
def __init__(self, pattern='[^a-zA-Z]', repl=' ', stopwords=None, max_features=1500,
test_size=0.2, random_state=0):
"""
Initializes the ModelTraining class.
Parameters
----------
pattern : str, optional
Regular expression pattern for text cleaning.
repl : str, optional
Replacement string for text cleaning.
stopwords : set, optional
Set of stopwords.
max_features : int, optional
Maximum number of features for the vectorizer.
test_size : float, optional
Proportion of the dataset to include in the test split.
random_state : int, optional
Random seed for shuffling the data.
"""
self.download_stopwords()
self.pattern = pattern
self.repl = repl
self.stopwords = stopwords if stopwords is not None else set(nltk_stopwords.words('english'))
self.max_features = max_features
self.test_size = test_size
self.random_state = random_state
self.ps = PorterStemmer()
self.cv = None
def download_stopwords(self):
"""
Downloads the NLTK stopwords if not already downloaded.
"""
if not ModelTraining.download_stopwords:
nltk.download('stopwords')
ModelTraining.download_stopwords = True
def clean_data(self, data, column_name='Cleaned_Message', pattern='[^a-zA-Z]', repl=' ', stopwords=None, ps=None):
"""
Cleans the text data by removing non-alphabetic characters, converting to lowercase, and removing stopwords.
Parameters
----------
data : DataFrame
The data to clean.
column_name : str, optional
The column name of the text data.
pattern : str, optional
Regular expression pattern for text cleaning.
repl : str, optional
Replacement string for text cleaning.
stopwords : set, optional
Set of stopwords.
ps : PorterStemmer, optional
Porter stemmer for stemming words.
Returns
-------
list
The cleaned text data.
"""
corpus = []
number = len(data)
if stopwords is None:
stopwords = self.stopwords
if ps is None:
ps = PorterStemmer()
for i in range(number):
if number > 1:
review = re.sub(self.pattern, self.repl, data[column_name][i])
else:
review = re.sub(pattern, repl, data[0])
review = review.lower()
review = [ps.stem(word) for word in review.split() if word not in stopwords]
review = ' '.join(review)
corpus.append(review)
return corpus
def vectorize_data(self, corpus, max_features=None):
"""
Vectorizes the text data using CountVectorizer.
Parameters
----------
corpus : list
The text data to vectorize.
max_features : int, optional
Maximum number of features for the vectorizer.
Returns
-------
array
The vectorized text data.
"""
if max_features is None:
max_features = self.max_features
self.cv = CountVectorizer(max_features=max_features)
X = self.cv.fit_transform(corpus).toarray()
return X
def split_data(self, X, y):
"""
Splits the data into training and testing sets.
Parameters
----------
X : array-like
Features.
y : array-like
Labels.
Returns
-------
tuple
Training and testing sets for features and labels.
"""
return train_test_split(X, y, test_size=self.test_size, random_state=self.random_state)
def pre_train(self, data, split=True, column=0, column_name='Cleaned_Message'):
"""
Prepares the data for training by cleaning and vectorizing it, and optionally splitting into training and testing sets.
Parameters
----------
data : DataFrame
The data to prepare.
split : bool, optional
Whether to split the data into training and testing sets.
column : int, optional
The column index of the target variable.
column_name : str, optional
The column name of the text data.
Returns
-------
tuple
Prepared data for training and testing sets, or the entire dataset if split is False.
"""
corpus = self.clean_data(data, column_name)
X = self.vectorize_data(corpus)
y = data.iloc[:, column].values
if split:
return self.split_data(X, y)
else:
return X, y
def clean_predict(self, predict):
"""
Cleans a single text message for prediction.
Parameters
----------
predict : str
The text message to clean.
Returns
-------
str
The cleaned text message.
"""
review = re.sub(pattern=self.pattern, repl=self.repl, string=predict)
review = review.lower()
review = [self.ps.stem(word) for word in review.split() if word not in self.stopwords]
review = ' '.join(review)
return review
def main():
pass
if __name__ == '__main__':
main() |
import React, { useState } from 'react';
import styles from './Layout.module.css';
import Slideshow from './Slideshow';
const Layout = () => {
const [isPlaying, setIsPlaying] = useState(false);
const togglePlay = () => {
setIsPlaying(!isPlaying);
};
const rectangleSlides = [
<div className={styles.rectangleButton}>Rectangular Button 1</div>,
<div className={styles.rectangleButton}>Rectangular Button 2</div>,
<div className={styles.rectangleButton}>Rectangular Button 3</div>
];
return (
<div className={styles.container}>
<div className={styles.header}>
<h1>Nicolle Gordillo</h1>
</div>
<div className={styles.main}>
<div className={styles.left}>
<div className={styles.vinylRecord} style={{ animationPlayState: isPlaying ? 'running' : 'paused' }}></div>
<div className={styles.needleCircle}></div>
<div className={styles.recordNeedle}></div>
<div className={styles.recordNeedleTip}></div>
<button className={styles.playButton} onClick={togglePlay}>
{isPlaying ? 'Pause' : 'Play'}
</button>
</div>
<div className={styles.right}>
<Slideshow slides={rectangleSlides} />
</div>
</div>
</div>
);
};
export default Layout; |
import React, { Component } from 'react';
import { Table } from 'antd';
import { connect } from 'react-redux';
import { getCategories } from '../../redux/Categories/categories.actions';
const columns = [
{
title: 'Category',
dataIndex: 'category_name',
key: 'category_name',
},
{
title: 'Description',
dataIndex: 'description',
key: 'description',
},
];
class CategoriesList extends Component {
// constructor(props) {
// super(props);
// }
componentDidMount() {
const { getCategories: getCategoriesRequest } = this.props;
getCategoriesRequest()
.then(() => {
console.log('successfull');
})
.catch((err) => console.log(err));
}
render() {
const { categories } = this.props;
return <Table columns={columns} dataSource={categories} />;
}
}
const mapStateToProps = ({ categories: { categories } }) => ({
categories,
});
const mapDispatchToProps = (dispatch) => ({
getCategories: () => dispatch(getCategories()),
});
export default connect(mapStateToProps, mapDispatchToProps)(CategoriesList); |
package eu.excitementproject.eop.transformations.utilities;
/**
*
* Used to acknowledge threads that they should abort their current work.
* When a task is divided into several threads, and is done in a multi-thread manner,
* if one of the threads fails to accomplish its work, than it means that the task will
* not be completed, which means that there is no need that the other threads will continue
* their work.
* <P>
* Instead of using {@link Thread#destroy()} or {@link Thread#stop()}, which
* are deprecated, a simple concept of {@link StopFlag} is introduced here.
* All the threads share the same instance of {@link StopFlag}, and constantly check
* its status by calling the method {@link #isStop()}. If that method returns <tt>true</tt>,
* it means that there was some failure in one of the threads, and the other threads will
* end their work safely.
* <BR>
* A thread that fails should call {@link #stop()} in order to acknowledge the other threads
* that there was a failure and they should abort their work.
*
* @author Asher Stern
* @since Jun 6, 2011
*
*/
public class StopFlag
{
@SuppressWarnings("serial")
public static class StopException extends Exception{}
/**
* A thread should call this if it has any failure and cannot accomplish its task.
*/
public synchronized void stop()
{
stop=true;
}
/**
* Indicates whether any thread had a failure.
*
* @return true if any thread had a failure (and called {@link #stop()} method).
*/
public boolean isStop()
{
return this.stop;
}
private boolean stop=false;
} |
<?xml version="1.0"?>
<?xml-stylesheet type="text/css" href="chrome://global/skin"?>
<?xml-stylesheet type="text/css" href="/tests/SimpleTest/test.css"?>
<!--
https://bugzilla.mozilla.org/show_bug.cgi?id=1034730
-->
<window title="Mozilla Bug 1034730"
xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul">
<script type="application/javascript"
src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"></script>
<script type="application/javascript"
src="chrome://mochikit/content/chrome-harness.js"></script>
<script type="application/javascript" src="head.js"/>
<!-- test results are displayed in the html:body -->
<body xmlns="http://www.w3.org/1999/xhtml">
<a href="https://bugzilla.mozilla.org/show_bug.cgi?id=1034730"
target="_blank">Mozilla Bug 1034730</a>
</body>
<script type="application/javascript">
<![CDATA[
/** Test for Bug 1034730 **/
"use strict";
SimpleTest.waitForExplicitFinish();
Cu.import("resource://gre/modules/Services.jsm");
Cu.import("resource://gre/modules/NativeApp.jsm");
Cu.import("resource://gre/modules/WebappOSUtils.jsm");
Cu.import("resource://gre/modules/Promise.jsm");
let runTest = Task.async(function*() {
let manifest = yield readJSON(getTestFilePath("data/appcached_app/manifest.webapp"));
let app = {
name: manifest.name,
manifestURL: "http://127.0.0.1:8888/chrome/toolkit/webapps/tests/data/appcached_app/manifest.webapp",
origin: "http://127.0.0.1:8888/",
};
let testAppInfo = new TestAppInfo(app, false);
// Get to a clean state before the test
yield testAppInfo.cleanup();
SimpleTest.registerCleanupFunction(() => testAppInfo.cleanup());
setDryRunPref();
// On Mac build servers, we don't have enough privileges to write to /Applications,
// so we install apps in a user-owned directory.
if (MAC) {
yield setMacRootInstallDir(OS.Path.join(OS.Constants.Path.homeDir, "Applications"));
}
confirmNextPopup();
let request = navigator.mozApps.install(app.manifestURL);
{
let deferred = Promise.defer();
request.onerror = function() {
deferred.reject(this.error.name);
};
request.onsuccess = deferred.resolve;
yield deferred.promise;
}
let appObject = request.result;
ok(appObject, "app is non-null");
while (!WebappOSUtils.isLaunchable(app)) {
yield wait(1000);
}
ok(true, "App launchable");
{
let size = 0;
do {
try {
size = yield dirSize(OS.Path.join(testAppInfo.profileDir.path, "OfflineCache"));
} catch (e) {
yield wait(1000);
}
} while (size == 0);
ok(size > 100000, "There are some files in the OfflineCache directory");
}
let exeFile = getFile(testAppInfo.exePath);
let appClosed = false;
testAppInfo.appProcess.init(exeFile)
testAppInfo.appProcess.runAsync([], 0, () => appClosed = true);
while (!(yield wasAppSJSAccessed()) && !appClosed) {
yield wait(1000);
}
ok(!appClosed, "App was launched and is still running");
{
let size = 0;
do {
try {
size = yield dirSize(OS.Path.join(testAppInfo.cacheDir.path, "OfflineCache"));
} catch (e) {
yield wait(1000);
}
} while (size == 0);
ok(size > 100000, "There are some files in the OfflineCache directory");
}
SimpleTest.finish();
});
runTest().catch((e) => {
ok(false, "Error during test: " + e);
SimpleTest.finish();
});
]]>
</script>
</window> |
import type { Preset } from "unocss"
export interface GridOptions {
gridTemplateAreas: {
[key: string]: string[];
};
}
export function presetGridAreas(options: GridOptions): Preset {
const gridTemplateAreas = (name) => options?.gridTemplateAreas?.[name] ? options?.gridTemplateAreas?.[name].map((row) => (`"${row}"`)).join('\n') : ''
return {
name: "unocss-preset-grid-areas",
rules: [
['grid-areas-none', { 'grid-template-areas': 'none' }],
['grid-areas-inherit', { 'grid-template-areas': 'inherit' }],
['grid-areas-initial', { 'grid-template-areas': 'initial' }],
['grid-areas-revert', { 'grid-template-areas': 'revert' }],
['grid-areas-revert-layer', { 'grid-template-areas': 'revert-layer' }],
['grid-areas-unset', { 'grid-template-areas': 'unset' }],
['grid-in-auto', { 'grid-area': 'auto' }],
['grid-in-inherit', { 'grid-area': 'inherit' }],
['grid-in-initial', { 'grid-area': 'initial' }],
['grid-in-revert', { 'grid-area': 'revert' }],
['grid-in-revert-layer', { 'grid-area': 'revert-layer' }],
['grid-in-unset', { 'grid-area': 'unset' }],
[/^grid-in-(.+)$/, ([_, name]) => ({ 'grid-area': `${name}` })],
[/^row-start-(.+)$/, ([_, name]) => ({ 'grid-row-start': `${name}-start` })],
[/^row-end-(.+)$/, ([_, name]) => ({ 'grid-row-end': `${name}-end` })],
[/^col-start-(.+)$/, ([_, name]) => ({ 'grid-column-start': `${name}-start` })],
[/^col-end-(.+)$/, ([_, name]) => ({ 'grid-column-end': `${name}-end` })],
[/^grid-areas-(.*)$/, ([_, name]) => ({ 'grid-template-areas': gridTemplateAreas(name) })],
],
}
}
export default presetGridAreas |
"""A tool used to search content of PFD files with steel construction General Arrangement drawings to find if all steel asseblies
have corresponding assembly marks. The tool reads all text from GA drawings, searches for assembly marks and compares the results
with list of given assembly drawings"""
from PyPDF2 import PdfReader
from pathlib import Path
import re
import tkinter as tk
import tkinter.filedialog as fd
import tkinter.scrolledtext as st
# Set display window
window = tk.Tk()
window.title('GA - Assembly compare')
# window.iconbitmap('compare.ico')
window.resizable(0, 0)
# Define application class
class GaAssemblyCompare:
def __init__(self, main):
self.main = main
# Define list of files to compare
self.ga_dwgs = []
self.assy_dwgs = []
self.log_txt = ""
# Define main frames grid
self.frame1 = tk.Frame(self.main, width=100, borderwidth=5)
self.frame2 = tk.Frame(self.main, width=100, borderwidth=5)
self.frame3 = tk.Frame(self.main, width=100, borderwidth=5)
self.frame4 = tk.Frame(self.main, width=100, borderwidth=5)
self.frame1.grid(row=0, column=0, padx=2)
self.frame2.grid(row=0, column=1, padx=2)
self.frame3.grid(row=0, column=2, padx=2, sticky=tk.N)
self.frame4.grid(row=0, column=3, padx=2)
# Define assembly and ga drawings listboxes
self.assy_lstbox = tk.Listbox(self.frame1, width=25, height=30, selectmode=tk.SINGLE)
self.assy_lstbox.grid(row=1, column=1)
self.assy_scrollbar = tk.Scrollbar(self.frame1, orient=tk.VERTICAL, command=self.assy_lstbox.yview)
self.assy_scrollbar.grid(row=1, column=0, sticky=tk.NS)
self.assy_lstbox.config(yscrollcommand=self.assy_scrollbar)
self.ga_lstbox = tk.Listbox(self.frame2, width=25, height=30, selectmode=tk.SINGLE)
self.ga_lstbox.grid(row=1, column=1)
self.ga_scrollbar = tk.Scrollbar(self.frame2, orient=tk.VERTICAL, command=self.ga_lstbox.yview)
self.ga_scrollbar.grid(row=1, column=0, sticky=tk.NS)
self.ga_lstbox.config(yscrollcommand=self.ga_scrollbar)
# Define buttons
self.button_add_assy = tk.Button(self.frame1, text='Select assembly drawings', command=self.select_assy_dwgs)
self.button_add_assy.grid(row=0, column=0, columnspan=2, sticky=tk.EW)
self.button_add_ga = tk.Button(self.frame2, text='Select GA drawings', command=self.select_ga_dwgs)
self.button_add_ga.grid(row=0, column=0, columnspan=2, sticky=tk.EW)
self.button_auto_fill = tk.Button(self.frame3, text='Auto-fill drawings', command=self.auto_select)
self.button_auto_fill.grid(row=0, column=0, columnspan=2, sticky=tk.EW, pady=(0,200))
self.button_compare = tk.Button(self.frame3, text='Compare marks \u279d', command=self.compare_drawings, width=21)
self.button_compare.grid(row=1, column=0, columnspan=2)
self.button_save = tk.Button(self.frame3, text='Save log file', command=self.save_log, width=21)
self.button_save.grid(row=2, column=0, columnspan=2)
# Define output text widget
self.output_txt = st.ScrolledText(self.frame4, width=40, height=30)
self.output_txt.grid(row=1, column=0, sticky=tk.NS)
self.output_txt.config(background='gray92', wrap='word')
self.display_message("Select assembly and GA drawings or Auto-fill and select \"Drawings\" folder")
self.display_message("\n\nAssembly marks printed in white/invisible color will be treated as visible!", clear_box=False)
# Define drop down menu to select assembly mark numbering pattern
self.assy_pattern = None
self.dropdown_label = tk.Label(self.frame3, text='Fabricator:')
self.dropdown_label.grid(row=3, column=0, sticky=tk.W)
self.fab_options = ['','ALM', 'BSC', 'TSC', 'CSS', 'other']
self.fab = tk.StringVar()
self.fab.set(self.fab_options[0])
self.dropdown = tk.OptionMenu(self.frame3, self.fab, *self.fab_options, command=self.pattern_changed)
self.dropdown.grid(row=3, column=1, sticky=tk.E)
# Define button functions
def display_message(self, message, clear_box=True):
"""Displays given message in textbox"""
self.output_txt.config(state='normal')
if clear_box:
self.output_txt.delete('1.0', tk.END)
else:
self.output_txt.insert(tk.INSERT, "\n")
self.output_txt.insert(tk.INSERT, message)
self.output_txt.config(state='disabled')
def pattern_changed(self, *args):
"""Change assembly numbering regex pattern to be used to find assembly marks on GA drawings"""
if self.fab.get() == '':
self.assy_pattern = None
elif self.fab.get() == 'ALM':
self.display_message('Numbering pattern:\n1B234\nE-3.2.1')
self.assy_pattern = re.compile(r'(\d+(?![X])[A-Z]{1,3}\d+)')
self.ga_pattern = re.compile(r'^E-\d{1,3}\.\d{1,3}\.\d{1,3}$')
elif self.fab.get() == 'TSC':
self.display_message('Numbering pattern:\n1234B\nE4321')
self.assy_pattern = re.compile(r'(\d{1,6}(?![X])[A-Z]{1,3})')
self.ga_pattern = re.compile(r'^[A-M]{1,2}\d{1,6}$')
elif self.fab.get() == 'BSC':
self.display_message('Numbering pattern:\n[G]1234\nE4321')
self.assy_pattern = re.compile(r'(G*\d{3,})')
self.ga_pattern = re.compile(r'^(?!G)[A-Z]{1,2}\d{1,6}$')
elif self.fab.get() == 'CSS':
self.display_message('Numbering pattern:\n123B\nE-321')
self.assy_pattern = re.compile(r'(\d+(?![X])[A-Z]{1,3})')
self.ga_pattern = re.compile(r'^[A-Z]{1,2}-\d{1,4}$')
elif self.fab.get() == 'other':
self.display_message('Log file will not contain all assembly marks on GA drawings list')
self.assy_pattern = re.compile(r'(.+)')
def select_assy_dwgs(self):
"""Empty assembly drawings list and listbox and populate with new selected files"""
self.assy_dwgs.clear()
self.assy_lstbox.delete(0, tk.END)
selected_files = self.select_files('Select assembly drawings')
for filepath in selected_files:
self.assy_dwgs.append((filepath, Path(filepath).stem))
self.populate_listbox(self.assy_lstbox, self.assy_dwgs)
def select_ga_dwgs(self):
"""Empty GA drawings list and listbox and populate with new selected files"""
self.ga_dwgs.clear()
self.ga_lstbox.delete(0, tk.END)
selected_files = self.select_files('Select GA drawings')
for filepath in selected_files:
self.ga_dwgs.append((filepath, Path(filepath).stem))
self.populate_listbox(self.ga_lstbox, self.ga_dwgs)
def select_files(self, msg):
"""Open a dialog window and select PDF files"""
root = tk.Tk()
root.withdraw()
selected_files = fd.askopenfilenames(parent=root, title=msg, filetypes=[('PDF', '.pdf')])
root.destroy()
return selected_files
def auto_select(self):
"""Open a dialog window and select folder containing all drawings. Auto fill assembly drawings and GA drawings lists."""
if not self.fab.get():
self.display_message("Select fabricator first.")
return
elif self.fab.get() == 'other':
self.display_message('Auto-fill can not be performed with "other" fabricator selected.')
return
else:
root = tk.Tk()
root.withdraw()
dwgs_dir = fd.askdirectory(parent=root, title='Select drawings folder')
root.destroy()
# List all files in selected directory
files_in_dir = list(Path(dwgs_dir).iterdir())
# Find assembly drawings and GA drawings paths
assy_paths = sorted([Path(file) for file in files_in_dir if self.assy_pattern.match(Path(file).stem)])
ga_paths = sorted([Path(file) for file in files_in_dir if self.ga_pattern.match(Path(file).stem)])
# Empty drawing lists
self.assy_dwgs.clear()
self.assy_lstbox.delete(0, tk.END)
self.ga_dwgs.clear()
self.ga_lstbox.delete(0, tk.END)
# Fill drawing lists
for filepath in assy_paths:
self.assy_dwgs.append((filepath, Path(filepath).stem))
self.populate_listbox(self.assy_lstbox, self.assy_dwgs)
for filepath in ga_paths:
self.ga_dwgs.append((filepath, Path(filepath).stem))
self.populate_listbox(self.ga_lstbox, self.ga_dwgs)
# Display number of drawings found
self.display_message(f'Assembly drawings found:\t{len(assy_paths)}')
self.display_message(f'GA drawings found:\t{len(ga_paths)}', clear_box=False)
def populate_listbox(self, lstbox, files):
"""Populate tkinter listbox with filenames from list"""
lstbox.delete(0, tk.END)
for file in files:
lstbox.insert(tk.END, file[1])
def save_log(self):
"""Save log file with list of missing assembly marks"""
if self.log_txt:
save_dir = Path(self.assy_dwgs[0][0]).parents[0]
file_dir = Path(save_dir, 'log.txt')
with open(file_dir, 'w') as f:
f.write(self.log_txt)
self.display_message(f'\nLog file saved:\n{file_dir}', clear_box=False)
else:
self.display_message('Nothing to save.\nRun "Compare marks" first.')
def compare_drawings(self):
"""Compare content of all selected GA drawings with list of selected assembly drawings"""
# Clear output text window
self.output_txt.config(state='normal')
self.output_txt.delete('1.0', tk.END)
# Clear out log string
self.log_txt = ""
log_string = ""
# Display warnings
if not self.assy_dwgs:
self.display_message('Select assembly drawings!')
return
if not self.ga_dwgs:
self.display_message('Select GA drawings!')
return
if not self.assy_pattern:
self.display_message('Select Fabricator!')
return
# Find all assembly marks matching given regex
assy_on_ga = set()
for dwg in self.ga_dwgs:
self.output_txt.insert(tk.INSERT, f'Searching {dwg[1]}...\n')
reader = PdfReader(dwg[0])
page = reader.pages[0]
page_text = page.extract_text()
page_assy_lst = set(re.findall(self.assy_pattern, page_text))
assy_on_ga.update(page_assy_lst)
# Create log file containilg list of all assembly marks on GA drawings
if self.fab.get() != 'other':
log_string += f'\t{dwg[1]}:\n'
for i in sorted(list(page_assy_lst)):
log_string += f'{i}\n'
self.main.update()
# Set of all assembly numbers from given assembly drawings
assy = {i[1] for i in self.assy_dwgs}
# Display result messages
if assy.issubset(assy_on_ga):
self.log_txt += "OK. All assemblies are shown on GA drawings."
self.display_message("OK. All assemblies are shown on GA drawings.")
else:
assy_not_shown = sorted(list(assy - assy_on_ga))
self.output_txt.delete('1.0', tk.END)
self.output_txt.insert(tk.INSERT, "Missing assembly marks on GA drawings:")
self.log_txt += "\tMissing assembly marks on GA drawings:\n"
for i in assy_not_shown:
self.output_txt.insert(tk.INSERT, f'\n{i}')
self.log_txt += f'{i}\n'
self.output_txt.config(state='disabled')
# Add list of assembly marks on GA drawings to log file
if self.fab.get() != 'other':
self.log_txt += "\nAssembly marks shown on GA drawings:\n"
self.log_txt += log_string
# Create app object
app = GaAssemblyCompare(window)
window.mainloop() |
import { Injectable } from '@nestjs/common';
import { InjectRepository } from "@nestjs/typeorm";
import { Repository } from "typeorm";
import { CreateCommentDto } from './dto/create-comment.dto';
import { UpdateCommentDto } from './dto/update-comment.dto';
import { Comment } from "./entities/comment.entity";
@Injectable()
export class CommentsService {
constructor(
@InjectRepository(Comment)
private repository: Repository<Comment>,
) {}
create(createCommentDto: CreateCommentDto) {
return this.repository.save({ ...createCommentDto });
}
findAll() {
return this.repository.find();
}
findOne(id: number) {
return this.repository.findOneBy({ id });
}
update(id: number, updateCommentDto: UpdateCommentDto) {
return this.repository.save({ ...updateCommentDto, id });
}
async remove(id: number) {
await this.repository.delete(id);
}
} |
package franxx.code.spring.core;
import franxx.code.spring.core.data.Bar;
import franxx.code.spring.core.data.Foo;
import franxx.code.spring.core.scope.DoubleScope;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.config.CustomScopeConfigurer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;
@Slf4j
@Configuration
public class ScopeConf {
@Bean
@Scope("prototype")
public Foo foo() {
log.info("Creating Foo");
return new Foo();
}
@Bean
@Scope("singleton") // default
public Bar bar() {
log.info("Creating Bar");
return new Bar();
}
@Bean
public CustomScopeConfigurer customScopeConfigurer() {
CustomScopeConfigurer configurer = new CustomScopeConfigurer();
configurer.addScope("double", new DoubleScope());
return configurer;
}
@Bean(name = "scope")
@Scope("double")
public Bar barScope() {
log.info("Create bar scope");
return new Bar();
}
} |
import type { ViteDevServer } from 'vite';
import lt from 'localtunnel';
import type { AddressInfo } from 'node:net';
type PluginOptions = lt.TunnelConfig & { timeout?: number };
export default (opts: PluginOptions) => ({
name: 'localtunnel-server',
enforce: 'post',
apply: 'serve',
configureServer(server: ViteDevServer) {
let tunnel: lt.Tunnel;
const logger = server.config.logger;
server.httpServer?.once('listening', async () => {
const address = server.httpServer!.address();
const isAddressInfo = (x: any): x is AddressInfo => x?.address;
if (!isAddressInfo(address)) {
logger.error(
'Could not retrieve ViteDevServer address. localtunnel could not start',
{
timestamp: true,
}
);
return;
}
if (tunnel != null) {
await tunnel.close();
}
await new Promise((r) => setTimeout(r, opts.timeout ?? 1000));
tunnel = await lt({
port: address.port,
subdomain: opts?.subdomain,
});
logger.info('\nlocaltunnel has started!\n');
server.resolvedUrls?.network.push(tunnel.url);
server.printUrls();
});
server.httpServer?.on('close', async () => {
if (tunnel != null) {
await tunnel.close();
logger.info('Shutting down localtunnel');
}
});
},
}); |
[toc]
Design a HashMap without using any built-in hash table libraries.
To be specific, your design should include these functions:
* `put(key, value)` : Insert a `(key, value)` pair into the HashMap. If the value already exists in the HashMap, update the value.
* `get(key)`: Returns the value to which the specified key is mapped, or -1 if this map contains no mapping for the key.
* `remove(key)` : Remove the mapping for the value key if this map contains the mapping for the key.
**Note**:
* All keys and values will be in the range of `[0, 1000000]`.
* The number of operations will be in the range of `[1, 10000]`.
* Please do not use the built-in HashMap library.
## 题目解读
 设计哈希表。
```java
class MyHashMap {
/** Initialize your data structure here. */
public MyHashMap() {
}
/** value will always be non-negative. */
public void put(int key, int value) {
}
/** Returns the value to which the specified key is mapped, or -1 if this map contains no mapping for the key */
public int get(int key) {
}
/** Removes the mapping of the specified value key if this map contains a mapping for the key */
public void remove(int key) {
}
}
/**
* Your MyHashMap object will be instantiated and called as such:
* MyHashMap obj = new MyHashMap();
* obj.put(key,value);
* int param_2 = obj.get(key);
* obj.remove(key);
*/
```
## 程序设计
* 设计变长的哈希表,超时,主要花销为重散列时数组拷贝。
```java
class MyHashMap {
private int size;
private Node[] table;
public MyHashMap() {
this.size = 0;
this.table = new Node[9];
}
public void put(int key, int value) {
if (size > table.length / 2) rehash();
Node temp = table[getHash(key)];
while (temp != null && temp.key != key) temp = temp.next;
if (temp != null) temp.val = value;
else {
table[getHash(key)] = new Node(key, value, table[getHash(key)]);
size++;
}
}
public int get(int key) {
Node temp = table[getHash(key)];
while (temp != null && temp.key != key) temp = temp.next;
return temp == null ? -1 : temp.val;
}
public void remove(int key) {
Node temp = table[getHash(key)];
if (temp == null) return;
if (temp.key == key) {
table[getHash(key)] = temp.next;
size--;
return;
}
while (temp.next != null && temp.next.key != key) temp = temp.next;
if (temp.next != null) {
temp.next = temp.next.next;
size--;
}
}
private int getHash(int key) {
return key % table.length;
}
private void rehash() {
int newSize = size >= Integer.MAX_VALUE / 2 ? Integer.MAX_VALUE : size * 2 + 1;
Node[] temp = table;
table = new Node[newSize];
for (Node cur : temp) {
if (cur == null) continue;
while (cur != null) {
put(cur.key, cur.val);
cur = cur.next;
}
}
temp = null;
}
class Node {
int key;
int val;
Node next;
Node(int key, int val, Node next) {
this.key = key;
this.val = val;
this.next = next;
}
}
}
```
* 事实上考虑复杂了,不考虑重散列,初始化时指定尺寸为2069:
```java
class MyHashMap {
private int size;
private Node[] table;
public MyHashMap() {
this.size = 0;
// 初始指定容量
this.table = new Node[2069];
}
public void put(int key, int value) {
// 本题无需考虑重散列
// if (size > table.length / 2) rehash();
Node temp = table[getHash(key)];
while (temp != null && temp.key != key) temp = temp.next;
if (temp != null) temp.val = value;
else {
table[getHash(key)] = new Node(key, value, table[getHash(key)]);
size++;
}
}
public int get(int key) {
Node temp = table[getHash(key)];
while (temp != null && temp.key != key) temp = temp.next;
return temp == null ? -1 : temp.val;
}
public void remove(int key) {
Node temp = table[getHash(key)];
if (temp == null) return;
if (temp.key == key) {
table[getHash(key)] = temp.next;
size--;
return;
}
while (temp.next != null && temp.next.key != key) temp = temp.next;
if (temp.next != null) {
temp.next = temp.next.next;
size--;
}
}
private int getHash(int key) {
return key % table.length;
}
class Node {
int key;
int val;
Node next;
Node(int key, int val, Node next) {
this.key = key;
this.val = val;
this.next = next;
}
}
}
```
## 性能分析
 时间复杂度最坏为$O(N)$,空间复杂度为$O(N)$。
执行用时:18ms,在所有java提交中击败了99.72%的用户。
内存消耗:42.8MB,在所有java提交中击败了100.00%的用户。
## 官方解题
 同上。 |
import Layout from '@/components/Layout';
import { useSession } from 'next-auth/react';
import { Inter, Plus_Jakarta_Sans } from 'next/font/google';
import Head from 'next/head';
import { SubmitHandler, useForm } from 'react-hook-form';
import axios from 'axios';
import { useRouter } from 'next/router';
import { GetServerSideProps, GetServerSidePropsContext } from 'next';
import { getServerSession } from 'next-auth';
import { authOptions } from '../api/auth/[...nextauth]';
import FormContact from '@/components/FormContact';
import Toast from '@/components/Toast';
import { useEffect, useState } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import {
changeBio,
changeFirstname,
changeImgUrl,
changeLastname,
changeOccupation,
changeTwitter,
resetForm,
} from '@/redux/formSlice';
const inter = Inter({ subsets: ['latin'] });
const jakarta = Plus_Jakarta_Sans({ subsets: ['latin'] });
export interface IFormInput {
firstName: string;
lastName: string;
occupation: string;
twitter: string;
bio: string;
imgUrl: string;
}
export const getServerSideProps: GetServerSideProps = async (
context: GetServerSidePropsContext
) => {
const session = await getServerSession(context.req, context.res, authOptions);
if (!session) {
return {
redirect: {
permanent: false,
destination: '/login',
},
};
}
return {
props: {},
};
};
function NewContact() {
const router = useRouter();
const session = useSession();
const [showError, setShowError] = useState(false);
const {
register,
handleSubmit,
reset,
formState: { errors, isSubmitting },
} = useForm<IFormInput>();
const formState = useSelector<{ form: IFormInput }>((state) => state.form);
const dispatch = useDispatch();
const onSubmit: SubmitHandler<IFormInput> = async (formData) => {
setShowError(false);
try {
await axios.post(
'/api/contacts',
{
...formData,
userId: session.data?.user.id,
},
{
headers: {
'Content-Type': 'application/json',
},
}
);
localStorage.removeItem('form');
dispatch(resetForm());
router.push('/');
} catch (error: any) {
console.log(error);
setShowError(true);
}
};
useEffect(() => {
reset(formState as IFormInput);
}, []);
return (
<>
<Head>
<title>Create Contact | Qontax</title>
</Head>
<Layout>
<section className={`${inter.className} py-8`}>
<div className='relative max-w-screen-xl mx-auto px-8 py-6 '>
<div className='max-w-lg mx-auto space-y-10'>
<div className='w-fit text-gray-400 flex gap-3 items-center'>
<div className='w-8 h-8 md:w-10 md:h-10 p-2 md:p-2.5 rounded-lg border border-gray-300/10 bg-gray-800'>
<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='currentColor'>
<path
fillRule='evenodd'
d='M19.5 21a3 3 0 003-3V9a3 3 0 00-3-3h-5.379a.75.75 0 01-.53-.22L11.47 3.66A2.25 2.25 0 009.879 3H4.5a3 3 0 00-3 3v12a3 3 0 003 3h15zm-6.75-10.5a.75.75 0 00-1.5 0v2.25H9a.75.75 0 000 1.5h2.25v2.25a.75.75 0 001.5 0v-2.25H15a.75.75 0 000-1.5h-2.25V10.5z'
clipRule='evenodd'
/>
</svg>
</div>
<h1 className={`${jakarta.className} text-2xl sm:text-4xl font-bold`}>
Create Contact
</h1>
</div>
{showError && <Toast>Failed to create the contact. Please try again.</Toast>}
<form autoComplete='off' onSubmit={handleSubmit(onSubmit)}>
<div className='grid gap-4 sm:grid-cols-2 sm:gap-6'>
<div className='w-full'>
<div className='flex items-center justify-between mb-2'>
<label
htmlFor='firstName'
className='block text-sm font-medium text-gray-300'>
Firstname
</label>
{errors.firstName?.type === 'required' && (
<span className='text-red-500 text-xs'>*Field required</span>
)}
</div>
<input
type='text'
id='firstName'
className='border text-sm rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-600 focus:border-blue-600 block w-full p-2.5 bg-gray-800/50 border-gray-700/50 placeholder-gray-500 text-white '
placeholder='John'
{...register('firstName', { required: true })}
onChange={(e) => dispatch(changeFirstname(e.target.value))}
/>
</div>
<div className='w-full'>
<div className='flex items-center justify-between mb-2'>
<label
htmlFor='lastName'
className='block text-sm font-medium text-gray-300'>
Lastname
</label>
{errors.lastName?.type === 'required' && (
<span className='text-red-500 text-xs'>*Field required</span>
)}
</div>
<input
type='text'
id='lastName'
className=' border text-sm rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-600 focus:border-blue-600 block w-full p-2.5 bg-gray-800/50 border-gray-700/50 placeholder-gray-500 text-white '
placeholder='Doe'
{...register('lastName', { required: true })}
onChange={(e) => dispatch(changeLastname(e.target.value))}
/>
</div>
<div className='sm:col-span-2'>
<div className='flex items-center justify-between mb-2'>
<label htmlFor='imgUrl' className='block text-sm font-medium text-gray-300'>
Image URL
</label>
{errors.imgUrl && (
<span className='text-red-500 text-xs'>*Enter valid URL</span>
)}
</div>
<input
type='text'
id='imgUrl'
className=' border text-sm rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-600 focus:border-blue-600 block w-full p-2.5 bg-gray-800/50 border-gray-700/50 placeholder-gray-500 text-white '
placeholder='https://images.unsplash.com/profile'
{...register('imgUrl', {
required: true,
pattern: {
value:
/https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\+.~#?&//=]*)/,
message: 'Enter valid URL',
},
})}
onChange={(e) => dispatch(changeImgUrl(e.target.value))}
/>
</div>
<div className='full'>
<div className='flex items-center justify-between mb-2'>
<label
htmlFor='occupation'
className='block text-sm font-medium text-gray-300'>
Occupation
</label>
{errors.occupation?.type === 'required' && (
<span className='text-red-500 text-xs'>*Field required</span>
)}
</div>
<input
type='text'
id='occupation'
className=' border text-sm rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-600 focus:border-blue-600 block w-full p-2.5 bg-gray-800/50 border-gray-700/50 placeholder-gray-500 text-white '
placeholder='Web Developer'
{...register('occupation', { required: true })}
onChange={(e) => dispatch(changeOccupation(e.target.value))}
/>
</div>
<div className='full'>
<div className='flex items-center justify-between mb-2'>
<label
htmlFor='twitter'
className='block text-sm font-medium text-gray-300'>
Twitter
</label>
{errors.twitter?.type === 'required' && (
<span className='text-red-500 text-xs'>*Field required</span>
)}
</div>
<input
type='text'
id='twitter'
className=' border text-sm rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-600 focus:border-blue-600 block w-full p-2.5 bg-gray-800/50 border-gray-700/50 placeholder-gray-500 text-white '
placeholder='johndoe'
{...register('twitter', { required: true })}
onChange={(e) => dispatch(changeTwitter(e.target.value))}
/>
</div>
<div className='sm:col-span-2'>
<div className='flex items-center justify-between mb-2'>
<label htmlFor='bio' className='block text-sm font-medium text-gray-300'>
Bio
</label>
{errors.bio?.type === 'required' && (
<span className='text-red-500 text-xs'>*Field required</span>
)}
</div>
<textarea
id='bio'
rows={4}
className='block p-2.5 w-full text-sm resize-none rounded-lg border sm:ring-blue-500 focus:outline-none focus:ring-2 focus:border-blue-500 bg-gray-800/50 border-gray-700/50 placeholder-gray-500 text-white focus:ring-blue-500 '
{...register('bio', { required: true })}
onChange={(e) => dispatch(changeBio(e.target.value))}
placeholder='Your bio here'></textarea>
</div>
</div>
<button
type='submit'
disabled={isSubmitting}
className='inline-flex items-center justify-center px-5 min-w-[10rem] py-2.5 mt-4 sm:mt-6 text font-medium text-center text-white bg-blue-700 rounded-lg focus:ring-4 focus:ring-blue-600 hover:bg-blue-800'>
{isSubmitting ? (
<svg
aria-hidden='true'
role='status'
className='inline w-6 h-6 animate-spin text-gray-600'
viewBox='0 0 100 101'
fill='none'
xmlns='http://www.w3.org/2000/svg'>
<path
d='M100 50.5908C100 78.2051 77.6142 100.591 50 100.591C22.3858 100.591 0 78.2051 0 50.5908C0 22.9766 22.3858 0.59082 50 0.59082C77.6142 0.59082 100 22.9766 100 50.5908ZM9.08144 50.5908C9.08144 73.1895 27.4013 91.5094 50 91.5094C72.5987 91.5094 90.9186 73.1895 90.9186 50.5908C90.9186 27.9921 72.5987 9.67226 50 9.67226C27.4013 9.67226 9.08144 27.9921 9.08144 50.5908Z'
className='fill-slate-400'
/>
<path
d='M93.9676 39.0409C96.393 38.4038 97.8624 35.9116 97.0079 33.5539C95.2932 28.8227 92.871 24.3692 89.8167 20.348C85.8452 15.1192 80.8826 10.7238 75.2124 7.41289C69.5422 4.10194 63.2754 1.94025 56.7698 1.05124C51.7666 0.367541 46.6976 0.446843 41.7345 1.27873C39.2613 1.69328 37.813 4.19778 38.4501 6.62326C39.0873 9.04874 41.5694 10.4717 44.0505 10.1071C47.8511 9.54855 51.7191 9.52689 55.5402 10.0491C60.8642 10.7766 65.9928 12.5457 70.6331 15.2552C75.2735 17.9648 79.3347 21.5619 82.5849 25.841C84.9175 28.9121 86.7997 32.2913 88.1811 35.8758C89.083 38.2158 91.5421 39.6781 93.9676 39.0409Z'
className='fill-slate-200'
/>
</svg>
) : (
'Submit'
)}
</button>
</form>
</div>
</div>
</section>
</Layout>
</>
);
}
export default NewContact; |
# Phirehose #
A PHP interface to the Twitter Streaming API (firehose, etc). This library makes it easy to connect to and consume the Twitter stream via the Streaming API.
See:
* https://github.com/fennb/phirehose/wiki/Introduction and
* http://dev.twitter.com/pages/streaming_api
## Goals ##
* Provide a simple interface to the Twitter Streaming API for PHP applications
* Comply to Streaming API recommendations for error handling, reconnection, etc
* Encourage well-behaved streaming API clients
* Operate independently of PHP extensions (ie: shared memory, PCNTL, etc)
In short:
require_once('Phirehose.php');
class MyStream extends Phirehose
{
public function enqueueStatus($status)
{
print $status;
}
}
$stream = new MyStream('username', 'password');
$stream->consume();
## What this library does do ##
* Handles connection/authentication to the twitter streaming API
* Consumes the stream handing off each status to be enqueued by a method of your choice
* Handles graceful reconnection/back-off on connection and API errors
* Monitors/reports performance metrics and errors
## What this library doesn't do ##
* Decode/process tweets
* Provide any sort of queueing mechanism for asynchronous processing (though some examples are included)
* Provide any sort of inter-process communication
* Provide any non-streaming API functionality (ie: user profile info, search, etc)
Please see the wiki for [documentation](https://github.com/fennb/phirehose/wiki/Introduction).
If you have any additional questions, head over to the Phirehose Users group [http://groups.google.com/group/phirehose-users]
It's recommended that you join (or at least regularly check) this group if you're actively using Phirehose so I can let you know when I release new versions.
Additionally, if you'd like to contact me directly, I'm [@fennb](http://twitter.com/fennb) on twitter. |
/*
* Copyright (c) 2008,
* Commissariat a l'Energie Atomique (CEA)
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* - Neither the name of CEA nor the names of its contributors may be used to
* endorse or promote products derived from this software without specific
* prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED.
* IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES;LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* Authors: Daniel Gracia Perez (daniel.gracia-perez@cea.fr)
*/
#ifndef __ST231_MEMORY_OP_HH__
#define __ST231_MEMORY_OP_HH__
#include <inttypes.h>
namespace st231
{
class MemoryOp
{public:
typedef uint32_t address_t;
typedef enum
{ READ,
WRITE,
PREFETCH
} type_t;
/**
* \brief Build a READ memory op
*/
MemoryOp(address_t address, uint32_t size, uint32_t &_dest, int32_t &_counter, bool aligned, bool read_signed) : dest(_dest) , counter(_counter)
{ type = READ;
this->address = address;
this->size = size;
target_reg = dest;
this->read_signed = read_signed;
this->aligned = aligned;
}
/**
* \brief Build a WRITE memory op
*/
MemoryOp(address_t address, uint32_t size, uint32_t value, int32_t &_counter) : dest(dest_none), counter(_counter)
{ type = WRITE;
this->address = address;
this->size = size;
write_value = value;
}
/**
* \brief Build a PREFETCH memory op
*/
MemoryOp(address_t address) : dest(dest_none), counter(counter_none)
{ type = PREFETCH;
this->address = address;
}
~MemoryOp() {}
type_t GetType() const
{ return type;
}
address_t GetAddress() const
{ return address;
}
uint32_t GetSize() const
{ return size;
}
uint32_t GetTargetReg() const
{ return target_reg;
}
uint32_t GetWriteValue() const
{ return write_value;
}
bool NeedAlignment() const
{ return !aligned;
}
bool IsSigned() const
{ return read_signed;
}
private:
address_t address;
type_t type;
uint32_t size;
uint32_t target_reg;
uint32_t write_value;
bool read_signed;
bool aligned;
uint32_t dest_none;
int32_t counter_none;
public:
uint32_t &dest;
int32_t &counter;
};
} // end of namespace st231
#endif |
# [SPRING: GPT-4 Out-performs RL Algorithms by Studying Papers and Reasoning](https://arxiv.org/abs/2305.15486)
## What is the central research question or hypothesis that this paper addresses?
Based on my reading of the paper, the central research question is:
How can we develop reinforcement learning agents that can efficiently learn to complete complex, multi-step tasks in procedurally generated open-world environments like Minecraft?
The key hypothesis is that by designing an environment called Crafter that captures the key challenges of Minecraft (procedural generation, sparse rewards, deep exploration, etc.) in a simpler and faster simulator, researchers can more rapidly prototype and benchmark reinforcement learning algorithms for solving these kinds of complex, open-ended environments.
The paper introduces Crafter as a new benchmark environment that:
- Procedurally generates survival sandboxes similar to Minecraft
- Provides a compact action space and fast simulation for quick iterations
- Provides a structured set of achievements for measuring multi-task learning
- Allows complex, multi-step tasks through a technology tree spanning tools, resources, etc.
The authors argue that developing and testing algorithms in Crafter that can efficiently learn policies to complete achievements across this technology tree will help drive progress towards more sample-efficient, generalizable agents for Minecraft and related open-world games. The paper includes experiments benchmarking various RL algorithms in Crafter as a first step.
In summary, the key hypothesis is that the Crafter environment can accelerate research on reinforcement learning for Minecraft-like games by providing a faster, more controlled environment that still captures the core challenges. The paper introduces Crafter and benchmarks performance of current algorithms as an initial investigation of this hypothesis.
## What is the main contribution of this paper?
Based on the LaTeX source code provided, the main contribution of this paper seems to be introducing a new environment called Crafter for benchmarking reinforcement learning algorithms. Some key points:
- Crafter is designed to capture the complexity of Minecraft in a simple and fast environment for faster experiment iteration. It features procedural generation, a deep tech tree, sparse rewards, and multiple objectives.
- The paper proposes a set of metrics for evaluating agent performance in Crafter across different skills like exploration, planning, generalization, and credit assignment. The main metric is a score function that aggregates success rates across achievements.
- Experiments are presented benchmarking various RL algorithms like PPO, Rainbow, etc. in Crafter using the proposed metrics. The results demonstrate Crafter poses significant challenges for current RL methods.
- In addition to extrinsic reward experiments, the paper introduces "intrinsically motivated" experiments without extrinsic rewards. This tests an agent's ability to set its own goals and explore efficiently.
In summary, the main contribution is proposing Crafter as a new challenging benchmark environment for RL research, along with a set of metrics for evaluation. The experiments demonstrate existing algorithms still have much room for improvement in Crafter.
## What is the TL;DR (Too Long, Didn't Read) version of the paper? If you had to summarize it in one sentence, what would that be?
Here is a one sentence summary of the key points from the paper:
The paper introduces Crafter, a new procedural generation environment inspired by Minecraft that captures key challenges like exploration, sparse rewards, and long-term credit assignment while being faster and easier to use than Minecraft itself.
## How does this paper compare to other research in the same field?
Here is a comparison of this paper to other related research in reinforcement learning for procedurally generated environments:
- This paper introduces Crafter, a new procedurally generated environment inspired by Minecraft. It is designed specifically for fast prototyping and benchmarking of RL algorithms. Other related environments include the actual Minecraft environment, MiniGrid, and NetHack. Crafter aims to balance complexity and speed.
- A key contribution of this paper is introducing a set of diverse and semantically meaningful metrics for evaluating agent performance in Crafter. These include an aggregated achievement score metric that measures success on unlocking achievements in the game's technology tree. Most prior work on procedural generation benchmarks use only sparse rewards. Defining good evaluation metrics has been an open challenge.
- The paper shows strong performance of modern model-based RL algorithms like Dreamer v2 in Crafter. These algorithms substantially outperform model-free methods like Rainbow DQN. Other recent work has also highlighted the advantages of model-based RL in procedurally generated or open worlds.
- The paper ablates different auxiliary losses used by algorithms like RND and Plan2Explore. The impact of these losses that aim to promote exploration is smaller in Crafter than in other benchmarks. The authors hypothesize this may be due to Crafter's dense rewards. Exploration techniques may be less critical in such environments.
- The paper introduces a simple imitation learning method by having agents clone human demonstrations. This cloning approach leads to large gains over the RL methods. Using human data has been shown to be highly effective in other work as well, but limited demonstration data is often available.
In summary, Crafter offers a new fast-paced benchmark for studying procedural generation with clear metrics. The paper provides insights into model-based RL and exploration methods in this setting. It also shows the value of leveraging human data through cloning, pointing to an important direction for future work. The environment and findings represent useful contributions to the field.
## What future research directions do the authors suggest?
Based on my reading of the paper, here are some of the main future research directions suggested by the authors:
1. Developing better exploration strategies and intrinsic motivation techniques for reinforcement learning algorithms to handle the challenges of Crafter's large state and action spaces. The authors suggest exploring methods like curiosity-driven exploration and empowerment to improve sample efficiency.
2. Studying transfer learning and generalization capabilities in procedural environments like Crafter. The procedural generation leads to a distribution shift between training and evaluation environments. Developing RL algorithms that can transfer knowledge across different procedural generations is an important direction.
3. Scaling up agents to handle even more complex environments like Minecraft. Crafter aims to provide a simpler alternative to Minecraft for faster iteration, but ultimately the goal is to develop methods that can handle full Minecraft.
4. Developing algorithms that can handle sparse and delayed rewards in Crafter more effectively. The authors suggest ideas like hierarchical reinforcement learning and intrinsic motivation as possible solutions.
5. Studying multi-task and continual learning settings in Crafter where agents need to pursue multiple objectives and learn new tasks sequentially.
6. Developing better evaluation protocols and metrics for open-ended environments like Crafter. Standard RL metrics like episodic return may not fully capture performance.
7. Combining model-based RL methods like world models with intrinsic motivation and information maximization objectives to take advantage of Crafter's perfect environment information.
8. Exploring ways to provide helpful priors and curriculum strategies to agents in Crafter to improve learning efficiency. Ideas like human demonstrations, advice, or curricula could help bootstrap learning.
In summary, the authors point to the need for more sample efficient, generalized, and multi-task capable RL algorithms to handle complex open-ended environments like Crafter and Minecraft. Combining model-based RL with intrinsic rewards, transfer learning, hierarchies, and better exploration seem like promising future directions.
## Summarize the paper in one paragraph.
Here is a one paragraph summary of the key points from the paper:
The paper introduces Crafter, a new procedurally generated environment for benchmarking reinforcement learning algorithms. Crafter is inspired by Minecraft and features key challenges such as exploration with a deep technology tree, multitasking, sparse rewards, and learning from pixels. The environment allows fast iteration compared to Minecraft while capturing many of its complexities. Key features include procedurally generated terrain, 22 achievements linked in a technology tree of depth 7, a day/night cycle with variable lighting, visual observations, and an action space with 17 discrete actions for interaction. The paper presents an analysis of various RL algorithms including PPO, Rainbow, RND, and Dreamer on the Crafter benchmark. The results demonstrate Crafter poses a difficult exploration challenge. The paper argues that Crafter provides a fertile testbed for developing new RL algorithms that can handle complex, long-horizon tasks requiring generalized policies for procedural environments.
## Summarize the paper in two paragraphs.
Here is a two paragraph summary of the key points from the paper:
The paper introduces a new benchmark environment called Crafter for training and testing reinforcement learning agents. Crafter is inspired by Minecraft and includes many of the same gameplay elements like mining, crafting, hunting, and exploration. However, Crafter is designed to be simpler and faster to train agents on compared to the full Minecraft game.
The key features of Crafter highlighted in the paper are: procedurally generated maps requiring generalization, a technology tree with many tools to craft, sparse rewards for achievements, and the ability to define many metrics to evaluate agent performance. Experiments are run with popular RL algorithms like PPO, Rainbow, and RND which achieve limited success. The authors argue Crafter poses challenges related to exploration, credit assignment, and long-term reasoning that current RL methods struggle to solve. They propose Crafter as a benchmark to drive progress on these challenges.
## Summarize the main method used in the paper in one paragraph.
Here is a one paragraph summary of the main method used in the paper:
The paper proposes SPRING, a novel framework that leverages large language models (LLMs) to tackle complex open-world survival games like Crafter. The framework has two main stages - studying the game's academic paper and reasoning about that knowledge to take actions. In the first stage, SPRING extracts key gameplay information from the LaTeX source code of Crafter's original paper through a series of questions targeted at identifying relevant paragraphs and summarizing important gameplay details. In the second reasoning stage, SPRING uses a directed acyclic graph (DAG) of questions about the current game state as nodes and dependencies as edges to prompt the LLM to reason through gameplay in a consistent chain-of-thought. The LLM's response to the final DAG node question is parsed into an executable game action. Experiments using GPT-4 show SPRING can surpass state-of-the-art reinforcement learning methods without any training, highlighting the potential of LLMs for complex game-based problems when provided proper prompting.
## What problem or question is the paper addressing?
Based on the abstract, the paper is addressing the challenge of developing AI agents that can perform well in complex open-world survival games like Minecraft. Such games pose significant difficulties for current AI methods due to factors like procedural generation, diverse action spaces, technology trees, and conflicting objectives.
The paper proposes a new environment called Crafter that captures many of the key challenges of Minecraft in a simpler and faster setting to help drive research progress. The goal is to provide an environment where results can be obtained much faster, and where many meaningful evaluation metrics are available.
So in summary, the main problem the paper is aiming to tackle is advancing AI capabilities in complex, open-world survival games using a simplified environment called Crafter as a testbed. The paper introduces this new environment to help accelerate research in this challenging domain.
## What are the keywords or key terms associated with this paper?
Based on a quick skim of the paper, here are some key terms that appear relevant:
- Crafter environment - The paper introduces this new procedurally generated environment inspired by Minecraft for benchmarking reinforcement learning algorithms. It features key challenges like exploration, sparse rewards, etc.
- Procedural generation - The Crafter environment uses procedural generation to create diverse worlds and situations to evaluate generalization.
- Technology tree - Similar to Minecraft, Crafter has a technology tree that requires crafting tools to gather resources to craft more advanced tools/weapons and unlock achievements. Requires long-term planning.
- Sparse rewards - The environment provides a sparse +1 reward for unlocking new achievements, making credit assignment very challenging.
- Object interactions - The environment features 17 different types of object interactions like hit, eat, equip, etc. that the agent needs to learn.
- Achievements - There are 22 achievements in Crafter aligned with the technology tree that serve as a curriculum of tasks for agents to solve.
- Reinforcement learning - The paper benchmarks various RL algorithms like PPO, Rainbow, etc. in the Crafter environment.
- Evaluation metrics - Two key metrics used are episodic reward and an aggregated score based on achievement unlocking rates.
So in summary, key terms include procedurally generated world, technology tree, sparse rewards, diverse object interactions, benchmarks for RL algorithms. The Crafter environment itself is the main focus.
## Based on the paper, what questions should we ask to create a comprehensive summary of it? Please list at least 10 questions.
Here are 10 potential questions to ask to create a comprehensive summary of the paper:
1. What problem is the paper trying to solve? This helps establish the motivation and goals.
2. What is the key idea or approach proposed in the paper? This summarizes the main technical contribution.
3. What are the key components or steps in the proposed method? This provides more details on how the method works.
4. What experiments were conducted to evaluate the method? This highlights the empirical evaluation.
5. What were the main results of the experiments? This summarizes the key findings.
6. How does the proposed method compare to prior or alternative approaches? This provides context relative to related work.
7. What are the limitations of the proposed method? This highlights assumptions or shortcomings.
8. What future work does the paper suggest? This indicates promising research directions.
9. What datasets were used in the experiments? This clarifies the data sources.
10. What metrics were used to evaluate performance? This specifies how results were measured.
The questions aim to summarize the key information needed to understand what was done in the paper, how the method works, how it was evaluated, and the significance of the results and future directions. The questions cover the problem, approach, method details, experiments, results, comparisons, limitations, future work, data, and evaluation metrics.
## Design 10 in-depth questions about method proposed in this paper and avoid simple question.
Here are 10 potential in-depth questions about the method proposed in the paper:
1. The paper proposes a framework called SPRING that consists of two main stages: studying the paper and reasoning. Could you elaborate more on how the studying stage works? What techniques are used to extract key information from the paper's LaTeX source code?
2. The reasoning stage uses a DAG-based prompting approach. What motivated this design choice compared to other prompting techniques? How was the DAG structure and questions determined? Were other DAG configurations experimented with?
3. The paper shows strong zero-shot performance of SPRING+GPT-4 compared to RL methods. To what extent could this be attributed to GPT-4's scale and few-shot reasoning ability versus the SPRING framework? Were experiments done with smaller LLMs to analyze this?
4. How does SPRING handle situations where the extracted paper knowledge is inaccurate or incomplete? Does it have any inherent robustness or ability to correct itself?
5. The paper focuses on the Crafter environment. How might SPRING need to be adapted for more complex games like Minecraft with bigger action spaces? Are there scalability challenges?
6. Beyond games, what other applications could benefit from SPRING's approach of extracting and reasoning over academic papers? Could scientific papers be used in a similar way?
7. The paper uses a fixed DAG structure and questions for reasoning. How sensitive is performance to the exact DAG configuration and question wording? Could the DAG be learned in a more automated way?
8. The visual observation descriptor plays an important role in grounding SPRING. How might visual-language models like ViLT be integrated to avoid needing an engineered descriptor?
9. How efficiently can SPRING transfer knowledge from one game paper to another? Does each new game require full re-training or could some components transfer?
10. What are the broader societal impacts - both positive and negative - of systems like SPRING that can rapidly acquire and reason about knowledge from academic papers?
## Write a very high-quality paragraph summarizing the paper that effectively covers the paper.
Here is a high-quality paragraph summarizing the key points of the paper:
This paper proposes a novel approach called SPRING that enables large language models (LLMs) like GPT-4 to effectively play complex open-world survival games like Crafter. The key idea is to first have the LLM read and extract knowledge from the academic paper that introduced Crafter, and then reason about that knowledge to determine actions using a question-answering framework. Specifically, the LLM first reads the LaTeX source code of the Crafter paper to identify gameplay information like objects, actions, dependencies etc. It then reasons about the current observation and extracted knowledge using a DAG of interdependent questions designed to promote consistent chain-of-thought reasoning. The LLM's answer to the final DAG node representing the best action is executed in the game environment. Experiments show SPRING with GPT-4 substantially outperforms state-of-the-art RL algorithms like DreamerV3 trained for 1 million steps, without any training. The work demonstrates the reliability of LLMs for understanding and reasoning with human knowledge, and their potential for complex games. It also proposes an effective way to integrate human priors into RL through intrinsic rewards or subgoal planning.
## Summarize the paper in one sentence.
The paper proposes SPRING, a novel approach that uses a large language model (GPT-4) to read the academic paper of the Crafter game environment and reason about gameplay through a QA framework, achieving state-of-the-art performance without any training.
## Summarize the paper in one paragraphs.
Here is a one paragraph summary of the key points from the paper:
The paper proposes SPRING, a novel method for playing complex open-world survival games like Crafter using large language models (LLMs). The approach has two main stages - first, the LLM reads and extracts key gameplay information from the academic paper that introduced Crafter. Second, the LLM reasons about this knowledge to plan actions using a QA framework structured as a directed acyclic graph. Each node in the graph is a question relevant for gameplay, with edges representing dependencies between questions. By traversing the graph and answering questions in topological order, the LLM produces a consistent chain of reasoning to select optimal actions. Experiments show SPRING with GPT-4 achieves state-of-the-art performance on Crafter, outperforming all RL baselines. The work demonstrates how LLMs can effectively leverage academic papers as a knowledge source for gameplay, using controlled prompting to enable complex reasoning and planning. It points to new ways of integrating human priors into RL through intrinsic rewards, hierarchies, or subgoal planning.
## Design 10 in-depth questions about the method proposed in this paper and avoid simple questions.
Here are 10 potential in-depth questions about the method proposed in this paper:
1. How does the Paper Studying module extract key information from the academic paper's LaTeX source code? What techniques does it use to identify relevant paragraphs and summarize the information?
2. What motivated the use of a directed acyclic graph (DAG) structure for the QA prompts in the Reasoning module? How does the DAG help promote consistent chain-of-thought reasoning over hundreds of time steps?
3. The method parses the final node of the DAG into an environment action using substring matching. What are some limitations of this simple parsing approach? How could more sophisticated natural language understanding techniques be incorporated?
4. What types of game-specific information does the context string C contain? How was the set of questions Q_game designed to extract the most useful information from the paper?
5. How robust is the method to variations in the phrasing of the questions in Q_act? Could the DAG structure compensate if certain questions are less effective at eliciting reasoning?
6. How does the visual descriptor d convert the raw visual observation into a textual description? What tradeoffs were made in its design between computational efficiency and descriptive accuracy?
7. The method achieves strong performance without any training, unlike RL methods. What are some ways the extracted knowledge could be used to improve sample efficiency of RL algorithms?
8. Could the approach be applied successfully to other complex games beyond Crafter? What modifications would be needed to handle different observation spaces or action sets?
9. The Component Analysis shows the importance of the full paper context and DAG reasoning. How could the approach be improved to rely less heavily on these aspects?
10. The paper hypothesizes games could be a useful testbed for evaluating LLMs. What specific capabilities of LLMs could games like Crafter effectively benchmark? |
alias Yagg.Unit
alias Yagg.Event
alias Yagg.Board
alias Yagg.Board.Grid
alias Yagg.Unit.Ability
defmodule Unit.Antente do
@behaviour Unit
@impl Unit
def new(position) do
Unit.new(
name: :antente,
attack: 5,
defense: 4,
triggers: %{
attack: Unit.Antente.Visible,
},
visible: :none,
position: position
)
end
end
defmodule Unit.Antente.Invisible do
@moduledoc """
Become invisible until your next attack
"""
use Ability, noreveal: :true
@impl Ability
def resolve(board, opts) do
{x, y} = opts[:coords]
{board, events} = Grid.update(
board,
{x, y},
&make_invisible/1
)
{board, [Event.ThingGone.new(x: x, y: y) | events]}
end
defp make_invisible(unit) do
%{unit | visible: :none, ability: :nil, triggers: %{ attack: Unit.Antente.Visible }}
end
end
defmodule Unit.Antente.Visible do
@moduledoc """
Becomes visible to opponent
"""
use Unit.Trigger.BeforeAttack
@impl Unit.Trigger.BeforeAttack
def before_attack(board, data) do
%{position: position} = data.unit
{x, y} = data.from
vis_event = Event.UnitPlaced.new(x: x, y: y, player: position)
{board, e1} = Grid.update(board, data.from, &make_visible/1, [vis_event])
{board, e2} = Board.do_battle(board, data.unit, data.opponent, data.from, data.to)
{board, e1 ++ e2}
end
defp make_visible(unit) do
unit = Unit.make_visible(unit, :player)
%{unit | ability: Unit.Antente.Invisible, triggers: %{}}
end
end |
---
title: Demo Elements Page
description: A demo page for the various markup elements in the Dot Org theme.
images: ["https://via.placeholder.com/250x200/d9d9d9/000000"]
---
This is a demo page, designed to show you the various elements of the theme and how they sit together.
It has a custom social image, which can be set in the frontmatter.
Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula get dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat massa quis enim. Donec pede justo, fringilla vel, aliquet nec, vulputate get, arcu. In enim justo, rhoncus ut imperdiet a.
First here's how the Heading markup displays:
# H1 Heading
## H2 Heading
### H3 Heading
#### H4 Heading
##### H5 Heading
###### H6 Heading
## Horizontal Rule
___
# Example Content
Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula get dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient.
## Table of contents (Shortcode)
{{< toc >}}
## Example Paragraph
Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula get dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient.
## [Header as a link](https://www.cncf.io)
Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo [link text](http://google.com) ligula get dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat massa quis enim. Donec pede justo, fringilla vel, aliquet nec, vulputate get, arcu. In enim justo, rhoncus ut imperdiet a.
Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula get dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient.
## Example Intro Paragraph
{{< intro >}}
Donec pede justo, fringilla vel, aliquet nec, vulputate get, arcu. In enim justo, rhoncus ut imperdiet a. Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula get dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat massa quis enim.
{{< /intro >}}
## Example Paragraph with Buttons
Donec pede justo, fringilla vel, aliquet nec, vulputate get, arcu. In enim justo, rhoncus ut imperdiet a. Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula get dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat massa quis enim.
{{< button link="/path/to/page" text="Default Button" >}}
Donec pede justo, fringilla vel, aliquet nec, vulputate get, arcu. In enim justo, rhoncus ut imperdiet a. Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula get dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat massa quis enim.
{{< button link="/path/to/page" text="Default Button" >}}
{{< button link="/path/to/page" style="secondary" text="Secondary Button" >}}
{{< button link="/path/to/page" style="tertiary" text="Tertiary Button" >}}
Donec pede justo, fringilla vel, aliquet nec, vulputate get, arcu. In enim justo, rhoncus ut imperdiet a. Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula get dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat massa quis enim.
Aenean commodo ligula get dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat massa quis enim.
## Columns
Use responsive columns to layout your page structure. You can use the option count to have 2, 3 or 4 column layouts.
{{< columns count=2 >}}
{{< column >}}
### Column 1
Lorem ipsum dolor sit amet consectetuer adipiscing elit aenean commodo:
- Aenean commodo ligula get dolor.
- Aenean massa.
- Cum sociis natoque penatibus et.
- Magnis dis parturient montes.
{{< /column >}}
{{< column >}}
### Column 2
Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula get dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat massa quis enim. Donec pede justo, fringilla vel, aliquet nec, vulputate get, arcu. In enim justo, rhoncus ut imperdiet a.
{{< /column >}}
{{< /columns >}}
Here's a 4 column example:
{{< columns count=4 >}}
{{< column >}}
#### Column 1
{{< /column >}}
{{< column >}}
#### Column 2
{{< /column >}}
{{< column >}}
#### Column 3
{{< /column >}}
{{< column >}}
#### Column 4
{{< /column >}}
{{< /columns >}}
## Cards
Use the cards shortcode to display highlighted content on your page.
{{< cards >}}
{{< card >}}
## Something special
Lorem ipsum dolor sit amet consectetuer adipiscing elit aenean commodo
{{< spacer >}}
[Get our app](#)
{{< /card >}}
{{< card >}}
## Our special feature
Lorem ipsum dolor sit amet consectetuer adipiscing elit aenean commodo
{{< spacer >}}
[See our special feature](#)
{{< /card >}}
{{< /cards >}}
## YouTube standard (Hugo Shortcode) (not recommended)
{{< youtube QFSBC7G0URY >}}
Pulls from youtube-nocookie (based on config privacy settings) but still slows the page load down. Not recommended.
## YouTube Enhanced (with Playlists) (Shortcode)
{{< youtube_enhanced id="9oVr7rrNZVI" >}}
{{< youtube_enhanced id="xPSXtoJNGLs" title="Play Videos from Kubecon" playlistid="PLj6h78yzYM2PyrvCoOii4rAopBswfz1p7" >}}
## Vimeo standard (Hugo Shortcode) (not recommended)
The standard vimeo shortcode loads lots of tracking data and is slow, recommended to avoid this if possible.
{{< vimeo id="146022717" title="My vimeo video" >}}
## Emphasis
**This is bold text**
__This is bold text__
*This is italic text*
_This is italic text_
~~Strikethrough~~
## Blockquotes
Some text and then a quote:
> Blockquotes can be cool. Lorem ipsum dolor sit amet consectetuer adipiscing elit aenean commodo.
And also they can:
> Blockquotes can also be nested...
>> ...by using additional greater-than signs right next to each other...
> > > ...or with spaces between arrows.
## Lists
Unordered
+ Create a list by starting a line with `+`, `-`, or `*`
+ Sub-lists are made by indenting 2 spaces:
- Marker character change forces new list start:
* Ac tristique libero volutpat at
+ Facilisis in pretium nisl aliquet
- Nulla volutpat aliquam velit
+ Very easy!
Ordered
1. Lorem ipsum dolor sit amet
2. Consectetur adipiscing elit
3. Integer molestie lorem at massa
1. You can use sequential numbers...
1. ...or keep all the numbers as `1.`
Start numbering with offset:
57. foo
1. bar
## Code
This is a paragraph but the words `Inline code` are actually inline code. Whoddathunkit.
And then we have some indented code with a comment:
// A comment.
line 1 of code
line 2 of code
line 3 of code
And then we have some block code. They should all look pretty similar:
```
Sample text here...
```
And finally some syntax highlighting, yes, out of the box:
``` js
var foo = function (bar) {
return bar++;
};
console.log(foo(5));
```
## Tables
### Short table:
| Project | Date |
|---------|------------|
| Alpha | 2023-07-01 |
| Beta | 2023-07-15 |
| Gamma | 2023-08-01 |
| Delta | 2023-08-15 |
| Epsilon | 2023-09-01 |
### Longer content table (using Shortcode):
{{< responsive_table >}}
| Option | Option | Description |
| ------ | ------ | ----------- |
| one | data | path to data files to supply the data that will be passed into templates. |
| two | engine | engine to be used for processing templates. Handlebars is the default. |
| three | ext | extension to be used for dest files. |
{{< /responsive_table >}}
## Links
[link text](http://dev.nodeca.com)
[link with title](http://nodeca.github.io/pica/demo/ "title text!")
Autoconverted link https://github.com/nodeca/pica
## Images
Images expand to fit the content width.


Coming soon: Advanced image handling, lazy loading, etc.
## Gist
{{< gist thinhong 218cb565018eab7db50aa7cfd53c16c6 >}}
## Tweets
Embedding tweets like this loads lots of tracking scripts and is not recommended. Use a screenshot of the tweet and link the image to the real tweet.
{{< tweet user="SanDiegoZoo" id="1453110110599868418" >}}
## Iframe
You can embed iFrame content simply using our shortcode:
{{< iframe src="https://docs.google.com/presentation/d/e/2PACX-1vT6TcnSJki1RdzzDTbLCKDl96POVoW4bNZH--0lsJXNrPRRjPC83o2DGKuhZj38qjALnZJPLa0yhMW5/embed?start=false&loop=true&delayms=5000" >}}
## Footnotes
Footnote 1 link[^first].
Footnote 2 link[^second].
Duplicated footnote reference[^second].
[^first]: Footnote is here.
[^second]: Footnote text. |
using System;
using Medidata.RWS.NET.Standard.Core.Requests.Datasets;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Medidata.RWS.NET.Standard.Tests.Core.Requests.Datasets
{
[TestClass]
public class VersionDatasetRequestTests
{
[TestMethod]
public void VersionDatasetRequest_default_version_path_is_correct()
{
var request = new VersionDatasetRequest(project_name: "Mediflex", environment_name: "Dev", version_oid: "001");
Assert.AreEqual("Mediflex", request.ProjectName);
Assert.AreEqual("Dev", request.EnvironmentName);
Assert.AreEqual("001", request.VersionOid);
Assert.AreEqual("studies/Mediflex(Dev)/versions/001/datasets/regular", request.UrlPath());
}
[TestMethod]
public void VersionDatasetRequest_raw_version_path_is_correct()
{
var request = new VersionDatasetRequest(project_name: "Mediflex", environment_name: "Dev", version_oid: "001", dataset_type: "raw");
Assert.AreEqual("Mediflex", request.ProjectName);
Assert.AreEqual("Dev", request.EnvironmentName);
Assert.AreEqual("001", request.VersionOid);
Assert.AreEqual("studies/Mediflex(Dev)/versions/001/datasets/raw", request.UrlPath());
}
[TestMethod]
public void VersionDatasetRequest_raw_version_path_with_form_is_correct()
{
var request = new VersionDatasetRequest(project_name: "Mediflex", environment_name: "Dev", version_oid: "001", dataset_type: "raw", formOid: "DM");
Assert.AreEqual("Mediflex", request.ProjectName);
Assert.AreEqual("Dev", request.EnvironmentName);
Assert.AreEqual("001", request.VersionOid);
Assert.AreEqual("studies/Mediflex(Dev)/versions/001/datasets/raw/DM", request.UrlPath());
}
[TestMethod]
[ExpectedException(typeof(NotSupportedException))]
public void VersionDatasetRequest_throws_with_improper_parameters()
{
var req = new VersionDatasetRequest("TESTPROJECT", "DEV", "1001", dataset_type: "newfie");
}
}
} |
# Default Game Commands
The following commands can be called at any time and are built into the game:
Autosaves the game and live-reloads all active scripts and mission locations to allow for live debugging and editing of missions
```lua
?reload_scripts
```
Kicks the associated player from the game.
```lua
?kick <peer_id>
```
Bans the associated player from the game.
```lua
?ban <peer_id>
```
Give a player admin status. Authorize a player to use commands and bypass custom menu lock.
```lua
?add_admin <peer_id>
```
Remove admin status from a player.
```lua
?remove_admin <peer_id>
```
Give a player auth status. Authorize a player to use workbenches.
```lua
?add_auth <peer_id>
```
Remove auth status from a player.
```lua
?remove_auth <peer_id>
```
Dedicated server only, lets you force the dedicated server to save. save_name parameter is optional and default uses save_name from server config (If config setting is left blank it will save to autosave_server.)
```lua
?save <save_name>
```
# Lua scripting overview
Lua scripting gives you the tools to create advanced missions and custom gamemodes. Stormworks provides a number of functions that allow your script to interface with the game.
This guide outlines the functions that are available but is not a comprehensive tutorial on using the Lua language
# API General Info
peer_id can be found on the left side of the player list, singleplayer games always use peer_id 0
The coordinate system uses Y as the vertical axis for matrices and vectors in world space
The functionalities of arguments in CAPS are detailed below the corresponding function
peer_id can be passed as -1 to send for all connected peers
Any variables saved to a lua table named g_savedata will be saved out and loaded from a per-save lua_data.xml, you can use this to make your scripts persistent
For code that you want to run once at the start of the save use onCreate(is_world_create) and check is_world_create is true
Using server.announce() in onCreate will usually cause the messages to be sent before your client is connected and they will not be received
Remember to avoid the table length operator # and iPairs unless dealing with contiguous tables that start at index 1 (If a table is unexpectedly showing as length 0 this probably means it is not contiguous, the following function can be used for non - standard tables)
```lua
function tableLength(T)
local count = 0
for _ in pairs(T) do count = count + 1 end
return count
end
```
# LUA FUNCTIONS
The following global lua functions are available:
- pairs
- ipairs
- next
- tostring
- tonumber
and additional functions are available through the following lua libraries:
- math
- table
- string
For full documentation of the functions provided by these libraries, visit https://www.lua.org/manual/.
# META FROM THE DEVS
This scripting API is very powerful and as such there are some important reminders to take note of:
- Your script has a max execution time of 1000 milliseconds, however it is still possible to create scripts that significantly slow down the game. It is your responsibility to ensure your script runs efficiently.
- peer_id can be passed as -1 to send for all connected peers
- Any variables saved to a lua table named g_savedata will be saved out and loaded from a per-save lua_data.xml, you can use this to make your scripts persistent
- A number of safeguards are in place to sandbox your script, however it is still possible to write scripts that will potentially crash your game. If you crash your game with a script, it's likely that you're doing something (very) wrong. This is your own responsibility. If you suspect you have encountered a legitimate bug, please report it on the Stormworks issue tracker (accessible from the pause-menu).
- Malicious and harmful scripts will not be tolerated on the Stormworks Steam Workshop.
Finally, enjoy the almost limitless possibilities that these scripts provide. This short wiki aims to give a good overview of how scripting in Stormworks works, however if you have any questions that are not covered here, please feel free to join us on Discord (accessible from the pause-menu)! |
package com.gnetop.letui.sleep.base.fg
import android.os.Bundle
import android.view.View
import androidx.databinding.ViewDataBinding
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import com.gnetop.letui.sleep.base.vm.BaseViewModel
import com.gnetop.letui.sleep.common.ActivityManager
import com.gnetop.letui.sleep.common.USER_LOGIN_STATE_CHANGED
import com.gnetop.letui.sleep.util.event.EventModel
import com.gnetop.letui.sleep.util.event.EventUtil
import com.gnetop.letui.sleep.widget.activity.LoginActivity
abstract class BaseVMFragment<VM : BaseViewModel, V : ViewDataBinding> : BaseFragment<V>() {
protected lateinit var mViewModel: VM
//懒加载
private var lazyLoaded = false
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
initViewModel()
initView()
observe()
// 因为Fragment恢复后savedInstanceState不为null,
// 重新恢复后会自动从ViewModel中的LiveData恢复数据,
// 不需要重新初始化数据。
if (savedInstanceState == null) {
initData()
}
}
override fun onResume() {
super.onResume()
// 实现懒加载
if (!lazyLoaded) {
lazyLoadData()
lazyLoaded = true
}
}
abstract fun viewModelClass(): Class<VM>
/**
* 初始化viewModel
*/
private fun initViewModel() {
mViewModel = ViewModelProvider(this).get(viewModelClass())
}
/**
* 如果有需要初始化
*/
open fun initData() {}
/**
* 如果有需要初始化
*/
open fun initView() {}
/**
* 如果有需要初始化
*/
open fun lazyLoadData() {
}
open fun observe() {
// 登录失效,跳转登录页
mViewModel.loginStatusInvalid.observe(viewLifecycleOwner, Observer {
if (it) {
EventUtil.send(EventModel(USER_LOGIN_STATE_CHANGED, false))
ActivityManager.start(LoginActivity::class.java)
}
})
}
/**
* 是否登录,如果登录了就执行then,没有登录就直接跳转登录界面
* @return true-已登录,false-未登录
*/
fun checkLogin(then: (() -> Unit)? = null): Boolean {
return if (mViewModel.loginState()) {
then?.invoke()
true
} else {
ActivityManager.start(LoginActivity::class.java)
false
}
}
} |
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
class Todo extends Model
{
use HasFactory;
protected $fillable = ['title', 'description', 'dueDate', 'public', 'image', 'note_id', 'user_id'];
public function note(): BelongsTo
{
return $this->belongsTo(Note::class);
}
public function creator(): BelongsTo
{
return $this->belongsTo(User::class, 'user_id'); //hier muss extra die ID genannt werden da creator automatisch eine creator_id suchen würde
}
public function tags(): BelongsToMany
{
return $this->belongsToMany(Tag::class)->withTimestamps();
}
public function users(): BelongsToMany
{
return $this->belongsToMany(User::class)->withTimestamps()->withPivot('assignedTo');
}
} |
import { type ReactElement } from 'react'
import { Link, usePage } from '@inertiajs/react'
import classNames from '@/Utils/classNames'
export default function AdminNavigation (): ReactElement {
const { component } = usePage()
const { canManageEditors, currentUserRole: role } = usePage().props
const dashboardLink: string = (role === 'admin' || role === 'super admin' || role === 'developer')
? route('admin.dashboard') : route('editor.dashboard')
const contentComponents: string[] = [
'Editor/Content/Index',
'Editor/Content/Collections/Index', 'Editor/Content/Collections/Create', 'Editor/Content/Collections/Show', 'Editor/Content/Collections/Edit',
'Editor/Content/Projects/Index', 'Editor/Content/Projects/Create', 'Editor/Content/Projects/Show', 'Editor/Content/Projects/Edit',
'Editor/Content/Goals/Index', 'Editor/Content/Goals/Create', 'Editor/Content/Goals/Show', 'Editor/Content/Goals/Edit',
'Editor/Content/Choices/Index', 'Editor/Content/Choices/Create', 'Editor/Content/Choices/Show', 'Editor/Content/Choices/Edit'
]
const mediaComponents: string[] = [
'Editor/Media/Index', 'Editor/Media/Create'
]
const assignmentComponents: string[] = [
'Admin/Assignments/Index', 'Admin/Assignments/Create', 'Admin/Assignments/Edit', 'Editor/Assignments/Show'
]
const editorManagementComponents: string[] = [
'Admin/Editors/Index', 'Admin/Editors/Create', 'Admin/Editors/Show', 'Admin/Editors/Edit'
]
const navigation = [
{ name: 'Dashboard', href: dashboardLink, show: true, components: ['Admin/Dashboard', 'Editor/Dashboard'] },
{ name: 'Content', href: route('editor.content.index'), show: true, components: contentComponents },
{ name: 'Media Library', href: route('editor.media.index'), show: true, components: mediaComponents },
{ name: 'Assignments', href: route('admin.assignments.index'), show: canManageEditors, components: assignmentComponents },
{ name: 'Admins & Editors', href: route('admin.editors.index'), show: canManageEditors, components: editorManagementComponents },
{ name: 'Navigation', href: route('admin.navigation.index'), show: canManageEditors, components: ['Admin/Navigation/Index'] }
]
const filteredNavigation = navigation.filter(item => item.show === true)
return (
<aside className="hidden lg:flex lg:flex-shrink-0">
<div className="flex flex-col w-64">
<div className="flex-1 flex flex-col min-h-0">
<div className="flex-1 flex flex-col py-8 overflow-y-auto">
<nav className="space-y-2 px-4" aria-label="Sidebar">
{filteredNavigation.map((item, index) => (
<Link
key={index}
href={item.href}
className={classNames(
item.components.includes(component) ? 'bg-gray-200 text-gray-900 font-semibold' : 'text-gray-600 hover:bg-gray-200 hover:text-gray-900',
'group flex items-center px-3 py-2 text-sm font-medium rounded-md'
)}
>
{item.name}
</Link>
))}
</nav>
</div>
</div>
</div>
</aside>
)
} |
import type {Options} from 'plyr'
import Plyr from 'plyr'
import {Socket} from 'socket.io-client'
import i18n from '@nuxtjs/i18n/dist/runtime/plugins/i18n.mjs'
import {getImageLink, hasScope} from '@vesp/frontend'
import {getFileLink} from '~/utils/vesp'
declare global {
type VespUserRole = {
id: number
title: string
scope: string[]
}
type VespUser = {
id: number
username: string
fullname?: string
password?: string
email?: string
phone?: string
active?: boolean
blocked?: boolean
notify?: boolean
role_id?: number
role?: VespUserRole
avatar_id?: number
avatar?: VespFile
subscription?: VespSubscription
new_avatar?: {file: string; metadata: {[key: string]: any}} | Boolean
}
type VespFile = {
id?: number
uuid: string
updated_at?: string
[key: string]: any
}
type VespVideo = {
id: string
title?: string
description?: string
[key: string]: any
}
type VespFileOptions = {
w?: string | number
h?: string | number
fit?: string
fm?: string
t?: string | number
}
type VespSetting = {
key: string
value: string
type: string
required: boolean
}
type VespLevel = {
id: number
title: string
content?: string
price: number
active: bool
new_cover?: {file: string; metadata: {[key: string]: any}} | Boolean
cover_id?: number
cover?: VespFile
}
type VespTopic = {
id: number
uuid?: string
title: string
content: Record<string, any>
user_id?: VespUser
level_id?: number
teaser?: string
price?: number | string
active: bool
closed: bool
new_cover?: {file: string; metadata: {[key: string]: any}} | Boolean
cover_id?: number
cover?: VespFile
level?: VespLevel
viewed_at?: string
comments_count?: number
views_count?: number
unseen_comments_count?: number
reactions_count?: number
tags?: VespTag[]
reaction?: number
[key: string]: any
}
type VespComment = {
id: number
topic_id?: number
topic?: VespTopic
content: Record<string, any>
active?: bool
created_at?: string
user?: VespUser
children?: VespComment[]
reactions_count?: number
reaction?: number
[key: string]: any
}
type VespPage = {
id: number
title: string
content: Record<string, any>
alias?: string
position?: string
rank?: number
active?: bool
[key: string]: any
}
type VespSubscription = {
id?: number
user_id?: number
level_id: number
next_level_id?: number
service?: string
period?: number
cancelled?: boolean
active?: boolean
active_until?: string
[key: string]: any
}
type VespPayment = {
id: number
amount: number
topic?: VespTopic
subscription?: VespSubscription
metadata?: Record<string, any>
}
type VespTag = {
id: number
title: string
topics?: number
[key: string]: any
}
type VespReaction = {
id: number
title: string
emoji: string
rank?: number
active?: boolean
}
}
declare module '@vue/runtime-core' {
interface ComponentCustomProperties {
$i18n: i18n
$image: getImageLink
$file: getFileLink
$scope: hasScope
$price: Function
$prism: Function
$prismLanguages: Record<string, any>
$socket: Socket
$sidebar: Ref<boolean>
$login: Ref<boolean>
$settings: Ref<Record<string, string | string[] | Record<string, any>>>
$pages: Ref<VespPage[]>
$levels: Ref<VespLevel[]>
$reactions: Ref<VespReaction[]>
$payment: Ref<undefined | VespTopic | VespLevel>
$isMobile: Ref<boolean>
$plyr: (element: HTMLElement | string, options: Options = {}) => Plyr
$plyrOptions: Options
$contentPreview: Function
$contentClick: (e: MouseClick) => void
}
}
declare module '#app' {
interface NuxtApp {
$i18n: i18n
$image: getImageLink
$file: getFileLink
$scope: hasScope
$price: Function
$prism: Function
$prismLanguages: Record<string, any>
$socket: Socket
$sidebar: Ref<boolean>
$login: Ref<boolean>
$settings: Ref<Record<string, string | string[] | Record<string, any>>>
$pages: Ref<Record<string, any>[]>
$levels: Ref<VespLevel[]>
$reactions: Ref<VespReaction[]>
$payment: Ref<undefined | VespTopic | VespLevel>
$isMobile: Ref<boolean>
$plyr: (element: HTMLElement | string, options: Options = {}) => Plyr
$plyrOptions: Options
$contentPreview: Function
$contentClick: (e: MouseClick) => void
}
}
export {} |
// Copyright 2023-Present Couchbase, Inc.
//
// Use of this software is governed by the Business Source License included
// in the file licenses/BSL-Couchbase.txt. As of the Change Date specified
// in that file, in accordance with the Business Source License, use of this
// software will be governed by the Apache License, Version 2.0, included in
// the file licenses/APL2.txt.
package execution
import (
"encoding/json"
"github.com/couchbase/query/errors"
"github.com/couchbase/query/plan"
"github.com/couchbase/query/value"
)
type AlterBucket struct {
base
plan *plan.AlterBucket
}
func NewAlterBucket(plan *plan.AlterBucket, context *Context) *AlterBucket {
rv := &AlterBucket{
plan: plan,
}
newRedirectBase(&rv.base, context)
rv.output = rv
return rv
}
func (this *AlterBucket) Accept(visitor Visitor) (interface{}, error) {
return visitor.VisitAlterBucket(this)
}
func (this *AlterBucket) Copy() Operator {
rv := &AlterBucket{plan: this.plan}
this.base.copy(&rv.base)
return rv
}
func (this *AlterBucket) PlanOp() plan.Operator {
return this.plan
}
func (this *AlterBucket) RunOnce(context *Context, parent value.Value) {
this.once.Do(func() {
defer context.Recover(&this.base) // Recover from any panic
active := this.active()
defer this.close(context)
this.switchPhase(_EXECTIME)
defer this.switchPhase(_NOTIME)
defer this.notify() // Notify that I have stopped
if !active || context.Readonly() {
return
}
this.switchPhase(_SERVTIME)
err := context.datastore.AlterBucket(this.plan.Node().Name(), this.plan.Node().With())
if err != nil {
if errors.IsNotFoundError("Requested resource", err) {
err = errors.NewCbBucketNotFoundError(nil, this.plan.Node().Name())
}
context.Error(err)
}
})
}
func (this *AlterBucket) MarshalJSON() ([]byte, error) {
r := this.plan.MarshalBase(func(r map[string]interface{}) {
this.marshalTimes(r)
})
return json.Marshal(r)
} |
import React, { useState, useEffect } from 'react';
import { View, StyleSheet, Text, ScrollView, Alert } from 'react-native';
import { Picker } from '@react-native-picker/picker';
import firestore from '@react-native-firebase/firestore';
const ViewStudent = ({ navigation }) => {
const [admissionClass, setAdmissionClass] = useState('');
const [studentsList, setStudentsList] = useState([]);
const [ageReport, setAgeReport] = useState(null);
const calculateAge = (dateOfBirth) => {
const dob = dateOfBirth.toDate();
const today = new Date();
const diff = Math.abs(today - dob);
const ageYears = Math.floor(diff / (1000 * 60 * 60 * 24 * 365));
const ageMonths = Math.floor((diff % (1000 * 60 * 60 * 24 * 365)) / (1000 * 60 * 60 * 24 * 30));
return { years: ageYears, months: ageMonths };
}
const generateAgeReport = (students) => {
const ageMap = new Map();
students.forEach(student => {
const age = calculateAge(student.dateOfBirth);
const key = `${age.years} years ${age.months} months`;
if (ageMap.has(key)) {
const count = ageMap.get(key);
ageMap.set(key, {
count: count.count + 1,
boys: count.boys + (student.gender.toLowerCase() === 'male' ? 1 : 0),
girls: count.girls + (student.gender.toLowerCase() === 'female' ? 1 : 0)
});
} else {
ageMap.set(key, {
count: 1,
boys: student.gender.toLowerCase() === 'male' ? 1 : 0,
girls: student.gender.toLowerCase() === 'female' ? 1 : 0
});
}
});
return ageMap;
};
const fetchStudentsByClass = async () => {
try {
if (admissionClass) {
const studentsQuerySnapshot = await firestore().collection('Students')
.where('admissionClass', '==', admissionClass)
.get();
if (studentsQuerySnapshot.empty) {
Alert.alert('Not Found', 'No students found in the selected class');
setStudentsList([]);
} else {
const studentsData = studentsQuerySnapshot.docs.map(doc => doc.data());
setStudentsList(studentsData);
}
} else {
Alert.alert('Missing Information', 'Please select a class');
}
} catch (error) {
Alert.alert('Error', error.message);
}
};
useEffect(() => {
fetchStudentsByClass();
}, [admissionClass]);
useEffect(() => {
if (studentsList.length > 0) {
const report = generateAgeReport(studentsList);
setAgeReport(report);
}
}, [studentsList]);
return (
<ScrollView contentContainerStyle={styles.container}>
<View style={styles.inputGroup}>
<Text style={styles.label}>Admission Class:</Text>
<Picker
selectedValue={admissionClass}
onValueChange={(itemValue) => setAdmissionClass(itemValue)}
style={styles.picker}
>
<Picker.Item label="Select Class" value="" />
<Picker.Item label="Nursery" value="nursery" />
<Picker.Item label="Prep" value="prep" />
<Picker.Item label="Class 1" value="class1" />
<Picker.Item label="Class 2" value="class2" />
<Picker.Item label="Class 3" value="class3" />
<Picker.Item label="Class 4" value="class4" />
<Picker.Item label="Class 5" value="class5" />
<Picker.Item label="Class 6" value="class6" />
<Picker.Item label="Class 7" value="class7" />
<Picker.Item label="Class 8" value="class8" />
</Picker>
</View>
{/* First Table */}
<View style={styles.tableContainer}>
<Text style={styles.listHeader}>Student Age Record Report for Class {admissionClass}</Text>
<View style={styles.table}>
<View style={styles.row}>
<Text style={styles.header}>Registration No</Text>
<Text style={styles.header}>Student Name</Text>
<Text style={styles.header}>Father Name</Text>
<Text style={styles.header}>Date of Birth</Text>
<Text style={styles.header}>Age (Years & Months)</Text>
</View>
{studentsList.map((student, index) => (
<View key={index} style={styles.row}>
<Text style={styles.data}>{student.registrationNumber}</Text>
<Text style={styles.data}>{student.name}</Text>
<Text style={styles.data}>{student.fatherDetails.fatherName}</Text>
<Text style={styles.data}>{new Date(student.dateOfBirth.seconds * 1000).toDateString()}</Text>
<Text style={styles.data}>{calculateAge(student.dateOfBirth).years} years {calculateAge(student.dateOfBirth).months} months</Text>
</View>
))}
</View>
</View>
{/* Second Table */}
<View style={styles.tableContainer}>
<Text style={styles.listHeader}>Age Distribution</Text>
<View style={styles.table}>
<View style={styles.row}>
<Text style={styles.header}>Age</Text>
<Text style={styles.header}>Number</Text>
<Text style={styles.header}>Boys</Text>
<Text style={styles.header}>Girls</Text>
</View>
{ageReport && Array.from(ageReport.entries()).map(([key, value], index) => (
<View key={index} style={styles.row}>
<Text style={styles.data}>{key}</Text>
<Text style={styles.data}>{value.count}</Text>
<Text style={styles.data}>{value.boys}</Text>
<Text style={styles.data}>{value.girls}</Text>
</View>
))}
</View>
</View>
</ScrollView>
);
};
const styles = StyleSheet.create({
container: {
flexGrow: 1,
paddingVertical: 20,
paddingHorizontal: 10,
backgroundColor: '#FFFFFF',
},
inputGroup: {
flexDirection: 'row',
alignItems: 'center',
marginBottom: 15,
width: '100%',
},
label: {
fontSize: 14,
color: '#000000',
fontWeight: 'bold',
flex: 1,
textAlign: 'left',
},
picker: {
flex: 2,
height: 40,
borderWidth: 1,
borderColor: '#ccc',
borderRadius: 5,
backgroundColor: '#F5F5F5',
},
tableContainer: {
marginBottom: 20,
},
table: {
borderWidth: 1,
borderColor: '#ccc',
borderRadius: 5,
},
row: {
flexDirection: 'row',
justifyContent: 'space-between',
borderBottomWidth: 1,
borderBottomColor: '#ccc',
paddingVertical: 5,
},
header: {
flex: 1,
textAlign: 'center',
fontWeight: 'bold',
},
data: {
flex: 1,
textAlign: 'center',
},
listHeader: {
fontSize: 16,
fontWeight: 'bold',
marginBottom: 10,
},
});
export default ViewStudent; |
import './index.css'
import {Component} from 'react'
import EventItem from '../EventItem'
import ActiveEventRegistrationDetails from '../ActiveEventRegistrationDetails'
const eventsList = [
{
id: 'f9bb2373-b80e-46b8-8219-f07217b9f3ce',
imageUrl:
'https://assets.ccbp.in/frontend/react-js/event-canada-dance-festival-img.png',
name: 'Canada Dance Festival',
location: 'Canada, America',
registrationStatus: 'YET_TO_REGISTER',
},
{
id: 'c0040497-e9cb-4873-baa9-ef5b994abfff',
imageUrl:
'https://assets.ccbp.in/frontend/react-js/events-kathakali-img.png',
name: 'Puthanalkkal Kalavela',
location: 'Karnataka, India',
registrationStatus: 'REGISTERED',
},
{
id: '0037d5e4-4005-4030-987b-ce41b691b92a',
imageUrl:
'https://assets.ccbp.in/frontend/react-js/events-kuchipudi-img.png',
name: 'Nithyopahara',
location: 'Kerala, India',
registrationStatus: 'REGISTRATIONS_CLOSED',
},
{
id: 'c9ff08cb-610c-4382-9939-78e5e50a72b2',
imageUrl:
'https://assets.ccbp.in/frontend/react-js/events-bharatanatyam-img.png',
name: 'Shivam',
location: 'Andhra Pradesh, India',
registrationStatus: 'YET_TO_REGISTER',
},
{
id: 'd1153723-5b6e-4628-9a1a-ccd8f84f1273',
imageUrl: 'https://assets.ccbp.in/frontend/react-js/events-kolatam-img.png',
name: 'Janapada Kolatam',
location: 'Tamil Nadu, India',
registrationStatus: 'REGISTERED',
},
{
id: '7d6ec013-d0ae-4d84-b776-14b733a9174f',
imageUrl:
'https://assets.ccbp.in/frontend/react-js/event-colonial-fest-img.png',
name: 'Colonial Fest',
location: 'Washington, America',
registrationStatus: 'REGISTRATIONS_CLOSED',
},
]
class Events extends Component {
state = {isEmpty: true, eventStatusDetails: {}}
onEvent = id => {
const specificEvent = eventsList.filter(each => each.id === id)
this.setState({isEmpty: false, eventStatusDetails: specificEvent[0]})
}
render() {
const {isEmpty, eventStatusDetails} = this.state
return (
<div className="event-background">
<div className="event-container">
<h1>Events</h1>
<ul>
{eventsList.map(eachEvent => (
<EventItem
onEvent={this.onEvent}
eachEvent={eachEvent}
key={eachEvent.id}
/>
))}
</ul>
</div>
{isEmpty ? (
<p className="empty-txt">
Click on an event, to view its registration details
</p>
) : (
<ActiveEventRegistrationDetails
key={eventStatusDetails.id}
eventStatusDetails={eventStatusDetails}
/>
)}
</div>
)
}
}
export default Events |
package com.cakefactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Lazy;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
private final UserDetailsService userDetailsService;
@Autowired
public SecurityConfig(@Lazy UserDetailsService userDetailsService) {
super();
this.userDetailsService = userDetailsService;
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth
.userDetailsService(userDetailsService)
.passwordEncoder(passwordEncoder());
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/account")
.authenticated()
.anyRequest()
.permitAll()
.and()
.oauth2Login();
//.loginPage("/login")
//.usernameParameter("emailAddress")
//.and()
//.logout()
//.logoutSuccessUrl("/");
}
@Bean
PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
} |
import hashlib
import pickle
import nltk
import matplotlib.pyplot as plt
import networkx as nx
import numpy as np
import plotly.express as px
import spacy
from nltk.corpus import stopwords
from nltk.stem import PorterStemmer
from preprocess import *
# added stop words
#gist_file = open("data/gist_stopwords.txt", "r")
#try:
# content = gist_file.read()
# extra_stopwords = content.split(",")
#finally:
# gist_file.close()
# stop words
nlp = spacy.load("en_core_web_sm")
nltk.download('stopwords')
nlp = spacy.load("en_core_web_sm")
# constants
stop_words = list(set(stopwords.words('english')))+list(set(stopwords.words('spanish')))+list(set(stopwords.words('portuguese')))
stop_words.extend(['rt', 'und','many','let','very','from', 'subject', 're', 'edu', 'whole','really',
'use', 'amp', 'get', 'go', 'say', 'people', 'need', 'see', 'know', 'make', 'take',
'think', 'would', 'still', 'keep', 'may', 'could', 'come','vaccination', 'vaccine', 'vaccines', 'vaccinated'])
with open('./rarelist.pkl', 'rb') as f:
mynewlist = pickle.load(f)
stop_words.extend(mynewlist)
stop_words = set(stop_words)
#print("Stopwords length = {}".format(len(stop_words)))
def stripStopWords(string):
if string not in stop_words:
return string
def removePunctuation(string):
punctuation = '''!()-[]{}; :'"\,<>./?@#$%^&*_~'''
for symbol in string:
if symbol in punctuation:
string = string.replace(symbol, '')
# else:
# string = 'None'
return string
def lemmatize(string, allowed_postags=['NOUN', 'ADJ', 'VERB', 'ADV']):
doc = nlp(string)
return ' '.join([token.lemma_ for token in doc if token.pos_ in allowed_postags])
def stemming(string):
if string is not None:
ps = PorterStemmer()
return ps.stem(string)
def removeDupChars(string):
string = re.sub(r'(.+?)\1+', r'\1', string)
return string
def lowercase(string):
return string.lower()
def deEmojify(string):
regrex_pattern = re.compile(pattern = "["
u"\U0001F600-\U0001F64F" # emoticons
u"\U0001F914" # thinking face emoji
u"\U0001F300-\U0001F5FF" # symbols & pictographs
u"\U0001F680-\U0001F6FF" # transport & map symbols
u"\U0001F1E0-\U0001F1FF" # flags (iOS)
"]+", flags = re.UNICODE)
return regrex_pattern.sub(r'', string)
def filterHashtag(hashtag): ### Clean one hashtag
hashtag = deEmojify(hashtag)
hashtag = removePunctuation(hashtag)
hashtag = lowercase(hashtag)
hashtag = removeDupChars(hashtag)
hashtag = stripStopWords(hashtag)
if hashtag == '':
hashtag = None
# print(hashtag)
return hashtag
def cleanHashtags(hashtag_list):
# hl = []
# for hashtag in hashtag_list:
# hashtag = filterHashtag(hashtag)
# hl.append(hashtag)
# return hl
# Clean a list of hashtags
return list(sorted(filter(bool,map(filterHashtag,hashtag_list))))
def rangeHash(s,r): ### takes a hashtag and returns hash value
return int(hashlib.md5(s.encode('utf8')).hexdigest(),16) % r
def orderAdjMatrix(graph, fmap):
nodes = list(graph.nodes)
nodes = [int(node) for node in nodes]
order = []
for ci, cnodes in sorted(fmap.items()):
for cnode in cnodes:
order.append(nodes.index(cnode))
matrix = nx.to_numpy_array(graph)[order][:,order]
x, y = np.argwhere(matrix == 1).T
return matrix, x, y, order
def drawAdjMatrixPlotly(df,title):
fig = px.scatter(df, x='x', y='y')
fig.update_traces(mode='markers', marker_size=10, marker_color='black')
fig.update_layout(yaxis_zeroline=False,
xaxis_zeroline=False,
xaxis_title='Nodes',
yaxis_title='Nodes',
autosize=False,
width=700,
height=700,
plot_bgcolor='rgb(255,255,255)')
# fig.update_layout(title=title,
# yaxis_zeroline=False,
# xaxis_zeroline=False,
# autosize=False,
# width=1000,
# height=1000,
# plot_bgcolor='rgb(250,250,250)')
fig.show()
def drawAdjMatrixMatplotlib(x,y,title,color='black'):
network_name = title.split(': ')[1]
type_fig = title.split(': ')[0]
if type_fig == 'Clusters before merging fingerprints':
type_fig = 'before'
elif type_fig == 'Graph clusters after merging fingerprints':
type_fig = 'after'
elif type_fig == 'Unclustered network':
type_fig = 'unclustered'
plt.rcParams["figure.figsize"] = (3, 3)
plt.scatter(x, y, s=1, c=color)
# add title and axis names
plt.title(title, fontsize=25)
plt.xlabel('Nodes', fontsize=25)
plt.ylabel('Nodes', fontsize=25)
# plt.savefig('../../../Projects/stream-graph/plots/adjacency_matrices/' + network_name + '_' + type_fig + '.png')
# plt.savefig('../../../Projects/covid-19/plots/adjacency_matrices_0.1/' + network_name + '_' + type_fig + '.png')
# plt.clf()
plt.show()
# ---------------------------------------------------------------------------
# G2 = nx.convert_node_labels_to_integers(G, first_label=0, ordering='default', label_attribute=None)
# communities = algorithms.louvain(G2, weight='weight', resolution=1.)
# clusters = communities.communities
# print('{} clusters found'.format(len(clusters)))
# sizes = []
# for cluster in clusters:
# cluster_size = len(cluster)
# sizes.append(cluster_size)
# # visualize ordered matrix
# fmap = defaultdict(list)
# for cluster, node_in_cluster in enumerate(clusters):
# fmap[cluster] = node_in_cluster
# m, x, y, order = orderAdjMatrix(G2, fmap)
# x_axis = x.tolist()
# y_axis = y.tolist()
# df = pd.DataFrame(list(zip(x_axis, y_axis)), columns =['x', 'y'])
# drawAdjMatrixPlotly(df,'Adjacency matrix ordered') |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Treemap Visualization</title>
<script src="https://d3js.org/d3.v6.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/d3-sankey@0.12.3/dist/d3-sankey.min.js"></script>
<style>
body {
font-family: Arial, sans-serif;
margin: 0;
padding: 0;
background-image: url('/static/images/reel.png'), url('/static/images/reel.png');
background-position: left top, right top;
background-repeat: repeat-y;
background-attachment: scroll;
background-size: 100px auto;
background-color: #f9f9f9c4;
}
@media (max-width: 768px) {
body {
background-image: none;
}
}
#intro, #treemap-description, #heatmap-description, footer {
margin: 20px;
padding: 10px;
}
h1, h2 {
color: #333;
}
p {
color: #666;
}
#genre-selector {
display: flex;
justify-content: center;
font-size: 16px; /* Increase the base font size */
}
#genreSelect {
padding: 0px 20px;
width: 30%;
font-size: 1.25em;
margin: 0 10px;
}
#genre-selector label {
font-size: 1.25em;
margin-right: 10px;
}
footer {
font-size: 0.8em;
text-align: center;
padding: 20px;
margin-top: 40px;
border-top: 1px solid #ccc;
}
</style>
</head>
<body>
<!-- Genre Selector -->
<div id="g-s">
</div>
<!-- Intro Text -->
<div id="intro" style="justify-content: center; width: 65%; margin: auto;">
<h1>Welcome to the Movie Revenue Visualization</h1>
<p>This visualization project explores the top-grossing movies of 2023 in the North American Box Office. The primary aim is to help movie makers strategize their releases suing the provided analysis.</p>
<p>In 2023, the film industry continued to captivate audiences with a wide array of cinematic experiences, ranging from high-octane action films and heartfelt comedies to groundbreaking adventures and intense dramas. As movie enthusiasts, one intriguing question always arises: <b>What was the best movie of the year?</b>
While "best" can be subjective, one objective measure is a movie's success at the box office. In this analysis, I delve into the North American box office gross earnings to uncover which movies not only captured our imagination but also drew the largest audiences to theaters.
The primary dataset comprises detailed box office earnings in North America for the top-grossing films of 2023. Each movie's financial success is a testament to its popularity, marketing effectiveness, and, arguably, its quality and appeal to the public.
I visualize this dataset through various unique ways, which allows us to intuitively understand the comparative scale of each movie's earnings. The colors represent different genres. This visual representation offers a clear perspective on which films led the box office, providing an immediate sense of the financial landscape of 2023's cinematic offerings.</p>
<p>This project presents a detailed visualization of movie revenue data to analyze factors influencing box office success in 2023. By employing various visualization techniques, the aim is to reveal trends and insights that might not be immediately evident through traditional data analysis.
The first visualization is a Sankey diagram, which depicts the distribution of box office earnings across different genres. This diagram is crucial for understanding the <b>financial impact</b> of each genre, highlighting which genres are the most lucrative and their respective shares of the total market.
Next, a treemap provides a more detailed breakdown of box office earnings by genre and individual movies. This visualization allows for a closer examination of which specific films are driving the financial success within their genres, offering a <b>granular perspective</b> on the contributions of individual movies to the genre's overall success.
Lastly, the project includes a heatmap that shows the distribution of box office earnings throughout the year, broken down by month. This heatmap is instrumental in identifying which months yield the highest revenues, illustrating <b>seasonal trends</b> and the optimal times for movie releases.</p>
<p>Together, these visualizations offer comprehensive insights into the strategic timing of movie releases, the impact of different genres on revenue, and the standout movies that dominate box office earnings. This data serves as a valuable resource for stakeholders in the film industry, aiding in strategic planning and decision-making to maximize box office returns. </p>
</div>
<!-- Sankey Diagram -->
<div id="sankey-text" style="justify-content: center; width: 65%; margin: auto;">
<h2>Genre Distribution of Box Office Earnings in 2023</h2>
<p>
For vizualizing the box office earnings across genres, I have employed a Snakey diagram. The Sankey diagram serves as a visual summary of the film industry's financial landscape over the past year, specifically highlighting the distribution of box office earnings among various movie genres in 2023. The diagram starts with a comprehensive block representing the total earnings, which then branches out into streams that connect to different genres.
As one examines the diagram, it's evident that certain genres have played a pivotal role in driving the industry's revenue. Notably, genres such as <b>Action</b> and <b>Adventure</b> show significantly larger streams (accounting for a third, and a fifth of the total revenue respectively), reflecting their dominance in the market and popularity among audiences. These thicker streams suggest that such genres have been the powerhouses of box office earnings.
Conversely, other genres like Documentary and Reality feature much slimmer streams. This visual disparity illustrates that while they contribute to the diversity of the industry's offerings, their financial impact is less pronounced when compared to the heavyweight genres.
</p>
<p>
The diagram effectively breaks down the complexity of revenue distribution into a straightforward visual narrative. This allows industry stakeholders to identify at a glance which genres may yield a better return on investment and to strategize accordingly for future productions and marketing efforts.
</p>
</div>
<div id="sankey" style="display: flex; justify-content: center; margin: auto; width: 70%; border: 1px solid #ccc;"></div>
<div id="sankey-controls" style="text-align: center; margin-top: 10px;">
<button id="resetZoom" style="padding: 5px 10px; font-size: 12px;">Reset Zoom</button>
</div>
<script>
const sankeyData = {{ sankey_data|safe }};
let svg, zoom;
function drawSankey() {
const colorScale = d3.scaleOrdinal()
.domain(["Total Earnings", "Action", "Adventure", "Black Comedy", "Comedy", "Concert/Perfor\u2026", "Documentary", "Drama", "Horror", "Multiple Genres", "Musical", "Reality", "Romantic Comedy", "Thriller/Suspense", "Western"])
// Use a color scheme of 14 pastel colors that are colorblind-friendly
.range(["grey", "#a6cee3", "#1f78b4", "#b2df8a", "#33a02c", "#fb9a99", "#e31a1c", "#fdbf6f", "#ff7f00", "#cab2d6", "#6a3d9a", "#ffff99", "#b15928", "#8dd3c7", "#ffffb3"]);
const margin = {top: 10, right: 10, bottom: 40, left: 10};
const width = Math.min(window.innerWidth * 0.65, 1600) - margin.left - margin.right;
const height = 1050 - margin.top - margin.bottom;
const totalEarningsColor = "grey";
// Define the zoom behavior
zoom = d3.zoom()
.scaleExtent([0.5, 2]) // Sets the minimum and maximum zoom scale
.on("zoom", function (event) {
svgContent.attr("transform", event.transform);
});
function setupGradients(svg, links, colorScale) {
// Create a defs (definitions) element for gradients
const defs = svg.append("defs");
// Create a gradient for each link
links.forEach((link, i) => {
const gradient = defs.append("linearGradient")
.attr("id", `gradient-${i}`)
.attr("gradientUnits", "userSpaceOnUse")
.attr("x1", link.source.x1)
.attr("y1", (link.source.y0 + link.source.y1) / 2)
.attr("x2", link.target.x0)
.attr("y2", (link.target.y0 + link.target.y1) / 2);
gradient.append("stop")
.attr("offset", "0%")
.attr("stop-color", colorScale(link.source.name));
gradient.append("stop")
.attr("offset", "100%")
.attr("stop-color", colorScale(link.target.name));
});
}
// Clear the previous SVG
d3.select("#sankey svg").remove();
// Create the SVG container and apply the zoom behavior
svg = d3.select("#sankey").append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.call(zoom);
// Create a container for the Sankey diagram contents
const svgContent = svg.append("g")
.attr("transform", `translate(${margin.left}, ${margin.top})`);
// Set up the sankey generator
const sankey = d3.sankey()
.nodeWidth(30)
.nodePadding(40)
.extent([[0, 0], [width, height]]);
const color = d3.scaleOrdinal(d3.schemeCategory10);
const nodeMap = new Map(sankeyData.nodes.map((node, i) => [node.id, i]));
// Link the nodes and the links
sankeyData.links.forEach(link => {
link.source = nodeMap.get(link.source);
link.target = nodeMap.get(link.target);
});
const {nodes, links} = sankey({
nodes: sankeyData.nodes.map(d => ({...d})),
links: sankeyData.links.map(d => ({...d}))
});
const totalFlow = d3.sum(links, d => d.value);
nodes.forEach(node => {
const nodeFlow = d3.sum(links.filter(d => d.source === node || d.target === node), d => d.value);
node.percentage = (nodeFlow / totalFlow * 100).toFixed(2); // Keep one decimals for percentage
});
setupGradients(svg, links, colorScale);
// Draw the links using the gradient
const link = svgContent.append("g")
.attr("fill", "none")
.attr("stroke-opacity", 0.5)
.selectAll("path")
.data(links)
.enter().append("path")
.attr("d", d3.sankeyLinkHorizontal())
.attr("stroke", (d, i) => `url(#gradient-${i})`) // Use gradient
.attr("stroke-width", d => Math.max(1, d.width));
// Draw the nodes
const node = svgContent.append("g")
.selectAll("rect")
.data(nodes)
.enter().append("rect")
.attr("x", d => d.x0)
.attr("y", d => d.y0)
.attr("height", d => d.y1 - d.y0)
.attr("width", sankey.nodeWidth())
.attr("fill", d => d.name === "Total Earnings" ? totalEarningsColor : colorScale(d.name))
.attr("stroke", "#000");
// Add node labels with percentages
svgContent.append("g")
.style("font", "14px sans-serif")
.selectAll("text")
.data(nodes)
.enter().append("text")
.attr("x", d => d.x0 < width / 2 ? d.x1 + 6 : d.x0 - 6)
.attr("y", d => (d.y1 + d.y0) / 2)
.attr("dy", "0.35em")
.attr("text-anchor", d => d.x0 < width / 2 ? "start" : "end")
.text(d => `${d.name} (${d.percentage}%)`);
// Add a tooltip for all nodes
node.append("title")
.text(d => `${d.name}\n${d.value.toLocaleString()} (${d.percentage}%)`);
// Add a title for the diagram
svg.append("text")
.attr("x", width / 2 + margin.left)
.attr("y", height + margin.top + 20)
.attr("class", "caption")
.style("font", "16px sans-serif")
.style("text-anchor", "middle")
.text("Distribution of Box Office Earnings Across Genres in 2023");
}
// Initial draw
drawSankey();
document.getElementById('resetZoom').addEventListener('click', function() {
svg.transition()
.duration(750)
.call(zoom.transform, d3.zoomIdentity); // Reset zoom to initial state
});
// Redraw based on the new size whenever the window is resized
window.addEventListener('resize', drawSankey);
</script>
<div id="Dive" style="justify-content: center; width: 65%; margin: auto;">
<p>Dive Deeper and Explore by Genre: </p>
<p>
Recognizing that the film industry is wonderfully diverse, I've incorporated an interactive element into our analysis: a genre selection dropdown. This tool enables users to refine the treemap visualization to display box office earnings within specific genres.
Whether you're interested in the adrenaline rush of action movies, the imaginative nature of adventure, the heartwarming moments of comedies, you can select your preferred genre from the dropdown. This interactivity allows for a tailored exploration of 2023's movies, providing insights into which genres dominated the box office and how different stories resonated with audiences across North America.
Select a genre from the dropdown to start your exploration and uncover the top movies of 2023 within each cinematic category.</p>
</div>
<!-- Genre Selector -->
<div id="genre-selector" style="display: flex; justify-content: center;">
<label for="genreSelect">Select Genre:</label>
<select id="genreSelect" onchange="updateVisualizations()">
<option value="All">All Genres</option>
{% for genre in genres %}
<option value="{{ genre }}">{{ genre }}</option>
{% endfor %}
</select>
</div>
<div style="display: flex; justify-content: center; align-items: center; width: 85%; margin: auto; height: 700px; flex-wrap: wrap; border: 1px solid #ccc;">
<div id="treemap" style="flex: 1 1 60%; display: flex; justify-content: center; align-items: center; min-width: 300px; height: 100%; background-color: #f9f9f9;">
</div>
<div id="heatmap" style="flex: 1 1 40%; display: flex; justify-content: center; align-items: center; min-width: 100px; height: 100%; background-color: #f9f9f9;">
</div>
</div>
<script>
const data = {{ treemap_data|safe }};
const genres = {{ genres|tojson }};
const heatmapData = {{ heatmap_data|safe }};
let filteredData = data;
function updateVisualizations() {
const selectedGenre = document.getElementById('genreSelect').value;
// Update Treemap
if (selectedGenre === 'All') {
drawTreemap(data);
} else {
const filteredTreemapData = {
name: selectedGenre,
children: data.children.find(d => d.name === selectedGenre).children
};
drawTreemap(filteredTreemapData);
}
// Update Heatmap
if (selectedGenre === 'All') {
const aggregatedHeatmapData = {};
Object.keys(heatmapData).forEach(month => {
// Initialize the aggregation for each month
aggregatedHeatmapData[month] = 0;
// Sum up all values for each genre within the month
Object.values(heatmapData[month]).forEach(value => {
aggregatedHeatmapData[month] += value;
});
});
drawHeatmap(aggregatedHeatmapData, true); // Pass 'true' to indicate that we're handling the 'All' case
} else {
const filteredHeatmapData = {};
Object.keys(heatmapData).forEach(month => {
filteredHeatmapData[month] = {};
filteredHeatmapData[month][selectedGenre] = heatmapData[month][selectedGenre];
});
drawHeatmap(filteredHeatmapData, false); // Pass 'false' to indicate a single-genre case
}
}
const colorScale = d3.scaleOrdinal()
.domain(["Action", "Adventure", "Black Comedy", "Comedy", "Concert/Perfor\u2026", "Documentary", "Drama", "Horror", "Multiple Genres", "Musical", "Reality", "Romantic Comedy", "Thriller/Suspense", "Western"])
// Use a color scheme of 14 pastel colors that are colorblind-friendly
.range(["#a6cee3", "#1f78b4", "#b2df8a", "#33a02c", "#fb9a99", "#e31a1c", "#fdbf6f", "#ff7f00", "#cab2d6", "#6a3d9a", "#ffff99", "#b15928", "#8dd3c7", "#ffffb3"]);
function getSize(containerId) {
return document.getElementById(containerId).getBoundingClientRect();
}
function drawTreemap(data) {
const containerSize = getSize('treemap');
const width = containerSize.width, height = Math.min(700, window.innerHeight * 0.6);
document.getElementById('treemap').innerHTML = ''; // Clear previous treemap
;
const root = d3.hierarchy(data).sum(d => d.value);
d3.treemap().size([width, height-100]).padding(2)(root);
const svg = d3.select("#treemap").append("svg")
.attr("width", width )
.attr("height", height + 30);
svg.append("text")
.attr("x", window.innerWidth / 4) // Centering the text
.attr("y", height ) // Position below the diagram
.attr("class", "caption")
.style("font", "16px sans-serif") // Style the font as needed
.style("text-anchor", "middle") // Center the text horizontally
.text("Distribution of Box Office Earnings Across Genres and Movies in 2023");
const cell = svg.selectAll("g")
.data(root.leaves())
.enter().append("g")
.attr("transform", d => `translate(${d.x0},${d.y0})`);
cell.append("rect")
.attr("width", d => d.x1 - d.x0)
.attr("height", d => d.y1 - d.y0)
.attr("fill", d => colorScale(d.parent.data.name)) // Use the color scale based on genre
.attr("stroke", "#fff");
// Add a tooltip for all boxes
cell.append("title")
.text(d => `${d.data.name}\n${d.value.toLocaleString()}`);
// Add text only if the box is large enough
cell.filter(d => (d.x1 - d.x0) > 40)
.append("text")
.attr("dx", 4)
.attr("dy", 20)
.text(d => d.data.name + "\n $ " + d.value.toLocaleString());
}
drawTreemap(data); // Draw initial treemap
function drawHeatmap(data, isAll) {
const containerSize = getSize('heatmap');
const width = containerSize.width, height = Math.min(700, window.innerHeight * 0.6);
// Clear previous content
document.getElementById('heatmap').innerHTML = '';
const svg = d3.select("#heatmap").append("svg")
.attr("width", width)
.attr("height", height);
const margin = { top: 1, right: 1, bottom: 10, left: 1},
g = svg.append("g").attr("transform", `translate(${margin.left}, ${margin.top})`);
const monthNames = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
const months = Object.keys(data).sort((a, b) => a - b); // Assume months are numeric strings
const genres = isAll ? ['All'] : Object.keys(data[months[0]]);
const y = d3.scaleBand().rangeRound([0, height-20]).padding(0.1).domain(months);
const x = d3.scaleBand().rangeRound([50, width/2]).padding(0.1).domain(genres);
const maxValue = d3.max(Object.values(data), month => isAll ? month : d3.max(Object.values(month)));
// Inverting the domain to correctly match the visual gradient
const z = d3.scaleSequential(d3.interpolateViridis).domain([maxValue, 0]);
g.selectAll(".heatmap-rect")
.data(months.map(month => ({ month, value: isAll ? data[month] : data[month][genres[0]] })))
.enter().append("rect")
.attr("y", d => y(d.month))
.attr("x", () => x(isAll ? 'All' : genres[0]))
.attr("width", width/3)
.attr("height", height / 24)
.attr("fill", d => z(d.value))
.attr("stroke", "black");
// Add text labels for months next to the bars
g.selectAll(".month-label")
.data(months)
.enter().append("text")
.attr("class", "month-label")
.attr("y", d => y(d) + y.bandwidth() / 3.5) // Centered in the band
.attr("x", width/3 + 100) // Positioned right of the bars based on fixed width
.attr("dy", ".35em")
.attr("alignment-baseline", "middle")
.text(d => monthNames[d - 1]); // Display the month names
// Adding captions for the x and y axis
svg.append("text")
.attr("x", 300) // Centering the text
.attr("y", height-10) // Position below the Sankey diagram
.attr("class", "caption")
.style("font", "16px sans-serif") // Style the font as needed
.style("text-anchor", "middle") // Center the text horizontally
.text("Distribution of Box Office Earnings Across Months in 2023");
// Adding the color gradient legend
const legendHeight = 300;
const legendWidth = 20;
const numSwatches = 10;
const colorScale = d3.scaleSequential(d3.interpolateViridis)
.domain([0, numSwatches - 1]);
const legend = svg.append("g")
.attr("transform", `translate(${width/3 + 150}, ${height/8})`); // Adjust these values as needed
legend.selectAll(".color-swatch")
.data(d3.range(numSwatches))
.enter().append("rect")
.attr("y", (d, i) => i * (legendHeight / numSwatches))
.attr("height", legendHeight / numSwatches)
.attr("width", legendWidth)
.attr("fill", d => colorScale(d));
// Add labels for the legend
legend.append("text")
.attr("x", legendWidth + 5)
.attr("y", 0)
.attr("dy", ".35em")
.text("High");
legend.append("text")
.attr("x", legendWidth + 5)
.attr("y", legendHeight)
.attr("dy", ".35em")
.text("Low");
}
const aggregatedHeatmapData = {};
Object.keys(heatmapData).forEach(month => {
// Initialize the aggregation for each month
aggregatedHeatmapData[month] = 0;
// Sum up all values for each genre within the month
Object.values(heatmapData[month]).forEach(value => {
aggregatedHeatmapData[month] += value;
});
});
drawHeatmap(aggregatedHeatmapData, true);
</script>
<div id="treemap-text" style="justify-content: center; width: 65%; margin: auto;">
<h2>Distribution of Box Office Earnings in 2023 across movies and genres</h2>
<p>
The second vizualization is a Treemap that provides a detailed breakdown of box office earnings by genre and individual movies.
The treemap provided is a portrayal of the box office earnings for 2023, classified by genre and further subdivided by individual movies. Each rectangle in the treemap is sized proportionally to the film's earnings, creating a visual hierarchy that immediately communicates the relative financial success of each title within its genre.
At first glance, it is apparent which movies have made a significant impact on the box office. Blockbusters in popular genres command large areas of the map, signifying their dominance in revenue generation. These standout movies are not only a testament to their own success but also act as flag bearers for their respective genres.
On the other end of the spectrum, the treemap includes smaller rectangles representing films with lower earnings, underscoring the competitive nature of the industry. The varied sizes and colors form a mosaic that echoes the diverse range of films offered to audiences during the year. The details can be viewed by hovering over each rectangle, revealing the movie's name and earnings by a tooltip.
</p>
<p>
The genres can be selected using the dropdown allowing for granular exploration of the box office earnings within specific genres. This interactive feature enables users to focus on their preferred genres and uncover the standout movies that contributed to the genre's financial success. By selecting a genre, you can delve deeper into the treemap and identify the top-performing movies that captivated audiences and drove box office revenues in 2023.
The clustering of movies within their genres allows for a comparative analysis of how different genres stack up against one another in terms of box office performance. This level of detail provides industry analysts and movie producers with concrete visual data to help guide future investment and production decisions.
</p>
</div>
<div id="heatmap-text" style="justify-content: center; width: 65%; margin: auto;">
<h2>Distribution of Box Office Earnings in 2023 across months of release</h2>
<p>
The third visualization is a heatmap that shows the distribution of box office earnings throughout the year, broken down by month.
The heatmap offers a straightforward visualization of box office earnings throughout the different months of 2023. Each bar on the heatmap corresponds to a month, with the length and color gradient indicative of the revenue earned within that time frame. The gradation of color from one end of the spectrum to the other, from green to purple denotes a range from low to high earnings.
This visual arrangement makes it immediately clear which months were most and least profitable for the film industry. For example, longer bars with a color closer to the purple end of the spectrum (July) would signify months where movie releases saw higher box office returns. Conversely, shorter, greener bars would indicate periods of lower revenue (January).
</p>
<p>
The genres can again be selected using the dropdown allowing for granular exploration of the box office earnings within specific genres.
Such a heatmap is instrumental for industry analysts and movie distributors in identifying patterns and seasonality in film consumption. It can highlight the months that typically see blockbuster releases and those that might be considered off-peak periods. Moreover, the visualization can trigger further investigation into the reasons behind these trends, such as holiday seasons, school breaks, or particular events that may influence movie-going behavior.
</p>
</div>
<div id="action-head" style="justify-content: center; width: 65%; margin: auto;">
<h2>Case Study: Action</h2>
</div>
<div id = "action" style="display: flex; justify-content: center; align-items: center; width: 85%; margin: auto; height: 700px; flex-wrap: wrap; border: 1px solid #ccc;">
<div id="treemap_action" style="flex: 1 1 60%; display: flex; justify-content: center; align-items: center; min-width: 300px; height: 100%; background-color: #f9f9f9;">
</div>
<div id="heatmap_action" style="flex: 1 1 40%; display: flex; justify-content: center; align-items: center; min-width: 100px; height: 100%; background-color: #f9f9f9;">
</div>
</div>
<script>
const data_2 = {{ treemap_data|safe }};
const genres_2 = {{ genres|tojson }};
const heatmapData_2 = {{ heatmap_data|safe }};
function drawVisualizationsForAction() {
const genre = "Action";
// Check if the genre exists in treemap data
const genreDataExists = data_2.children.find(d => d.name === genre);
if (!genreDataExists) {
console.error('No data for genre:', genre);
return; // Exit if no data found
}
// Treemap Data Filtering
const filteredTreemapData = {
name: genre,
children: data_2.children.find(d => d.name === genre)?.children || []
};
function drawTreemap2(data) {
const containerSize = getSize('treemap_action');
const width = containerSize.width, height = Math.min(700, window.innerHeight * 0.6);
document.getElementById('treemap_action').innerHTML = ''; // Clear previous treemap
const root = d3.hierarchy(data).sum(d => d.value).sort((a, b) => b.value - a.value);
d3.treemap().size([width, height-100]).padding(2)(root);
const svg = d3.select("#treemap_action").append("svg")
.attr("width", width)
.attr("height", height + 30);
svg.append("text")
.attr("x", window.innerWidth / 4) // Centering the text
.attr("y", height) // Position below the diagram
.attr("class", "caption")
.style("font", "16px sans-serif")
.style("text-anchor", "middle")
.text("Distribution of Box Office Earnings for Action Movies in 2023 with top 3 movies highlighted");
const cell = svg.selectAll("g")
.data(root.leaves())
.enter().append("g")
.attr("transform", d => `translate(${d.x0},${d.y0})`);
cell.append("rect")
.attr("width", d => d.x1 - d.x0)
.attr("height", d => d.y1 - d.y0)
.attr("fill", d => colorScale(d.parent.data.name))
.attr("stroke", "#fff");
cell.append("title")
.text(d => `${d.data.name}\n${d.value.toLocaleString()}`);
cell.filter(d => (d.x1 - d.x0) > 40)
.append("text")
.attr("dx", 4)
.attr("dy", 20)
.text(d => d.data.name + "\n $ " + d.value.toLocaleString());
const totalEarnings = root.value;
const topMovies = root.leaves().slice(0, 3);
topMovies.forEach((movie, index) => {
const percentage = ((movie.value / totalEarnings) * 100).toFixed(2);
const text = `${movie.data.name}: (${percentage}%)`;
const textWidth = text.length * 6; // Approximation of text width
const textX = movie.x0 + (movie.x1 - movie.x0) / 2 + 50;
const textY = movie.y0 - 30 - 20 * index + 100;
// Draw dialog box path
svg.append("path")
.attr("d", `M${textX - textWidth/2} ${textY + 20}
L${textX - 10} ${textY + 20}
L${textX} ${textY + 30}
L${textX + 10} ${textY + 20}
L${textX + textWidth/2} ${textY + 20}
V${textY - 20}
H${textX - textWidth/2}
Z`)
.attr("fill", "white")
.attr("stroke", "black");
// Add text on top of the dialog box
svg.append("text")
.attr("x", textX)
.attr("y", textY)
.text(text)
.attr("font-size", "12px")
.attr("text-anchor", "middle")
.attr("fill", "black");
});
}
drawTreemap2(filteredTreemapData);
// Heatmap Data Filtering
const filteredHeatmapData = {};
Object.keys(heatmapData_2).forEach(month => {
filteredHeatmapData[month] = {};
filteredHeatmapData[month][genre] = heatmapData_2[month][genre] || 0;
});
console.log(filteredHeatmapData);
function drawHeatmap2(data, isAll) {
const containerSize = getSize('heatmap_action');
const width = containerSize.width, height = Math.min(700, window.innerHeight * 0.6);
// Clear previous content
document.getElementById('heatmap_action').innerHTML = '';
const svg = d3.select("#heatmap_action").append("svg")
.attr("width", width)
.attr("height", height);
const margin = { top: 1, right: 1, bottom: 10, left: 1},
g = svg.append("g").attr("transform", `translate(${margin.left}, ${margin.top})`);
const monthNames = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
const months = Object.keys(data).sort((a, b) => a - b); // Assume months are numeric strings
const genres = isAll ? ['All'] : Object.keys(data[months[0]]);
const y = d3.scaleBand().rangeRound([0, height-20]).padding(0.1).domain(months);
const x = d3.scaleBand().rangeRound([50, width/2]).padding(0.1).domain(genres);
let totalRevenue = d3.sum(months, month => isAll ? data[month] : d3.sum(Object.values(data[month])));
let monthValues = months.map(month => ({
month,
value: isAll ? data[month] : d3.sum(Object.values(data[month])),
percentage: ((isAll ? data[month] : d3.sum(Object.values(data[month]))) / totalRevenue * 100).toFixed(2)
}));
//month text for the name of the month and the percentage of the revenue
monthText = monthValues.map(d => `${monthNames[d.month - 1]}: (${d.percentage}%)`);
console.log(monthText);
// Find the max and min month values
const maxValue = d3.max(monthValues, d => d.value);
const minValue = d3.min(monthValues, d => d.value);
const maxMonth = monthValues.find(d => d.value === maxValue).month;
const minMonth = monthValues.find(d => d.value === minValue).month;
// Map months to values for the heatmap
const z = d3.scaleSequential(d3.interpolateViridis).domain([maxValue, minValue]);
g.selectAll(".heatmap-rect")
.data(months.map(month => ({ month, value: isAll ? data[month] : data[month][genres[0]] })))
.enter().append("rect")
.attr("y", d => y(d.month))
.attr("x", () => x(isAll ? 'All' : genres[0]))
.attr("width", width/3)
.attr("height", y.bandwidth()/1.5)
.attr("fill", d => z(d.value))
.attr("stroke", "black");
// Draw special borders for the highest and lowest months
[maxMonth, minMonth].forEach(month => {
g.append("rect")
.attr("x", x(isAll ? 'All' : genres[0]))
.attr("y", y(month))
.attr("width", width/3)
.attr("height", y.bandwidth()/1.5)
.attr("stroke", month === maxMonth ? "orange" : "red") // gold for max, red for min
.attr("stroke-width", 10) // thicker border
.attr("fill", "none");
});
// Draw text labels with percentage
g.selectAll(".month-label")
.data(monthValues)
.enter().append("text")
.attr("class", "month-label")
.attr("y", d => y(d.month) + y.bandwidth() / 3.5) // Centered in the band
.attr("x", width/3 + 100) // Positioned right of the bars based on fixed width
.attr("dy", ".35em")
.attr("alignment-baseline", "middle")
.text(d => `${monthNames[d.month - 1]} (${d.percentage}%)`); // Display the month names with percentages
// Adding captions for the x and y axis
svg.append("text")
.attr("x", 300) // Centering the text
.attr("y", height-10) // Position below the diagram
.attr("class", "caption")
.style("font", "16px sans-serif") // Style the font as needed
.style("text-anchor", "middle") // Center the text horizontally
.text("Distribution of Box Office Earnings Across Months in 2023");
// Adding the color gradient legend
const legendHeight = 300;
const legendWidth = 20;
const numSwatches = 10;
const colorScale = d3.scaleSequential(d3.interpolateViridis)
.domain([0, numSwatches - 1]);
const legend = svg.append("g")
.attr("transform", `translate(${width/3 + 200}, ${height/8})`); // Adjust these values as needed
legend.selectAll(".color-swatch")
.data(d3.range(numSwatches))
.enter().append("rect")
.attr("y", (d, i) => i * (legendHeight / numSwatches))
.attr("height", legendHeight / numSwatches)
.attr("width", legendWidth)
.attr("fill", d => colorScale(d));
// Add labels for the legend
legend.append("text")
.attr("x", legendWidth + 5)
.attr("y", 0)
.attr("dy", ".35em")
.text("High");
legend.append("text")
.attr("x", legendWidth + 5)
.attr("y", legendHeight)
.attr("dy", ".35em")
.text("Low");
}
drawHeatmap2(filteredHeatmapData, false);
}
drawVisualizationsForAction(); // Initialize visualizations specifically for Action genre
</script>
<div id="action-text" style="justify-content: center; width: 65%; margin: auto;">
<p>In 2023, the distribution of box office earnings across genres and months demonstrated significant variations, indicative of consumer preferences and industry trends. We can observe these for individual genres using the filter implemented in the earlier visualizations. However, to showcase the variation between how the revenue changes across genres, I will discuss some through case studies. The first one is for Action, this genre is especially important as it contributed the most in terms of revenue, single-handedly accounting for one-third of the total revenue of all genres. </p>
<p>In the action movie genre, standout performers such as "The Super Mario Bros. Movie," "Avatar: The Way of Water," and "Guardians of the Galaxy Vol 3" highlighted a robust appetite for high-budget, visually captivating narratives. "The Super Mario Bros. Movie" led the pack with an impressive 18.88% of the action genre’s total revenue, cementing its place as one of the successful adaptations of video game franchises in cinematic formats. While the first place Mario movie does take a chunk of the Action movie revenue, after this the fall off is more gradual, possibly indicating <b>close competition</b> in the niche. </p>
<p>The heatmap of monthly earnings further demonstrates seasonal trends in movie-going habits. The start of the year saw minimal activity, with January accounting for only 1.24% of annual earnings. However, a significant surge occurred in April, capturing 19.85% of the year's total, likely bolstered by <b>spring break</b> holidays and major blockbuster releases timed to capitalize on this period. May continued the strong performance with 17.12%, reinforcing the trend that late spring to early summer constitutes a prime release window for major films. On the other hand, October saw a stark decline to a mere 0.18%, possibly due to a lack of major releases or competing entertainment options such as televised sports and seasonal festivities. The year rounded out with a spike in December (14.57%), typically driven by <b>holiday season</b> releases and high-budget spectacles aiming to maximize audience turnout during festive periods.</p>
<p>These visualizations not only underscore the cyclical nature of the film industry's revenue streams but also reflect strategic scheduling by studios to align major releases with periods of high audience availability, thereby maximizing their box office potential. </p>
</div>
<div id="comedy-head" style="justify-content: center; width: 65%; margin: auto;">
<h2>Case Study: Comedy</h2>
</div>
<div id = "comedy" style="display: flex; justify-content: center; align-items: center; width: 85%; margin: auto; height: 700px; flex-wrap: wrap; border: 1px solid #ccc;">
<div id="treemap_comedy" style="flex: 1 1 60%; display: flex; justify-content: center; align-items: center; min-width: 300px; height: 100%; background-color: #f9f9f9;">
</div>
<div id="heatmap_comedy" style="flex: 1 1 40%; display: flex; justify-content: center; align-items: center; min-width: 100px; height: 100%; background-color: #f9f9f9;">
</div>
</div>
<script>
function drawVisualizationsForAction() {
const genre = "Comedy";
// Check if the genre exists in treemap data
const genreDataExists = data_2.children.find(d => d.name === genre);
if (!genreDataExists) {
console.error('No data for genre:', genre);
return; // Exit if no data found
}
// Treemap Data Filtering
const filteredTreemapData = {
name: genre,
children: data_2.children.find(d => d.name === genre)?.children || []
};
function drawTreemap2(data) {
const containerSize = getSize('treemap_comedy');
const width = containerSize.width, height = Math.min(700, window.innerHeight * 0.6);
document.getElementById('treemap_comedy').innerHTML = ''; // Clear previous treemap
const root = d3.hierarchy(data).sum(d => d.value).sort((a, b) => b.value - a.value);
d3.treemap().size([width, height-100]).padding(2)(root);
const svg = d3.select("#treemap_comedy").append("svg")
.attr("width", width)
.attr("height", height + 30);
svg.append("text")
.attr("x", window.innerWidth / 4) // Centering the text
.attr("y", height) // Position below the diagram
.attr("class", "caption")
.style("font", "16px sans-serif")
.style("text-anchor", "middle")
.text("Distribution of Box Office Earnings for Comedy Movies in 2023 with top 3 movies highlighted");
const cell = svg.selectAll("g")
.data(root.leaves())
.enter().append("g")
.attr("transform", d => `translate(${d.x0},${d.y0})`);
cell.append("rect")
.attr("width", d => d.x1 - d.x0)
.attr("height", d => d.y1 - d.y0)
.attr("fill", d => colorScale(d.parent.data.name))
.attr("stroke", "#fff");
cell.append("title")
.text(d => `${d.data.name}\n${d.value.toLocaleString()}`);
cell.filter(d => (d.x1 - d.x0) > 40)
.append("text")
.attr("dx", 4)
.attr("dy", 20)
.text(d => d.data.name + "\n $ " + d.value.toLocaleString());
const totalEarnings = root.value;
const topMovies = root.leaves().slice(0, 3);
topMovies.forEach((movie, index) => {
const percentage = ((movie.value / totalEarnings) * 100).toFixed(2);
const text = `${movie.data.name}: (${percentage}%)`;
const textWidth = text.length * 6; // Approximation of text width
const textX = movie.x0 + (movie.x1 - movie.x0) / 2 + 50;
const textY = movie.y0 - 30 - 20 * index + 100;
// Draw dialog box path
svg.append("path")
.attr("d", `M${textX - textWidth/2} ${textY + 20}
L${textX - 10} ${textY + 20}
L${textX} ${textY + 30}
L${textX + 10} ${textY + 20}
L${textX + textWidth/2} ${textY + 20}
V${textY - 20}
H${textX - textWidth/2}
Z`)
.attr("fill", "white")
.attr("stroke", "black");
// Add text on top of the dialog box
svg.append("text")
.attr("x", textX)
.attr("y", textY)
.text(text)
.attr("font-size", "12px")
.attr("text-anchor", "middle")
.attr("fill", "black");
});
}
drawTreemap2(filteredTreemapData);
// Heatmap Data Filtering
const filteredHeatmapData = {};
Object.keys(heatmapData_2).forEach(month => {
filteredHeatmapData[month] = {};
filteredHeatmapData[month][genre] = heatmapData_2[month][genre] || 0;
});
console.log(filteredHeatmapData);
function drawHeatmap2(data, isAll) {
const containerSize = getSize('heatmap_comedy');
const width = containerSize.width, height = Math.min(700, window.innerHeight * 0.6);
// Clear previous content
document.getElementById('heatmap_comedy').innerHTML = '';
const svg = d3.select("#heatmap_comedy").append("svg")
.attr("width", width)
.attr("height", height);
const margin = { top: 1, right: 1, bottom: 10, left: 1},
g = svg.append("g").attr("transform", `translate(${margin.left}, ${margin.top})`);
const monthNames = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
const months = Object.keys(data).sort((a, b) => a - b); // Assume months are numeric strings
const genres = isAll ? ['All'] : Object.keys(data[months[0]]);
const y = d3.scaleBand().rangeRound([0, height-20]).padding(0.1).domain(months);
const x = d3.scaleBand().rangeRound([50, width/2]).padding(0.1).domain(genres);
let totalRevenue = d3.sum(months, month => isAll ? data[month] : d3.sum(Object.values(data[month])));
let monthValues = months.map(month => ({
month,
value: isAll ? data[month] : d3.sum(Object.values(data[month])),
percentage: ((isAll ? data[month] : d3.sum(Object.values(data[month]))) / totalRevenue * 100).toFixed(2)
}));
//month text for the name of the month and the percentage of the revenue
monthText = monthValues.map(d => `${monthNames[d.month - 1]}: (${d.percentage}%)`);
console.log(monthText);
// Find the max and min month values
const maxValue = d3.max(monthValues, d => d.value);
const minValue = d3.min(monthValues, d => d.value);
const maxMonth = monthValues.find(d => d.value === maxValue).month;
const minMonth = monthValues.find(d => d.value === minValue).month;
// Map months to values for the heatmap
const z = d3.scaleSequential(d3.interpolateViridis).domain([maxValue, minValue]);
g.selectAll(".heatmap-rect")
.data(months.map(month => ({ month, value: isAll ? data[month] : data[month][genres[0]] })))
.enter().append("rect")
.attr("y", d => y(d.month))
.attr("x", () => x(isAll ? 'All' : genres[0]))
.attr("width", width/3)
.attr("height", y.bandwidth()/1.5)
.attr("fill", d => z(d.value))
.attr("stroke", "black");
// Draw special borders for the highest and lowest months
[maxMonth, minMonth].forEach(month => {
g.append("rect")
.attr("x", x(isAll ? 'All' : genres[0]))
.attr("y", y(month))
.attr("width", width/3)
.attr("height", y.bandwidth()/1.5)
.attr("stroke", month === maxMonth ? "orange" : "red") // gold for max, red for min
.attr("stroke-width", 10) // thicker border
.attr("fill", "none");
});
// Draw text labels with percentage
g.selectAll(".month-label")
.data(monthValues)
.enter().append("text")
.attr("class", "month-label")
.attr("y", d => y(d.month) + y.bandwidth() / 3.5) // Centered in the band
.attr("x", width/3 + 100) // Positioned right of the bars based on fixed width
.attr("dy", ".35em")
.attr("alignment-baseline", "middle")
.text(d => `${monthNames[d.month - 1]} (${d.percentage}%)`); // Display the month names with percentages
// Adding captions for the x and y axis
svg.append("text")
.attr("x", 300) // Centering the text
.attr("y", height-10) // Position below the diagram
.attr("class", "caption")
.style("font", "16px sans-serif") // Style the font as needed
.style("text-anchor", "middle") // Center the text horizontally
.text("Distribution of Box Office Earnings Across Months in 2023");
// Adding the color gradient legend
const legendHeight = 300;
const legendWidth = 20;
const numSwatches = 10;
const colorScale = d3.scaleSequential(d3.interpolateViridis)
.domain([0, numSwatches - 1]);
const legend = svg.append("g")
.attr("transform", `translate(${width/3 + 200}, ${height/8})`); // Adjust these values as needed
legend.selectAll(".color-swatch")
.data(d3.range(numSwatches))
.enter().append("rect")
.attr("y", (d, i) => i * (legendHeight / numSwatches))
.attr("height", legendHeight / numSwatches)
.attr("width", legendWidth)
.attr("fill", d => colorScale(d));
// Add labels for the legend
legend.append("text")
.attr("x", legendWidth + 5)
.attr("y", 0)
.attr("dy", ".35em")
.text("High");
legend.append("text")
.attr("x", legendWidth + 5)
.attr("y", legendHeight)
.attr("dy", ".35em")
.text("Low");
}
drawHeatmap2(filteredHeatmapData, false);
}
drawVisualizationsForAction(); // Initialize visualizations specifically for Comedy genre
</script>
<div id="comedy-text" style="justify-content: center; width: 65%; margin: auto;">
<p>The case for comedy movies in 2023 reveals a striking dominance by "Barbie," which alone bagged a substantial 56.3% of the genre's total box office earnings, dramatically showcasing the film's overwhelming appeal and commercial success. This stark proportion highlights not only the movie's popularity but also its significant contribution to the genre, overshadowing other entries like "Haunted Mansion" and "A Man Called Otto," which managed 5.99% and 5.68% respectively. The steep drop-off after "Barbie" suggests a market <b>heavily skewed</b> towards this standout performer, with other films struggling to capture similar audience interest or financial success.</p>
<p>The monthly distribution of box office earnings once again tells the seasonality of cinema attendance and the strategic timing of releases. July, a peak month for movie-going due to <b>summer vacations</b>, saw an extraordinary 64.84% of the annual comedy genre earnings, likely inflated by "Barbie's" release. Such timing might be a strategic choice to exploit the increased availability of families and young audiences, maximizing viewership and revenue. In contrast, quieter months like November, January, and September experienced significantly lower earnings, highlighting the challenges films face during off-peak seasons. The year-end holiday season was not a big standout here as opposed to Action as we saw before. This could indicate that the audiences prefer other genres more during that time.</p>
<p>This case study not only reflects the strategic release schedules employed by studios to capitalize on high audience times, but studying this could also help reduce the potential wastage of marketing and distribution efforts by identifying the low turnout periods. </p>
</div>
<div id="concert-head" style="justify-content: center; width: 65%; margin: auto;">
<h2>Case Study: Concert/Performance</h2>
</div>
<div id = "concert" style="display: flex; justify-content: center; align-items: center; width: 85%; margin: auto; height: 700px; flex-wrap: wrap; border: 1px solid #ccc;">
<div id="treemap_concert" style="flex: 1 1 60%; display: flex; justify-content: center; align-items: center; min-width: 300px; height: 100%; background-color: #f9f9f9;">
</div>
<div id="heatmap_concert" style="flex: 1 1 40%; display: flex; justify-content: center; align-items: center; min-width: 100px; height: 100%; background-color: #f9f9f9;">
</div>
</div>
<script>
function drawVisualizationsForAction() {
const genre = "Concert/Perfor\u2026";
// Check if the genre exists in treemap data
const genreDataExists = data_2.children.find(d => d.name === genre);
if (!genreDataExists) {
console.error('No data for genre:', genre);
return; // Exit if no data found
}
// Treemap Data Filtering
const filteredTreemapData = {
name: genre,
children: data_2.children.find(d => d.name === genre)?.children || []
};
function drawTreemap2(data) {
const containerSize = getSize('treemap_concert');
const width = containerSize.width, height = Math.min(700, window.innerHeight * 0.6);
document.getElementById('treemap_concert').innerHTML = ''; // Clear previous treemap
const root = d3.hierarchy(data).sum(d => d.value).sort((a, b) => b.value - a.value);
d3.treemap().size([width, height-100]).padding(2)(root);
const svg = d3.select("#treemap_concert").append("svg")
.attr("width", width)
.attr("height", height + 30);
svg.append("text")
.attr("x", window.innerWidth / 4) // Centering the text
.attr("y", height) // Position below the diagram
.attr("class", "caption")
.style("font", "16px sans-serif")
.style("text-anchor", "middle")
.text("Distribution of Box Office Earnings for Concert/Performance Movies in 2023 with top 3 movies highlighted");
const cell = svg.selectAll("g")
.data(root.leaves())
.enter().append("g")
.attr("transform", d => `translate(${d.x0},${d.y0})`);
cell.append("rect")
.attr("width", d => d.x1 - d.x0)
.attr("height", d => d.y1 - d.y0)
.attr("fill", d => colorScale(d.parent.data.name))
.attr("stroke", "#fff");
cell.append("title")
.text(d => `${d.data.name}\n${d.value.toLocaleString()}`);
cell.filter(d => (d.x1 - d.x0) > 40)
.append("text")
.attr("dx", 4)
.attr("dy", 20)
.text(d => d.data.name + "\n $ " + d.value.toLocaleString());
const totalEarnings = root.value;
const topMovies = root.leaves().slice(0, 3);
topMovies.forEach((movie, index) => {
const percentage = ((movie.value / totalEarnings) * 100).toFixed(2);
const text = `${movie.data.name}: (${percentage}%)`;
const textWidth = text.length * 6; // Approximation of text width
const textX = movie.x0 + (movie.x1 - movie.x0) / 2 + 50;
const textY = movie.y0 - 30 - 20 * index + 100;
// Draw dialog box path
svg.append("path")
.attr("d", `M${textX - textWidth/2} ${textY + 20}
L${textX - 10} ${textY + 20}
L${textX} ${textY + 30}
L${textX + 10} ${textY + 20}
L${textX + textWidth/2} ${textY + 20}
V${textY - 20}
H${textX - textWidth/2}
Z`)
.attr("fill", "white")
.attr("stroke", "black");
// Add text on top of the dialog box
svg.append("text")
.attr("x", textX)
.attr("y", textY)
.text(text)
.attr("font-size", "11px")
.attr("text-anchor", "middle")
.attr("fill", "black");
});
}
drawTreemap2(filteredTreemapData);
// Heatmap Data Filtering
const filteredHeatmapData = {};
Object.keys(heatmapData_2).forEach(month => {
filteredHeatmapData[month] = {};
filteredHeatmapData[month][genre] = heatmapData_2[month][genre] || 0;
});
console.log(filteredHeatmapData);
function drawHeatmap2(data, isAll) {
const containerSize = getSize('heatmap_concert');
const width = containerSize.width, height = Math.min(700, window.innerHeight * 0.6);
// Clear previous content
document.getElementById('heatmap_concert').innerHTML = '';
const svg = d3.select("#heatmap_concert").append("svg")
.attr("width", width)
.attr("height", height);
const margin = { top: 1, right: 1, bottom: 10, left: 1},
g = svg.append("g").attr("transform", `translate(${margin.left}, ${margin.top})`);
const monthNames = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
const months = Object.keys(data).sort((a, b) => a - b); // Assume months are numeric strings
const genres = isAll ? ['All'] : Object.keys(data[months[0]]);
const y = d3.scaleBand().rangeRound([0, height-20]).padding(0.1).domain(months);
const x = d3.scaleBand().rangeRound([50, width/2]).padding(0.1).domain(genres);
let totalRevenue = d3.sum(months, month => isAll ? data[month] : d3.sum(Object.values(data[month])));
let monthValues = months.map(month => ({
month,
value: isAll ? data[month] : d3.sum(Object.values(data[month])),
percentage: ((isAll ? data[month] : d3.sum(Object.values(data[month]))) / totalRevenue * 100).toFixed(2)
}));
//month text for the name of the month and the percentage of the revenue
monthText = monthValues.map(d => `${monthNames[d.month - 1]}: (${d.percentage}%)`);
console.log(monthText);
// Find the max and min month values
const maxValue = d3.max(monthValues, d => d.value);
const minValue = d3.min(monthValues, d => d.value);
const maxMonth = monthValues.find(d => d.value === maxValue).month;
const minMonth = monthValues.find(d => d.value === minValue).month;
// Map months to values for the heatmap
const z = d3.scaleSequential(d3.interpolateViridis).domain([maxValue, minValue]);
g.selectAll(".heatmap-rect")
.data(months.map(month => ({ month, value: isAll ? data[month] : data[month][genres[0]] })))
.enter().append("rect")
.attr("y", d => y(d.month))
.attr("x", () => x(isAll ? 'All' : genres[0]))
.attr("width", width/3)
.attr("height", y.bandwidth()/1.5)
.attr("fill", d => z(d.value))
.attr("stroke", "black");
// Draw special borders for the highest and lowest months
[maxMonth, minMonth].forEach(month => {
g.append("rect")
.attr("x", x(isAll ? 'All' : genres[0]))
.attr("y", y(month))
.attr("width", width/3)
.attr("height", y.bandwidth()/1.5)
.attr("stroke", month === maxMonth ? "orange" : "red") // gold for max, red for min
.attr("stroke-width", 10) // thicker border
.attr("fill", "none");
});
// Draw text labels with percentage
g.selectAll(".month-label")
.data(monthValues)
.enter().append("text")
.attr("class", "month-label")
.attr("y", d => y(d.month) + y.bandwidth() / 3.5) // Centered in the band
.attr("x", width/3 + 100) // Positioned right of the bars based on fixed width
.attr("dy", ".35em")
.attr("alignment-baseline", "middle")
.text(d => `${monthNames[d.month - 1]} (${d.percentage}%)`); // Display the month names with percentages
// Adding captions for the x and y axis
svg.append("text")
.attr("x", 300) // Centering the text
.attr("y", height-10) // Position below the diagram
.attr("class", "caption")
.style("font", "16px sans-serif") // Style the font as needed
.style("text-anchor", "middle") // Center the text horizontally
.text("Distribution of Box Office Earnings Across Months in 2023");
// Adding the color gradient legend
const legendHeight = 300;
const legendWidth = 20;
const numSwatches = 10;
const colorScale = d3.scaleSequential(d3.interpolateViridis)
.domain([0, numSwatches - 1]);
const legend = svg.append("g")
.attr("transform", `translate(${width/3 + 200}, ${height/8})`); // Adjust these values as needed
legend.selectAll(".color-swatch")
.data(d3.range(numSwatches))
.enter().append("rect")
.attr("y", (d, i) => i * (legendHeight / numSwatches))
.attr("height", legendHeight / numSwatches)
.attr("width", legendWidth)
.attr("fill", d => colorScale(d));
// Add labels for the legend
legend.append("text")
.attr("x", legendWidth + 5)
.attr("y", 0)
.attr("dy", ".35em")
.text("High");
legend.append("text")
.attr("x", legendWidth + 5)
.attr("y", legendHeight)
.attr("dy", ".35em")
.text("Low");
}
drawHeatmap2(filteredHeatmapData, false);
}
drawVisualizationsForAction(); // Initialize visualizations specifically for Action genre
</script>
<div id="concert-text" style="justify-content: center; width: 65%; margin: auto;">
<p>The distribution of box office earnings for concert/performance movies in 2023 is particularly interesting, given the unprecedented success of "Taylor Swift | The Eras Tour," which alone amassed a staggering 79.63% of the genre’s total earnings. This dominant performance not only showcases Taylor Swift's immense popularity but also her ability to draw massive audiences to theaters, perhaps indicative of a broader trend where live concert films can effectively translate live music experiences to the cinematic format. This case study is important because while this niche was not a big part of the total annual box office revenue, it still has its own unique strategy for success. </p>
<p>Further analysis into the seasonal distribution of these earnings reveals that October and December were peak months, with October alone accounting for 79.65% of the annual earnings within this genre. This timing likely coincides with <b>strategic release</b> planning aimed at maximizing attendance by capturing the enthusiasm of fans during the <b>fall season</b>, possibly enhanced by holiday leisure time and the thematic resonance of live performances during festive periods. December also saw a significant uptick, capturing 19.10% of the earnings, likely driven by holiday season audiences seeking entertainment and festive experiences. The Taylor swift tour movie was strategically released during the middle of the tour, likely to capitalize on the hype and tie its success to that of the live performances. In stark contrast, other months like February, May, and June saw negligible or zero contributions to the genre’s earnings, highlighting the challenges of attracting audiences outside of optimal release windows. This pattern shows the importance of timing in the release strategy of concert films, which, unlike traditional movie genres, may rely heavily on the live event's fanbase and seasonal audience behaviors more than typical cinematic content.</p>
<p>The overwhelmingly central role of a single concert film in shaping the financial landscape of its genre for the year also raises questions about the sustainability and diversity of content within this niche. While "Taylor Swift | The Eras Tour" clearly set a high bar, it also overshadowed other performances, suggesting a potential area for growth in diversifying offerings and exploring different creative approaches to concert films to attract broader audiences throughout the year.</p>
</div>
<div id="Conclusion-text" style="justify-content: center; width: 65%; margin: auto;">
<h2>Conclusion</h2>
<p>The visualizations of the 2023 box office data present a clear and efficient way to digest complex financial information across different film genres and their distribution across the months. By leveraging formats like treemaps, heatmaps, and bar charts, these not only demonstrate the financial success of various movies and genres but also facilitate immediate insights into the timing of these earnings. This visual approach allows stakeholders to quickly discern patterns such as seasonal peaks in revenue and the outstanding performance of certain films, aiding in strategic decision-making concerning marketing efforts and release scheduling.</p>
<p>Despite their apparent advantages, these visualizations come with inherent drawbacks and risks of misinterpretation. One significant risk is the potential overemphasis on outliers, such as the massive revenue from the Taylor Swift concert movie which might give a skewed perception of typical market performance. Additionally, these visualizations might lack the necessary context about broader market conditions or economic factors that significantly impact box office results. To mitigate these risks, several strategies can be employed. Providing additional contextual data about the competitive landscape and broader economic conditions can enrich the interpretation of visual data, offering a more balanced view. In the explanation, I have made an effort to remedy this. However, some additional analysis or removal of outliers could be an alternative way to conduct this analysis. The alternative approach could provide insights that might be more relevant to up-and-coming movie makers as their works would more likely match the average and not the exception. </p>
</div>
<div id="acknowledgement-text" style="justify-content: center; width: 65%; margin: auto;">
<h3>Acknowledgements</h3>
<p>The data for this project was mined from https://www.the-numbers.com/market/2023/top-grossing-movies using python. Which was then processed and cleaned using the same. The data consists of the top 580 movies by box office revenue in North America (US and Canada). The visualizations were made using D3 and Javascript. The page is hosted on Github Pages, and is static HTML which uses Flask (python module).</p>
</div>
<footer>
<p>Created by Kinshuk Sharma. Code can be found at https://github.com/kinshuk1207/movie23/tree/main. Data from https://www.the-numbers.com/market/2023/top-grossing-movies.</p>
</body>
</html> |
//
// ArticleView.swift
// newsfeed
//
// Created by Jordan Yee on 3/10/22.
//
import SwiftUI
import UIKit
import URLImage
struct ArticleView: View {
let article: Article
var body: some View {
HStack {
// TODO: Add image view
if let image = article.image,
let url = URL(string: image){
URLImage(url, identifier: url.absoluteString) {
// This view is displayed before download starts
EmptyView()
} inProgress: { progress in
// Display progress
ProgressView()
} failure: { error, retry in
// Display error and retry button
Image(systemName: "photo.fill")
.foregroundColor(.white)
.background(Color.gray)
.frame(width: 100, height: 100)
.cornerRadius(10)
} content: { image in
// Downloaded image
image
.resizable()
.aspectRatio(contentMode: .fill)
.frame(width: 100, height: 100)
.clipShape(RoundedRectangle(cornerRadius: 10))
}
.environment(\.urlImageOptions,
.init(fetchPolicy: .returnStoreElseLoad(downloadDelay: nil)))
} else {
Image(systemName: "photo.fill")
.foregroundColor(.white)
.background(Color.gray)
.frame(width: 100, height: 100)
.cornerRadius(10)
}
VStack(alignment: .leading, spacing: 4) {
Text(article.title ?? "")
.foregroundColor(.black)
.font(.system(size: 18, weight: .semibold))
Text(article.source ?? "")
.foregroundColor(.gray)
.font(.system(size: 12, weight: .regular))
}
}
}
}
struct ArticleView_Previews: PreviewProvider {
static var previews: some View {
ArticleView(article: Article.dummyData)
.previewLayout(.sizeThatFits)
}
} |
/**
************************************************************************************************************************
* @file HelloWall.pde
* @author
* @version V0.1.0
* @date 4-April-2017
* @brief Test example for creating a virtual wall using the hAPI
************************************************************************************************************************
* @attention
*
*
************************************************************************************************************************
*/
/* library imports *****************************************************************************************************/
import processing.serial.*;
import com.dhchoi.CountdownTimer;
import com.dhchoi.CountdownTimerService;
/* Device block definitions ********************************************************************************************/
Device haply_2DoF;
byte deviceID = 5;
Board haply_board;
DeviceType device_type;
/* Animation Speed Parameters *****************************************************************************************/
long baseFrameRate = 120;
long count = 0;
/* Simulation Speed Parameters ****************************************************************************************/
final long SIMULATION_PERIOD = 1; //ms
final long HOUR_IN_MILLIS = 36000000;
CountdownTimer haptic_timer;
/* Graphics Simulation parameters *************************************************************************************/
PShape pantograph, joint1, joint2, handle;
PShape wall;
int pixelsPerMeter = 4000;
float radsPerDegree = 0.01745;
float l = .05; // in m: these are length for graphic objects
float L = .07;
float d = .02;
float r_ee = d/3;
PVector device_origin = new PVector (0, 0) ;
/* Physics Simulation parameters **************************************************************************************/
PVector f_wall = new PVector(0, 0);
float k_wall = 400; //N/mm
PVector pen_wall = new PVector(0, 0);
PVector pos_wall = new PVector(d/2, .07);
/* generic data for a 2DOF device */
/* joint space */
PVector angles = new PVector(0, 0);
PVector torques = new PVector(0, 0);
/* task space */
PVector pos_ee = new PVector(0, 0);
PVector f_ee = new PVector(0, 0);
/**********************************************************************************************************************
* Main setup function, defines parameters for physics simulation and initialize hardware setup
**********************************************************************************************************************/
void setup() {
/* Setup for the graphic display window and drawing objects */
/* 20 cm x 15 cm */
size(1057, 594, P2D); //px/m*m_d = px
background(0);
frameRate(baseFrameRate);
/* Initialization of the Board, Device, and Device Components */
/* BOARD */
haply_board = new Board(this, Serial.list()[0], 0);
/* DEVICE */
haply_2DoF = new Device(device_type.HaplyTwoDOF, deviceID, haply_board);
/* Initialize graphical simulation components */
/* set device in middle of frame on the x-axis and in the fifth on the y-axis */
device_origin.add((width/2), (height/5) );
/* create pantograph graphics */
createpantograph();
/* create wall graphics */
wall= createWall(pos_wall.x-.2,pos_wall.y,pos_wall.x+.2,pos_wall.y);
wall.setStroke(color(0));
/* haptics event timer, create and start a timer that has been configured to trigger onTickEvents */
/* every TICK (1ms or 1kHz) and run for HOUR_IN_MILLIS (1hr), then resetting */
haptic_timer = CountdownTimerService.getNewCountdownTimer(this).configure(SIMULATION_PERIOD, HOUR_IN_MILLIS).start();
}
/**********************************************************************************************************************
* Main draw function, updates simulation animation at prescribed framerate
**********************************************************************************************************************/
void draw() {
update_animation(angles.x*radsPerDegree, angles.y*radsPerDegree, pos_ee.x, pos_ee.y);
}
/**********************************************************************************************************************
* Haptics simulation event, engages state of physical mechanism, calculates and updates physics simulation conditions
**********************************************************************************************************************/
void onTickEvent(CountdownTimer t, long timeLeftUntilFinish){
/* check if new data is available from physical device */
if (haply_board.data_available()) {
/* GET END-EFFECTOR POSITION (TASK SPACE) */
angles.set(haply_2DoF.get_device_angles());
pos_ee.set( haply_2DoF.get_device_position(angles.array()));
pos_ee.set(device2graphics(pos_ee));
/* PHYSICS OF THE SIMULATION */
f_wall.set(0, 0);
pen_wall.set(0, (pos_wall.y - (pos_ee.y+r_ee)));
if (pen_wall.y < 0) {
f_wall = f_wall.add((pen_wall.mult(-k_wall)));
}
f_ee = (f_wall.copy()).mult(-1);
f_ee.set(graphics2device(f_ee));
}
/* update device torque in simulation and on physical device */
haply_2DoF.set_device_torques(f_ee.array());
torques.set(haply_2DoF.mechanisms.get_torque());
haply_2DoF.device_write_torques();
}
/* Graphical and physics functions ************************************************************************************/
/**
* Specifies the parameters for a haply_2DoF pantograph animation object
*/
void createpantograph() {
/* modify pantograph parameters to fit screen */
float l_ani=pixelsPerMeter*l;
float L_ani=pixelsPerMeter*L;
float d_ani=pixelsPerMeter*d;
float r_ee_ani = pixelsPerMeter*r_ee;
/* parameters for create pantograph object */
pantograph = createShape();
pantograph.beginShape();
pantograph.fill(255);
pantograph.stroke(0);
pantograph.strokeWeight(2);
pantograph.vertex(device_origin.x, device_origin.y);
pantograph.vertex(device_origin.x, device_origin.y);
pantograph.vertex(device_origin.x, device_origin.y);
pantograph.vertex(device_origin.x-d_ani, device_origin.y);
pantograph.vertex(device_origin.x-d_ani, device_origin.y);
pantograph.endShape(CLOSE);
joint1 = createShape(ELLIPSE, device_origin.x, device_origin.y, d_ani/5, d_ani/5);
joint1.setStroke(color(0));
joint2 = createShape(ELLIPSE, device_origin.x-d_ani, device_origin.y, d_ani/5, d_ani/5);
joint2.setStroke(color(0));
handle = createShape(ELLIPSE, device_origin.x, device_origin.y, 2*r_ee_ani, 2*r_ee_ani);
handle.setStroke(color(0));
strokeWeight(5);
}
/**
* Specifies the parameters for static wall animation object
*/
PShape createWall(float x1, float y1, float x2, float y2){
/* modify wall parameters to fit screen */
x1= pixelsPerMeter*x1;
y1= pixelsPerMeter*y1;
x2=pixelsPerMeter*x2;
y2=pixelsPerMeter*y2;
return createShape(LINE, device_origin.x+x1, device_origin.y+y1, device_origin.x+x2, device_origin.y+y2);
}
/**
* update animations of all virtual objects rendered
*/
void update_animation(float th1, float th2, float x_E, float y_E){
/* To clean up the left-overs of drawings from the previous loop */
background(255);
/* modify virtual object parameters to fit screen */
x_E = pixelsPerMeter*x_E;
y_E = pixelsPerMeter*y_E;
th1 = 3.14-th1;
th2 = 3.14-th2;
float l_ani = pixelsPerMeter*l;
float L_ani = pixelsPerMeter*L;
float d_ani = pixelsPerMeter*d;
/* Vertex A with th1 from encoder reading */
pantograph.setVertex(1,device_origin.x+l_ani*cos(th1), device_origin.y+l_ani*sin(th1));
/* Vertex B with th2 from encoder reading */
pantograph.setVertex(3,device_origin.x-d_ani+l_ani*cos(th2), device_origin.y+l_ani*sin(th2));
/* Vertex E from Fwd Kin calculations */
pantograph.setVertex(2,device_origin.x+x_E, device_origin.y+y_E);
/* Display the virtual objects with new parameters */
shape(pantograph);
shape(joint1);
shape(joint2);
shape(wall);
pushMatrix();
shape(handle,x_E+(d/12*pixelsPerMeter), y_E, 2*r_ee*pixelsPerMeter, 2*r_ee*pixelsPerMeter);
stroke(0);
popMatrix();
}
/**
* translates from device frame of reference to graphics frame of reference
*/
PVector device2graphics(PVector deviceFrame){
return deviceFrame.set(-deviceFrame.x, deviceFrame.y);
}
/**
* translates from graphics frame of reference to device frame of reference
*/
PVector graphics2device(PVector graphicsFrame){
return graphicsFrame.set(-graphicsFrame.x, graphicsFrame.y);
}
/* Timer control event functions **************************************************************************************/
/**
* haptic timer reset
*/
void onFinishEvent(CountdownTimer t){
println("Resetting timer...");
haptic_timer.reset();
haptic_timer = CountdownTimerService.getNewCountdownTimer(this).configure(SIMULATION_PERIOD, HOUR_IN_MILLIS).start();
} |
import React from 'react';
import {
Card, CardActions, CardContent,
Button, Typography
} from '@mui/material';
import { ThemeProvider } from '@mui/material/styles';
import posts from '../../themes/posts'
export default function AllPostCard({
viewFunction,
name = '',
author = '',
publication_date,
image_path,
post_id }) {
return (
<ThemeProvider theme={posts}>
<Card>
<CardContent>
<Typography variant="h5" component="div">
{name}
</Typography>
<Typography >
{author}
</Typography>
<Typography variant="body2">
{publication_date}
</Typography>
</CardContent>
<CardActions>
<Button size="small"
onClick={(() =>
viewFunction(post_id))}>Mirar
</Button>
</CardActions>
</Card>
</ThemeProvider>
);
} |
package com.example.tgeorge.temajoc;
import android.graphics.Color;
import java.util.Random;
/**
* Created by TGeorge (TODOSI GEORGE VASILE GRUPA 3131B AN 3 CALCULATOARE) on 04-Jan-18.
* Clasa ce reprezinta modelul matricei 4x4
*/
public class GameModel {
Field tablajoc[][] = new Field[4][4]; //matrice 4x4 de tip Field
private int scor_u = 0; //camp ce memoreaza numarul de victorii ale utilizatorului
private int scor_m = 0; //camp ce memoreaza numarul de victorii ale calculatorului
public GameModel()
{
//constructor ce initialieaza fiecare camp ca fiind gol si de culoare gri
for(int i = 0 ; i < 4; i++)
for(int j = 0; j < 4; j++)
tablajoc[i][j] = new Field(Color.GRAY,"");
}
//getter si settere
public int GetPlayerScore()
{
return scor_u;
}
public int GetMobileScore()
{
return scor_m;
}
public void IncreaseUserScore()
{
scor_u++;
}
public void IncreaseMobileScore()
{
scor_m++;
}
public void Clear()
{
//metoda ce reseteaza scorul si matricea pentru a incepe un joc nou
int scor_u = 0;
int scor_m = 0;
for(int i = 0 ; i < 4; i++)
for(int j = 0; j < 4; j++) {
tablajoc[i][j].SetColor(Color.GRAY);
tablajoc[i][j].SetOwner("");
}
}
public void DoPCTurn()
{
//metoda ce efectueaza mutarea calculatorului
int i,j;
Random rnd = new Random();
//se cauta campuri aleatoriu pana cand se gaseste unul gol
do {
i = rnd.nextInt(4);
j = rnd.nextInt(4);
}
while(!tablajoc[i][j].GetOwner().equals(""));
//campului gasit este setat ca apartinand calculatorului
tablajoc[i][j].SetOwner("m");
tablajoc[i][j].SetColor(Color.GREEN);
}
public boolean CheckVictoryForInput(String input)
{
//metoda ce verifica daca jocul a fost castigat
//parametrul input specifica a cui victorie sa se verifice
//verificarea se face cautand campuri consecutive ce apartin aceluiasi utilizator
//variabila consecutiv este incrementata de fiecare data cand sunt gasite campuri consecutive
//daca variabila atinge valoarea 3 functia returneaza true
//daca se gaseste un camp care nu este consecutiv si variabila nu a atins valoarea 3 ea este resetata la 0
//daca nu se iese din functie cu true pana la terminarea parcurgerilor functia returneaza false
//verificare victorie pe linie
int consecutive = 0;
for(int i = 0 ; i < 4; i++) {
consecutive = 0;
for (int j = 0; j < 4; j++) {
if (tablajoc[i][j].GetOwner().equals(input)) {
consecutive++;
if (consecutive == 3)
return true;
} else
consecutive = 0;
}
}
//verificare victorie pe coloana
consecutive = 0;
for(int j = 0 ; j < 4; j++) {
consecutive = 0;
for (int i = 0; i < 4; i++) {
if (tablajoc[i][j].GetOwner().equals(input)) {
consecutive++;
if (consecutive == 3)
return true;
} else
consecutive = 0;
}
}
//verificare victorie pe diagonala principala
consecutive = 0;
for (int i = 0; i < 4; i++)
if (tablajoc[i][i].GetOwner().equals(input)) {
consecutive++;
if (consecutive == 3)
return true;
} else
consecutive = 0;
//verificare victorie pe diagonala secundara
consecutive = 0;
for (int i = 0; i < 4; i++)
if (tablajoc[i][3-i].GetOwner().equals(input)) {
consecutive++;
if (consecutive == 3)
return true;
} else
consecutive = 0;
//verificare victorie diagonalele mici principale
consecutive = 0;
for (int i = 0; i < 3; i++)
if (tablajoc[i][i+1].GetOwner().equals(input)) {
consecutive++;
if (consecutive == 3)
return true;
} else
consecutive = 0;
consecutive = 0;
for (int i = 1; i < 4; i++)
if (tablajoc[i][i-1].GetOwner().equals(input)) {
consecutive++;
if (consecutive == 3)
return true;
} else
consecutive = 0;
//verificare victorie pe diagonalele mici secundare
consecutive = 0;
for(int i = 1; i < 4; i++)
if (tablajoc[i][3-i+1].GetOwner().equals(input)) {
consecutive++;
if (consecutive == 3)
return true;
} else
consecutive = 0;
consecutive = 0;
for(int i = 0; i < 3; i++)
if (tablajoc[i][3-i-1].GetOwner().equals(input)) {
consecutive++;
if (consecutive == 3)
return true;
} else
consecutive = 0;
return false;
}
public boolean isRemiza()
{
//metoda care verifica daca jocul este o remiza
//se cauta un camp gol iar daca este gasit se retunreaza false
//daca nu se gasesc campuri goale functia returneaza true
for (int i = 0; i < 4; i++)
for (int j = 0; j < 4; j++)
if(tablajoc[i][j].GetOwner().equals(""))
return false;
return true;
}
} |
module Flipper
# Builds an adapter from a stack of adapters.
#
# adapter = Flipper::AdapterBuilder.new do
# use Flipper::Adapters::Strict
# use Flipper::Adapters::Memoizable
# store Flipper::Adapters::Memory
# end.to_adapter
#
class AdapterBuilder
def initialize(&block)
@stack = []
# Default to memory adapter
store Flipper::Adapters::Memory
block.arity == 0 ? instance_eval(&block) : block.call(self) if block
end
if RUBY_VERSION >= '3.0'
def use(klass, *args, **kwargs, &block)
@stack.push ->(adapter) { klass.new(adapter, *args, **kwargs, &block) }
end
else
def use(klass, *args, &block)
@stack.push ->(adapter) { klass.new(adapter, *args, &block) }
end
end
if RUBY_VERSION >= '3.0'
def store(adapter, *args, **kwargs, &block)
@store = adapter.respond_to?(:call) ? adapter : -> { adapter.new(*args, **kwargs, &block) }
end
else
def store(adapter, *args, &block)
@store = adapter.respond_to?(:call) ? adapter : -> { adapter.new(*args, &block) }
end
end
def to_adapter
@stack.reverse.inject(@store.call) { |adapter, wrapper| wrapper.call(adapter) }
end
end
end |
from nicegrill import Message, run, startup
from config import GOOGLE_DEV_API, GOOGLE_CX_ID
from telethon import TelegramClient as Client
from google_images_search import GoogleImagesSearch
from pytube import YouTube
from googlesearch import search
from youtube_search import YoutubeSearch
from requests.exceptions import ReadTimeout, ConnectTimeout
from nicegrill.utils import get_full_log, strip_prefix
from io import BytesIO
from bs4 import BeautifulSoup
from yt_dlp import YoutubeDL
import asyncio
import html
import json
import os
class Media:
"""this is a test"""
GOOGLE_CLIENT: GoogleImagesSearch = None
SEARCH_LIMIT = 5
UPLOADED_IMAGES = []
CURRENT_MESSAGE = None
URL = "https://www.bing.com/images/search?q="
async def simple_progress_tracker(received_bytes=None, total_bytes=None, url=None, progress=None):
if received_bytes:
progress = round((received_bytes/total_bytes) * 100, 2)
try:
if int(progress) % 7 == 0:
await Media.CURRENT_MESSAGE.edit(f"<b>URL:</b> <i>{url}</i>\n<b>Progress:</b> <i>{progress}%</i>")
except:
pass
@run(command="yt")
async def youtube_search(message: Message, client: Client, only_url=False):
if only_url:
return YoutubeSearch(
search_terms=message.args,
max_results=1
).to_dict()
if not message.args:
await message.edit("<i>You need to type in a keyword first</i>")
return
await message.edit(f"<i>Searching for the keyword <u>{message.args}</u> in YouTube</i>")
results = (await asyncio.to_thread(YoutubeSearch,
search_terms=message.args,
max_results=Media.SEARCH_LIMIT
)).to_dict()
result_page = ""
for result in results:
result_page += f"""
<b>◍ {result.get('title')}</b>
<b>URL:</b> <i>https://www.youtube.com{result.get('url_suffix')}</i>
<b>Channel:</b> <i>{result.get('channel')}</i>
<b>Duration:</b> <i>{result.get("Duration")}</i>
"""
await message.edit(result_page, link_preview=False)
@run(command="song")
async def song_downloader(message: Message, client: Client):
if not message.args:
await message.edit("<i>You need to tell me what to search for</i>")
return
await message.edit("<i>Searching for songs</i>")
opts = {
"outtmpl": f"{message.args}.m4a",
'format': 'm4a/bestaudio/best',
'postprocessors': [{
'key': 'FFmpegExtractAudio',
'preferredcodec': 'm4a',
}]
}
yt_client = YoutubeDL(opts)
result = await Media.youtube_search(
message=message,
client=client,
only_url=True
)
if result:
song_url = "https://youtube.com" + result[0].get("url_suffix")
else:
await message.edit(f"No song found with keyword {message.args}</i>")
return
await message.edit("<i>Song found, downloading it rn</i>")
yt_client.download(song_url)
await message.edit("<i>Uploading the song to Telegram</i>")
await client.send_file(
entity=message.chat,
file=message.args + ".m4a",
voice_note=True
)
os.remove(message.args + ".m4a")
await message.delete()
@run(command="ytv")
async def youtube_downloader(message: Message, client: Client):
if not message.args:
await message.edit("<i>Enter in a valid URL first</i>")
return
try:
await message.edit("<i>Searching in YouTube for a downloadable media in the link</i>")
youtube_search = YouTube(message.args).streams.filter()
except Exception as e:
await message.edit("<i>Video is unavailable</i>")
return
result = youtube_search.get_highest_resolution()
if not result:
await message.edit("<i>There is no downloadable media found in this link</i>")
return
await message.edit("<i>Downloading the video into buffer</i>")
video_buffer = BytesIO()
result.stream_to_buffer(video_buffer)
video_buffer.seek(0)
video_buffer.name = result.default_filename
Media.CURRENT_MESSAGE = message
await message.edit("<i>Uploading the video into telegram</i>")
video_handle = await message.respond(
file=video_buffer,
progress_callback=lambda received_bytes, total_bytes:
asyncio.get_event_loop().create_task(
Media.simple_progress_tracker(
url=message.args,
progress=round((received_bytes/total_bytes) * 100, 2),
message=f"<i>Here's the downloaded video for the input link {message.args}</i>",
supports_streaming=True
)
)
)
await message.delete()
@run(command="google")
async def google_regular_search(message: Message, client: Client):
await message.edit("<i>Searching..</i>")
google_search = search(
message.args,
advanced=True,
num_results=Media.SEARCH_LIMIT,
timeout=10
)
try:
result_page = ""
for search_result in await asyncio.to_thread(list, google_search):
result_page += f"""
<b>◍ {search_result.title}</b>
<i>{search_result.url}</i>
{search_result.description}
"""
except (ReadTimeout, ConnectTimeout):
await message.edit("<i>Time has run out for this search</i>")
return
except:
await message.edit("<i>Google search API is dead</i>")
return
await message.edit(result_page, link_preview=False)
@run(command="bimg")
async def bing_image_scrape_search(message: Message, client: Client):
if not message.args:
await message.edit("<i>Give me a keyword to look for in Bing images</i>")
return
await message.edit("<i>Retrieving data from image search</i>")
try:
url_data = await get_full_log(Media.URL + message.args)
except Exception as e:
await message.edit(f"<b>Error:</b> <i>{html.escape(str(e))}</i>")
return
if not url_data:
await message.edit("<i>Link cannot be retrieved</i>")
return
try:
parser = await asyncio.to_thread(BeautifulSoup, url_data.text, "lxml")
except Exception as e:
await message.edit(f"<b>Error:</b> <i>{html.escape(str(e))}</i>")
return
result = parser.find_all("a", class_="iusc")
image_urls = []
for item in result:
if item := item.get("m"):
image_data_dict = json.loads(item)
image_urls.append(image_data_dict.get("murl"))
if not image_urls:
await message.edit("<i>No images found, make sure you have a valid keyword</i>")
return
await message.edit("<i>Uploading image files to telegram</i>")
result.clear()
hit_counter = 0
for image_url in image_urls:
if hit_counter == Media.SEARCH_LIMIT:
break
try:
image_bytes = (await get_full_log(image_url)).content
if not image_bytes or image_bytes in result:
continue
except Exception:
continue
result.append(
await client.upload_file(
file=image_bytes,
file_name=strip_prefix(image_url) + ".png",
file_size=len(image_bytes)
)
)
hit_counter += 1
if not result:
await message.edit("<i>No images were downloaded, therefore process has failed</i>")
return
try:
await message.respond(
file=result,
message=f"<i>Here is the search result for the keyword <u>{message.args}</u></i>"
)
except:
await message.respond("<i>Media files may be corrupted, you can retry with retry command</i>")
Media.UPLOADED_IMAGES = result
await message.delete()
@run(command="gimg")
async def google_image_search(message: Message, client: Client):
if not message.args:
await message.edit("<i>Input a search keyword first</i>")
return
search_parameters = {
'q': message.args,
"num": Media.SEARCH_LIMIT,
"safe": "off"
}
Media.CURRENT_MESSAGE = await message.edit(f"<i>Searching images on google for the keyword: <u>{message.args}</u></i>")
try:
await asyncio.to_thread(Media.GOOGLE_CLIENT.search, search_parameters)
except Exception as e:
print(e)
await message.edit(f"<i>Error: {html.escape(e)}</i>")
return
image_files = []
image_bytes = BytesIO()
for image in Media.GOOGLE_CLIENT.results():
image.copy_to(image_bytes)
image_bytes.seek(0)
image_files.append(
await client.upload_file(
file=image_bytes,
file_size=image_bytes.getbuffer().nbytes,
file_name=strip_prefix(image.url)
)
)
image_bytes.seek(0)
if not image_files:
await message.edit(f"<i>No results found for {message.args}</i>")
return
await message.edit("<i>Uploading images to telegram</i>")
try:
await message.respond(
file=image_files,
message=f"<i>Here is the search result for the keyword <u>{message.args}</u></i>"
)
await message.delete()
except:
Media.UPLOADED_IMAGES = image_files
await message.edit(
"<i>Something went wrong with the file upload, you can retry with <code>reupload</code> command</i>"
)
return
@run(command="reupload")
async def retry_sending_images(message: Message, client: Client):
if not Media.UPLOADED_IMAGES:
await message.edit("<i>No photos stored in memory right now</i>")
return
await message.edit("<i>Retrying to upload the previous search</i>")
successful = False
for uploaded_image in Media.UPLOADED_IMAGES:
try:
await message.reply(
file=uploaded_image
)
successful = True
except:
pass
if not successful:
await message.edit("<i>Failed to upload the photos again, unfortunately have to delete</i>")
Media.UPLOADED_IMAGES = []
return
await message.delete()
@run(command="limit")
async def set_photo_count(message: Message, client: Client):
if not message.args or not message.args.isdigit():
await message.edit("<i>Please input a valid photo count</i>")
return
try:
Media.SEARCH_LIMIT = int(message.args) if int(message.args) > 0 else 1
except:
return
await message.edit(f"<i>Bing photo search count updated to {Media.SEARCH_LIMIT}</i>")
@startup
def google_client_initializer():
Media.GOOGLE_CLIENT = GoogleImagesSearch(
GOOGLE_DEV_API,
GOOGLE_CX_ID,
progressbar_fn=lambda url, progress:
asyncio.get_event_loop().create_task(Media.simple_progress_tracker(url,progress))
) |
# PIC12F675 and 74HC4067 MULTIPLEXER
This folder showcases the processing of analog readings from various sensors using the PIC12F675 and the 74HC4067 analog multiplexer.
## Content
1. [Overview](#overview)
2. [About this project](#about-this-project)
3. [Schematic - PIC12F675 and 74HC4067 monitoring 8 sensors](#pic12f675-and-74hc4067-monitoring-up-to-8-analog-sensors)
* [KiCad Schematic](./KiCad/)
4. [PIC12F675 PINOUT](#pic12f675-pinout)
5. [74HC4067 PINOUT](#74hc4067-pinout)
6. [Prototype](#prototype---pic12f675-and-74hc4067-monitoring-with-3-lm35-and-3-tmp36-temperature-analog-sensors)
7. [MPLABX EXAMPLE](./MPLAB_EXAMPLE/)
8. [References](#references)
## Overview
The PIC12F675 is a compact, versatile microcontroller from Microchip's PIC12F series, offering a mix of analog and digital functionalities in a small 8-pin package. This microcontroller stands out for its integrated 10-bit Analog-to-Digital Converter (ADC), which supports up to four analog inputs, allowing for direct interfacing with various sensors and analog signals. These analog channels make the PIC12F675 particularly suitable for applications requiring the measurement of physical parameters such as temperature, light intensity, or other analog sensor data.
Although the PIC12F675 features four analog inputs (AN0, AN1, AN2, and AN3), dedicating all of these for analog readings can render it impractical due to the limited number of pins remaining for other crucial functionalities, such as triggering alerts for external modules. For applications necessitating the analog monitoring of multiple sensors, leveraging a multiplexer such as the 74HC4067 offers a practical solution. This approach enables the efficient connection of up to eight sensors to the system, optimizing resource use while maintaining functionality. Once again, the purpose of this experiment is merely to demonstrate the interfacing of the 74HC4067 multiplexer with the microcontroller, without necessarily making a judgment on the strategy employed to address a potential problem.
## About this project
This project with the PIC12F675 and the 74HC4067 can gather data from up to 8 LM35 or TMP36 temperature sensors, or even a combination of both. The program allows for individual calibration for each sensor. This way, it is possible to standardize the behavior of the sensors or to alert about different temperatures in different objects.
Although the 74HC4067 device allows for up to 16 addressable analog sensors through a combination of 4 bits (S0, S1, S2, and S3), in the configuration with the PIC12F675, it is only possible to address a maximum of 8 sensors. This is because there are not enough digital output pins on the PIC12F675 to fully utilize the 74HC4067.
It's important to highlight that since these are analog sensors, which typically produce a voltage between 0 and 5V depending on the magnitude they are designed to measure, it is easily feasible to replace them with other types of analog sensors as required by your application.
## PIC12F675 and 74HC4067 monitoring up to 8 analog sensors

The table below showcases the combinations for sensor selection based on the high and low values of the GP0, GP1, and GP2 pins of the PIC12F675, which are connected to the S0, S1, and S2 pins of the 74HC4067 device, respectively. It's important to note that the S3 pin of the 74HC4067 will not be used due to pin limitations on the PIC12F675. This way, S3 must be connected to GND.
| ANALOG SENSOR | S3 / GND | S2 / GP2 | S1 / GP1 | S0 / GP0 |
| --------------| -----------| --------- | --------- | -------- |
| Sensor 0 | 0 | 0 | 0 | 0 |
| Sensor 1 | 0 | 0 | 0 | 1 |
| Sensor 2 | 0 | 0 | 1 | 0 |
| Sensor 3 | 0 | 0 | 1 | 1 |
| Sensor 4 | 0 | 1 | 0 | 0 |
| Sensor 5 | 0 | 1 | 0 | 1 |
| Sensor 6 | 0 | 1 | 1 | 0 |
| Sensor 7 | 0 | 1 | 1 | 1 |
## PIC12F675 PINOUT

The PIC12F675 is a part of Microchip's PIC12F series of microcontrollers, which are known for their compact size and efficiency in simple applications. Here's a breakdown of each pin's function on the PIC12F675:
1. **GP0/AN0 (Pin 7)**: This pin serves as a general-purpose input/output (GPIO) pin and can also function as an analog input (AN0). It's often used for reading analog values when the microcontroller's analog-to-digital converter (ADC) is utilized. **In this application, this pin is used as analog input**.
2. **GP1/AN1 (Pin 6)**: Similar to GP0, this pin can be used as either a GPIO or an analog input (AN1). This versatility allows for flexibility in connecting various sensors or input devices. **In this application this pin is used as digital output (LSB) of sensor selection**.
3. **GP2/AN2/INT/COUT/VREF (Pin 5)**: This multi-functional pin can act as a GPIO, an analog input (AN2), an external interrupt input (INT), a comparator output (COUT), or a voltage reference (VREF). Its diverse functions enable it to support a wide range of applications.
4. **GP3/MCLR/VPP (Pin 4)**: This pin is used as the Master Clear (Reset) input (MCLR) when configured as an input. It can also function as the programming voltage input (VPP) during In-Circuit Serial Programming (ICSP). Note that GP3 is input-only and has an internal weak pull-up.
5. **GP4/AN3/T0CKI/CIN+ (Pin 3)**: This pin offers functionalities such as GPIO, analog input (AN3), timer0 clock input (T0CKI), and positive input to the comparator (CIN+). It's useful for timing applications and analog signal processing.
6. **GP5/CIN-/OSC1/CLKIN (Pin 2)**: GP5 serves multiple roles, including GPIO, negative input to the comparator (CIN-), and oscillator input (OSC1/CLKIN) for external clock sources.
7. **OSC2/CLKOUT (Pin 8)**: This pin can be used as an oscillator output (OSC2/CLKOUT) for clocking external devices or for feedback in resonator configurations. It's also involved in the microcontroller's internal clock generation system.
8. **VDD (Pin 1)**: This is the positive power supply pin. The PIC12F220 typically operates at a voltage range of 2.0V to 5.5V.
9. **VSS (Pin 8)**: This pin is the ground (GND) connection for the microcontroller.
## 74HC4067 PINOUT
The 74HC4067 is a 16-channel analog multiplexer/demultiplexer integrated circuit, featuring multiple pins for various functions.
- **Vcc (24)**: This is the power supply pin, which powers the device. It typically operates at a voltage range from 2V to 6V.
- **S0 to S3**: These are the select pins used to choose one of the 16 available channels. By applying a combination of HIGH and LOW signals to these four pins, a specific channel is selected for communication.
- **COMMON INPUT/OUTPU (1)**: The common input/output pin. In multiplexer mode, it serves as the output through which the selected channel's signal is sent. In demultiplexer mode, it serves as the common input that is routed to the selected output channel.
- **E (15)**: Enable pin. When this pin is LOW, the device operates normally. If set HIGH, all channels are disconnected from the common Z pin, effectively disabling the device.
- **I0 to I15**: These are the input/output pins for each of the 16 channels. In multiplexer mode, signals from any of these pins can be sent to the "COMMON INPUT/OUTPU" pin when the corresponding channel is selected. In demultiplexer mode, the signal from the "COMMON INPUT/OUTPU" pin can be routed to any of these pins, depending on which channel is selected.
- **GND (12)**: Ground pin, which is connected to the circuit's ground.
The image below shows the 74HC4067 pinout.

## Prototype - PIC12F675 and 74HC4067 monitoring WITH 3 LM35 and 3 TMP36 temperature analog sensors

## Contribution
If you've found value in this repository, please consider contributing. Your support will assist me in acquiring new components and equipment, as well as maintaining the essential infrastructure for the development of future projects. [Click here](https://www.paypal.com/donate/?business=LLV4PHKTXC4JW&no_recurring=0&item_name=Your+support+will+assist+me+in++maintaining+the+essential+infrastructure+for+the+development+of+future+projects.+¤cy_code=BRL) to make a donation or scan the QR code provided below.

## References
- [74HC4067; 74HCT4067 Data Sheet](https://www.mouser.com/datasheet/2/302/74HC_HCT4067-224948.pdf)
- [74HC4067 Data Sheet](https://www.ti.com/lit/ds/symlink/cd74hc4067.pdf?ts=1712408119726&ref_url=https%253A%252F%252Fwww.ti.com%252Fproduct%252FCD74HC4067%253Futm_source%253Dgoogle%2526utm_medium%253Dcpc%2526utm_campaign%253Dasc-int-null-44700045336317248_prodfolderdynamic-cpc-pf-google-wwe_int%2526utm_content%253Dprodfolddynamic%2526ds_k%253DDYNAMIC+SEARCH+ADS%2526DCM%253Dyes%2526gad_source%253D1%2526gclid%253DCj0KCQjw5cOwBhCiARIsAJ5njua--idu3oMmmJlBPdJG1XiHKPkUcuo6TcF6jwI5wmPTOeduiskG2oAaAoujEALw_wcB%2526gclsrc%253Daw.ds) |
/*
* Copyright (C) 2011 Keijiro Takahashi
* Copyright (C) 2012 GREE, Inc.
*
* 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.
*/
using UnityEngine;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.InteropServices;
#if UNITY_2018_4_OR_NEWER
using UnityEngine.Networking;
#endif
#if UNITY_STANDALONE_OSX || UNITY_EDITOR_OSX
using System.IO;
using System.Text.RegularExpressions;
using UnityEngine.Rendering;
#endif
#if UNITY_ANDROID
using UnityEngine.Android;
#endif
#if UNITY_IPHONE || UNITY_STANDALONE_OSX || UNITY_EDITOR_OSX
using AOT;
#endif
using Callback = System.Action<string>;
using ErrorCallback = System.Action<string, string>;
#if UNITY_IPHONE || UNITY_STANDALONE_OSX || UNITY_EDITOR_OSX
public class Singleton
{
private static Singleton _instance;
public Callback onJS;
public ErrorCallback onError;
public ErrorCallback onHttpError;
public Callback onAuth;
public Callback onLog;
public static Singleton Instance
{
get
{
if (_instance == null)
{
_instance = new Singleton();
}
return _instance;
}
}
}
#endif
public class WebViewObject
{
private const string TAG = "[WebViewObject]";
Callback onJS;
ErrorCallback onError;
ErrorCallback onHttpError;
Callback onAuth;
Callback onLog;
#if UNITY_ANDROID
class AndroidCallback : AndroidJavaProxy
{
private Action<string> callback;
public AndroidCallback(Action<string> callback) : base("net.gree.unitywebview.WebViewCallback")
{
this.callback = callback;
}
public void call(String message) {
callback(message);
}
}
AndroidJavaObject webView;
#else
IntPtr webView;
#endif
#if UNITY_IPHONE
[DllImport("__Internal")]
private static extern IntPtr _CWebViewPlugin_Init(string ua);
[DllImport("__Internal")]
private static extern int _CWebViewPlugin_Destroy(IntPtr instance);
[DllImport("__Internal")]
private static extern void _CWebViewPlugin_LoadURL(
IntPtr instance, string url);
[DllImport("__Internal")]
private static extern void _CWebViewPlugin_EvaluateJS(
IntPtr instance, string url);
[DllImport("__Internal")]
private static extern void _CWebViewPlugin_LaunchAuthURL(IntPtr instance, string url);
[DllImport("__Internal")]
private static extern void _CWebViewPlugin_SetDelegate(DelegateMessage callback);
[DllImport("__Internal")]
private static extern void _CWebViewPlugin_ClearCache(IntPtr instance, bool includeDiskFiles);
[DllImport("__Internal")]
private static extern void _CWebViewPlugin_ClearStorage(IntPtr instance);
#elif UNITY_STANDALONE_OSX
[DllImport("WebView")]
private static extern IntPtr _CWebViewPlugin_Init(string ua);
[DllImport("WebView")]
private static extern int _CWebViewPlugin_Destroy(IntPtr instance);
[DllImport("WebView")]
private static extern void _CWebViewPlugin_LoadURL(
IntPtr instance, string url);
[DllImport("WebView")]
private static extern void _CWebViewPlugin_EvaluateJS(
IntPtr instance, string url);
[DllImport("WebView")]
private static extern void _CWebViewPlugin_LaunchAuthURL(IntPtr instance, string url, string redirectUri);
[DllImport("WebView")]
private static extern void _CWebViewPlugin_SetDelegate(DelegateMessage callback);
#elif UNITY_WEBGL
[DllImport("__Internal")]
private static extern void _gree_unity_webview_init();
[DllImport("__Internal")]
private static extern void _gree_unity_webview_loadURL(string url);
[DllImport("__Internal")]
private static extern void _gree_unity_webview_evaluateJS(string js);
[DllImport("__Internal")]
private static extern void _gree_unity_webview_destroy();
#endif
#if UNITY_IPHONE || UNITY_STANDALONE_OSX || UNITY_EDITOR_OSX
private delegate void DelegateMessage(string key, string message);
[MonoPInvokeCallback(typeof(DelegateMessage))]
private static void delegateMessageReceived(string key, string message) {
if (key == "CallOnLog") {
if (Singleton.Instance.onLog != null) {
Singleton.Instance.onLog(message);
}
}
if (key == "CallFromJS") {
if (Singleton.Instance.onJS != null) {
Debug.Log($"{TAG} ==== onJS callback running message: " + message);
Singleton.Instance.onJS(message);
}
return;
}
if (key == "CallOnError" || key == "CallFromAuthCallbackError") {
if (Singleton.Instance.onError != null) {
Debug.Log($"{TAG} ==== onError callback running message: " + message);
Singleton.Instance.onError(key, message);
}
return;
}
if (key == "CallOnHttpError") {
if (Singleton.Instance.onHttpError != null) {
Debug.Log($"{TAG} ==== onHttpError callback running message: " + message);
Singleton.Instance.onHttpError(key, message);
}
return;
}
if (key == "CallFromAuthCallback") {
if (Singleton.Instance.onAuth != null) {
Debug.Log($"{TAG} ==== CallFromAuthCallback callback running message: " + message);
Singleton.Instance.onAuth(message);
}
return;
}
}
#endif
public void handleMessage(string message)
{
var i = message.IndexOf(':', 0);
if (i == -1)
return;
switch (message.Substring(0, i))
{
case "CallFromJS":
CallFromJS(message.Substring(i + 1));
break;
case "CallOnError":
CallOnError("CallOnError", message.Substring(i + 1));
break;
case "CallOnHttpError":
CallOnHttpError("CallOnHttpError", message.Substring(i + 1));
break;
}
}
public void Init(
Callback cb = null,
ErrorCallback err = null,
ErrorCallback httpErr = null,
Callback auth = null,
Callback log = null,
string ua = "",
// android
int androidForceDarkMode = 0 // 0: follow system setting, 1: force dark off, 2: force dark on
)
{
onJS = cb;
onError = err;
onHttpError = httpErr;
onAuth = auth;
onLog = log;
#if UNITY_WEBGL
#if !UNITY_EDITOR
_gree_unity_webview_init();
#endif
#elif UNITY_WEBPLAYER
Application.ExternalCall("unityWebView.init");
#elif UNITY_EDITOR_WIN || UNITY_STANDALONE_WIN || UNITY_EDITOR_LINUX
//TODO: UNSUPPORTED
Debug.LogError("Webview is not supported on this platform.");
#elif UNITY_IPHONE || UNITY_STANDALONE_OSX
webView = _CWebViewPlugin_Init(ua);
Singleton.Instance.onJS = ((message) => CallFromJS(message));
Singleton.Instance.onError = ((id, message) => CallOnError(id, message));
Singleton.Instance.onHttpError = ((id, message) => CallOnHttpError(id, message));
Singleton.Instance.onAuth = ((message) => CallOnAuth(message));
Singleton.Instance.onLog = ((message) => CallOnLog(message));
_CWebViewPlugin_SetDelegate(delegateMessageReceived);
#elif UNITY_ANDROID
webView = new AndroidJavaObject("net.gree.unitywebview.CWebViewPluginNoUi");
webView.Call("Init", ua);
webView.Call("setCallback", new AndroidCallback((message) => handleMessage(message)));
#else
Debug.LogError("Webview is not supported on this platform.");
#endif
}
public void LoadURL(string url)
{
if (string.IsNullOrEmpty(url))
return;
#if UNITY_WEBGL
#if !UNITY_EDITOR
_gree_unity_webview_loadURL(url);
#endif
#elif UNITY_WEBPLAYER
Application.ExternalCall("unityWebView.loadURL", url);
#elif UNITY_EDITOR_WIN || UNITY_STANDALONE_WIN || UNITY_EDITOR_LINUX
//TODO: UNSUPPORTED
#elif UNITY_STANDALONE_OSX || UNITY_IPHONE
if (webView == IntPtr.Zero)
return;
_CWebViewPlugin_LoadURL(webView, url);
#elif UNITY_ANDROID
if (webView == null)
return;
webView.Call("LoadURL", url);
#endif
}
public void EvaluateJS(string js)
{
#if UNITY_WEBGL
#if !UNITY_EDITOR
_gree_unity_webview_evaluateJS(js);
#endif
#elif UNITY_WEBPLAYER
Application.ExternalCall("unityWebView.evaluateJS", js);
#elif UNITY_EDITOR_WIN || UNITY_STANDALONE_WIN || UNITY_EDITOR_LINUX
//TODO: UNSUPPORTED
#elif UNITY_STANDALONE_OSX || UNITY_IPHONE
if (webView == IntPtr.Zero)
return;
_CWebViewPlugin_EvaluateJS(webView, js);
#elif UNITY_ANDROID
if (webView == null)
return;
webView.Call("EvaluateJS", js);
#endif
}
public void LaunchAuthURL(string url, string redirectUri)
{
#if UNITY_STANDALONE_OSX
if (webView == IntPtr.Zero)
return;
_CWebViewPlugin_LaunchAuthURL(webView, url, redirectUri != null ? redirectUri : "");
#elif UNITY_IPHONE
if (webView == IntPtr.Zero)
return;
_CWebViewPlugin_LaunchAuthURL(webView, url);
#else
Application.OpenURL(url);
#endif
}
public void CallOnError(string id, string error)
{
if (onError != null)
{
onError(id, error);
}
}
public void CallOnHttpError(string id, string error)
{
if (onHttpError != null)
{
onHttpError(id, error);
}
}
public void CallOnAuth(string url)
{
if (onAuth != null)
{
onAuth(url);
}
}
public void CallFromJS(string message)
{
if (onJS != null)
{
#if !UNITY_ANDROID
#if UNITY_2018_4_OR_NEWER
message = UnityWebRequest.UnEscapeURL(message.Replace("+", "%2B"));
#else // UNITY_2018_4_OR_NEWER
message = WWW.UnEscapeURL(message.Replace("+", "%2B"));
#endif // UNITY_2018_4_OR_NEWER
#endif // !UNITY_ANDROID
onJS(message);
}
}
public void CallOnLog(string message)
{
Debug.Log($"{TAG} CallOnLog {message}");
if (onLog != null)
{
onLog(message);
}
}
public void ClearCache(bool includeDiskFiles)
{
#if UNITY_IPHONE && !UNITY_EDITOR
if (webView == IntPtr.Zero)
return;
_CWebViewPlugin_ClearCache(webView, includeDiskFiles);
#elif UNITY_ANDROID && !UNITY_EDITOR
if (webView == null)
return;
webView.Call("ClearCache", includeDiskFiles);
#else
throw new NotSupportedException();
#endif
}
public void ClearStorage()
{
#if UNITY_IPHONE && !UNITY_EDITOR
if (webView == IntPtr.Zero)
return;
_CWebViewPlugin_ClearStorage(webView);
#elif UNITY_ANDROID && !UNITY_EDITOR
if (webView == null)
return;
webView.Call("ClearStorage");
#else
throw new NotSupportedException();
#endif
}
} |
package leetcode;
public class SqrtX {
/**
* Leetcode 69
* Given a non-negative integer x, return the square root of x rounded down to the nearest integer. The returned
* integer should be non-negative as well.
* You must not use any built-in exponent function or operator.
*/
static int mySqrt(int x) {
if (x == 0) {
return x;
}
int left = 1;
int right = x;
while (left <= right) {
int mid = left + (right - left) / 2;
if (mid == x / mid) {
return mid;
} else if (mid > x / mid) {
right = mid - 1;
} else {
left = mid + 1;
}
}
return right;
}
} |
package code {
import flash.display.*;
import flash.text.*;
import flash.geom.*;
public class EnergyCube extends Sprite {
const FRONT_TOP_Y_POSITION:int = 45;
const EFFICIENCY_HEIGHT:int = 52;
const ELECTRICITY_HEIGHT:int = 116;
const HEAT_HEIGHT:int = 116;
const VEHICLE_HEIGHT:int = 116;
var data:EnergyData;
var xPos:Number;
var yPos:Number;
var efficiencyContainer:Sprite = null;
var electricityContainer:Sprite = null;
var heatContainer:Sprite = null;
var vehicleContainer:Sprite = null;
var frontSiblings:int;
public function EnergyCube(data:EnergyData,
x:Number,
y:Number) {
this.data = data;
xPos = x;
yPos = y;
frontSiblings = 0;
drawTitle();
drawCube();
updateUsage();
}
function drawTitle():void {
setupTextField(EnergyConsts.ENERGY_NAME, xPos + 20, yPos, 25, 16, true);
}
function setupTextField(name:String, x:Number, y:Number, h:Number, fontSize:Object, bold:Object=false) {
var tf:TextField = new TextField();
tf.text = name;
tf.x = x;
tf.y = y;
tf.width = 66;
tf.height = h;
tf.autoSize = TextFieldAutoSize.CENTER;
tf.selectable = false;
var format:TextFormat = new TextFormat();
format.align = TextFormatAlign.CENTER;
format.size = fontSize;
format.bold = bold;
format.font = "Arial";
tf.setTextFormat(format);
addChild(tf);
}
function drawCube():void {
// width - 86, height 420 starting at 25 (for title), 20 x 20 for diagonal lines
var line:Shape = new Shape();
line.graphics.lineStyle(2, 0x000000, 1, false, LineScaleMode.NONE, CapsStyle.NONE, JointStyle.MITER, 1);
line.graphics.drawRect(xPos + 20, yPos + 25, 66, 400);
line.graphics.moveTo(xPos, yPos + 445);
line.graphics.lineTo(xPos + 20, yPos + 425);
addChild(line);
var mc:MovieClip = new EfficiencyMC();
mc.x = xPos + 29;
mc.y = yPos + 42;
addChild(mc);
frontSiblings++;
mc = new ElectricityMC();
mc.x = xPos + 25;
mc.y = yPos + 112;
addChild(mc);
frontSiblings++;
mc = new HeatMC();
mc.x = xPos + 17;
mc.y = yPos + 251;
addChild(mc);
frontSiblings++;
mc = new VehicleMC();
mc.x = xPos + 22;
mc.y = yPos + 341;
addChild(mc);
frontSiblings++;
line = new Shape();
line.graphics.lineStyle(2, 0x000000, 1, false, LineScaleMode.NONE, CapsStyle.NONE, JointStyle.MITER, 1);
line.graphics.drawRect(xPos, yPos + FRONT_TOP_Y_POSITION, 66, 400);
line.graphics.moveTo(xPos, yPos + FRONT_TOP_Y_POSITION);
line.graphics.lineTo(xPos + 20, yPos + 25);
line.graphics.moveTo(xPos + 66, yPos + FRONT_TOP_Y_POSITION);
line.graphics.lineTo(xPos + 86, yPos + 25);
line.graphics.moveTo(xPos + 66, yPos + 445);
line.graphics.lineTo(xPos + 86, yPos + 425);
addChild(line);
frontSiblings++;
setupTextField(EnergyConsts.VEHICLE_FUEL_NAME, xPos,
yPos + FRONT_TOP_Y_POSITION + EFFICIENCY_HEIGHT + ELECTRICITY_HEIGHT + HEAT_HEIGHT + VEHICLE_HEIGHT - 15,
15, 9);
frontSiblings++;
setupTextField(EnergyConsts.HEAT_NAME, xPos,
yPos + FRONT_TOP_Y_POSITION + EFFICIENCY_HEIGHT + ELECTRICITY_HEIGHT + HEAT_HEIGHT - 15,
15, 9);
frontSiblings++;
setupTextField(EnergyConsts.ELECTRICITY_NAME, xPos,
yPos + FRONT_TOP_Y_POSITION + EFFICIENCY_HEIGHT + ELECTRICITY_HEIGHT - 15,
15, 9);
frontSiblings++;
setupTextField(EnergyConsts.EFFICIENCY_NAME, xPos,
yPos + FRONT_TOP_Y_POSITION + EFFICIENCY_HEIGHT - 15,
15, 9);
frontSiblings++;
}
public function updateUsage():void {
clearSectorContainers();
this.efficiencyContainer = new Sprite();
this.electricityContainer = new Sprite();
this.heatContainer = new Sprite();
this.vehicleContainer = new Sprite();
var effHeight:Number = 0;
var eHeight:Number = 0;
var hHeight:Number = 0;
var vHeight:Number = 0;
var dataItem:EnergyDataItem = this.data.currentDataItem;
if (dataItem) {
effHeight = Math.round(EFFICIENCY_HEIGHT * dataItem.efficiency / dataItem.efficiencyLimit);
eHeight = Math.round(ELECTRICITY_HEIGHT * dataItem.electricity / dataItem.electricityLimit);
hHeight = Math.round(HEAT_HEIGHT * dataItem.heat / dataItem.heatLimit);
vHeight = Math.round(VEHICLE_HEIGHT * dataItem.vehicleFuel / dataItem.vehicleFuelLimit);
}
// the following update order is important;
// it affects the index position of the container in the display list;
updateSectorUsage(vehicleContainer, vHeight, 0x8ABDE5,
yPos + FRONT_TOP_Y_POSITION + EFFICIENCY_HEIGHT + ELECTRICITY_HEIGHT + HEAT_HEIGHT + VEHICLE_HEIGHT - vHeight);
updateSectorUsage(heatContainer, hHeight, 0xE25B64,
yPos + FRONT_TOP_Y_POSITION + EFFICIENCY_HEIGHT + ELECTRICITY_HEIGHT + HEAT_HEIGHT - hHeight);
updateSectorUsage(electricityContainer, eHeight, 0xFEF05A,
yPos + FRONT_TOP_Y_POSITION + EFFICIENCY_HEIGHT + ELECTRICITY_HEIGHT - eHeight);
updateSectorUsage(efficiencyContainer, effHeight, 0xAECE7A,
yPos + FRONT_TOP_Y_POSITION + EFFICIENCY_HEIGHT - effHeight);
}
function updateSectorUsage(container:Sprite, cubeHeight:Number, color:uint, yBase:Number) {
var box:Shape;
if (cubeHeight > 1.0) {
box = new Shape();
box.graphics.lineStyle(2, 0x000000, 1, false, LineScaleMode.NONE, CapsStyle.NONE, JointStyle.MITER, 1);
box.graphics.beginFill(color);
box.graphics.drawRect(xPos, yBase, 66, cubeHeight);
box.graphics.moveTo(xPos + 66, yBase);
box.graphics.lineTo(xPos + 66, yBase + cubeHeight);
box.graphics.lineTo(xPos + 86, yBase + cubeHeight - 20);
box.graphics.lineTo(xPos + 86, yBase - 20);
box.graphics.lineTo(xPos + 66, yBase);
box.graphics.endFill();
container.addChild(box);
}
box = new Shape();
box.graphics.lineStyle(2, 0x000000, 1, false, LineScaleMode.NONE, CapsStyle.NONE, JointStyle.MITER, 1);
box.graphics.beginFill(color);
box.graphics.moveTo(xPos, yBase);
box.graphics.lineTo(xPos + 66, yBase);
box.graphics.lineTo(xPos + 86, yBase - 20);
box.graphics.lineTo(xPos + 20, yBase - 20);
box.graphics.lineTo(xPos, yBase);
box.graphics.endFill();
container.addChild(box);
addChildAt(container, numChildren - frontSiblings);
}
function clearSectorContainers():void {
if (efficiencyContainer && efficiencyContainer.parent) {
removeChild(efficiencyContainer);
}
if (electricityContainer && electricityContainer.parent) {
removeChild(electricityContainer);
}
if (heatContainer && heatContainer.parent) {
removeChild(heatContainer);
}
if (vehicleContainer && vehicleContainer.parent) {
removeChild(vehicleContainer);
}
}
}
} |
#!/usr/bin/Rscript
########################################################
# #
# Script to get an overview of finances within self- #
# employed buissnes and to create tables which can be #
# load with latex to automatically create a bill. #
# #
# Start of development: 28.12.2020 #
# #
########################################################
rm(list=ls())
##################### Libraries ########################
library(tidyverse)
library(shiny)
library(rstudioapi)
# library(zoo) # this package provides an easy way for moving average.
###################### Datasets ########################
# set working directory
file_path <- getSourceEditorContext()$path
file_pos <- file_path %>% str_locate_all("/") %>% unlist()
work_path <- file_path %>% str_sub(end = file_pos[length(file_pos)])
setwd(work_path)
# read time_records
tab <- read_csv(paste0("time_records/", sort(list.files(path = "time_records", pattern = glob2rx("timerecord*")), decreasing = T)[1]),
col_types = "iDcccTTdddcll")
tab$start <- as.character(tab$start) %>% str_sub(start = 11, end = -4)
tab$end <- as.character(tab$end) %>% str_sub(start = 11, end = -4)
project <- NULL
# create varables which are needed later in the GUI
min_date <- min(tab$date)
max_date <- max(tab$date)
customers <- unique(as.vector(tab$customer))
projects <- unique(as.vector(tab$project))
###################### Plotstyle ########################
source(paste0(work_path, "plot_style.R"))
################# Implement in Shiny ###################
# Frontend
ui <- fluidPage(
# Filter data to display in map
titlePanel("Finanzübersicht"),
# tags$h1("Nimburger Ried"),
tags$p("Mit iesem Programm können die Finanzen im Verlauf angeschaut werden und rechnungen geschrieben werden."),
tags$hr(),
# Sidebar with a slider input for the number of bins
sidebarLayout(
sidebarPanel(
# Filter by Date:
sliderInput(inputId = "daterange",
label = "Aufträge von-bis:",
min = as.Date(min_date),
max = as.Date(max_date),
value = c(as.Date(min_date), as.Date(max_date)),
timeFormat = "%Y-%m-%d"),
# Filter by Species group:
# checkboxGroupInput(inputId = "select_customer",
# label = "Filter nach Auftraggeber",
# choices = customers,
# selected = customers),
# Filter by Species group:
checkboxGroupInput(inputId = "select_project",
label = "Filter nach Projekten",
choices = projects,
selected = projects),
# Bill send or not?
# checkboxGroupInput(inputId = "billed",
# label = "Rechnung erstellt?",
# choiceNames = c("ja", "nein"),
# choiceValues = c(TRUE, FALSE),
# selected = c(TRUE, FALSE)),
# Print a bill according to the selected projects / customers
# textInput(inputId = "bill_input",
# label = "Für welches Projekt soll eine Rechnung erstellt werden?",
# placeholder = "Bsp. Ökopunkte A5"),
# verbatimTextOutput("project"),
#
# actionButton(inputId = "bill_button",
# label = "Rechnung erstellen")
),
mainPanel(
plotOutput("plot"),
tableOutput("table")
)
)
)
# Backend
server <- function(input, output, session) {
disp_tab <- reactive({tab %>% dplyr::filter(between(date, input$daterange[1], input$daterange[2]) &
project %in% input$select_project)
})
output$table <- renderTable(disp_tab())
output$plot <- renderPlot({disp_tab() %>% ggplot(aes(x = date, y = duration)) +
#geom_area(fill = colour.palette[1], alpha = .7) +
geom_point(col = colour.palette[2], size = 3) +
#geom_line(aes(y = rollmean(x = duration, 3, na.pad=TRUE))) +
geom_line(col=colour.palette[3]) + geom_smooth(col = colour.palette[4], se = F) +
geom_text(mapping = aes(x = date, y = duration, label = project), col = colour.palette[5], size = 6, hjust = 1.5)
})
observeEvent(input$bill_button, {
project <- input$bill_input
output$project <- renderText({ input$bill_input })
#source("../billing.R")
})
}
# Start
shinyApp(ui, server) |
#pragma once
#include <SDL2/SDL.h>
#include <SDL2/SDL_mixer.h>
#include "ProjectState.h"
#include "settings/EngineSettings.h"
#include "settings/Project.h"
#include "GUIImage.h"
enum SoundState { SS_STOPPED, SS_PLAYING, SS_PAUSED };
struct EngineVersion {
int major;
int minor;
int fix;
bool is_pre_release;
std::string version_string;
EngineVersion() : major(2), minor(0), fix(2), is_pre_release(true), version_string("ngine ") {
version_string += std::to_string(major) + "." + std::to_string(minor) + "." +
std::to_string(fix);
if (is_pre_release)
version_string.append("-pre");
};
};
class App {
public:
EngineVersion engine_version;
SDL_Renderer *renderer;
SDL_Window *window;
EngineSettings engine_settings;
Project project;
ProjectState state;
SDL_Texture *app_texture;
// audio
Mix_Chunk *audio_sample;
SoundState audio_state;
const char *default_title = "NGine - N64 Engine Powered by Libdragon";
bool is_running;
SDL_TimerID docker_check_timer;
explicit App(std::string engine_directory);
bool LoadAssets();
void GetImagePosition(std::string name, ImVec2 &uv0, ImVec2 &uv1);
bool OpenProject(const std::string &path);
void CloseProject();
[[nodiscard]] std::string GetEngineDirectory() const {
return engine_directory;
}
static void OpenUrl(const char *url);
private:
std::string engine_directory;
std::vector<GUIImage> images;
ImVec2 image_size;
}; |
# Matter Telink Shell Example Application
You can use this example as a reference for creating your own application.

## Build and flash
1. Run the Docker container:
```bash
$ docker run -it --rm -v $PWD:/host -w /host ghcr.io/project-chip/chip-build-telink:$(wget -q -O - https://raw.githubusercontent.com/project-chip/connectedhomeip/master/.github/workflows/examples-telink.yaml 2> /dev/null | grep chip-build-telink | awk -F: '{print $NF}')
```
Compatible docker image version can be found in next file:
```bash
$ .github/workflows/examples-telink.yaml
```
2. Activate the build environment:
```bash
$ source ./scripts/activate.sh -p all,telink
```
3. In the example dir run (replace _<build_target>_ with your board name, for
example, `tlsr9518adk80d` or `tlsr9528a`):
```bash
$ west build -b <build_target>
```
Also use key `-DFLASH_SIZE`, if your board has memory size different from 2
MB, for example, `-DFLASH_SIZE=1m` or `-DFLASH_SIZE=1m`:
```bash
$ west build -b tlsr9518adk80d -- -DFLASH_SIZE=4m
```
4. Flash binary:
```
$ west flash --erase
```
## Usage
### UART
To get output from device, connect UART to following pins:
| Name | Pin |
| :--: | :---------------------------- |
| RX | PB3 (pin 17 of J34 connector) |
| TX | PB2 (pin 16 of J34 connector) |
| GND | GND | |
const expect = require('expect');
const request = require('supertest');
const {ObjectID} = require('mongodb');
const {app} = require('./../server');
const {Todo} = require('./../models/todo');
const todos = [{
_id: new ObjectID(),
text: 'First test todo'
}, {
_id: new ObjectID(),
text: 'Second test todo'
}];
beforeEach((done) => {
Todo.deleteMany({}).then(() =>{
return Todo.insertMany(todos);
}).then(() => done());
});
// describe('POST /todos', () => {
// it('Should create a new todo', (done) => {
// var text = 'Test todo text';
// request(app)
// .post('/todos')
// .send({text})
// .expect(200)
// .expect((res) => {
// expect(res.body.text).toBe(text);
// })
// .end((err, res) => {
// if (err) {
// return done(err);
// }
// Todo.find({text}).then((todos) => {
// expect(todos.length).toBe(1);
// expect(todos[0].text).toBe(text);
// done();
// }).catch((e) => done(e));
// });
// });
// });
// it('should not create todo with invalid body data', (done) => {
// request(app)
// .post('/todos')
// .send({})
// .expect(400)
// .end((err, res) => {
// if (err){
// return done(err);
// }
// Todo.find().then((todos) => {
// expect(todos.length).toBe(2);
// done();
// }).catch((e) => done(e));
// });
// });
describe('GET /todos/:id', () => {
it('should return todo doc', (done) => {
request(app)
.get(`/todos/${todos[0]._id.toHexString()}`)
.expect(200)
.expect((res) => {
expect(res.body.todo.text).toBe(todos[0].text);
})
.end(done);
console.log(`${todos[0]._id.toHexString()}`);
});
it('Should return 404 if todo not found', (done) => {
var hexId = new ObjectID().toHexString();
request(app)
.get(`/todos/${hexId}`)
.expect(404)
.end(done);
});
it('should return 404 for non-objects ids', (done) => {
request(app)
.get('/todos/123abc')
.expect(404)
.end(done);
});
}); |
#!/usr/bin/perl
# vim: set filetype=perl :
use strict;
use warnings;
use 5.010;
use English qw( -no_match_vars);
use autodie;
use File::stat;
use Cwd;
main() unless caller(0);
sub main {
use Pod::Usage;
use Getopt::Long qw( :config auto_help pass_through );
use File::Path qw( make_path );
use Git;
my $ldif_cmd = '@sbindir@/safe-ldif';
my $backup_dir = '/var/backups/ldap';
my $commit_msg = 'ldap-git-backup';
my $commit_date = time();
my $gc = 1;
my $help;
GetOptions(
'ldif-cmd=s' => \$ldif_cmd,
'backup-dir=s' => \$backup_dir,
'commit-msg=s' => \$commit_msg,
'commit-date=s' => \$commit_date,
'gc!' => \$gc,
'help' => \$help,
);
pod2usage('-verbose' => 2, '-exit_status' => 0) if $help;
pod2usage() if @ARGV;
if ( -e $commit_date ) {
$commit_date = stat($commit_date)->mtime();
}
if ( $backup_dir =~ m{\A [^/]}xms ) {
$backup_dir = getcwd() . '/' . $backup_dir;
}
my $ldif_aref = LDAP::Utils::read_ldif($ldif_cmd);
make_path($backup_dir, {mode => 0700});
my $mode = stat($backup_dir)->mode;
warn "backup directory $backup_dir is world readable\n" if $mode & 05;
warn "backup directory $backup_dir is world writable\n" if $mode & 02;
chdir($backup_dir);
Git::command('init');
my $repo = Git->repository(Directory => $backup_dir);
my @filelist = $repo->command('ls-files', '*.ldif');
my %files_before = ();
for my $f (@filelist) { $files_before{$f} = 1 }
@filelist = ();
for my $ldif (@$ldif_aref) {
my $filename = LDAP::Utils::filename($ldif);
open(my $fh, '>', "$backup_dir/$filename");
print {$fh} $ldif;
close($fh);
push(@filelist, $filename);
delete($files_before{$filename});
}
$repo->command('add', @filelist) if @filelist;
$repo->command('rm', (keys %files_before)) if %files_before;
$repo->command('commit', "--message=$commit_msg", "--date=$commit_date");
$repo->command('gc', '--quiet') if $gc;
}
package LDAP::Utils;
use strict;
use warnings;
use 5.010;
use English qw( -no_match_vars);
use Carp;
use autodie;
use MIME::Base64;
sub read_ldif {
my ($ldif_cmd) = @_;
my $entry_count = -1;
my $ldif_aref = [];
until ($entry_count == @$ldif_aref) {
$entry_count = @$ldif_aref;
$ldif_aref = read_ldif_raw($ldif_cmd);
}
return $ldif_aref;
}
sub read_ldif_raw {
my ($ldif_cmd) = @_;
my $ldif_aref = [];
my $ldif_fh;
local $INPUT_RECORD_SEPARATOR = "\n\n";
open( $ldif_fh, '-|', $ldif_cmd) or die "Can't exec '$ldif_cmd': $!";
while (my $record = <$ldif_fh>) {
push(@$ldif_aref, $record);
}
close($ldif_fh) or die "$ldif_cmd exited with $?: $!";
return $ldif_aref;
}
our %filename_list = ();
sub filename {
my ($ldif) = @_;
use Digest::MD5 qw( md5_hex );
my $filename = timestamp($ldif) . '-' . substr(md5_hex(dn($ldif)), 0, 7);
if (defined($filename_list{$filename})) {
$filename_list{$filename} += 1;
$filename .= '-' . $filename_list{$filename};
}
else {
$filename_list{$filename} = 0;
}
return $filename . '.ldif';
}
sub dn {
my ($ldif) = @_;
$ldif =~ s{\n }{}gs; # combine multiline attributes
for my $line (split("\n", $ldif)) {
next unless $line =~ m{\A dn:}xmsi;
my $dn = get_value_from_attribute($line);
return canonicalize_dn($dn);
}
return '';
}
sub canonicalize_dn {
my ($dn) = @_;
my @rdns = split(',', $dn);
@rdns = map { canonicalize_rdn($_) } @rdns;
return join(',', @rdns);
}
sub canonicalize_rdn {
my ($rdn) = @_;
my ($key, $value) = split('=', $rdn, 2);
$key =~ s{\A\s+}{}xms;
$key =~ s{\s+\Z}{}xms;
$value =~ s{\A\s+}{}xms;
$value =~ s{\s+\Z}{}xms;
return lc($key) . '=' . lc($value);
}
sub timestamp {
my ($ldif) = @_;
$ldif =~ s{\n }{}gs; # combine multiline attributes
for my $line (split("\n", $ldif)) {
next unless $line =~ m{\A createtimestamp:}xmsi;
return get_value_from_attribute($line);
}
return '00000000000000Z';
}
sub get_value_from_attribute {
my ($attribute) = @_;
my $value;
if ( $attribute =~ m{\A [^:]+ ::}xms ) {
$value = ( split(':: ', $attribute, 2) )[1];
$value = decode_base64($value);
}
else {
$value = ( split(': ', $attribute, 2) )[1];
}
return $value;
}
1;
__END__
=head1 NAME
ldap-git-backup - check in LDIF from an LDAP server into a GIT repository
=head1 SYNOPSIS
ldap-git-backup [options]
ldap-git-backup --help
=head1 DESCRIPTION
ldap-git-backup takes an LDIF dump of an LDAP server and updates a GIT repository
that serves as a versioned backup.
ldap-git-backup splits the LDIF data into separate entries. It constructs
unique but stable file names using a combination of the creation time stamp for
ordering and the DN as the unique key for an entry.
=head1 OPTIONS
=over 4
=item B<--ldif-cmd E<lt>dump_ldif_commandE<gt>>
Specify a command to create a complete LDIF dump of the LDAP directory suitable
for a backup. It should contain all entries necessary to restore the LDAP
database. By default C<@sbindir@/safe-ldif> is taken which calls
C</usr/sbin/slapcat> from OpenLDAP.
If you have access to an LDAP server over the network you can use ldapsearch as
your C<--ldif-cmd>. Example:
=over
--ldif-cmd 'ldapsearch -u -x -o ldif-wrap=no \
-H ldaps://ldap.example.org -b dc=example,dc=org'
=back
If you need to log in to a certain server first you would use something along
the lines of
=over
--ldif-cmd 'ssh host.example.org ldapsearch -u -x -o ldif-wrap=no \
-H ldaps://ldap.example.org -b dc=example,dc=org'
=back
You can make this as complicated as you like as long as it fits into a one line
command. If you need more you may want to create a script for the purpose.
=item B<--backup-dir E<lt>backup_directoryE<gt>>
Specify the directory where the GIT repository for the versioned backup is held.
Default: F</var/backups/ldap>
=item B<--commit-msg E<lt>commit_stringE<gt>>
Specify a custom commit message. Default: ldap-git-backup
Example:
=over
--commit-msg "Import $(date --rfc-3339=seconds)"
=back
=item B<--commit-date E<lt>date_stringE<gt>>
=item B<--commit-date E<lt>fileE<gt>>
Specify a custom commit date. If a file is given its modification time is used.
=item B<--no-gc>
Do not perform a garbage collection (git gc) after checking in the new backup.
By default gc is done so as to keep the size of the backup down. You may want
to skip gc for the occasional backup run but leave it on for the scheduled
backups.
=item B<--help>
Prints this page.
=back
=head1 AUTHOR
Elmar S. Heeb <elmar@heebs.ch>
=cut |
mod commands;
mod config;
mod server;
use std::cell::OnceCell;
use std::collections::VecDeque;
use std::env;
use std::net::SocketAddr;
use std::sync::{Arc, Mutex};
use std::time::Duration;
use color_eyre::Result;
use dashmap::DashMap;
use enum_map::enum_map;
use log::{error, info};
use serenity::async_trait;
use serenity::model::application::command::Command;
use serenity::model::application::interaction::{Interaction, InteractionResponseType};
use serenity::model::gateway::Ready;
use serenity::model::id::GuildId;
use serenity::model::prelude::{Activity, ActivityType};
use serenity::prelude::*;
use server::{create_server, s2c, c2s};
use tokio::sync::{self, mpsc::Receiver};
struct CommandExecutionWaiter;
impl TypeMapKey for CommandExecutionWaiter {
type Value = Arc<DashMap<u64, sync::oneshot::Sender<c2s::CommandReplyEvent>>>;
}
struct ServerConnection;
impl TypeMapKey for ServerConnection {
type Value = Arc<DashMap<SocketAddr, sync::mpsc::Sender<s2c::ClientEvent>>>;
}
struct Handler {
rx_server: Arc<Mutex<OnceCell<Receiver<c2s::ServerEvent>>>>,
}
#[async_trait]
impl EventHandler for Handler {
async fn interaction_create(&self, ctx: Context, interaction: Interaction) {
if let Interaction::ApplicationCommand(command) = interaction {
info!("Received command interaction: {:#?}", command);
let content = match command.data.name.as_str() {
// "ping" => commands::ping::run(&command.data.options),
// "id" => commands::id::run(&command.data.options),
// "attachmentinput" => commands::attachmentinput::run(&command.data.options),
_ => "not implemented :(".to_string(),
};
if let Err(why) = command
.create_interaction_response(&ctx.http, |response| {
response
.kind(InteractionResponseType::ChannelMessageWithSource)
.interaction_response_data(|message| message.content(content))
})
.await
{
error!("Cannot respond to slash command: {}", why);
}
}
}
async fn ready(&self, ctx: Context, ready: Ready) {
info!("{} is connected!", ready.user.name);
let guild_id = GuildId(
env::var("GUILD_ID")
.expect("Expected GUILD_ID in environment")
.parse()
.expect("GUILD_ID must be an integer"),
);
let commands = GuildId::set_application_commands(&guild_id, &ctx.http, |commands| {
commands
// .create_application_command(|command| commands::ping::register(command))
// .create_application_command(|command| commands::id::register(command))
// .create_application_command(|command| commands::welcome::register(command))
// .create_application_command(|command| commands::numberinput::register(command))
// .create_application_command(|command| commands::attachmentinput::register(command))
})
.await;
info!(
"I now have the following guild slash commands: {:#?}",
commands
);
let guild_command = Command::create_global_application_command(&ctx.http, |command| {
commands::execute::register(command)
})
.await;
info!(
"I created the following global slash command: {:#?}",
guild_command
);
let rx_server = self.rx_server.clone();
tokio::spawn(async move {
let mut rx = {
let mut lock = rx_server.lock().unwrap();
lock.take().unwrap()
};
let mut log_deqs = enum_map! {
_ => VecDeque::new()
};
let mut interval = tokio::time::interval(Duration::from_secs(10));
interval.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);
loop {
tokio::select! {
Some(event) = rx.recv() => {
match event {
c2s::ServerEvent::Status(status) => {
ctx.set_presence(
status.activity.map(|name| {
let mut activity = Activity::playing("~");
activity.state = Some(name);
activity.kind = ActivityType::Custom;
activity
}),
status.status,
)
.await
},
c2s::ServerEvent::Log(log) => {
log_deqs[log.r#type].push_back(log.message)
},
c2s::ServerEvent::CommandReply(_) => todo!("Haven't done command execution yet")
}
},
_ = interval.tick() => {
for (log_type, deq) in log_deqs.iter_mut() {
}
}
}
}
});
}
}
#[tokio::main]
async fn main() -> Result<()> {
color_eyre::install()?;
pretty_env_logger::init();
if let Err(_) = dotenvy::dotenv() {
error!("Couldn't find .env file, using environment variables directly.")
}
// Configure the client with your Discord bot token in the environment.
let token = env::var("DISCORD_TOKEN").expect("Expected a DISCORD_TOKEN in the environment");
let (rx_server, connected_servers) = create_server().await?;
let cell = OnceCell::new();
cell.set(rx_server).expect("Couldn't set Receiver");
let handler = Handler {
rx_server: Arc::new(Mutex::new(cell)),
};
// Build our client.
let mut client = Client::builder(token, GatewayIntents::empty())
.event_handler(handler)
.await
.expect("Error creating client");
{
let mut data = client.data.write().await;
data.insert::<ServerConnection>(connected_servers);
data.insert::<CommandExecutionWaiter>(Arc::new(DashMap::new()));
}
// Finally, start a single shard, and start listening to events.
//
// Shards will automatically attempt to reconnect, and will perform
// exponential backoff until it reconnects.
client.start().await?;
Ok(())
} |
<div class="add-container py-5">
<div class="card-body my-5 py-0">
<h1 class="text-center mt-2">Add User</h1>
<form [formGroup]="registerForm" (ngSubmit)="onSubmit()">
<div class="form-group">
<label for="userName" class="mb-1" [ngStyle]="{'font-size': '16px', 'font-weight': '400' }">Username</label>
<input type="text" id="userName" placeholder="Username" formControlName="userName" class="form-control" [ngClass]="{ 'is-invalid': submitted && f.userName.errors }" />
<div *ngIf="submitted && f.userName.errors" class="invalid-feedback">
<div *ngIf="f.userName.errors.required">Username is required</div>
<div *ngIf="f.userName.errors?.['minlength']">Username must be ateast 4 characters</div>
<div *ngIf="f.userName.errors?.['maxlength']">Username must be maximum of 20 characters</div>
</div>
</div>
<div class="form-group">
<label for="password" class="mb-1" [ngStyle]="{'font-size': '16px', 'font-weight': '400' }">Password</label>
<div class="input-group">
<input type="{{(showPassword === false)?'password':'text'}}" class="form-control" id="password" placeholder="Password" formControlName="password" [ngClass]="{ 'is-invalid': submitted && f.password.errors }">
<div class="input-group-append">
<span class="input-group-text">
<i
class="fa"
[ngClass]="{
'fa-eye-slash': !showPassword,
'fa-eye': showPassword,
'font-weight': 'bold'
}"
(click)="toggleShowPassword()"
></i>
</span>
</div>
<div *ngIf="submitted && f.password.errors" class="invalid-feedback">
<div *ngIf="f.password.errors.required">Password is required</div>
<div *ngIf="f.password.errors?.['minlength']">Password must be atleast 8 characters</div>
</div>
</div>
</div>
<div class="form-group">
<label for="email" class="mb-1" [ngStyle]="{'font-size': '16px', 'font-weight': '400' }">Email address</label>
<input type="email" class="form-control" id="email" placeholder="name@example.com" formControlName="email" [ngClass]="{ 'is-invalid': submitted && f.email.errors }">
<div *ngIf="submitted && f.email.errors" class="invalid-feedback">
<div *ngIf="f.email.errors.required">Email must be a valid email address</div>
</div>
</div>
<div class="form-group">
<label for="age" class="mb-1" [ngStyle]="{'font-size': '16px', 'font-weight': '400' }">Age</label>
<input type="number" class="form-control" id="age" placeholder="age" min="18" max="99" formControlName="age"[ngClass]="{ 'is-invalid': submitted && f.age.errors }">
<div *ngIf="submitted && f.age.errors" class="invalid-feedback">
<div *ngIf="f.age.errors.required">Age is required</div>
</div>
</div>
<div class="form-group">
<label for="gender" class="mb-1" [ngStyle]="{'font-size': '16px', 'font-weight': '400' }">Gender</label>
<select id="gender" class="form-control" formControlName="gender">
<option value=0>---select gender---</option>
<option selected value="MALE">MALE</option>
<option value="FEMALE">FEMALE</option>
</select>
</div>
<div class="form-group">
<label for="profilePicUrl" class="mb-1" [ngStyle]="{'font-size': '16px', 'font-weight': '400' }">ProfilePic Url</label>
<input type="text" class="form-control" id="profilePicUrl" placeholder="profilePicUrl" formControlName="profilePicUrl">
</div>
<div class="form-group text-center">
<button [disabled]="loading" class="btn btn-primary mr-2" type="submit">
<span *ngIf="loading" class="spinner-border spinner-border-sm mr-1"></span>
Add
</button>
<a routerLink="/users" [ngStyle]="{'color': 'black', 'text-decoration':'none' }" >Cancel</a>
</div>
</form>
</div>
</div> |
import Server from '../model/server';
import config from '@kaetram/common/config';
import type { SerializedServer } from '@kaetram/common/types/api';
type AddCallback = (id: number) => void;
type RemoveCallback = (key: string) => void;
// Raw server data received from the server itself.
export interface ServerData {
lastPing: number;
serverId: number;
host: string;
port: number;
apiPort: number;
accessToken: string;
remoteServerHost: string;
remoteApiHost: string;
maxPlayers: number; // Max players in the world.
players: string[]; // String array of usernames
}
/**
* We keep track of the servers that are connected to the hub.
* When a server goes online, it pings the hub (if hub config is enabled)
* and it will ping the hub at a set interval. We keep track of those
* pings here. If a server does not ping for a certain period of time,
* we just remove it to preserve resources.
*/
export default class Servers {
private servers: { [key: string]: Server } = {};
private addCallback?: AddCallback;
private removeCallback?: RemoveCallback;
private updateCallback?: () => void;
public constructor() {
// Create the cleaning interval.
setInterval(this.handleCleanUp.bind(this), config.cleanupTime);
}
/**
* Handles cleaning and deletion of servers that have not
* responded in a while. Also updates the total amount of players.
*/
private handleCleanUp(): void {
this.forEachServer((server, key) => {
if (!this.isServerTimedOut(server)) return;
this.removeCallback?.(key);
delete this.servers[key];
});
}
/**
* Adds a new server to our dictionary of servers. If the server already
* exists, then we just update the last pinged time instead.
* @param data Raw server data information obtained during server pinging.
*/
public add(data: ServerData): void {
if (data.serverId in this.servers) return this.servers[data.serverId].update(data);
this.servers[data.serverId] = new Server(
data.serverId,
`${config.name} ${data.serverId}`,
data.host,
data.port,
data.apiPort,
data.accessToken,
data.remoteServerHost,
data.remoteApiHost,
data.players,
data.maxPlayers
);
this.addCallback?.(data.serverId);
this.servers[data.serverId].onUpdate(() => this.updateCallback?.());
}
/**
* Grabs a server from our list based on its id.
* @param id The id of the server we are trying to grab.
* @returns A server object.
*/
public get(id: string): Server {
return this.servers[id];
}
/**
* Serialize all servers and store them in an array of Server
* objects. This is used for the hub to send to the client.
*/
public getAll(): SerializedServer[] {
return Object.values(this.servers).map((server) => {
return server.serialize();
});
}
/**
* Checks the servers to see whether or not we
* have at least one server with space in it.
* @returns Boolean if we have at least one server with space.
*/
public hasEmpty(): boolean {
return Object.values(this.servers).some((server: Server) => {
return server.players.length < server.maxPlayers - 1;
});
}
/**
* Looks through all the servers and finds one
* that has enough space.
* @param callback Server with enough space for players.
*/
public findEmpty(callback: (server: Server) => void): void {
this.forEachServer((server) => {
// -1 for a threshold of empty space.
if (server.players.length >= server.maxPlayers - 1) return;
callback(server);
});
}
/**
* Searches through all the servers and finds whether or not
* the server contains the `username` specified.
* @param username The username we are looking for.
* @returns The server containing the user.
*/
public findPlayer(username: string): Server | undefined {
for (let key in this.servers)
if (this.servers[key].players.includes(username)) return this.servers[key];
return undefined;
}
/**
* Checks if the last time we pinged a server is greater than the
* threshold for cleaning up and removing the server.
* @param server The server we are checking.
* @returns True if the difference between the last ping and the current time is greater than the threshold.
*/
private isServerTimedOut(server: Server): boolean {
return Date.now() - server.lastPing > config.cleanupThreshold;
}
/**
* Total amount of servers that are in our list.
* @returns Length of the keys of the dictionary of servers.
*/
public getServerCount(): number {
return Object.keys(this.servers).length;
}
/**
* Goes through all the servers and obtains the total amount of players.
* @returns Number indicating the total amount of players.
*/
public getTotalPlayers(): number {
let totalPlayers = 0;
for (let server of Object.values(this.servers)) totalPlayers += server.players.length;
return totalPlayers;
}
/**
* Iterates through each server in our list and creates a callback.
* @param callback Callback containing the server object and server key.
*/
public forEachServer(callback: (server: Server, key: string) => void): void {
for (let key in this.servers) callback(this.servers[key], key);
}
/**
* Callback for when we are adding a new server to our list.
* @param callback The server id and the server object we are adding.
*/
public onAdd(callback: AddCallback): void {
this.addCallback = callback;
}
/**
* Callback for when we remove a server from our list.
* @param callback The server key and object that we are removing.
*/
public onRemove(callback: RemoveCallback): void {
this.removeCallback = callback;
}
/**
* Callback for when one of the servers has updated.
*/
public onUpdate(callback: () => void): void {
this.updateCallback = callback;
}
} |
shared_examples_for 'a filterable DataFrame' do
describe '#uniq' do
let(:df) { DaruLite::DataFrame.from_csv 'spec/fixtures/duplicates.csv' }
context 'with no args' do
subject { df.uniq }
it 'returns the correct result' do
expect(subject.shape.first).to eq 30
end
end
context 'given a vector' do
subject { df.uniq('color') }
it 'returns the correct result' do
expect(subject.shape.first).to eq 2
end
end
context 'given an array of vectors' do
subject { df.uniq("color", "director_name") }
it 'returns the correct result' do
expect(subject.shape.first).to eq 29
end
end
end
describe "#filter" do
let(:df) { DaruLite::DataFrame.new({ a: [1,2,3], b: [2,3,4] }) }
context 'avis is row' do
subject { df.filter(:row) { |r| r[:a] % 2 == 0 } }
it { is_expected.to eq(df.filter_rows { |r| r[:a] % 2 == 0 }) }
end
context 'avis is vector' do
subject { df.filter(:vector) { |v| v[0] == 1 } }
it { is_expected.to eq(df.filter_vectors { |v| v[0] == 1 }) }
end
context 'avis is unknown' do
subject { df.filter(:kitten) {} }
it { expect { subject }.to raise_error ArgumentError, /axis/ }
end
end
describe '#reject_values' do
let(:df) do
DaruLite::DataFrame.new({
a: [1, 2, 3, nil, Float::NAN, nil, 1, 7],
b: [:a, :b, nil, Float::NAN, nil, 3, 5, 8],
c: ['a', Float::NAN, 3, 4, 3, 5, nil, 7]
}, index: 11..18)
end
before { df.to_category :b }
context 'remove nils only' do
subject { df.reject_values nil }
it { is_expected.to be_a DaruLite::DataFrame }
its(:'b.type') { is_expected.to eq :category }
its(:'a.to_a') { is_expected.to eq [1, 2, 7] }
its(:'b.to_a') { is_expected.to eq [:a, :b, 8] }
its(:'c.to_a') { is_expected.to eq ['a', Float::NAN, 7] }
its(:'index.to_a') { is_expected.to eq [11, 12, 18] }
end
context 'remove Float::NAN only' do
subject { df.reject_values Float::NAN }
it { is_expected.to be_a DaruLite::DataFrame }
its(:'b.type') { is_expected.to eq :category }
its(:'a.to_a') { is_expected.to eq [1, 3, nil, 1, 7] }
its(:'b.to_a') { is_expected.to eq [:a, nil, 3, 5, 8] }
its(:'c.to_a') { is_expected.to eq ['a', 3, 5, nil, 7] }
its(:'index.to_a') { is_expected.to eq [11, 13, 16, 17, 18] }
end
context 'remove both nil and Float::NAN' do
subject { df.reject_values nil, Float::NAN }
it { is_expected.to be_a DaruLite::DataFrame }
its(:'b.type') { is_expected.to eq :category }
its(:'a.to_a') { is_expected.to eq [1, 7] }
its(:'b.to_a') { is_expected.to eq [:a, 8] }
its(:'c.to_a') { is_expected.to eq ['a', 7] }
its(:'index.to_a') { is_expected.to eq [11, 18] }
end
context 'any other values' do
subject { df.reject_values 1, 5 }
it { is_expected.to be_a DaruLite::DataFrame }
its(:'b.type') { is_expected.to eq :category }
its(:'a.to_a') { is_expected.to eq [2, 3, nil, Float::NAN, 7] }
its(:'b.to_a') { is_expected.to eq [:b, nil, Float::NAN, nil, 8] }
its(:'c.to_a') { is_expected.to eq [Float::NAN, 3, 4, 3, 7] }
its(:'index.to_a') { is_expected.to eq [12, 13, 14, 15, 18] }
end
context 'when resultant dataframe has one row' do
subject { df.reject_values 1, 2, 3, 4, 5, nil, Float::NAN }
it { is_expected.to be_a DaruLite::DataFrame }
its(:'b.type') { is_expected.to eq :category }
its(:'a.to_a') { is_expected.to eq [7] }
its(:'b.to_a') { is_expected.to eq [8] }
its(:'c.to_a') { is_expected.to eq [7] }
its(:'index.to_a') { is_expected.to eq [18] }
end
context 'when resultant dataframe is empty' do
subject { df.reject_values 1, 2, 3, 4, 5, 6, 7, nil, Float::NAN }
it { is_expected.to be_a DaruLite::DataFrame }
its(:'b.type') { is_expected.to eq :category }
its(:'a.to_a') { is_expected.to eq [] }
its(:'b.to_a') { is_expected.to eq [] }
its(:'c.to_a') { is_expected.to eq [] }
its(:'index.to_a') { is_expected.to eq [] }
end
end
describe "#keep_row_if" do
pending "changing row from under the iterator trips this"
it "keeps row if block evaluates to true" do
df = DaruLite::DataFrame.new({b: [10,12,20,23,30], a: [50,30,30,1,5],
c: [10,20,30,40,50]}, order: [:a, :b, :c],
index: [:one, :two, :three, :four, :five])
df.keep_row_if do |row|
row[:a] % 10 == 0
end
# TODO: write expectation
end
end
describe "#keep_vector_if" do
it "keeps vector if block evaluates to true" do
df.keep_vector_if do |vector|
vector == [1,2,3,4,5].dv(nil, [:one, :two, :three, :four, :five])
end
expect(df).to eq(DaruLite::DataFrame.new({a: [1,2,3,4,5]}, order: [:a],
index: [:one, :two, :three, :four, :five]))
end
end
describe "#filter_vectors" do
context DaruLite::Index do
subject { df.filter_vectors { |vector| vector[0] == 1 } }
let(:df) { DaruLite::DataFrame.new({ a: [1,2,3], b: [2,3,4] }) }
it "filters vectors" do
expect(subject).to eq(DaruLite::DataFrame.new({a: [1,2,3]}))
end
end
end
describe "#filter_rows" do
context DaruLite::Index do
subject { df.filter_rows { |r| r[:a] != 2 } }
let(:df) { DaruLite::DataFrame.new a: 1..3, b: 4..6 }
it "preserves names of vectors" do
expect(subject[:a].name).to eq(df[:a].name)
end
context "when specified no index" do
subject { df.filter_rows { |row| row[:a] % 2 == 0 } }
let(:df) { DaruLite::DataFrame.new({ a: [1,2,3], b: [2,3,4] }) }
it "filters rows" do
expect(subject).to eq(DaruLite::DataFrame.new({ a: [2], b: [3] }, order: [:a, :b], index: [1]))
end
end
context "when specified numerical index" do
subject { df.filter_rows { |row| row[:a] % 2 == 0 } }
let(:df) { DaruLite::DataFrame.new({ a: [1,2,3], b: [2,3,4] }, index: [1,2,3]) }
it "filters rows" do
expect(subject).to eq(DaruLite::DataFrame.new({ a: [2], b: [3] }, order: [:a, :b], index: [2]))
end
end
end
end
context "#filter_vector" do
subject { df.filter_vector(:id) { |c| c[:id] == 2 or c[:id] == 4 } }
let(:df) do
DaruLite::DataFrame.new(
{
id: DaruLite::Vector.new([1, 2, 3, 4, 5]),
name: DaruLite::Vector.new(%w(Alex Claude Peter Franz George)),
age: DaruLite::Vector.new([20, 23, 25, 27, 5]),
city: DaruLite::Vector.new(['New York', 'London', 'London', 'Paris', 'Tome']),
a1: DaruLite::Vector.new(['a,b', 'b,c', 'a', nil, 'a,b,c'])
},
order: [:id, :name, :age, :city, :a1]
)
end
it "creates new vector with the data of a given field for which block returns true" do
expect(subject).to eq(DaruLite::Vector.new([2,4]))
end
end
end |
########################################################################
## Script to generate assortativity distribution plots.
## Chromosomal assortativity per tissue and condition, expression
## assortativity in cancer and enriched vs not enriched communities
## in cancer with chromosomal and expression assortativity.
######################################################################
library(readr)
library(dplyr)
library(ggplot2)
library(ggthemes)
library(ggpubr)
library(tidyr)
tissues <- c("bladder", "brain", "breast", "colorectal", "esophagus",
"kidney", "liver", "lung", "ovary", "pancreas", "prostate",
"skin", "testis", "thyroid","uterus")
names(tissues) <- tissues
substr(names(tissues),1, 1) <- toupper(substr(names(tissues),1, 1))
color_pal <- c("#e3a098", "#a32e27")
labels <- c( "Normal", "Cancer")
names(color_pal) <- labels
getSummaries <- function(cond, tss) {
all_summaries <- lapply(tss, function(ts) {
read_tsv(paste0(ts, "/network_aracne/assortativity/", cond, "-comm-summary-100000.tsv")) %>%
mutate(tissue = ts, id = paste(tissue, community_id, sep="_")) %>%
select(id, tissue, community_id, everything())
})
return(bind_rows(all_summaries))
}
normal <- getSummaries("normal", tissues)
normal$cond <- "normal"
cancer <- getSummaries("cancer", tissues)
cancer$cond <- "cancer"
all <- bind_rows(normal, cancer)
all$cond <- factor(all$cond, levels = c("normal", "cancer"), labels = labels)
capitalize <- function(string) {
substr(string, 1, 1) <- toupper(substr(string, 1, 1))
string
}
p <- ggplot(all , aes(x = tissue, y = chr_assortativity, fill = cond,
color = cond)) +
geom_violin() +
scale_fill_manual(values = color_pal) +
scale_color_manual(values = color_pal) +
theme_base(base_size = 20) +
ylab("Chromosomal\nAssortativity") +
xlab("") +
theme(legend.position = "none", axis.text.x = element_blank(),
plot.background = element_blank(),
strip.text.x = element_text(size = 22),
strip.text.y = element_text(size = 20)) +
facet_grid(cond~tissue, scale= "free_x", labeller = labeller(tissue = capitalize))
png(paste0("pan-loss/network_aracne_plots/assortativity/chr_assortativity.png"),
width = 2000, height = 350)
print(p)
dev.off()
### Only Cancer and compare enriched vs not enriched communities
cancer$cond <- "Cancer"
p <- ggplot(cancer , aes(x = tissue, y = expr_assortativity, fill = cond,
color = cond)) +
geom_violin() +
scale_fill_manual(values = color_pal) +
scale_color_manual(values = color_pal) +
theme_base(base_size = 20) +
ylab("Expression\nAssortativity") +
xlab("") +
theme(legend.position = "none", axis.text.x = element_blank(),
plot.background = element_blank(),
strip.text.x = element_text(size = 22),
strip.text.y = element_text(size = 20), ) +
facet_grid(cond~tissue, scale= "free_x", labeller = labeller(tissue = capitalize))
png(paste0("pan-loss/network_aracne_plots/assortativity/expr_assortativity.png"),
width = 2000, height = 200)
print(p)
dev.off()
cancer_enriched <- cancer %>%
filter(size >= 5) %>%
mutate(isEnriched = if_else(enriched_terms > 0, "go", "no_go" ),
isEnriched = factor(isEnriched, levels = c("no_go", "go"), labels = c("No GO", "GO"),
ordered = TRUE))
symnum.args <- list(cutpoints = c(0, 0.0001, 0.001, 0.01, 0.05, 1), symbols = c("****", "***", "**", "*", ""))
color_pal_enriched <- c("#878787", "#699B61")
p <- ggplot(cancer_enriched, aes(x=isEnriched, y=expr_assortativity, color=isEnriched)) +
geom_boxplot(size=1) +
ylab("Expression Assortativity") +
scale_color_manual(name = "", values = color_pal_enriched,
labels = c("No biologically associated", "Gene Ontology enriched")) +
theme_base(base_size = 30) +
xlab("") +
stat_compare_means(aes(label = ..p.signif..), label.x = 1.5, label.y = 1.1, symnum.args = symnum.args,
show.legend = F, size = 5)+
stat_summary(fun.data = ~c(y = -0.8, label = length(.)), geom = "text", color = "black", size = 5) +
ylim(c(-1, 1.20)) +
theme(axis.text.x = element_blank(), axis.ticks.x=element_blank(),
legend.position="bottom", plot.margin = unit(c(0.5, 1, 0.5, 0.5), "cm")) +
facet_wrap(~tissue, scale= "free_x", labeller = labeller(tissue = capitalize), nrow = 3)
png(paste0("pan-loss/network_aracne_plots/assortativity/cancer_expr_assort_enrichement.png"),
width = 820, height = 720)
print(p)
dev.off()
p <- ggplot(cancer_enriched, aes(x=isEnriched, y=chr_assortativity, color=isEnriched)) +
geom_boxplot(size=1) +
ylab("Chromosomal Assortativity") +
scale_color_manual(name = "", values = color_pal_enriched,
labels = c("No biologically associated", "Gene Ontology enriched")) +
theme_base(base_size = 30) +
xlab("") +
theme(axis.text.x = element_blank(), axis.ticks.x=element_blank(),
legend.position="bottom", plot.margin = unit(c(0.5, 1, 0.5, 0.5), "cm")) +
stat_compare_means(aes(label = ..p.signif..), label.x = 1.5, label.y = 1.1, symnum.args = symnum.args,
show.legend = F, size = 5) +
stat_summary(fun.data = ~c(y = -1.18, label = length(.)), geom = "text", color = "black", size = 5) +
ylim(c(-1.25, 1.20)) +
facet_wrap(~tissue, scale= "free_x", labeller = labeller(tissue = capitalize), nrow = 3)
png(paste0("pan-loss/network_aracne_plots/assortativity/cancer_chr_assort_enrichement.png"),
width = 820, height = 720)
print(p)
dev.off()
normal_enriched <- normal %>%
filter(size >= 5) %>%
mutate(isEnriched = if_else(enriched_terms > 0, "go", "no_go" ),
isEnriched = factor(isEnriched, levels = c("no_go", "go"), labels = c("No GO", "GO"),
ordered = TRUE))
p <- ggplot(normal_enriched, aes(x=isEnriched, y=chr_assortativity, color=isEnriched)) +
geom_boxplot(size=1) +
ylab("Chromosomal Assortativity") +
scale_color_manual(name = "", values = color_pal_enriched,
labels = c("No biologically associated", "Gene Ontology enriched")) +
theme_base(base_size = 30) +
xlab("") +
theme(axis.text.x = element_blank(), axis.ticks.x=element_blank(),
legend.position="bottom", plot.margin = unit(c(0.5, 1, 0.5, 0.5), "cm")) +
stat_compare_means(aes(label = ..p.signif..), label.x = 1.5, label.y = 1.1, symnum.args = symnum.args,
show.legend = F, size = 5) +
stat_summary(fun.data = ~c(y = -1.15, label = length(.)), geom = "text", color = "black", size = 5) +
ylim(c(-1.25, 1)) +
facet_wrap(~tissue, scale= "free_x", labeller = labeller(tissue = capitalize), nrow = 3)
png(paste0("pan-loss/network_aracne_plots/assortativity/normal_chr_assort_enrichement.png"),
width = 820, height = 720)
print(p)
dev.off() |
// Caffeine Script (7Kyu)
/*
Complete the function caffeineBuzz, which takes a non-zero integer as its argument.
If the integer is divisible by 3, return the string "Java".
If the integer is divisible by 3 and divisible by 4, return the string "Coffee"
If one of the condition above is true and the integer is even, add "Script" to the end of the string.
If none of the condition is true, return the string "mocha_missing!"
caffeineBuzz(1) => "mocha_missing!"
caffeineBuzz(3) => "Java"
caffeineBuzz(6) => "JavaScript"
caffeineBuzz(12) => "CoffeeScript"
*/
function caffeineBuzz(n){
let val = '';
if(n % 3 === 0 && n % 4 === 0){
val += 'Coffee';
}else if(n % 3 === 0){
val += 'Java';
}
if(n % 3 !== 0){
return 'mocha_missing!';
}else if(n % 2 === 0){
return val + 'Script';
}
return val;
}
/* Best practice
function caffeineBuzz(n){
if (n % 12 === 0) return "CoffeeScript";
if (n % 6 === 0) return "JavaScript";
if (n % 3 === 0) return "Java";
return "mocha_missing!";
}
*/ |
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class StorecompanyRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*/
public function authorize(): bool
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array<string, \Illuminate\Contracts\Validation\ValidationRule|array<mixed>|string>
*/
public function rules(): array
{
return [
'company_name' => ['required', 'string', 'max:255'],
'company_website' => ['required', 'string', 'max:255'],
'company_email' => ['required', 'string', 'email', 'max:255','unique:companies,company_email'],
'company_address' => ['required', 'string', 'max:255'],
'telephone1' => ['required', 'numeric'],
'company_currencysymbol' => ['required', 'exists:currencies,id'],
'country' => ['required', 'exists:countries,id'],
'state' =>['required', 'exists:states,id'],
'city' => ['required', 'exists:cities,id'],
'timezone' => ['required', 'exists:timezones,id'],
'zip' => ['required', 'string', 'max:255'],
// 'currently_allowed_employee' => ['required', 'numeric'],
];
}
} |
import 'package:flutter/material.dart';
import 'package:flutter_gen/gen_l10n/app_localizations.dart';
import 'package:islami/core/provider/app_provider.dart';
import 'package:islami/moduls/settings/widget/selected_option.dart';
import 'package:islami/moduls/settings/widget/unselected_option.dart';
import 'package:provider/provider.dart';
class ThemeMoodBottom extends StatelessWidget {
const ThemeMoodBottom({super.key});
@override
Widget build(BuildContext context) {
var theme = Theme.of(context);
var appProvider = Provider.of<AppProvider>(context);
var local = AppLocalizations.of(context)!;
return Container(
padding: EdgeInsets.symmetric(horizontal: 25, vertical: 60),
decoration: BoxDecoration(
color: theme.primaryColor.withOpacity(0.8),
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
GestureDetector(
onTap: () {
appProvider.changeTheme(ThemeMode.dark);
Navigator.pop(context);
},
child: appProvider.isDark()
? SelectedOption(selectedTitle: local.dark)
: UnSelectedOption(unSelectedTitle: local.dark),
),
SizedBox(height: 30),
GestureDetector(
onTap: () {
appProvider.changeTheme(ThemeMode.light);
Navigator.pop(context);
},
child: appProvider.isDark()
? UnSelectedOption(unSelectedTitle: local.light)
: SelectedOption(selectedTitle: local.light)),
],
),
);
}
} |
/* -*- c++ -*- */
/*
* Copyright 2008-2014 Free Software Foundation, Inc.
*
* This file is part of GNU Radio
*
* SPDX-License-Identifier: GPL-3.0-or-later
*
*/
#ifndef SPECTRUM_UPDATE_EVENTS_H
#define SPECTRUM_UPDATE_EVENTS_H
#include <gnuradio/high_res_timer.h>
#include <gnuradio/qtgui/api.h>
#include <gnuradio/tags.h>
#include <volk/volk_alloc.hh>
#include <QEvent>
#include <QString>
#include <complex>
#include <cstdint>
#include <vector>
static constexpr int SpectrumUpdateEventType = 10005;
static constexpr int SpectrumWindowCaptionEventType = 10008;
static constexpr int SpectrumWindowResetEventType = 10009;
static constexpr int SpectrumFrequencyRangeEventType = 10010;
class SpectrumUpdateEvent : public QEvent
{
public:
SpectrumUpdateEvent(const float* fftPoints,
const uint64_t numFFTDataPoints,
const double* realTimeDomainPoints,
const double* imagTimeDomainPoints,
const uint64_t numTimeDomainDataPoints,
const gr::high_res_timer_type dataTimestamp,
const bool repeatDataFlag,
const bool lastOfMultipleUpdateFlag,
const gr::high_res_timer_type generatedTimestamp,
const int droppedFFTFrames);
~SpectrumUpdateEvent() override;
const float* getFFTPoints() const;
const double* getRealTimeDomainPoints() const;
const double* getImagTimeDomainPoints() const;
uint64_t getNumFFTDataPoints() const;
uint64_t getNumTimeDomainDataPoints() const;
gr::high_res_timer_type getDataTimestamp() const;
bool getRepeatDataFlag() const;
bool getLastOfMultipleUpdateFlag() const;
gr::high_res_timer_type getEventGeneratedTimestamp() const;
int getDroppedFFTFrames() const;
protected:
private:
std::vector<float> d_fft_points;
std::vector<double> d_real_data_time_domain_points;
std::vector<double> d_imag_data_time_domain_points;
gr::high_res_timer_type _dataTimestamp;
bool _repeatDataFlag;
bool _lastOfMultipleUpdateFlag;
gr::high_res_timer_type _eventGeneratedTimestamp;
int _droppedFFTFrames;
};
class SpectrumWindowCaptionEvent : public QEvent
{
public:
SpectrumWindowCaptionEvent(const QString&);
~SpectrumWindowCaptionEvent() override;
QString getLabel();
protected:
private:
QString _labelString;
};
class SpectrumWindowResetEvent : public QEvent
{
public:
SpectrumWindowResetEvent();
~SpectrumWindowResetEvent() override;
protected:
private:
};
class SpectrumFrequencyRangeEvent : public QEvent
{
public:
SpectrumFrequencyRangeEvent(const double, const double, const double);
~SpectrumFrequencyRangeEvent() override;
double GetCenterFrequency() const;
double GetStartFrequency() const;
double GetStopFrequency() const;
protected:
private:
double _centerFrequency;
double _startFrequency;
double _stopFrequency;
};
class TimeUpdateEvent : public QEvent
{
public:
TimeUpdateEvent(const std::vector<volk::vector<double>> timeDomainPoints,
const uint64_t numTimeDomainDataPoints,
const std::vector<std::vector<gr::tag_t>> tags);
~TimeUpdateEvent() override;
int which() const;
const std::vector<double*> getTimeDomainPoints() const;
uint64_t getNumTimeDomainDataPoints() const;
bool getRepeatDataFlag() const;
const std::vector<std::vector<gr::tag_t>> getTags() const;
static QEvent::Type Type() { return QEvent::Type(SpectrumUpdateEventType); }
protected:
private:
size_t _nplots;
std::vector<double*> _dataTimeDomainPoints;
uint64_t _numTimeDomainDataPoints;
std::vector<std::vector<gr::tag_t>> _tags;
};
/********************************************************************/
class FreqUpdateEvent : public QEvent
{
public:
FreqUpdateEvent(const std::vector<volk::vector<double>> dataPoints,
const uint64_t numDataPoints);
~FreqUpdateEvent() override;
int which() const;
const std::vector<double*> getPoints() const;
uint64_t getNumDataPoints() const;
bool getRepeatDataFlag() const;
static QEvent::Type Type() { return QEvent::Type(SpectrumUpdateEventType); }
protected:
private:
size_t _nplots;
std::vector<double*> _dataPoints;
uint64_t _numDataPoints;
};
class SetFreqEvent : public QEvent
{
public:
SetFreqEvent(const double, const double);
~SetFreqEvent() override;
double getCenterFrequency() const;
double getBandwidth() const;
private:
double _centerFrequency;
double _bandwidth;
};
/********************************************************************/
class QTGUI_API ConstUpdateEvent : public QEvent
{
public:
ConstUpdateEvent(const std::vector<volk::vector<double>> realDataPoints,
const std::vector<volk::vector<double>> imagDataPoints,
const uint64_t numDataPoints);
~ConstUpdateEvent() override;
int which() const;
const std::vector<double*> getRealPoints() const;
const std::vector<double*> getImagPoints() const;
uint64_t getNumDataPoints() const;
bool getRepeatDataFlag() const;
static QEvent::Type Type() { return QEvent::Type(SpectrumUpdateEventType); }
protected:
private:
size_t _nplots;
std::vector<double*> _realDataPoints;
std::vector<double*> _imagDataPoints;
uint64_t _numDataPoints;
};
/********************************************************************/
class WaterfallUpdateEvent : public QEvent
{
public:
WaterfallUpdateEvent(const std::vector<volk::vector<double>> dataPoints,
const uint64_t numDataPoints,
const gr::high_res_timer_type dataTimestamp);
~WaterfallUpdateEvent() override;
int which() const;
const std::vector<double*> getPoints() const;
uint64_t getNumDataPoints() const;
bool getRepeatDataFlag() const;
gr::high_res_timer_type getDataTimestamp() const;
static QEvent::Type Type() { return QEvent::Type(SpectrumUpdateEventType); }
protected:
private:
size_t _nplots;
std::vector<double*> _dataPoints;
uint64_t _numDataPoints;
gr::high_res_timer_type _dataTimestamp;
};
/********************************************************************/
class TimeRasterUpdateEvent : public QEvent
{
public:
TimeRasterUpdateEvent(const std::vector<volk::vector<double>> dataPoints,
const uint64_t numDataPoints);
~TimeRasterUpdateEvent() override;
int which() const;
const std::vector<double*> getPoints() const;
uint64_t getNumDataPoints() const;
bool getRepeatDataFlag() const;
static QEvent::Type Type() { return QEvent::Type(SpectrumUpdateEventType); }
protected:
private:
size_t _nplots;
std::vector<double*> _dataPoints;
uint64_t _numDataPoints;
};
class TimeRasterSetSize : public QEvent
{
public:
TimeRasterSetSize(const double nrows, const double ncols);
~TimeRasterSetSize() override;
double nRows() const;
double nCols() const;
static QEvent::Type Type() { return QEvent::Type(SpectrumUpdateEventType + 1); }
private:
double _nrows;
double _ncols;
};
/********************************************************************/
class HistogramUpdateEvent : public QEvent
{
public:
HistogramUpdateEvent(const std::vector<volk::vector<double>> points,
const uint64_t npoints);
~HistogramUpdateEvent() override;
int which() const;
const std::vector<double*> getDataPoints() const;
uint64_t getNumDataPoints() const;
bool getRepeatDataFlag() const;
static QEvent::Type Type() { return QEvent::Type(SpectrumUpdateEventType); }
protected:
private:
size_t _nplots;
std::vector<double*> _points;
uint64_t _npoints;
};
class HistogramSetAccumulator : public QEvent
{
public:
HistogramSetAccumulator(const bool en);
~HistogramSetAccumulator() override;
bool getAccumulator() const;
static QEvent::Type Type() { return QEvent::Type(SpectrumUpdateEventType + 1); }
private:
bool _en;
};
class HistogramClearEvent : public QEvent
{
public:
HistogramClearEvent() : QEvent(QEvent::Type(SpectrumUpdateEventType + 2)) {}
~HistogramClearEvent() override {}
static QEvent::Type Type() { return QEvent::Type(SpectrumUpdateEventType + 2); }
};
/********************************************************************/
class NumberUpdateEvent : public QEvent
{
public:
NumberUpdateEvent(const std::vector<float> samples);
~NumberUpdateEvent() override;
int which() const;
const std::vector<float> getSamples() const;
static QEvent::Type Type() { return QEvent::Type(SpectrumUpdateEventType); }
protected:
private:
size_t _nplots;
std::vector<float> _samples;
};
#endif /* SPECTRUM_UPDATE_EVENTS_H */ |
"use client";
import { motion } from "framer-motion";
const SectionTransition = () => {
return (
<>
<motion.div
initial={{ opacity: 0, x: -100 }} // Mulai dengan opacity 0 dan diposisikan di luar layar sebelah kiri
animate={{
opacity: 1,
x: [null, -20, 20, -10, 10, 0],
transition: { duration: 1.5 },
}} // Animate opacity ke 1 dan geser ke kiri dan kanan dengan efek bouncing
>
<section>
<h1>Section 1</h1>
<p>This is the first section.</p>
</section>
</motion.div>
<motion.div
initial={{ opacity: 0, x: 100 }} // Mulai dengan opacity 0 dan diposisikan di luar layar sebelah kiri
animate={{
opacity: 1,
x: [null, 20, -20, 10, -10, 0],
transition: { duration: 1.5, delay: 1 },
}} // Animate opacity ke 1 dan geser ke kiri dan kanan dengan efek bouncing
>
<section>
<h1>Section 2</h1>
<p>This is the second section.</p>
</section>
</motion.div>
</>
);
};
export default SectionTransition; |
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { RouterModule } from '@angular/router';
import { CapaComponent } from './capa/capa.component';
import { PrincipalComponent } from './capa/principal/principal.component';
import { FormsModule } from '@angular/forms';
import { GestionComponent } from './capa/principal/gestion/gestion.component';
import { ResultadosComponent } from './capa/principal/gestion/resultados/resultados.component';
import { ActualizarComponent } from './capa/principal/gestion/actualizar/actualizar.component';
import { CuboService } from './servicios/cubo-servicio/cubo.service'
//Nucleo representa al modulo que va a contener los componentes que van a orquestar la aplicacion
//Debe ser importado en el componente principal AppModule
@NgModule({
declarations: [CapaComponent, PrincipalComponent, GestionComponent, ResultadosComponent, ActualizarComponent],
imports: [
CommonModule, RouterModule, FormsModule
],
exports: [
CapaComponent
],
providers: [
CuboService
]
})
export class NucleoModule { } |
import React, { useState } from "react";
import { useSelector, useDispatch } from "react-redux";
import {
increment,
decrement,
incrementByAmount,
} from "../features/counterSlice";
export default function Counter() {
const count = useSelector(state => state.counter.value);
const dispatch = useDispatch();
const [customValue, setCustomValue] = useState(0);
const onCustomSubmit = (e) => {
e.preventDefault();
e.target.reset();
dispatch(incrementByAmount(Number(customValue)));
setCustomValue(0);
};
return (
<div>
<h1>{count}</h1>
<div>
<button onClick={(e) => dispatch(increment())}>Increment</button>
<button onClick={(e) => dispatch(decrement())}>Decrement</button>
</div>
<div>
<h3>Custom value</h3>
<form onSubmit={onCustomSubmit}>
<input type="number" onChange={e => setCustomValue(e.target.value)}/>
<button>Custom Increment</button>
</form>
</div>
</div>
);
} |
import { GuildQueue, Track, useQueue } from 'discord-player';
import { EmbedBuilder, MessageComponentInteraction } from 'discord.js';
import { BaseComponentInteraction } from '../../classes/interactions';
import { BaseComponentParams, BaseComponentReturnType } from '../../types/interactionTypes';
import { checkQueueCurrentTrack, checkQueueExists } from '../../utils/validation/queueValidator';
import { checkInVoiceChannel, checkSameVoiceChannel } from '../../utils/validation/voiceChannelValidator';
class NowplayingSkipButton extends BaseComponentInteraction {
constructor() {
super('nowplaying-skip-button');
}
async execute(params: BaseComponentParams): BaseComponentReturnType {
const { executionId, interaction, referenceId } = params;
const logger = this.getLogger(this.name, executionId, interaction);
const queue: GuildQueue = useQueue(interaction.guild!.id)!;
await this.runValidators({ interaction, queue, executionId }, [
checkInVoiceChannel,
checkSameVoiceChannel,
checkQueueExists,
checkQueueCurrentTrack
]);
if (!queue || (queue.tracks.data.length === 0 && !queue.currentTrack)) {
return await this.handleNoQueue(interaction);
}
if (queue.currentTrack!.id !== referenceId) {
return await this.handleAlreadySkipped(interaction);
}
const skippedTrack: Track = queue.currentTrack!;
queue.node.skip();
logger.debug('Skipped the track.');
logger.debug('Responding with success embed.');
return await this.handleSuccess(interaction, skippedTrack, queue);
}
private async handleNoQueue(interaction: MessageComponentInteraction) {
return await interaction.editReply({
embeds: [
new EmbedBuilder()
.setDescription(
`**${this.embedOptions.icons.warning} Oops!**\nThere is nothing currently playing. First add some tracks with **\`/play\`**!`
)
.setColor(this.embedOptions.colors.warning)
],
components: []
});
}
private async handleAlreadySkipped(interaction: MessageComponentInteraction) {
return await interaction.editReply({
embeds: [
new EmbedBuilder()
.setDescription(
`**${this.embedOptions.icons.warning} Oops!**\nThis track has already been skipped or is no longer playing.`
)
.setColor(this.embedOptions.colors.warning)
],
components: []
});
}
private async handleSuccess(interaction: MessageComponentInteraction, skippedTrack: Track, queue: GuildQueue) {
const successEmbed = new EmbedBuilder()
.setAuthor(this.getEmbedUserAuthor(interaction))
.setDescription(
`**${this.embedOptions.icons.skipped} Skipped track**\n` +
`${this.getDisplayTrackDurationAndUrl(skippedTrack)}\n\n` +
`${this.getDisplayRepeatMode(queue.repeatMode, 'success')}`
)
.setThumbnail(skippedTrack.thumbnail)
.setColor(this.embedOptions.colors.success);
return await interaction.editReply({
embeds: [successEmbed],
components: []
});
}
}
export default new NowplayingSkipButton(); |
<!DOCTYPE html>
<html lang="pt-br">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Desafio - Aula 06</title>
<link rel="stylesheet" href="estilo.css">
</head>
<body>
<h1 class="alinhamento">h1 - Título de Nível 01</h1>
<h2 class="alinhamento">h2 - Título de Nível 02</h2>
<h3 class="alinhamento">h3 - Título de Nível 03</h3>
<h4 class="alinhamento">h4 - Título de Nível 04</h4>
<h5 class="alinhamento">h5 - Título de Nível 05</h5>
<h6 class="alinhamento">h6 - Título de Nível 06</h6>
<h2 class="alinhamento subtitulos fontes">Margin - 80px</h2>
<p class="caixa fontes margem">Lorem ipsum dolor sit amet consectetur adipisicing elit. Et possimus mollitia incidunt debitis, minima nam harum eius, voluptatibus inventore voluptatem unde excepturi pariatur itaque. Alias, libero distinctio. Temporibus, soluta error!
Veritatis error aut earum perferendis quidem laudantium velit libero sunt. Accusamus harum deleniti quos quibusdam libero dolorem labore ducimus officiis, voluptas, inventore impedit rem, odit tenetur mollitia optio voluptatem quaerat.</p>
<h2 class="alinhamento subtitulos fontes">Padding - 80px</h2>
<p class="caixa fontes padd">Lorem ipsum dolor sit amet consectetur adipisicing elit. Ad quisquam, eaque laboriosam autem ab voluptatem commodi quam unde beatae pariatur officiis? Asperiores ducimus cupiditate vero voluptatibus voluptate minus sapiente iusto?
Placeat consectetur necessitatibus commodi a eius assumenda, voluptatibus ratione blanditiis dolore totam quidem cupiditate dicta provident quae quis unde aliquam, dolor, fugit at fuga magni. Ut quisquam mollitia reprehenderit culpa?</p>
<h2 class="alinhamento subtitulos fontes">Border - 20px</h2>
<p class="caixa fontes borda">Lorem ipsum dolor sit amet consectetur adipisicing elit. Impedit vero dolor at pariatur nam architecto reiciendis quis? Libero deserunt molestiae consectetur veritatis culpa nam, id mollitia, dignissimos consequuntur voluptas nobis.
Id iusto recusandae sit! Consequatur libero accusamus culpa autem, est omnis nisi veritatis eum repellat, nam, molestiae possimus dolorum recusandae molestias rerum ab voluptatibus illum. Doloribus molestiae molestias neque sapiente!</p>
<hr>
<h3 class="alinhamento">a - Link</h3>
<p class="alinhamento"><a href="https://jabrasil.org.br/elasnatech23/">Acesse a página aqui.</a></p>
<hr>
<h3>Lista Não Ordenada</h3>
<ul>
<li>Item 01</li>
<li>Item 02</li>
<li>Item 03</li>
</ul>
<h3>Lista Ordenada</h3>
<ol>
<li>Item 01</li>
<li>Item 02</li>
<li>Item 03</li>
</ol>
</body>
</html> |
// 频道信息
export type Channel = {
// 频道名,如"1+1 Hello"
name: string
// logo 地址,可能为空
logo: string | undefined
// 直播源地址,如"https://example.com/playlist.m3u8"
url: string
// 分类,如"Movies"、"Music"
category: string | undefined
// 频道语言,[ { "code": "eng", "name": "English" } ]
languages: Array<{ code: string, name: string }>
// 地区:[ { "code": "cn", "name": "China" } ]
countries: Array<{ code: string, name: string }>
} |
function refreshWeather(response) {
let temperatureElement = document.querySelector("#temperature");
let temperature = response.data.temperature.current;
let cityElement = document.querySelector("#city");
let descriptionElement = document.querySelector("#description");
let humidityElement = document.querySelector("#humidity");
let speedElement = document.querySelector("#speed");
let timeElement = document.querySelector("#time");
let date = new Date(response.data.time * 1000);
let iconElement = document.querySelector("#icon");
iconElement.innerHTML = `<img src="${response.data.condition.icon_url}"
class="weather-app-icon"/>`;
cityElement.innerHTML = response.data.city;
timeElement.innerHTML = formatDate(date);
descriptionElement.innerHTML = response.data.condition.description;
humidityElement.innerHTML = `${response.data.temperature.humidity}%`;
speedElement.innerHTML = `${response.data.wind.speed}km/h`;
temperatureElement.innerHTML = Math.round(temperature);
getForecast(response.data.city);
}
function formatDate(date) {
let hours = date.getHours();
let minutes = date.getMinutes();
let days = [
"Sunday",
"Monday",
"Tuesday",
"Wednesday",
"Thursday",
"Friday",
"Saturday",
];
let day = days[date.getDay()];
if (minutes < 10) {
minutes = `0${minutes}`;
}
return `${day} ${hours}:${minutes},`;
}
function searchCity(city) {
let apiKey = "f875398bf20cafeft6b46o1403180fac";
let apiUrl = `https://api.shecodes.io/weather/v1/current?query=${city}&key=${apiKey}&units=metric`;
axios.get(apiUrl).then(refreshWeather);
}
function handleSearchSubmit(event) {
event.preventDefault();
let searchInput = document.querySelector("#search-form-input");
searchCity(searchInput.value);
}
function formatDay(timestamp) {
let date = new Date(timestamp * 1000);
let days = [`Sun`, `Mon`, `Tue`, `Wed`, `Thu`, `Fri`, `Sat`];
return days[date.getDay()];
}
function getForecast(city) {
let apiKey = "f875398bf20cafeft6b46o1403180fac";
let apiUrl = `https://api.shecodes.io/weather/v1/current?query={query}&key={key}=${apiKey}&units=metric`;
axios(apiUrl).then(displayForecast);
}
function displayForecast(response) {
let forecastHtml = "";
response.data.daily.forEach(function (day, index) {
if (index < 5) {
forecastHtml =
forecastHtml +
`
<div class="weather-forecast-day">
<div class="weather-forecast-date">${formatDay(day.time)}</div>
<div>
<img src= "${
day.condition.icon_url
}" class="weather-forecast-icon"/>
</div>
<div class="weather-forecast-temperature">
<span class="weather-forecast-temperature-max">${Math.round(
day.temperature.maximum
)}° </span>
<span class="weather-forecast-temperature-min">${Math.round(
day.temperature.minimum
)}°</span>
</div>
</div>
`;
}
});
let forecastElement = document.querySelector("#forecast");
forecastElement.innerHTML = forecastHtml;
}
let searchFormElement = document.querySelector("#search-form");
searchFormElement.addEventListener("submit", handleSearchSubmit);
searchCity("Pretoria"); |
import { UserModel } from './UserModel'
describe('UserModel', () => {
it('should not be able create a new ID and new encrypted password', () => {
const hash_id = 'HASH_ID'
const hash_password = 'HASH_PASS'
const user = new UserModel(
{
name: 'Maycon Silva',
email: 'a@g.com',
password: hash_password,
},
hash_id
)
expect(user._id).toBe(hash_id)
expect(user.password).toBe(hash_password)
})
it('should not be able create user with wrong email', () => {
let errorMessage = ''
try {
new UserModel({
name: 'Maycon Silva',
email: '@g.com',
password: '123456',
})
} catch (e) {
errorMessage = e.message
}
expect(errorMessage).toBe('E-mail mal formatado')
})
it('should be able create ID', () => {
const user = new UserModel({
name: 'Maycon Silva',
email: 'a@g.com',
password: '123456',
})
expect(user).toHaveProperty('_id')
})
// it('should not be able create a User with wrong password', () => {
// let errorMessage = ''
// try {
// new UserModel({
// name: 'Maycon Silva',
// email: 'a@g.com',
// password: '12345',
// })
// } catch (e) {
// errorMessage = e.message
// }
// expect(errorMessage).toBe('Senha inválida')
// })
it('should be able encrypt password', () => {
const password = '123456'
const user = new UserModel({
name: 'Maycon Silva',
email: 'a@g.com',
password,
})
expect(user.password).not.toBe(password)
})
it('should be able encrypt new password', () => {
const password = '123456'
const user = new UserModel({
name: 'Maycon Silva',
email: 'a@g.com',
password,
})
const new_password = '654321'
user.setPassword(new_password)
expect(user.comparePassword(new_password)).toBeTruthy()
})
it('should be able to do unsuccessful password comparison', () => {
const clean_password = '123456'
const user = new UserModel({
name: 'Maycon',
email: 'a@g.com',
password: clean_password,
})
expect(user.comparePassword('wrong password')).not.toBeTruthy()
})
it('should be able to successfully do password comparison', () => {
const clean_password = '123456'
const user = new UserModel({
name: 'Maycon',
email: 'a@g.com',
password: clean_password,
})
expect(user.comparePassword(clean_password)).toBeTruthy()
})
it('should ble able add workspace', () => {
const user = new UserModel({
name: 'Maycon',
email: 'a@g.com',
password: '123456',
})
expect(user.workspaces).toHaveLength(0)
const workspace = user.addWorkspace({
title: 'Dia-a-dia',
})
expect(user.workspaces).toHaveLength(1)
expect(workspace).toHaveProperty('_id')
})
it('should ble able add step in workspace', () => {
const user = new UserModel({
name: 'Maycon',
email: 'a@g.com',
password: '123456',
}) as Required<UserModel>
const workspace = user.addWorkspace({
title: 'Dia-a-dia',
})
expect(user.workspaces[0].steps).toHaveLength(3)
const data = {
label: 'Analisar código',
index: 0,
}
const step = user.addStepToWorkspace(workspace._id, data)
expect(user.workspaces[0].steps).toContain(step)
})
it('should ble able update step in workspace', () => {
const user = new UserModel({
name: 'Maycon',
email: 'a@g.com',
password: '123456',
}) as Required<UserModel>
const workspace = user.addWorkspace({
title: 'Dia-a-dia',
})
const data = {
label: 'Analisar código',
index: 0,
}
const step = user.addStepToWorkspace(workspace._id, data)
const new_label = 'Revisar código'
user.updateStepInWorkspace(step._id, workspace._id, {
label: new_label,
})
expect(user.workspaces[0].steps).toContainEqual({
...step,
label: new_label,
})
})
it('should ble able delete step in workspace', () => {
const user = new UserModel({
name: 'Maycon',
email: 'a@g.com',
password: '123456',
}) as Required<UserModel>
const workspace = user.addWorkspace({
title: 'Dia-a-dia',
})
const data = {
label: 'Analisar código',
index: 0,
}
const step = user.addStepToWorkspace(workspace._id, data)
expect(user.workspaces[0].steps).toHaveLength(4)
user.deleteStepInWorkspace(step._id, workspace._id)
expect(user.workspaces[0].steps).toHaveLength(3)
})
it('should ble able delete workspace', () => {
const user = new UserModel({
name: 'Maycon',
email: 'a@g.com',
password: '123456',
})
const workspace = user.addWorkspace({
title: 'Dia-a-dia',
})
expect(user.workspaces).toHaveLength(1)
user.deleteWorkspace(workspace._id)
expect(user.workspaces).toHaveLength(0)
})
it('should ble able add task', () => {
const user = new UserModel({
name: 'Maycon',
email: 'a@g.com',
password: '123456',
}) as Required<UserModel>
const workspace = user.addWorkspace({
title: 'Dia-a-dia',
})
expect(user.workspaces[0].tasks).toHaveLength(0)
user.addTask(workspace._id, {
title: 'Fazer café',
step_id: '12',
})
expect(user.workspaces[0].tasks).toHaveLength(1)
})
it('should ble able update task', () => {
const user = new UserModel({
name: 'Maycon',
email: 'a@g.com',
password: '123456',
}) as Required<UserModel>
const workspace = user.addWorkspace({
title: 'Dia-a-dia',
})
expect(user.workspaces[0].tasks).toHaveLength(0)
const task = user.addTask(workspace._id, {
title: 'Fazer café',
step_id: '12',
})
expect(user.workspaces[0].tasks).toHaveLength(1)
const new_title = 'Fazer achocolatado'
const data_to_update = {
title: new_title,
}
user.updateTask(task._id, workspace._id, data_to_update)
expect(user.workspaces[0].tasks[0].title).toBe(new_title)
})
it('should ble able delete task', () => {
const user = new UserModel({
name: 'Maycon',
email: 'a@g.com',
password: '123456',
}) as Required<UserModel>
const workspace = user.addWorkspace({
title: 'Dia-a-dia',
})
expect(user.workspaces[0].tasks).toHaveLength(0)
const task = user.addTask(workspace._id, {
title: 'Fazer café',
step_id: '12',
})
expect(user.workspaces[0].tasks).toHaveLength(1)
user.deleteTask(task._id, workspace._id)
expect(user.workspaces[0].tasks).toHaveLength(0)
})
it('should ble able get User as object without functions', () => {
const user = new UserModel({
name: 'Maycon',
email: 'a@g.com',
password: '123456',
})
const user_obj = user.toObj()
expect(user_obj).not.toHaveProperty('password')
})
it('should ble able get User as object without functions but with password', () => {
const user = new UserModel({
name: 'Maycon',
email: 'a@g.com',
password: '123456',
})
const user_payload = user.payload()
expect(user_payload.password).toBeDefined()
})
}) |
import { useDispatch } from 'react-redux';
import { cartActions } from '../../store/cart';
import classes from './CartItem.module.css';
const CartItem = (props) => {
const { id, title, quantity, total, price } = props.item;
const dispatch = useDispatch()
const handleAddProductToCart = () => {
dispatch(cartActions.addItemToCart({
id, title, price
}))
}
const handleRemoveItemFromCart = () => {
dispatch(cartActions.removeItemFromCart(id))
}
return (
<li className={classes.item}>
<header>
<h3>{title}</h3>
<div className={classes.price}>
${total.toFixed(2)}{' '}
<span className={classes.itemprice}>(${price.toFixed(2)}/item)</span>
</div>
</header>
<div className={classes.details}>
<div className={classes.quantity}>
x <span>{quantity}</span>
</div>
<div className={classes.actions}>
<button onClick={handleRemoveItemFromCart}>-</button>
<button onClick={handleAddProductToCart}>+</button>
</div>
</div>
</li>
);
};
export default CartItem; |
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
part 'counter_event.dart';
part 'counter_state.dart';
class CounterBloc extends Bloc<CounterEvent, CounterState> {
CounterBloc() : super(const CounterState(0)) {
on<IncrementEvent>((event, emit) {
emit(CounterState(state.count + 1));
});
on<DecrementEvent>((event, emit) {
emit(CounterState(state.count - 1));
});
}
} |
// ACross cross-compile development toolkit
// Author: Javier Peletier <jm@friendev.com>
// Summary: ACross allows you to build your Arduino projects using Visual Studio.
// Your Arduino code is cross - compiled and runs in your PC, which enables
// step - by - step debugging
//
// Copyright (c) 2015 All Rights Reserved, http://friendev.com
//
// This source is subject to the GPLv2 license.
// Please see the License.txt file for more information.
// All other rights reserved.
//
// THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY
// KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
// PARTICULAR PURPOSE.
#ifndef __VIRTUAL_SERIAL_H
#define __VIRTUAL_SERIAL_H
#include "AConfig.h"
#include "SerialEx.h"
#include "Stream.h"
using namespace std;
const uint16_t SERIAL_BUFFER_SIZE = 64;
struct ring_buffer
{
unsigned char buffer[SERIAL_BUFFER_SIZE];
volatile unsigned int head;
volatile unsigned int tail;
};
class VirtualSerial : public Stream, private CSerialEx
{
protected:
ring_buffer rx_buffer;
HANDLE ghMutex;
HANDLE ghReadEvent;
HANDLE consoleThread;
public:
inline void store_char(unsigned char c, ring_buffer *buffer)
{
int i = (unsigned int)(buffer->head + 1) % SERIAL_BUFFER_SIZE;
// if we should be storing the received character into the location
// just before the tail (meaning that the head would advance to the
// current location of the tail), we're about to overflow the buffer
// and so we don't write the character or advance the head.
if (i != buffer->tail) {
buffer->buffer[buffer->head] = c;
buffer->head = i;
}
}
void OnEvent(EEvent eEvent, EError eError);
static DWORD WINAPI consoleThreadProc(LPVOID lpArg);
DWORD consoleThreadProc(void);
int available(void);
void begin(unsigned int baudrate);
int read();
size_t write(uint8_t);
inline size_t write(unsigned long n) { return write((uint8_t)n); }
inline size_t write(long n) { return write((uint8_t)n); }
inline size_t write(unsigned int n) { return write((uint8_t)n); }
inline size_t write(int n) { return write((uint8_t)n); }
inline size_t write(const uint8_t* buffer, size_t size){ return Print::write(buffer, size); }
void flush();
int peek();
int _timedRead(unsigned long timeout, bool peekData=false);
void lock();
void unlock();
int waitAvailable(unsigned long timeout);
};
#endif |
import { LensHubProxy } from '@abis/LensHubProxy';
import { gql, useMutation } from '@apollo/client';
import { GridItemEight, GridItemFour, GridLayout } from '@components/GridLayout';
import UserProfile from '@components/Shared/UserProfile';
import { Button } from '@components/UI/Button';
import { Card, CardBody } from '@components/UI/Card';
import { Modal } from '@components/UI/Modal';
import { Spinner } from '@components/UI/Spinner';
import { WarningMessage } from '@components/UI/WarningMessage';
import Seo from '@components/utils/Seo';
import { CreateBurnProfileBroadcastItemResult } from '@generated/types';
import { ExclamationIcon, TrashIcon } from '@heroicons/react/outline';
import { Mixpanel } from '@lib/mixpanel';
import omit from '@lib/omit';
import splitSignature from '@lib/splitSignature';
import Cookies from 'js-cookie';
import React, { FC, useEffect, useState } from 'react';
import toast from 'react-hot-toast';
import { APP_NAME, ERROR_MESSAGE, LENSHUB_PROXY, SIGN_WALLET } from 'src/constants';
import Custom404 from 'src/pages/404';
import { useAppPersistStore, useAppStore } from 'src/store/app';
import { PAGEVIEW, SETTINGS } from 'src/tracking';
import { useContractWrite, useDisconnect, useSignTypedData } from 'wagmi';
import Sidebar from '../Sidebar';
const CREATE_BURN_PROFILE_TYPED_DATA_MUTATION = gql`
mutation CreateBurnProfileTypedData($options: TypedDataOptions, $request: BurnProfileRequest!) {
createBurnProfileTypedData(options: $options, request: $request) {
id
expiresAt
typedData {
domain {
name
chainId
version
verifyingContract
}
types {
BurnWithSig {
name
type
}
}
value {
nonce
deadline
tokenId
}
}
}
}
`;
const DeleteSettings: FC = () => {
useEffect(() => {
Mixpanel.track(PAGEVIEW.SETTINGS.DELETE);
}, []);
const [showWarningModal, setShowWarningModal] = useState<boolean>(false);
const userSigNonce = useAppStore((state) => state.userSigNonce);
const setUserSigNonce = useAppStore((state) => state.setUserSigNonce);
const setIsConnected = useAppPersistStore((state) => state.setIsConnected);
const isAuthenticated = useAppPersistStore((state) => state.isAuthenticated);
const setIsAuthenticated = useAppPersistStore((state) => state.setIsAuthenticated);
const currentUser = useAppPersistStore((state) => state.currentUser);
const setCurrentUser = useAppPersistStore((state) => state.setCurrentUser);
const { disconnect } = useDisconnect();
const { isLoading: signLoading, signTypedDataAsync } = useSignTypedData({
onError(error) {
toast.error(error?.message);
Mixpanel.track(SETTINGS.DELETE, { result: 'typed_data_error', error: error?.message });
}
});
const onCompleted = () => {
Mixpanel.track(SETTINGS.DELETE);
setIsAuthenticated(false);
setIsConnected(false);
setCurrentUser(null);
Cookies.remove('accessToken');
Cookies.remove('refreshToken');
localStorage.removeItem('lenster.store');
if (disconnect) disconnect();
location.href = '/';
};
const { isLoading: writeLoading, write } = useContractWrite({
addressOrName: LENSHUB_PROXY,
contractInterface: LensHubProxy,
functionName: 'burnWithSig',
mode: 'recklesslyUnprepared',
onSuccess() {
onCompleted();
},
onError(error: any) {
toast.error(error?.data?.message ?? error?.message);
}
});
const [createBurnProfileTypedData, { loading: typedDataLoading }] = useMutation(
CREATE_BURN_PROFILE_TYPED_DATA_MUTATION,
{
async onCompleted({
createBurnProfileTypedData
}: {
createBurnProfileTypedData: CreateBurnProfileBroadcastItemResult;
}) {
const { typedData } = createBurnProfileTypedData;
const { deadline } = typedData?.value;
try {
const signature = await signTypedDataAsync({
domain: omit(typedData?.domain, '__typename'),
types: omit(typedData?.types, '__typename'),
value: omit(typedData?.value, '__typename')
});
setUserSigNonce(userSigNonce + 1);
const { tokenId } = typedData?.value;
const { v, r, s } = splitSignature(signature);
const sig = { v, r, s, deadline };
write?.({ recklesslySetUnpreparedArgs: [tokenId, sig] });
} catch (error) {}
},
onError(error) {
toast.error(error.message ?? ERROR_MESSAGE);
}
}
);
const handleDelete = () => {
if (!isAuthenticated) return toast.error(SIGN_WALLET);
createBurnProfileTypedData({
variables: {
options: { overrideSigNonce: userSigNonce },
request: { profileId: currentUser?.id }
}
});
};
const isDeleting = typedDataLoading || signLoading || writeLoading;
if (!currentUser) return <Custom404 />;
return (
<GridLayout>
<Seo title={`Delete Profile • ${APP_NAME}`} />
<GridItemFour>
<Sidebar />
</GridItemFour>
<GridItemEight>
<Card>
<CardBody className="space-y-5">
<UserProfile profile={currentUser} />
<div className="text-lg font-bold text-red-500">This will deactivate your account</div>
<p>
Deleting your account is permanent. All your data will be wiped out immediately and you
won’t be able to get it back.
</p>
<div className="text-lg font-bold">What else you should know</div>
<div className="text-sm text-gray-500 divide-y dark:divide-gray-700">
<p className="pb-3">
You cannot restore your {APP_NAME} account if it was accidentally or wrongfully deleted.
</p>
<p className="py-3">
Some account information may still be available in search engines, such as Google or Bing.
</p>
<p className="py-3">Your @handle will be released immediately after deleting the account.</p>
</div>
<Button
variant="danger"
icon={isDeleting ? <Spinner variant="danger" size="xs" /> : <TrashIcon className="w-5 h-5" />}
disabled={isDeleting}
onClick={() => setShowWarningModal(true)}
>
{isDeleting ? 'Deleting...' : 'Delete your account'}
</Button>
<Modal
title="Danger Zone"
icon={<ExclamationIcon className="w-5 h-5 text-red-500" />}
show={showWarningModal}
onClose={() => setShowWarningModal(false)}
>
<div className="p-5 space-y-3">
<WarningMessage
title="Are you sure?"
message={
<div className="leading-6">
Confirm that you have read all consequences and want to delete your account anyway
</div>
}
/>
<Button
variant="danger"
icon={<TrashIcon className="w-5 h-5" />}
onClick={() => {
setShowWarningModal(false);
handleDelete();
}}
>
Yes, delete my account
</Button>
</div>
</Modal>
</CardBody>
</Card>
</GridItemEight>
</GridLayout>
);
};
export default DeleteSettings; |
import React, { useState } from 'react';
const ForgotPassword = () => {
const [email, setEmail] = useState('');
const [message, setMessage] = useState('');
const handleEmailChange = (e) => {
setEmail(e.target.value);
};
const handleSubmit = (e) => {
e.preventDefault();
// Here you can implement the logic to send a password reset link to the provided email
// For simplicity, let's just display a message here
setMessage(`A password reset link has been sent to ${email}`);
setEmail('');
};
return (
<div>
<style>
{`
*,
*::before,
*::after {
padding: 0;
margin: 0;
box-sizing: border-box;
}
body {
background-color: #000112;
font-family: 'Poppins', sans-serif;
}
form {
width: 90%; /* Adjust the width */
max-width: 500px; /* Set max-width for larger screens */
background-color: rgba(255, 255, 255, 0.13);
margin: 10% auto; /* Center the form */
border-radius: 10px;
padding: 30px; /* Adjust the padding */
display: flex;
flex-direction: column;
justify-content: left;
align-items: left;
}
form * {
color: #ffffff;
outline: none;
border: none;
}
form h2 {
font-size: 24px; /* Adjust the font size */
font-weight: 500;
line-height: 32px;
text-align: left;
margin-bottom: 20px; /* Adjust the margin */
}
label {
display: block;
margin-top: 15px; /* Adjust the margin */
font-size: 16px;
font-weight: 500;
}
input {
width: 100%;
height: 25px; /* Adjust the height */
background-color: rgba(255, 255, 255, 0.07);
border-radius: 13px;
padding: 0 10px;
margin-top: 8px;
font-size: 14px;
font-weight: 400;
}
::placeholder {
color: #e5e5e5;
}
button {
margin-top: 30px; /* Adjust the margin */
width: 100%;
background-color: #ffffff;
color: #080710;
padding: 12px 0; /* Adjust the padding */
font-size: 16px; /* Adjust the font size */
font-weight: 600;
border-radius: 5px;
cursor: pointer;
}
button:hover {
background: linear-gradient(#616161, #424242);
}
`}
</style>
<h2>Forgot Password</h2>
<form onSubmit={handleSubmit}>
<div>
<label htmlFor="email">Email:</label>
<input
type="email"
id="email"
value={email}
onChange={handleEmailChange}
required
/>
</div>
<button type="submit">Reset Password</button>
</form>
{message && <p>{message}</p>}
</div>
);
};
export default ForgotPassword; |
import { ReactElement, createContext, useMemo, useReducer } from "react";
export type CartItemType = {
sku: string;
name: string;
price: number;
qty: number;
};
type CartStateType = { cart: CartItemType[] };
const initCartState: CartStateType = { cart: [] };
const REDUCER_ACTION_TYPE = {
ADD: "ADD",
REMOVE: "REMOVE",
QUANTITY: "QUANTITY",
SUBMIT: "SUBMIT",
};
export type ReducerActionType = typeof REDUCER_ACTION_TYPE;
export type ReducerAction = {
type: string;
payload?: CartItemType;
};
const reducer = (
state: CartStateType,
action: ReducerAction
): CartStateType => {
switch (action.type) {
case REDUCER_ACTION_TYPE.ADD: {
if (!action.payload)
throw new Error("Action.payload missing in ADD action");
const { sku, name, price } = action.payload;
const filteredCart: CartItemType[] = state.cart.filter(
(item) => item.sku !== sku
);
const itemExists: CartItemType | undefined = state.cart.find(
(item) => item.sku === sku
);
const qty: number = itemExists ? itemExists.qty + 1 : 1;
return {
...state,
cart: [...filteredCart, { sku, name, price, qty }],
};
}
case REDUCER_ACTION_TYPE.REMOVE: {
if (!action.payload)
throw new Error("Action.payload missing in REMOVE action");
const { sku } = action.payload;
const filteredCart: CartItemType[] = state.cart.filter(
(item) => item.sku !== sku
);
return { ...state, cart: [...filteredCart] };
}
case REDUCER_ACTION_TYPE.QUANTITY: {
if (!action.payload)
throw new Error("Action.payload missing in QUANTITY action");
const { sku, qty } = action.payload;
const itemExists: CartItemType | undefined = state.cart.find(
(item) => item.sku === sku
);
if (!itemExists)
throw new Error("Item must exist in order to update the quantity");
return {
...state,
cart: state.cart.map((item) => {
if (item.sku === sku) {
return { ...item, qty };
}
return item;
}),
};
}
case REDUCER_ACTION_TYPE.SUBMIT: {
return { ...state, cart: [] };
}
default:
throw new Error("Unexpected Reducer Action");
}
};
const useCartContext = (initCartState: CartStateType) => {
const [state, dispatch] = useReducer(reducer, initCartState);
const REDUCER_ACTIONS = useMemo(() => {
return REDUCER_ACTION_TYPE;
}, []);
const totalItems: number = state.cart.reduce((prevValue, cartItem) => {
return prevValue + cartItem.qty;
}, 0);
const totalPrice = new Intl.NumberFormat("en-US", {
style: "currency",
currency: "USD",
}).format(
state.cart.reduce((prevValue, cartItem) => {
return prevValue + cartItem.price * cartItem.qty;
}, 0)
);
const cart = state.cart.sort((a, b) => {
const ItemA = Number(a.sku.slice(-4));
const ItemB = Number(b.sku.slice(-4));
return ItemA - ItemB;
});
return { dispatch, REDUCER_ACTIONS, totalItems, totalPrice, cart };
};
export type useCartContextType = ReturnType<typeof useCartContext>;
const initCartContextState: useCartContextType = {
dispatch: () => {},
REDUCER_ACTIONS: REDUCER_ACTION_TYPE,
totalItems: 0,
totalPrice: "",
cart: [],
};
export const CartContext =
createContext<useCartContextType>(initCartContextState);
type ChildrenType = { children?: ReactElement | ReactElement[] };
export const CartProvider = ({ children }: ChildrenType): ReactElement => {
return (
<CartContext.Provider value={useCartContext(initCartState)}>
{children}
</CartContext.Provider>
);
};
export default CartContext; |
# Opens a new tab in the current Terminal window and optionally executes a command.
# When invoked via a function named 'newwin', opens a new Terminal *window* instead.
function newtab_internal {
# If this function was invoked directly by a function named 'newwin', we open a new *window* instead
# of a new tab in the existing window.
local funcName=$0
local targetType='tab'
local targetDesc='new tab in the active Terminal window'
local makeTab=1
case "${FUNCNAME[1]}" in
newwin)
makeTab=0
funcName=${FUNCNAME[1]}
targetType='window'
targetDesc='new Terminal window'
;;
esac
# Command-line help.
if [[ "$1" == '--help' || "$1" == '-h' ]]; then
cat <<EOF
Synopsis:
$funcName [command [param1 ...]]
Description:
Opens a $targetDesc and optionally executes a command.
The new $targetType will run a login shell (i.e., load the user's shell profile) and inherit
the working folder from this shell.
When a command is specified, its first token will become the new ${targetType}'s title.
Quoted parameters are handled properly.
To specify multiple commands, use 'eval' followed by a single, *double*-quoted string
in which the commands are separated by ';' Do NOT use escaped double quotes inside
the string; rather, use backslash-escaping.
Use 'exit' as the last command to automatically close the tab when the command
terminates; precede it with 'read -s -n 1' to wait for a keystroke first.
Alternatively, pass a script name or path; prefix with 'exec' to automatically
close the $targetType when the script terminates.
Examples:
$funcName ls -l "\$Home/Library/Application Support"
$funcName eval "ls \\\$HOME/Library/Application\ Support; echo Press a key to exit.; read -s -n 1; exit"
$funcName /path/to/someScript
$funcName exec /path/to/someScript
EOF
return 0
fi
local CMD_PREFIX='tell application "Terminal" to do script'
# Command for opening a new Terminal window (with a single, new tab).
local CMD_NEWWIN=$CMD_PREFIX # Curiously, simply executing 'do script' with no further arguments opens a new *window*.
# Commands for opening a new tab in the current Terminal window.
# Sadly, there is no direct way to open a new tab in an existing window, so we must activate Terminal first, then send a keyboard shortcut.
local CMD_ACTIVATE='tell application "Terminal" to activate'
local CMD_NEWTAB='tell application "System Events" to keystroke "t" using {command down}'
if (( ${#@} )); then # Command specified; open a new tab or window, then execute command.
# Use the command's first token as the tab title.
local tabTitle=$1
case "$tabTitle" in
exec|eval) # Use following token instead, if the 1st one is 'eval' or 'exec'.
tabTitle=$(echo "$2" | awk '{ print $1 }')
;;
esac
local CMD_SETTITLE="tell application \"Terminal\" to set custom title of front window to \"$tabTitle\""
# The tricky part is to quote the command tokens properly when passing them to AppleScript:
# Step 1: Quote all parameters (as needed) using printf '%q' - this will perform backslash-escaping.
local quotedArgs=$(printf '%q ' "$@")
# Step 2: Escape all backslashes again (by doubling them), because AppleScript expects that.
local cmd="$CMD_PREFIX \"${quotedArgs//\\/\\\\}\""
# Open new tab or window, execute command, and assign tab title.
# '>/dev/null' suppresses AppleScript's output when it creates a new tab.
if (( makeTab )); then
osascript -e "$CMD_ACTIVATE" -e "$CMD_NEWTAB" -e "$cmd in front window" -e "$CMD_SETTITLE" >/dev/null
else
# Note: Even though we do not strictly need to activate Terminal first, we do it, as assigning the custom title to the 'front window' would otherwise sometimes target the wrong window.
osascript -e "$CMD_ACTIVATE" -e "$cmd" -e "$CMD_SETTITLE" >/dev/null
fi
else # No command specified; simply open a new tab or window.
if (( makeTab )); then
osascript -e "$CMD_ACTIVATE" -e "$CMD_NEWTAB" >/dev/null
else
# Note: Even though we do not strictly need to activate Terminal first, we do it so as to better visualize what is happening (the new window will appear stacked on top of an existing one).
osascript -e "$CMD_ACTIVATE" -e "$CMD_NEWWIN" >/dev/null
fi
fi
}
newtab_internal $@ |
import { BrowserModule } from '@angular/platform-browser';
import { NgModule, APP_INITIALIZER } from '@angular/core';
import { AppComponent } from './app.component';
import { CoreModule } from './core/core.module';
import { CoreRoutingModule } from './core/core-routing.module';
import { HttpClientModule } from '@angular/common/http';
import { FormsModule } from '@angular/forms';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { getUser } from './shared/services/userDetailsService';
import {MatProgressSpinnerModule } from '@angular/material';
import { UserIdleModule } from 'angular-user-idle'
// Trying to initialize application
export function init_app(getUser: getUser) {
return () => getUser.initializeApp();
}
// Get user details and set whether user is enrolled as phonepal or not
export function getUserDetails(getUser: getUser) {
return () => getUser.getUserDetails();
}
// Make API call to LDAP server and get the alias of the user
export function getAlias(getUser: getUser) {
return () => getUser.getAlias();
}
@NgModule({
declarations: [
AppComponent,
],
imports: [
BrowserModule,
CoreModule,
CoreRoutingModule,
BrowserModule,
HttpClientModule,
FormsModule,
BrowserAnimationsModule,
HttpClientModule,
MatProgressSpinnerModule,
UserIdleModule.forRoot({
idle: 60 * 30,
timeout: 60 * 5,
ping: 60 * 2,
}),
],
providers: [
getUser,
{ provide: APP_INITIALIZER, useFactory: init_app, deps: [getUser], multi: true },
{ provide: APP_INITIALIZER, useFactory: getAlias, deps: [getUser], multi: true }
],
bootstrap: [AppComponent]
})
export class AppModule { } |
from typing import Optional
from pydantic import BaseModel, EmailStr, Field, constr, conint, create_model
class SchemaUser(BaseModel):
nombre: constr(strict=True) = Field(...)
apellido: constr(strict=True) = Field(...)
dni: conint(strict=True) = Field(...)
email: EmailStr = Field(...)
telefono: constr(strict=True) = Field(None)
direccion: constr(strict=True) = Field(None)
codigo_postal: constr(strict=True) = Field(None)
class config:
schema_extra = {
"ejemplo": {
"nombre": "Juana",
"apellido": "Pilo",
"dni": 27358783,
"email": "jpilo@x.ar",
"telefono": "+54 9 456789",
"direccion": "calle pública S/n",
"codigo_postal": "5823"
}
}
@classmethod
def as_optional(cls):
annonations = cls.__fields__
fields = {
attribute: (Optional[data_type.type_], None)
for attribute, data_type in annonations.items()
}
OptionalModel = create_model(f"Optional{cls.__name__}", **fields)
return OptionalModel
def ResponseModel(data, message):
return {
"data": [data],
"code": 200,
"message": message,
}
def ErrorResponseModel(error, code, message):
return {"error": error, "code": code, "message": message} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.