Dataset Viewer
question_id
stringlengths 32
32
| text
stringlengths 2.57k
30k
|
---|---|
636d38ae40394826bb89c4085261be72 | Please work-out the essence of the following in a precise and compelling way: ### High-Level Investor Review and Optimization for Germany's Energy Transition**Germany's Energy Transition: Decarbonization, Decentralization, and the Opportunities Ahead**
**Background:**
Germany, through its ambitious "Energiewende," is undergoing a significant transformation in its energy sector. The key objectives of this transition are threefold: decarbonization, decentralization, and digital transformation, aiming for a more sustainable and resilient energy future.
**Key Objectives of Germany's Energiewende:**
- **Decarbonization:** Germany has set itself an ambitious target of reducing greenhouse gas emissions by 65% by 2030 and achieving climate neutrality by 2045. This involves a shift away from fossil fuels and nuclear power.
- **Increase in Renewable Energy:** The country aims to have renewables, such as wind, solar, and hydropower, contribute at least 80% of the electricity supply by 2030, significantly reducing the carbon footprint of the energy sector.
- **Phase-Out of Nuclear and Coal:** As part of its decarbonization goals, Germany is phasing out nuclear power by 2022 and coal by 2038, marking a decisive step towards a more sustainable energy mix.
**Decentralized Power Generation Model:**
- **Structure:** The new energy market model embraces decentralization, utilizing a diverse range of renewable energy sources. Energy production is distributed across various locations, closer to consumption points, with a focus on individual households, businesses, and community projects.
- **Control:** A key feature of decentralization is the distributed control system, involving multiple small-scale producers and prosumers (consumers who also produce energy). This system relies on both supply-side and demand-side management, with a focus on real-time adjustments and energy efficiency.
**Opportunities in Decentralization:**
- **Lower Emissions:** The increased adoption of renewable energy sources significantly reduces greenhouse gas emissions, bringing Germany closer to its climate goals.
- **Enhanced Resilience:** Decentralized systems are inherently more resilient to disruptions. They can quickly adapt to changes in demand and supply, ensuring a more reliable energy supply.
- **Local Economic Growth:** Local energy generation keeps economic benefits within communities, fostering job creation and local economic development.
**Digitalization and Technological Innovation:**
- **Smart Grids, AI, and IoT:** Germany is at the forefront of digital transformation in the energy sector. The adoption of smart grid technologies, AI, and IoT enhances the efficiency, reliability, and management of the entire energy system, unlocking new opportunities for innovation.
**Problem Analysis:**
While the energy transition brings numerous benefits, it also presents several challenges that need to be addressed:
- **Integration of Variable Renewables:** Balancing supply and demand is complex when dealing with variable renewable sources like wind and solar, which are weather-dependent.
- **Solution:** Advanced forecasting and real-time management technologies, powered by AI and machine learning, are crucial for optimizing the integration of renewable sources and ensuring grid stability.
- **Grid Management in Decentralized Systems:** Managing a decentralized grid with numerous small-scale producers and consumers requires sophisticated grid management to prevent outages and maintain stability.
- **Solution:** Investment in smart grid technologies and decentralized energy storage solutions, such as Battery Energy Storage Systems (BESS), is essential for efficient energy flow management and grid stability.
- **Regulatory and Market Adaptation:** Existing regulatory frameworks are often designed for centralized systems, hindering the rapid deployment of decentralized generation.
- **Solution:** Policymakers play a critical role in adapting regulations to facilitate distributed generation. This includes improving grid access for small producers and implementing innovative market mechanisms, such as dynamic pricing and demand response programs, to encourage flexible energy usage.
**Solution Analysis: Flexibility and Optimization:**
The key to addressing these challenges lies in the development of flexible and optimized energy management solutions:
- **Energy Storage with BESS:** Battery Energy Storage Systems (BESS) provide the much-needed flexibility in the energy grid. They store excess energy generated from renewable sources and discharge it during peak demand or low generation periods. This ensures grid stability and reduces the need for fossil fuel backup.
- **Grid Stability and Renewable Integration:** By co-locating BESS with renewable sources, the stability of the grid is enhanced. This integration allows for a continuous energy supply, even during fluctuations in renewable generation, ensuring a reliable and consistent power output.
**Real-Time Optimization with AI:**
- **AI-Driven BESS Optimization:** AI and machine learning algorithms optimize BESS operations by adjusting charge and discharge cycles based on market conditions and grid requirements. This real-time optimization ensures financial benefits and improves grid stability.
- **Forecasting and Market Participation:** Advanced forecasting models, powered by AI, predict energy prices, demand, and generation patterns. This enables better planning and utilization of BESS, as well as strategic participation in energy markets, enhancing revenue streams.
**Conclusion:**
Germany's Energiewende presents a comprehensive set of challenges and opportunities in the energy sector. With a focus on decarbonization, decentralization, and digitalization, the country is transforming its energy landscape. The integration of renewable sources demands flexible solutions, and energy storage, with BESS development playing a crucial role. Additionally, AI-driven management and optimization of these flexibilities ensure grid stability, enhance resilience, and create economic benefits. As Germany navigates its energy transition, strategic investments in innovative solutions, coupled with regulatory support, will be key to unlocking a successful and sustainable future.
C) Problem Statement โ Addressing the Energy Trilemma
Energy Security and Economic Stability: Europe's increasing reliance on renewables has introduced price volatility and supply uncertainties, impacting energy security and economic growth. IONESS aims to stabilize energy costs and enhance economic resilience through our advanced BESS solutions.
Grid Stability: The intermittent nature of renewable energy generation, including solar and wind power, demands significant upgrades to grid infrastructure and sophisticated management systems. Our BESS solutions provide the necessary flexibility and stability, addressing one of the critical dimensions of the energy trilemma.
Storage Infrastructure Gap: Europe's existing storage infrastructure is insufficient to accommodate the growing volume of renewable energy, leading to inefficiencies and economic setbacks. IONESS bridges this gap with our advanced and flexible BESS technology.
D) IONESS Solution โ End-to-End BESS Expertise
Advanced BESS Development & Deployment: We design, develop, and deploy turn-key custom-built, scalable BESS solutions, partnering with industry leaders like E.ON and BRAWO. Our systems are tailored to the specific needs of each project, ensuring optimal performance and seamless integration.
AI-Driven BESS Trading & Optimization: Our advanced AI and machine learning technologies maximize BESS performance and revenue generation of our BESS assets and the flexibilities of third parties through dynamic optimization and participation in energy markets. Our platform enables stakeholders to capitalize on market opportunities and enhance their financial returns.
E) Market Outlook โ Significant Growth
### The Need for Flexibility Development and Real-Time Optimization in the Energy Sector
The energy sector is undergoing significant transformation driven by the need for decarbonization. This shift necessitates the development of flexibility solutions and real-time optimization to manage the increasing integration of renewable energy sources.
### Problem Analysis
#### Centralized Power Generation Model
**Challenges:**
- **High Emissions:** Reliance on fossil fuels results in significant greenhouse gas emissions.
- **Inefficiencies:** Large energy losses occur during long-distance transmission.
- **Inflexibility:** Centralized systems are less adaptable to incorporating variable renewable energy sourcesใ11โ sourceใใ12โ sourceใ.
#### Decentralized Power Generation Model
**Opportunities:**
- **Lower Emissions:** Utilization of renewable energy significantly reduces greenhouse gas emissions.
- **Enhanced Resilience:** Decentralized systems are more resilient to disruptions and adaptable to demand and supply changes.
- **Local Benefits:** Local generation promotes economic benefits within communities and creates jobs.
- **Technological Innovation:** Adoption of smart grids, AI, and IoT technologies enhances system efficiency and reliabilityใ13โ sourceใใ14โ sourceใใ15โ sourceใ.
**Constraints:**
- **Integration of Variable Renewables:** Wind and solar power are weather-dependent, making it challenging to balance supply and demand.
- **Grid Management:** Decentralized systems require sophisticated management to maintain stability and prevent outages.
- **Regulatory and Market Adaptation:** Current regulatory frameworks often do not support rapid deployment of decentralized generationใ12โ sourceใใ13โ sourceใ.
### Solution Analysis
#### Flexibility Development: The Role of Battery Energy Storage Systems (BESS)
**Flexibility:**
- **Energy Storage:** BESS store excess energy generated from renewable sources and release it during high demand or low generation periods, providing crucial flexibility to the grid.
- **Grid Stability:** BESS help manage the variability of renewables, reducing the need for fossil fuel backup and enhancing grid reliabilityใ27โ sourceใใ28โ sourceใ.
**Co-Location with Renewables:**
- **Efficiency:** Co-locating BESS with wind and solar installations ensures more efficient use of generated power, reducing energy curtailment.
- **Stability:** This integration supports the stability of the grid by allowing continuous energy supply even when renewable generation fluctuatesใ27โ sourceใใ28โ sourceใ.
#### Real-Time Optimization: The Use of AI and Advanced Technologies
**Real-Time Management:**
- **AI-Driven Optimization:** AI and machine learning algorithms optimize BESS operations in real-time by adjusting charge and discharge cycles based on market conditions and grid requirements.
- **Forecasting:** Advanced forecasting models predict energy prices, demand, and generation, allowing for better planning and utilization of BESSใ14โ sourceใใ27โ sourceใใ28โ sourceใ.
**Algorithmic Trading:**
- **Automated Trading:** Self-learning algorithms execute trades autonomously, optimizing financial returns and reducing transaction costs.
- **Market Participation:** AI enables strategic participation in energy markets, including frequency regulation and voltage support, enhancing revenue streamsใ27โ sourceใใ28โ sourceใ.
### Summary
The transition from centralized to decentralized power generation models necessitates the development of flexibility solutions such as Battery Energy Storage Systems (BESS) and real-time optimization technologies. These solutions address the inherent challenges of integrating variable renewable energy sources and maintaining grid stability. By leveraging advanced technologies like AI for real-time optimization and co-locating BESS with renewable sources, the energy sector can enhance resilience, reduce emissions, and create economic benefits. However, strategic investments and regulatory adaptations are essential to fully realize these benefits and ensure a successful energy transition.
### Old and New Market Models in the Energy Sector
The energy sector is undergoing a fundamental transformation driven by the need for decarbonization, leading to significant changes in market models, opportunities, and constraints.
### Old Market Model
**Centralized Power Generation:**
- **Structure:** The traditional energy market is characterized by centralized power generation where large-scale power plants, often fueled by coal, natural gas, or nuclear energy, produce electricity. This electricity is then transmitted over long distances through high-voltage transmission lines to consumers.
- **Control:** Energy production and distribution are controlled by a few large utility companies.
- **Demand Response:** The system is designed to meet predictable demand patterns with a focus on supply-side management.
**Constraints of the Old Model:**
- **High Emissions:** Reliance on fossil fuels leads to high greenhouse gas emissions.
- **Inefficiencies:** Significant energy losses occur during transmission over long distances.
- **Inflexibility:** Centralized systems are less adaptable to integrating renewable energy sources, which are variable and decentralized by natureใ11โ sourceใใ12โ sourceใ.
### New Market Model
**Decentralized Power Generation:**
- **Structure:** The new energy market model is characterized by decentralized power generation with a mix of renewable energy sources such as solar, wind, and hydropower. Energy is produced closer to the point of consumption, often by individual households, businesses, and community projects.
- **Control:** A more distributed control system where multiple small-scale producers and prosumers (consumers who also produce energy) participate.
- **Demand Response:** The system relies on both supply-side and demand-side management, with a greater focus on real-time adjustments and energy efficiency.
**Opportunities of the New Model:**
- **Lower Emissions:** Increased use of renewable energy sources significantly reduces greenhouse gas emissions.
- **Enhanced Resilience:** Decentralized systems are more resilient to disruptions and can adapt more quickly to changes in demand and supply.
- **Local Benefits:** Local generation keeps economic benefits within communities and can create local jobs.
- **Technological Innovation:** Adoption of smart grids, AI, and IoT technologies enhances the efficiency and reliability of energy systemsใ13โ sourceใใ14โ sourceใใ15โ sourceใ.
### Constraints of the New Model
**Integration of Variable Renewables:**
- **Challenge:** Renewable energy sources such as wind and solar are variable and weather-dependent, making it challenging to balance supply and demand.
- **Solution:** Advanced forecasting and real-time management technologies, including AI and machine learning, are crucial for optimizing the integration of these sourcesใ14โ sourceใ.
**Grid Management:**
- **Challenge:** Decentralized systems require sophisticated grid management to ensure stability and prevent outages.
- **Solution:** Investment in smart grid technologies and decentralized energy storage solutions, such as Battery Energy Storage Systems (BESS), helps manage energy flows and maintain grid stabilityใ11โ sourceใใ15โ sourceใ.
**Regulatory and Market Adaptation:**
- **Challenge:** Existing regulatory frameworks and market structures are often designed for centralized systems and may not support the rapid deployment of decentralized generation.
- **Solution:** Policymakers need to adapt regulations to facilitate distributed generation, grid access for small producers, and innovative market mechanisms such as dynamic pricing and demand response programsใ12โ sourceใใ13โ sourceใ.
### The Need for Flexibility Development
**Role of Battery Energy Storage Systems (BESS):**
- **Flexibility:** BESS provide crucial flexibility to the energy system by storing excess energy generated from renewable sources and releasing it during periods of high demand or low generation. This flexibility is essential for managing the variability of renewables like wind and solarใ27โ sourceใใ28โ sourceใ.
- **Real-Time Optimization:** AI-driven real-time optimization of BESS can significantly enhance their efficiency and economic viability. By dynamically adjusting charge and discharge cycles based on real-time market conditions and grid requirements, BESS can maximize their utility and financial returnsใ27โ sourceใใ28โ sourceใ.
- **Co-Location with Renewables:** Co-locating BESS with renewable energy sources such as wind and PV allows for more efficient use of generated power, reducing curtailment and enhancing the overall stability of the grid. This integration ensures that renewable energy can be utilized even when generation exceeds demand, further supporting decarbonization goalsใ27โ sourceใใ28โ sourceใ.
### Summary
The shift from the old centralized energy market model to a new decentralized and digitalized model presents both opportunities and challenges. To address the inherent challenges of integrating variable renewable energy sources and ensuring grid stability, the development of flexibility solutions like BESS is essential. By leveraging advanced technologies such as AI for real-time optimization and strategic co-location with renewable sources, the energy sector can enhance resilience, reduce emissions, and create economic benefits. However, careful management and strategic investments are necessary to realize these benefits fully. |
58718e7f24284aacb455b3583d9e045b | This Java application is producing an error when clicking the Schedule Appointment button.
How to fix this error?
Exception in thread "JavaFX Application Thread" java.util.concurrent.RejectedExecutionException: Task java.util.concurrent.FutureTask@5f620252[Not completed, task = java.util.concurrent.Executors$RunnableAdapter@679720d7[Wrapped task = project.Appointments$$Lambda/0x000001ca813bd268@1658f6c7]] rejected from java.util.concurrent.ThreadPoolExecutor@1b36f653[Terminated, pool size = 0, active threads = 0, queued tasks = 0, completed tasks = 1]
at java.base/java.util.concurrent.ThreadPoolExecutor$AbortPolicy.rejectedExecution(ThreadPoolExecutor.java:2081)
at java.base/java.util.concurrent.ThreadPoolExecutor.reject(ThreadPoolExecutor.java:841)
at java.base/java.util.concurrent.ThreadPoolExecutor.execute(ThreadPoolExecutor.java:1376)
at java.base/java.util.concurrent.AbstractExecutorService.submit(AbstractExecutorService.java:123)
at project.Appointments.scheduleAppointment(Appointments.java:92)
at project.Appointments.lambda$0(Appointments.java:78)
at [email protected]/com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:86)
at [email protected]/com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:232)
at [email protected]/com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:189)
at [email protected]/com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(CompositeEventDispatcher.java:59)
at [email protected]/com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:58)
at [email protected]/com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at [email protected]/com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
at [email protected]/com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at [email protected]/com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
at [email protected]/com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at [email protected]/com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:74)
at [email protected]/com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:49)
at [email protected]/javafx.event.Event.fireEvent(Event.java:198)
at [email protected]/javafx.scene.Node.fireEvent(Node.java:8875)
at [email protected]/javafx.scene.control.Button.fire(Button.java:203)
at [email protected]/com.sun.javafx.scene.control.behavior.ButtonBehavior.mouseReleased(ButtonBehavior.java:207)
at [email protected]/com.sun.javafx.scene.control.inputmap.InputMap.handle(InputMap.java:274)
at [email protected]/com.sun.javafx.event.CompositeEventHandler$NormalEventHandlerRecord.handleBubblingEvent(CompositeEventHandler.java:247)
at [email protected]/com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:80)
at [email protected]/com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:232)
at [email protected]/com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:189)
at [email protected]/com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(CompositeEventDispatcher.java:59)
at [email protected]/com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:58)
at [email protected]/com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at [email protected]/com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
at [email protected]/com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at [email protected]/com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
at [email protected]/com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at [email protected]/com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:74)
at [email protected]/com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:54)
at [email protected]/javafx.event.Event.fireEvent(Event.java:198)
at [email protected]/javafx.scene.Scene$MouseHandler.process(Scene.java:3984)
at [email protected]/javafx.scene.Scene.processMouseEvent(Scene.java:1890)
at [email protected]/javafx.scene.Scene$ScenePeerListener.mouseEvent(Scene.java:2708)
at [email protected]/com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:411)
at [email protected]/com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:301)
at java.base/java.security.AccessController.doPrivileged(AccessController.java:400)
at [email protected]/com.sun.javafx.tk.quantum.GlassViewEventHandler.lambda$handleMouseEvent$2(GlassViewEventHandler.java:450)
at [email protected]/com.sun.javafx.tk.quantum.QuantumToolkit.runWithoutRenderLock(QuantumToolkit.java:424)
at [email protected]/com.sun.javafx.tk.quantum.GlassViewEventHandler.handleMouseEvent(GlassViewEventHandler.java:449)
at [email protected]/com.sun.glass.ui.View.handleMouseEvent(View.java:551)
at [email protected]/com.sun.glass.ui.View.notifyMouse(View.java:937)
at [email protected]/com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
at [email protected]/com.sun.glass.ui.win.WinApplication.lambda$runLoop$3(WinApplication.java:185)
at java.base/java.lang.Thread.run(Thread.java:1583)
public class Appointments {
private Scene scene;
private TextArea appointmentArea;
private HealthcareApplication app;
private static DatabaseManager dbManager = new DatabaseManager();
private ExecutorService executorService = Executors.newCachedThreadPool();
public Appointments(HealthcareApplication app) {
this.app = app;
BorderPane borderPane = new BorderPane();
scene = new Scene(borderPane, 500, 500);
GridPane grid = new GridPane();
grid.setAlignment(Pos.TOP_LEFT);
grid.setVgap(5);
grid.setHgap(5);
grid.setPadding(new Insets(20));
Label patientLabel = new Label("Patient Name:");
Label dateLabel = new Label("Date:");
Label timeLabel = new Label("Time:");
Label reasonLabel = new Label("Reason:");
TextField patientField = new TextField();
DatePicker datePicker = new DatePicker();
TextField timeField = new TextField();
TextField reasonField = new TextField();
reasonField.setPrefWidth(300);
Button scheduleButton = new Button("Schedule Appointment");
grid.add(patientLabel, 0, 0);
grid.add(patientField, 1, 0);
grid.add(dateLabel, 0, 1);
grid.add(datePicker, 1, 1);
grid.add(timeLabel, 0, 2);
grid.add(timeField, 1, 2);
grid.add(reasonLabel, 0, 3);
grid.add(reasonField, 1, 3);
grid.add(scheduleButton, 0, 4);
appointmentArea = new TextArea();
appointmentArea.setEditable(false);
grid.add(appointmentArea, 0, 6, 2, 1);
borderPane.setLeft(grid);
HBox bottomButtons = new HBox(10);
bottomButtons.setAlignment(Pos.CENTER);
bottomButtons.setPadding(new Insets(10, 0, 0, 0));
Button viewDashboard = new Button("Go Back");
Button logoutButton = new Button("Logout");
bottomButtons.getChildren().addAll(viewDashboard, logoutButton);
borderPane.setBottom(bottomButtons);
loadAppointments();
// Lambda expressions for button actions
scheduleButton.setOnAction(e -> {
scheduleAppointment(patientField.getText(), datePicker.getValue(), timeField.getText(),
reasonField.getText());
appointmentArea.clear();
loadAppointments();
});
viewDashboard.setOnAction(e -> app.goToDashboard());
logoutButton.setOnAction(e -> app.goToLogin());
}
public Scene getScene() {
return scene;
}
private void scheduleAppointment(String patient, LocalDate date, String time, String reason) {
executorService.submit(() -> {
try {
Appointment appointment = new Appointment(patient, date, time, reason);
Connection conn = dbManager.getConnection();
if (conn != null) {
System.out.println("Database connected!");
conn.createStatement()
.execute("INSERT INTO appointments (patient_name, appointment_date, time, reason) VALUES ('"
+ appointment.getPatient() + "', '" + appointment.getDate() + "', '"
+ appointment.getTime() + "', '" + appointment.getReason() + "')");
}
System.out.println("Data written to database!");
} catch (Exception e) {
System.out.println("Error connecting the database");
e.printStackTrace();
}
});
executorService.shutdown();
}
private void loadAppointments() {
executorService.submit(() -> {
try {
Connection conn = dbManager.getConnection();
if (conn != null) {
System.out.println("Database connected!");
ResultSet rs = conn.createStatement().executeQuery("SELECT * FROM appointments");
appointmentArea.appendText("Appointment Records:\n\n");
while (rs.next()) {
appointmentArea.appendText("Patient: " + rs.getString("patient_name") + "\n");
appointmentArea.appendText("Date: " + rs.getString("appointment_date") + "\n");
appointmentArea.appendText("Time: " + rs.getString("time") + "\n");
appointmentArea.appendText("Reason: " + rs.getString("reason") + "\n\n");
}
}
System.out.println("Data read from database!");
} catch (Exception e) {
System.out.println("Error connecting the database");
e.printStackTrace();
}
});
executorService.shutdown();
}
}
public class PatientRecords {
private Scene scene;
private HealthcareApplication app;
private TextArea patientArea;
private static DatabaseManager dbManager = new DatabaseManager();
// private ExecutorService executorService = Executors.newCachedThreadPool();
public PatientRecords(HealthcareApplication app) {
this.app = app;
BorderPane borderPane = new BorderPane();
scene = new Scene(borderPane, 500, 500);
GridPane grid = new GridPane();
grid.setAlignment(Pos.TOP_LEFT);
grid.setVgap(5);
grid.setHgap(5);
grid.setPadding(new Insets(20));
Label nameLabel = new Label("Name:");
Label ageLabel = new Label("Age:");
Label historyLabel = new Label("Medical History:");
Label contactLabel = new Label("Contact Info:");
TextField nameField = new TextField();
TextField ageField = new TextField();
TextField historyField = new TextField();
TextField contactField = new TextField();
contactField.setPrefWidth(300);
Button addButton = new Button("Add Patient");
grid.add(nameLabel, 0, 0);
grid.add(nameField, 1, 0);
grid.add(ageLabel, 0, 1);
grid.add(ageField, 1, 1);
grid.add(historyLabel, 0, 2);
grid.add(historyField, 1, 2);
grid.add(contactLabel, 0, 3);
grid.add(contactField, 1, 3);
grid.add(addButton, 0, 4);
patientArea = new TextArea();
patientArea.setEditable(false);
grid.add(patientArea, 0, 6, 2, 1);
borderPane.setLeft(grid);
HBox bottomButtons = new HBox(10);
bottomButtons.setAlignment(Pos.CENTER);
bottomButtons.setPadding(new Insets(10, 0, 0, 0));
Button viewDashboard = new Button("Go Back");
Button logoutButton = new Button("Logout");
bottomButtons.getChildren().addAll(viewDashboard, logoutButton);
borderPane.setBottom(bottomButtons);
loadPatients();
// Lambda expressions for button actions
addButton.setOnAction(e -> {
addPatient(nameField.getText(), ageField.getText(), historyField.getText(), contactField.getText());
patientArea.clear();
loadPatients();
});
viewDashboard.setOnAction(e -> app.goToDashboard());
logoutButton.setOnAction(e -> app.goToLogin());
}
public Scene getScene() {
return scene;
}
private void addPatient(String name, String age, String history, String contact) {
String query = "INSERT INTO patients (name, age, medical_history, contact_info) VALUES ('" + name + "', " + age
+ ", '" + history + "', '" + contact + "')";
Thread thread = new Thread(new DatabaseTask(query, patientArea, dbManager));
thread.start();
}
private void loadPatients() {
String query = "SELECT * FROM patients";
Thread thread = new Thread(new DatabaseTask(query, patientArea, dbManager));
thread.start();
}
}
public class DatabaseManager {
private String url;
private String user;
private String password;
public static Connection connection;
public DatabaseManager() {
try {
String propertiesPath = getClass().getResource("db.properties").getPath().replace("%20", " ");
FileInputStream fis = new FileInputStream(propertiesPath);
Properties props = new Properties();
props.load(fis);
url = props.getProperty("db.url");
user = props.getProperty("db.username");
password = props.getProperty("db.password");
fis.close();
connection = DriverManager.getConnection(url, user, password);
} catch (IOException e) {
e.printStackTrace();
} catch(SQLException e){
System.out.println("Failed to connect to database");
e.printStackTrace();
}
}
public Connection getConnection() throws SQLException {
return connection;
}
public void closeConnection(Connection conn) {
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
public class DatabaseTask implements Runnable {
private final String query;
private final TextArea outputArea;
private final DatabaseManager dbManager;
public DatabaseTask(String query, TextArea outputArea, DatabaseManager dbManager) {
this.query = query;
this.outputArea = outputArea;
this.dbManager = dbManager;
}
@Override
public void run() {
try {
Connection conn = dbManager.getConnection();
if (conn != null) {
System.out.println("Database connected!");
if (query.toLowerCase().startsWith("select")) {
ResultSet rs = conn.createStatement().executeQuery(query);
StringBuilder result = new StringBuilder();
while (rs.next()) {
result.append("Name: ").append(rs.getString("name")).append("\n");
result.append("Age: ").append(rs.getInt("age")).append("\n");
result.append("Medical History: ").append(rs.getString("medical_history")).append("\n");
result.append("Contact Info: ").append(rs.getString("contact_info")).append("\n\n");
}
String finalResult = result.toString();
Platform.runLater(() -> {
synchronized (outputArea) {
outputArea.clear();
outputArea.appendText(finalResult);
}
});
} else {
conn.createStatement().executeUpdate(query);
System.out.println("Data written to database!");
}
}
} catch (Exception e) {
System.out.println("Error connecting the database");
e.printStackTrace();
}
}
}
public class Dashboard {
private Scene scene;
private HealthcareApplication app;
public Dashboard(HealthcareApplication app) {
this.app = app;
VBox vbox = new VBox(5);
scene = new Scene(vbox, 500, 500);
vbox.setAlignment(Pos.CENTER);
Label dashboardLabel = new Label("Medical Healthcare Application Dashboard");
Button patientRecordsButton = new Button("Patient Records");
Button appointmentSchedulesButton = new Button("Appointment Schedules");
Button logoutButton = new Button("Logout");
vbox.getChildren().addAll(dashboardLabel, patientRecordsButton, appointmentSchedulesButton, logoutButton);
// Lambda expressions for button actions
patientRecordsButton.setOnAction(e -> showPatientRecords());
appointmentSchedulesButton.setOnAction(e -> showAppointments());
logoutButton.setOnAction(e -> app.goToLogin());
}
public Scene getScene() {
return scene;
}
private void showPatientRecords() {
app.goToPatientRecords();
}
private void showAppointments() {
app.goToAppointments();
}
}
public class HealthcareApplication extends Application {
private Stage primaryStage;
private static DatabaseManager dbManager = new DatabaseManager();
@Override
public void start(Stage primaryStage) {
this.primaryStage = primaryStage;
primaryStage.setTitle("Medical Healthcare Application");
goToLogin();
primaryStage.show();
}
//Login Screen
public void goToLogin() {
LoginScreen loginScreen = new LoginScreen(this);
primaryStage.setScene(loginScreen.getScene());
}
//Dashboard Screen
public void goToDashboard() {
Dashboard dashboard = new Dashboard(this);
primaryStage.setScene(dashboard.getScene());
}
//Patient Records Screen
public void goToPatientRecords() {
PatientRecords patientRecords = new PatientRecords(this);
primaryStage.setScene(patientRecords.getScene());
}
//Appointments Screen
public void goToAppointments() {
Appointments appointments = new Appointments(this);
primaryStage.setScene(appointments.getScene());
}
public static void main(String[] args) {
launch(args);
}
} |
99c23f33a35a4df5889ef3053c44cd87 | ### Directory Structure
base_processor.py
create_data.py
extrapolate_data.py
head_csv.py
project_scraper_4gpt.py
tokens_data.py
token_data.py
data_frames
extrapolated_data
heads
### base_processor.py
import requests
import pandas as pd
import logging
from datetime import datetime
from tenacity import retry, wait_fixed, stop_after_attempt
import re
# Configure logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
def validate_profile_description(description):
if not isinstance(description, str):
logging.warning(f"Non-string type encountered in profile description: {description}")
return ""
try:
# Convert to lowercase
description = description.lower()
# Remove URLs
description = re.sub(r'http\S+', '', description)
# Remove emojis
description = re.sub(r'[^\x00-\x7F]+', '', description)
# Remove non-alphanumeric characters except for spaces
description = re.sub(r'[^a-z0-9\s]', '', description)
# Ensure only words with single spaces in between (no excessive spaces)
description = ' '.join(description.split())
# Ensure the total length is no longer than 50 characters
description = description[:50]
except AttributeError as e:
logging.error(f"AttributeError in validate_profile_description: {e}")
description = ""
return description
class BaseDataProcessor:
BASE_URL = "https://api.moonshot.cc"
def __init__(self, endpoint):
self.endpoint = endpoint
self.data = None
self.processed_df = None
@retry(wait=wait_fixed(2), stop=stop_after_attempt(3))
def fetch_data(self):
url = f"{self.BASE_URL}/{self.endpoint}"
try:
response = requests.get(url)
response.raise_for_status()
logging.info(f"Data fetched successfully for endpoint: {self.endpoint}")
self.data = response.json()
except requests.exceptions.HTTPError as http_err:
logging.error(f"HTTP error occurred: {http_err}")
raise
except requests.exceptions.ConnectionError as conn_err:
logging.error(f"Connection error occurred: {conn_err}")
raise
except requests.exceptions.Timeout as timeout_err:
logging.error(f"Timeout error occurred: {timeout_err}")
raise
except requests.exceptions.RequestException as req_err:
logging.error(f"An error occurred: {req_err}")
raise
def preprocess_data(self):
if self.data is None:
logging.error("No data to preprocess")
return None
try:
# Normalize the data into a DataFrame
df = pd.json_normalize(self.data, sep='_')
# Create a new date column and a new time column from createdAt
df['createdAt_date'] = pd.to_datetime(df['createdAt'], unit='ms').dt.strftime('%d-%m-%Y')
df['createdAt_time'] = pd.to_datetime(df['createdAt'], unit='ms').dt.strftime('%H:%M:%S')
# List of numerical columns to format
numerical_columns = [
'fdv', 'marketCap',
'txns_m5_buys', 'txns_m5_sells', 'txns_m5_total', 'txns_h1_buys', 'txns_h1_sells', 'txns_h1_total',
'txns_h6_buys', 'txns_h6_sells', 'txns_h6_total', 'txns_h24_buys', 'txns_h24_sells', 'txns_h24_total',
'volume_m5_buys', 'volume_m5_sell', 'volume_m5_total', 'volume_h1_buys', 'volume_h1_sell', 'volume_h1_total',
'volume_h6_buys', 'volume_h6_sell', 'volume_h6_total', 'volume_h24_buys', 'volume_h24_sell', 'volume_h24_total',
'makers_m5_buyers', 'makers_m5_sellers', 'makers_m5_total', 'makers_h1_buyers', 'makers_h1_sellers', 'makers_h1_total',
'makers_h6_buyers', 'makers_h6_sellers', 'makers_h6_total', 'makers_h24_buyers', 'makers_h24_sellers', 'makers_h24_total',
'liquidity_usd', 'liquidity_base', 'liquidity_quote'
]
# Format numerical columns with thousands separators and no decimals
for col in numerical_columns:
if col in df.columns:
df[col] = df[col].apply(lambda x: "{:,.0f}".format(float(x)) if pd.notnull(x) else x)
# Validate and sanitize profile_description column
if 'profile_decription' in df.columns:
df['profile_decription'] = df['profile_decription'].apply(validate_profile_description)
# Log the cleaned descriptions
logging.info("Profile descriptions cleaned.")
logging.info("Data preprocessing completed successfully")
self.processed_df = df
except Exception as e:
logging.error(f"Error during data preprocessing: {e}")
def fetch_and_preprocess_data(self):
self.fetch_data()
self.preprocess_data()
return self.processed_df
### create_data.py
import os
import logging
from tokens_data import get_processed_data
# Configure logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
def main():
try:
# Define the endpoint types you want to process
endpoint_types = ["trending", "top", "rising", "new", "finalized"]
# Fetch and preprocess data
logging.info("Starting data processing...")
dfs = get_processed_data(endpoint_types)
# Log summary of processed data
for endpoint_type, df in dfs.items():
logging.info(f"Data for {endpoint_type} processed successfully.")
logging.info("Data processing completed successfully.")
except Exception as e:
logging.error(f"An error occurred during data processing: {e}")
if __name__ == "__main__":
main()
### extrapolate_data.py
import os
import pandas as pd
import logging
from datetime import datetime
# Configure logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
def update_creation_hour_counts(df, counts):
df['createdAt_hour'] = pd.to_datetime(df['createdAt'], unit='ms').dt.hour
df['createdAt_date'] = pd.to_datetime(df['createdAt'], unit='ms').dt.date
# Filter out today's data
today = datetime.utcnow().date()
df = df[df['createdAt_date'] < today]
for date in df['createdAt_date'].unique():
date_data = df[df['createdAt_date'] == date]
hour_counts = date_data['createdAt_hour'].value_counts().to_dict()
if date not in counts:
counts[date] = {hour: 0 for hour in range(24)}
for hour, count in hour_counts.items():
counts[date][hour] += count
def main():
try:
# Load finalized data from CSV
finalized_csv_path = os.path.join('data_frames', 'finalized.csv')
if not os.path.exists(finalized_csv_path):
logging.error(f"{finalized_csv_path} does not exist. Please ensure the finalized CSV file is present.")
return
df = pd.read_csv(finalized_csv_path)
# Load existing counts if they exist
counts_file_path = os.path.join('data_frames', 'extrapolated_data', 'creation_hour_counts.csv')
if os.path.exists(counts_file_path):
counts_df = pd.read_csv(counts_file_path, index_col=0)
creation_hour_counts = counts_df.to_dict(orient='index')
creation_hour_counts = {pd.to_datetime(k).date(): v for k, v in creation_hour_counts.items()}
else:
creation_hour_counts = {}
# Update the counts with new data
update_creation_hour_counts(df, creation_hour_counts)
# Save the updated counts
counts_df = pd.DataFrame.from_dict(creation_hour_counts, orient='index').fillna(0).astype(int)
counts_df.index.name = 'date'
counts_df.to_csv(counts_file_path)
logging.info(f"Updated creation hour counts saved to {counts_file_path}")
except Exception as e:
logging.error(f"An error occurred during data processing: {e}")
if __name__ == "__main__":
# Ensure the extrapolated_data directory exists
extrapolated_data_dir = os.path.join('data_frames', 'extrapolated_data')
if not os.path.exists(extrapolated_data_dir):
os.makedirs(extrapolated_data_dir)
main()
### head_csv.py
import os
import pandas as pd
import logging
# Configure logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
def extract_csv_heads(data_frames_dir, heads_dir):
# Create the heads directory if it doesn't exist
if not os.path.exists(heads_dir):
os.makedirs(heads_dir)
# Iterate through each file in the data_frames directory
for filename in os.listdir(data_frames_dir):
if filename.endswith('.csv'):
file_path = os.path.join(data_frames_dir, filename)
try:
# Read the CSV file
df = pd.read_csv(file_path)
# Get the first 5 rows
head_df = df.head()
# Save the first 5 rows to a new CSV in the heads directory
head_file_path = os.path.join(heads_dir, filename)
head_df.to_csv(head_file_path, index=False)
logging.info(f"First 5 rows of {filename} saved to {head_file_path}")
except Exception as e:
logging.error(f"Error processing {filename}: {e}")
if __name__ == "__main__":
data_frames_dir = 'data_frames'
heads_dir = os.path.join(data_frames_dir, 'heads')
extract_csv_heads(data_frames_dir, heads_dir)
### project_scraper_4gpt.py
import os
import pyperclip
def get_directory_structure(root_dir, exclude_dirs=None):
"""
Create a nested dictionary that represents the folder structure of root_dir
"""
if exclude_dirs is None:
exclude_dirs = ['__pycache__', '.git', '.venv', '.gitattributes']
dir_structure = {}
for dirpath, dirnames, filenames in os.walk(root_dir):
# Exclude specified directories
dirnames[:] = [d for d in dirnames if d not in exclude_dirs]
folder = os.path.relpath(dirpath, root_dir)
subdir = dir_structure
if folder != '.':
for part in folder.split(os.sep):
subdir = subdir.setdefault(part, {})
# Include Python files, exclude hidden files
subdir.update({filename: None for filename in filenames if not filename.startswith('.') and filename.endswith('.py')})
return dir_structure
def dict_to_str(d, indent=0):
"""
Convert the directory structure dictionary to a string for display
"""
lines = []
for key, value in d.items():
lines.append(' ' * indent + str(key))
if isinstance(value, dict):
lines.extend(dict_to_str(value, indent + 1))
return lines
def scrape_files_to_clipboard(directory):
content = ""
# Retrieve and convert the directory structure to a dictionary
dir_structure = get_directory_structure(directory)
content += "### Directory Structure\n"
content += "\n".join(dict_to_str(dir_structure))
content += "\n\n"
# Process only the files listed in the directory structure
def process_files(subdir, path=[]):
nonlocal content
for name, content_or_sub in subdir.items():
current_path = path + [name]
if content_or_sub is None: # It's a file
file_path = os.path.join(directory, *current_path)
content += f"### {name}\n"
with open(file_path, 'r', encoding='utf-8') as file:
content += file.read()
content += "\n\n"
else: # It's a subdirectory
process_files(content_or_sub, current_path)
process_files(dir_structure)
pyperclip.copy(content)
print("Project contents and directory structure copied to clipboard.")
if __name__ == "__main__":
target_directory = os.getcwd() # Use the current working directory
scrape_files_to_clipboard(target_directory)
### tokens_data.py
import os
import logging
from base_processor import BaseDataProcessor
class MarketDataProcessor(BaseDataProcessor):
def __init__(self, endpoint_type='trending'):
endpoint = f"tokens/v1/{endpoint_type}/solana"
super().__init__(endpoint)
def get_processed_data(endpoint_types=['trending', 'top', 'rising', 'new', 'finalized']):
dfs = {}
output_folder = 'data_frames'
# Create the output folder if it doesn't exist
if not os.path.exists(output_folder):
os.makedirs(output_folder)
for endpoint_type in endpoint_types:
try:
processor = MarketDataProcessor(endpoint_type)
df = processor.fetch_and_preprocess_data()
if df is not None:
dfs[endpoint_type] = df
# Save DataFrame to CSV
csv_path = os.path.join(output_folder, f"{endpoint_type}.csv")
df.to_csv(csv_path, index=False)
logging.info(f"Data for {endpoint_type} saved to {csv_path}")
else:
logging.warning(f"No data fetched for endpoint: {endpoint_type}")
except Exception as e:
logging.error(f"Error processing {endpoint_type}: {e}")
return dfs
### token_data.py
from base_processor import BaseDataProcessor
class TokenDataProcessor(BaseDataProcessor):
def __init__(self, token_or_pair_address):
endpoint = f"token/v1/solana/{token_or_pair_address}"
super().__init__(endpoint)
def get_token_data(token_or_pair_address):
processor = TokenDataProcessor(token_or_pair_address)
return processor.fetch_and_preprocess_data()
# Example usage
if __name__ == "__main__":
token_address = "fbbrt3skd8925muwtfbcahcskw6myvz676zdl13zxgzq"
df = get_token_data(token_address)
print(df)
|
8e753428dc804f61a6971ff3f7d2c35f | def custom_collate(batch):
# ๆพๅบๆนๆฌกไธญๆ้ฟ็ๅบๅ้ฟๅบฆ
max_len = max([item.shape[0] for item in batch])
# ๅฐๆๆๅบๅๅกซๅ
ๅฐ็ธๅ้ฟๅบฆ
padded_batch = []
for item in batch:
padding = torch.zeros(max_len - item.shape[0], 1)
padded_item = torch.cat([item, padding], dim=0)
padded_batch.append(padded_item)
# ๅ ๅ ๅกซๅ
ๅ็ๅบๅ
return torch.stack(padded_batch)
# ๅ ่ฝฝNTUๆฐๆฎ้
def load_ntu_data(file_path):
try:
print(f"Attempting to load file: {file_path}")
data = []
with open(file_path, 'r') as f:
lines = f.readlines()
for line in lines[1:]: # ่ทณ่ฟ็ฌฌไธ่ก
values = line.strip().split()
if len(values) > 0:
frame_data = [float(v) for v in values]
data.append(frame_data)
# ไฝฟ็จๅ่กจๆจๅฏผๅผๆพๅบๆ้ฟ็ๅธง
max_length = max(len(frame) for frame in data)
# ๅฐๆๆๅธงๅกซๅ
ๅฐ็ธๅ้ฟๅบฆ
padded_data = [frame + [0.0] * (max_length - len(frame)) for frame in data]
return np.array(padded_data, dtype=np.float32)
except Exception as e:
print(f"Error loading file {file_path}: {str(e)}")
raise
# ๆฐๆฎๅฝไธๅ
def normalize_data(data):
if isinstance(data, np.ndarray):
data = torch.from_numpy(data).float()
min_val = torch.min(data)
max_val = torch.max(data)
eps = 1e-8 # ๆทปๅ ๅฐ็epsilonๅผ
normalized_data = (data - min_val) / (max_val - min_val + eps)
return normalized_data
# ๆฐๆฎ้็ฑป
class NTUSkeletonDataset(Dataset):
def __init__(self, data_dir, transform=None):
self.data_dir = data_dir
self.transform = transform
self.data_files = [os.path.join(data_dir, f) for f in os.listdir(data_dir) if f.endswith('.skeleton')]
def __len__(self):
return len(self.data_files)
def __getitem__(self, idx):
file_path = self.data_files[idx]
data = load_ntu_data(file_path)
if isinstance(data, np.ndarray):
data = torch.from_numpy(data).float()
data = normalize_data(data)
print(f"Data shape after normalization: {data.shape}")
# ่ฎก็ฎ้ๆๅบๅ
static_sequence = torch.mean(data, dim=0, keepdim=True)
# ่ฎก็ฎๅทฎๅผ
difference = data - static_sequence
if self.transform:
difference = self.transform(difference)
return difference
# ๆฐๆฎๅขๅผบ
class DataAugmentation:
def __call__(self, data):
print(f"Data shape before transform: {data.shape}")
if data.dim() == 2:
# ๅฏน2็ปดๆฐๆฎ่ฟ่ก้ๅฝ็ๅค็
if data.shape[1] > 1:
start = np.random.randint(0, data.shape[1] - 1)
cropped_data = data[:, start:start+1]
else:
# ๅฆๆๆฐๆฎ็ฌฌไบ็ปดๅบฆๅฐไบ็ญไบ 1๏ผๅไธ่ฟ่ก่ฃๅช
cropped_data = data
elif data.dim() == 3:
# ๅฏน3็ปดๆฐๆฎ่ฟ่กๅค็
if data.shape[2] > 10:
cropped_data = data[:, :, np.random.randint(0, data.shape[2]-10)]
else:
cropped_data = data # If the last dimension is 10 or less, don't crop
elif data.dim() == 4:
# ็กฎไฟ่ฃๅช็็ปดๅบฆๅคงไบ0
if data.shape[2] > 0 and data.shape[3] > 0:
cropped_data = data[:, :, np.random.randint(0, data.shape[2]):np.random.randint(data.shape[2], data.shape[2]+10),
np.random.randint(0, data.shape[3]):np.random.randint(data.shape[3], data.shape[3]+10)]
else:
cropped_data = data
else:
raise ValueError(f"Unexpected data dimension: {data.dim()}")
print(f"Data shape after transform: {cropped_data.shape}")
return cropped_data
# ๅฎไน็ผ็ ๅจ.ๅจๅท็งฏๅฑๅๅ
จ่ฟๆฅๅฑไนๅๆทปๅ ไบๆน้ๅฝไธๅ๏ผๅๅฐๅ
้จๅๅ้ๅ็งป๏ผๆ้ซๆจกๅ็ๆง่ฝๅๆถๆ้ๅบฆ
class Encoder(nn.Module):
def __init__(self):
super(Encoder, self).__init__()
self.conv1 = nn.Conv2d(in_channels=1, out_channels=64, kernel_size=(3, 1), stride=1, padding=(1, 0))
self.bn1 = nn.BatchNorm2d(64)
self.conv2 = nn.Conv2d(in_channels=64, out_channels=128, kernel_size=(3, 1), stride=1, padding=(1, 0))
self.bn2 = nn.BatchNorm2d(128)
self.conv3 = nn.Conv2d(in_channels=128, out_channels=256, kernel_size=(3, 1), stride=1, padding=(1, 0))
self.bn3 = nn.BatchNorm2d(256)
self.pool = nn.AdaptiveAvgPool2d((16, 1))
self.fc1 = nn.Linear(256 * 16, 512)
self.bn4 = nn.BatchNorm1d(512)
self.fc2 = nn.Linear(512, 256)
self.bn5 = nn.BatchNorm1d(256)
self.fc3 = nn.Linear(256, 128)
self.bn6 = nn.BatchNorm1d(128)
self.output_dim = 128
def forward(self, x):
if x.dim() == 2:
x = x.unsqueeze(0).unsqueeze(0) # ๆทปๅ ๆนๆฌก็ปดๅบฆๅ้้็ปดๅบฆ
if x.dim() == 3:
x = x.unsqueeze(1) # ๆทปๅ ้้็ปดๅบฆ
# ็กฎไฟๆฐๆฎๅฝข็ถไธบ [batch_size, channels, sequence_length, features]
x = x.permute(0, 3, 1, 2)
# ๅฆๆ้้ๆฐไธๆฏ1๏ผๅๅ็ฌฌไธไธช้้
if x.size(1) != 1:
x = x[:, 0:1, :, :]
x = F.relu(self.bn1(self.conv1(x)))
x = F.relu(self.bn2(self.conv2(x)))
x = F.relu(self.bn3(self.conv3(x)))
x = self.pool(x)
x = x.reshape(x.size(0), -1)
x = F.relu(self.bn4(self.fc1(x)))
x = F.relu(self.bn5(self.fc2(x)))
x = self.bn6(self.fc3(x))
return x
# ๅฎไนMoCo้ข่ฎญ็ป่ฟ็จ
def moco_pretrain(encoder1, encoder2, data_loader, optimizer, criterion, scheduler, num_epochs=10):
momentum = 0.999
for epoch in range(num_epochs):
total_loss = 0
for batch in data_loader:
normalized_batch = normalize_data(batch)
batch_size = normalized_batch .size(0)
# ๅฏนๆฏไธชๅบๅๅ็ฌ่ฎก็ฎ้ๆๅบๅ
static_sequences = torch.mean(normalized_batch , dim=1, keepdim=True) # [batch_size, 1, channels, height, width]
# ่ฎก็ฎๆฏไธชๅจไฝๅบๅๅๅ
ถๅฏนๅบ้ๆๅบๅ็ๅทฎๅผ
differences = normalized_batch - static_sequences
positive_pairs = DataAugmentation()(differences.clone())
negative_pairs = DataAugmentation()(differences.clone())
# ๅๅปบ่ดๆ ทๆฌๅฏน
for i in range(batch_size):
negative_pairs[i] = differences[(i + 1) % batch_size]
features1 = encoder1(positive_pairs)
features2 = encoder2(negative_pairs)
negative_features = encoder2(negative_pairs)
loss = criterion(features1, features2, negative_features)
optimizer.zero_grad()
loss.backward()
# ไธคไธช็ผ็ ๅจ็ๆขฏๅบฆ่ฃๅช๏ผ้ฒๆญขๆขฏๅบฆ็็ธ
for param in list(encoder1.parameters()) + list(encoder2.parameters()):
param.grad.data.clamp_(-1.0, 1.0) # clip gradients between -1 and 1
optimizer.step()
# ๅจ้ๆดๆฐencoder2็ๅๆฐ
with torch.no_grad():
for param_q, param_k in zip(encoder1.parameters(), encoder2.parameters()):
param_k.data = param_k.data * momentum + param_q.data * (1. - momentum)
total_loss += loss.item()
avg_loss = total_loss / len(data_loader)
print(f"Epoch {epoch+1}/{num_epochs}, Loss: {avg_loss:.4f}")
scheduler.step(avg_loss)
# ๅฎไนๅฏนๆฏๆๅคฑๅฝๆฐ
class InfoNCELoss(nn.Module):
def __init__(self, encoder, temperature=0.1):
super(InfoNCELoss, self).__init__()
self.temperature = temperature
self.encoder = encoder
def forward(self, query, positive, negative):
query = F.normalize(query, dim=1)
positive = F.normalize(positive, dim=1)
if negative.dim() != query.dim():
negative = self.encoder(negative) # ็จencoder2็ผ็ ่ดๆ ทๆฌ
negative = F.normalize(negative, dim=1)
pos_sim = torch.sum(query * positive, dim=-1) / (self.temperature + 1e-8)
neg_sim = torch.sum(query * negative, dim=-1) / (self.temperature + 1e-8)
logits = torch.cat([pos_sim.unsqueeze(1), neg_sim.unsqueeze(1)], dim=1)
labels = torch.zeros(query.size(0), dtype=torch.long, device=query.device)
loss = F.cross_entropy(logits, labels)
return loss
# ๅ
จๅฑๅนณๅๆฑ ๅ
def global_average_pooling(features):
if features.dim() == 2:
return features.mean(dim=1)
elif features.dim() == 3:
return features.mean(dim=(1, 2))
elif features.dim() == 4:
return features.mean(dim=(2, 3))
else:
raise ValueError(f"Unexpected number of dimensions: {features.dim()}")
# ็ฆป็บฟๆๅฝฑๅจ
class OfflineProjector(nn.Module):
def __init__(self, input_dim, output_dim):
super(OfflineProjector, self).__init__()
self.fc = nn.Linear(input_dim, output_dim)
def forward(self, x):
if x.dim() == 1:
x = x.unsqueeze(0)
return self.fc(x)
# ๆฏ่พๅจไฝๅบๅๅ้ๆๅบๅ
def compare_sequences(action_sequence, static_sequence):
difference = action_sequence - static_sequence
return difference
# ๅๅไผ ๆญ้ๆฉๅจไฝๅ
็ด ๏ผไฝฟ็จๆฐๆฎๅขๅผบ็ๆๆญฃๆ ทๆฌ๏ผไป่ฎฐๅฟๅบ่ทๅ่ดๆ ทๆฌ
def select_action_elements(difference, encoder, criterion, optimizer, memory_bank, is_training=False):
if not is_training:
encoder.eval()
difference = difference.requires_grad_()
with torch.set_grad_enabled(is_training):
features = encoder(difference)
# ๆฐๆฎๅขๅผบ็ๆๆญฃๆ ทๆฌ
augmented_difference = DataAugmentation()(difference.clone())
positive = encoder(augmented_difference)
# ไป่ฎฐๅฟๅบ่ทๅ่ดๆ ทๆฌ
negative = memory_bank.get_negative_samples(features.size(0))
# ๆดๆฐ่ฎฐๅฟๅบ
memory_bank.update(features.detach())
loss = criterion(features, positive, negative)
optimizer.zero_grad()
loss.backward() #ๅๅไผ ๆญ
torch.nn.utils.clip_grad_norm_(encoder.parameters(), max_norm=1.0) #ๆขฏๅบฆ่ฃๅช๏ผ้ฒๆญขๆขฏๅบฆ็็ธ
optimizer.step()
gradients = difference.grad
if gradients is not None:
important_joints = torch.argmax(gradients, dim=1)
else:
important_joints = torch.zeros(difference.size(0), dtype=torch.long)
return important_joints
# MemoryBank็ฑป็ฎก็่ดๆ ทๆฌ
class MemoryBank:
def __init__(self, size, feature_dim):
self.size = size
self.features = torch.randn(size, feature_dim)
self.ptr = 0
def update(self, new_features):
batch_size = new_features.size(0)
self.features[self.ptr:self.ptr+batch_size] = new_features
self.ptr = (self.ptr + batch_size) % self.size
def get_negative_samples(self, num_samples):
idx = torch.randperm(self.size)[:num_samples]
return self.features[idx]
# ๆจกๅ่ฎญ็ป
def train_model(data_dir, epochs, batch_size, lr, temperature):
dataset = NTUSkeletonDataset(data_dir, transform=DataAugmentation())
data_loader = DataLoader(dataset, batch_size=batch_size, shuffle=True, collate_fn=custom_collate, num_workers=4)
encoder1 = Encoder()
encoder2 = Encoder()
criterion = InfoNCELoss(encoder2, temperature=args.temperature)
optimizer = optim.Adam(list(encoder1.parameters()) + list(encoder2.parameters()), lr=lr)
# ไฝฟ็จไฝๅผฆ้็ซๅญฆไน ็่ฐๅบฆๅจ
scheduler = optim.lr_scheduler.CosineAnnealingLR(optimizer, T_max=epochs)
moco_pretrain(encoder1, encoder2, data_loader, optimizer, criterion, scheduler, num_epochs=epochs)
torch.save(encoder1.state_dict(), 'encoder1.pth') # ไธป็ผ็ ๅจ๏ผ็จไบ็ผ็ ๆฅ่ฏขๆ ทๆฌ๏ผๅจๆฏๆฌก่ฟญไปฃไธญ้ฝไผๆดๆฐๅๆฐ๏ผไธป็ผ็ ๅจไผ็จไบไธๆธธไปปๅกใ
torch.save(encoder2.state_dict(), 'encoder2.pth') # ๅจ้็ผ็ ๅจ๏ผ็จไบ็ผ็ ้ฎๆ ทๆฌ๏ผๅๆฐๆดๆฐๆฏ้่ฟๅจ้ๆดๆฐๆบๅถ๏ผ่ไธๆฏ็ดๆฅ้่ฟๅๅไผ ๆญ๏ผๅฎ็ๅๆฐๆฏไธป็ผ็ ๅจๅๆฐ็ๆๆฐ็งปๅจๅนณๅ
# ๆจกๅไฝฟ็จ
def use_model(file_path):
skeleton_data = load_ntu_data(file_path)
normalized_data = normalize_data(skeleton_data)
# ็กฎไฟๆฐๆฎๅฝข็ถไธบ [batch_size, sequence_length, features]
if normalized_data.dim() == 2:
normalized_data = normalized_data.unsqueeze(0)
encoder1 = Encoder()
encoder1.load_state_dict(torch.load('encoder1.pth'))
encoder1.eval() #ๅจไฝฟ็จๆจกๅไนๅ๏ผๅฐๆจกๅ่ฎพ็ฝฎไธบ่ฏไผฐๆจกๅผ๏ผ้ฟๅ
ๆฏๆฌก็ป่ฎกๆฐๆฎ
features = encoder1(normalized_data)
pooled_features = global_average_pooling(features)
if pooled_features.dim() == 1:
pooled_features = pooled_features.unsqueeze(0)
print("Pooled features shape:", pooled_features.shape)
projected_features = OfflineProjector(input_dim=pooled_features.shape[-1], output_dim=64)(pooled_features)
importance_weights = torch.relu(pooled_features)
# ่ฎก็ฎๅไธชๆไปถ็้ๆๅบๅ
static_sequence = torch.mean(normalized_data, dim=0).unsqueeze(0)
difference = compare_sequences(normalized_data, static_sequence)
encoder = Encoder()
encoder.load_state_dict(torch.load('encoder1.pth'))
# ไฝฟ็จไธ่ฎญ็ปๆถ็ธๅ็ๅฏนๆฏๆๅคฑๅฝๆฐ
criterion = InfoNCELoss(encoder, temperature=0.1)
optimizer = optim.Adam(encoder.parameters(), lr=0.0001)
memory_bank = MemoryBank(size=1024, feature_dim=encoder.output_dim)
actionlet = select_action_elements(difference, encoder1, criterion, optimizer, memory_bank, is_training=True)
print(actionlet)
def parse_args():
parser = argparse.ArgumentParser(description="Train MoCo model on NTU Skeleton data")
parser.add_argument('--data_dir', type=str, help='Path to NTU skeleton data')
parser.add_argument('--epochs', type=int, default=10, help='Number of epochs to train')
parser.add_argument('--batch_size', type=int, default=8, help='Batch size for training')
parser.add_argument('--lr', type=float, default=0.00001, help='Learning rate')
parser.add_argument('--temperature', type=float, default=0.1, help='Temperature parameter for InfoNCE loss')
return parser.parse_args()
if __name__ == '__main__':
args = parse_args()
DEFAULT_DATA_DIR = 'dataset/ntu/skeleton'
data_dir = args.data_dir if args.data_dir is not None else DEFAULT_DATA_DIR
train_model(data_dir, args.epochs, args.batch_size, args.lr, args.temperature)
ไธ่ฟฐไปฃ็ ๆง่กๆจกๅ่ฎญ็ป๏ผๆๅฐEpoch 1/10, Loss: nan๏ผไฟฎๆญฃไปฃ็ ่งฃๅณ Loss: nan้ฎ้ข |
7a72c9a0e60447febae1fee6667d7dcf | Use the learning objective table at the bottom to align the questions below to the appropriate learning objective(s). Put the results in a table.
Q1: Which functional group is most likely to be polar uncharged under normal cellular conditions? a) Hydroxyl group (-OH) b) Carboxyl group (-COOH) c) Amino group (-NH2) d) Sulfhydryl group (-SH)
Q2: Insulin is a protein produced by cells in the pancreas. If you wanted to permanently change just one amino acid in insulin, what would you need to alter? a) The mRNA sequence coding for insulin b) The tRNA molecules used during translation c) The DNA sequence of the insulin gene d) The ribosomes that synthesize insulin
Learning Objective Table:
Day Designation Objective Code Learning Objective
Day 001: Scientific argumentation and cell model 1.1 Describe your current understanding of how cells work
Day 001: Scientific argumentation and cell model 1.2 Describe the claim-evidence-reasoning (CER) framework and use to make scientific arguments
Day 001: Scientific argumentation and cell model 1.3 Create a concrete plan for your success in BS161
Day 002: Covalent Bonds and Intermolecular Forces 2.1 Compare and contrast covalent bonds and intermolecular forces
Day 002: Covalent Bonds and Intermolecular Forces 2.2 Describe intermolecular forces and their relative strength in aqueous environments
Day 002: Covalent Bonds and Intermolecular Forces 2.3 Given the names or structures of two functional groups, predict the most relevant intermolecular force between them
Day 002: Covalent Bonds and Intermolecular Forces 2.4 Describe one way that you can observe intermolecular forces in your daily life
Day 003: Introduction to Macromolecules 3.1 Identify types of macromolecules and their monomers based on molecular structures
Day 003: Introduction to Macromolecules 3.2 Predict macromolecular shapes and interactions based on molecular structure
Day 003: Introduction to Macromolecules 3.3 Explain the relationship between a molecule's structure and its function in the cell
Day 004: Gene Expression I 4.1 Describe the outcome of gene expression and explain how this relates to cell function
Day 004: Gene Expression I 4.2 Interpret the experimental evidence that identified DNA as the genetic material
Day 004: Gene Expression I 4.3 Describe key features of DNA structure and RNA structure important for the storage and transfer of genetic information
Day 004: Gene Expression I 4.4 Use a model to describe the process of transcription
Day 005: Gene Expression II 5.1 Predict the sequence of an mRNA produced by transcription from a gene diagram and sequence
Day 005: Gene Expression II 5.2 Predict the sequence of a protein produced by translation from a gene diagram/sequence
Day 005: Gene Expression II 5.3 Use a model to describe the process of translation
Day 005: Gene Expression II 5.4 Use a model to explain the overall process of how a cell uses genetic information (DNA) to produce proteins
Day 006: Chromosome Connections Gene Expression and Protein Structure 6.1 Explain how a protein's primary structure is related to its tertiary structure
Day 006: Chromosome Connections Gene Expression and Protein Structure 6.2 Develop a model to show the flow of information in gene expression
Day 006: Chromosome Connections Gene Expression and Protein Structure 6.3 Use your model to explain the flow of information and how different genes produce different proteins
Day 006: Chromosome Connections Gene Expression and Protein Structure 6.4 Explain how a change in a gene can lead to a change in protein function and potentially a disease
Day 007: Model of protein engineering 7.1 Predict amino acids that could interact favorably to create a protein's tertiary structure
Day 007: Model of protein engineering 7.2 Predict amino acids in a binding site that could interact favorably with a specific substrate molecule
Day 007: Model of protein engineering 7.3 Use a model to explain how a change in the tertiary structure of a protein could lead to a different function
Day 008: Exam I 8.1 Recall information on molecular interactions, macromolecules, transcription, and translation
Day 008: Exam I 8.2 Test your mastery of the material covered up to Exam I
Day 008: Exam I 8.3 Refine your plan for success in BS161
Day 009: Bioenergetics and Enzymes 9.1 Use principles of equilibrium to explain the difference between energetically favorable versus energetically unfavorable processes
Day 009: Bioenergetics and Enzymes 9.2 Explain how cells use ATP to drive processes that would otherwise be energetically unfavorable
Day 009: Bioenergetics and Enzymes 9.3 Use a model to explain the role of enzymes in the rate and specificity of favorable chemical reactions
Day 010: Membranes, Compartments, and Transport 10.1 Use the structure and properties of membrane lipids to develop a model of how and why membranes form and use this model to explain:
Day 010: Membranes, Compartments, and Transport 10.1.1 how and why changes in membrane components and/or temperatures affect membrane fluidity
Day 010: Membranes, Compartments, and Transport 10.1.2 what allows membranes to be selectively permeable and why this is important for cellular function
Day 010: Membranes, Compartments, and Transport 10.2 Compare and contrast cellular organization of prokaryotic and eukaryotic cells. Explain why compartmentalization is advantageous for eukaryotic cells.
Day 010: Membranes, Compartments, and Transport 10.3 Based on the properties of a given solute and concentration gradients, predict the type of transport required to move that solute across a membrane
Day 010: Membranes, Compartments, and Transport 10.4 Construct a model to show solutes, concentration gradients, and transporter proteins in a membrane. Use this model to explain how cells use energetic coupling to transport solutes across membranes and why this is important for cellular function
Day 011: Introduction to Energy Metabolism 11.1 Compare and contrast anabolic and catabolic pathways
Day 011: Introduction to Energy Metabolism 11.2 Explain how cells create conditions to couple favorable processes with unfavorable processes and why this is required in metabolic pathways
Day 011: Introduction to Energy Metabolism 11.3 Explain how the same enzyme would catalyze a reaction in opposite directions in different cell types or cell compartments
Day 012: Cellular Respiration 12.1 Describe the principles of cellular respiration, including the transformations of energy and matter that occur in the process
Day 012: Cellular Respiration 12.2 Explain why respiration generates more ATP than fermentation, and why cells produce more ATP from the metabolism of fats compared to the metabolism of sugars
Day 012: Cellular Respiration 12.3 Use a model of cellular respiration to explain how changes to metabolic substrate or product concentrations in one part of the process affect other parts of the process
Day 012: Cellular Respiration 12.4 Use a model of cellular respiration to predict how cellular respiration is affected by mutations in genes encoding cellular respiration proteins or by chemicals
Day 013: Photosynthesis 13.1 Describe the principles of photosynthesis, including the transformations of energy and matter that occur in the process
Day 013: Photosynthesis 13.2 Use a model to explain how changes to metabolic substrate or product concentrations in one part of the process affect other parts of the process
Day 013: Photosynthesis 13.3 Use a model of photosynthesis to predict how photosynthesis is affected by mutations in genes encoding photosynthesis proteins or chemicals
Day 013: Photosynthesis 13.4 Use a model of photosynthesis to explain the connections between photosynthesis and respiration in a plant cell
Day 014: Model of Energy and Matter Transformations 14.1 Use a model to compare and contrast metabolic pathways
Day 014: Model of Energy and Matter Transformations 14.2 Analyze data to formulate hypotheses about metabolic pathways
Day 014: Model of Energy and Matter Transformations 14.3 Use a model to show the connections between photosynthesis in plants and respiration within plant cells and between plants and non-photosynthetic organisms
Day 014: Model of Energy and Matter Transformations 14.4 Use a model to make predictions about the relationship between mutations in genes encoding metabolic enzymes and metabolic pathways
Day 015: Exam II 15.1 Recall information on bioenergetics, membranes and membrane transport, cellular structures, and metabolism
Day 015: Exam II 15.2 Test your mastery of the material covered up to Exam II
Day 015: Exam II 15.3 Refine your plan for success in BS161
Day 016: Cell Communication 16.1 Use the components of signaling pathways to explain why different cells respond differently to the environment
Day 016: Cell Communication 16.2 Explain how the following receptor signaling pathways are activated and terminated: receptor kinase, intracellular receptor, G protein-coupled receptor, and ligand-gated ion channel
Day 016: Cell Communication 16.3 Explain how signal transduction components allow for signal amplification and multiple levels of control, and why this is advantageous to cells
Day 016: Cell Communication 16.4 Using a model of a signal transduction pathway, predict how changes in signaling components will impact cellular responses
Day 017: Cell Cycle: Activity on DNA replication and mitosis (Chromosome Connections Model of DNA Replication, Model of Mitosis) 17.1 List the major phases of the cell cycle and identify key events and features of each phase
Day 017: Cell Cycle: Activity on DNA replication and mitosis (Chromosome Connections Model of DNA Replication, Model of Mitosis) 17.2 Create a model to show how chromosomes with specific genes and sequences change during DNA replication. Use the model to support explanations regarding gene expression
Day 017: Cell Cycle: Activity on DNA replication and mitosis (Chromosome Connections Model of DNA Replication, Model of Mitosis) 17.3 Create a model to show how chromosomes with sister chromatids containing specific genes and sequences are divided during mitosis. Use the model to support explanations of how genetically identical daughter cells are created
Day 017: Cell Cycle: Activity on DNA replication and mitosis (Chromosome Connections Model of DNA Replication, Model of Mitosis) 17.4 Using your models, explain how DNA amount varies across cell cycle stages and relate to DNA synthesis and changes in the mitotic spindle
Day 018: Cell Cycle Regulation 18.1 Use models to explain the roles of cyclins, CDKs and checkpoints in cell cycle control, including mechanisms of how cell cycle regulators are activated or inactivated
Day 018: Cell Cycle Regulation 18.2 Define oncogene and tumor suppressor in terms of their effects on the cell cycle and identify proteins as either oncogenic or anti-tumor in function
Day 018: Cell Cycle Regulation 18.3 Predict how alterations of the processes involved in the cell cycle will impact the cell
Day 019: DNA Replication 19.1 Describe the extracellular and intracellular requirements for DNA replication and identify when DNA replication occurs in the cell cycle
Day 019: DNA Replication 19.2 Construct models to demonstrate the process and outcome of DNA replication
Day 019: DNA Replication 19.3 Use a model of DNA replication to explain why continuous synthesis of both DNA strands is not possible
Day 020: Ras and cancer model 20.1 Use a model of Ras signaling to explain how and why a specific Ras mutation is associated with cancer
Day 020: Ras and cancer model 20.2 Use a model of Ras signaling and your knowledge of the Ras signaling pathway to propose other drug targets that might block the abnormal cell division caused by mutations to Ras.
Day 020: Ras and cancer model 20.3 Use a model of Ras signaling and your knowledge of cell cycle regulation to predict how a specific mutation or drug that binds to a protein in the Ras pathway would impact signaling, cyclins, and cell division
Day 021: Exam III 21.1 Recall information on cell communication, cell division, and DNA replication
Day 021: Exam III 21.2 Test your mastery of the material covered up to Exam III
Day 021: Exam III 21.3 Refine your plan for success in BS161
Day 022: Regulation of Gene Expression I 22.1 Explain what it means for a gene to be 'expressed'
Day 022: Regulation of Gene Expression I 22.2 Use a model to explain the role of DNA sequences, DNA-binding proteins (transcription factors), and their interactions in controlling gene expression.
Day 022: Regulation of Gene Expression I 22.3 Explain the role of epigenetic modifications in the regulation of gene expression.
Day 022: Regulation of Gene Expression I 22.4 Use a model to explain how differences in gene expression account for the diverse cell types present in multicellular organisms.
Day 023: Regulation of Gene Expression II 23.1 Compare and contrast eukaryotic and prokaryotic gene expression
Day 023: Regulation of Gene Expression II 23.2 Use a model to explain how gene expression is affected by changing environmental conditions
Day 023: Regulation of Gene Expression II 23.3 Use a model to predict changes in gene expression resulting from mutations
Day 024: Model of gene regulation 24.1 Interpret data to formulate hypotheses about gene expression
Day 024: Model of gene regulation 24.2 Develop a model to show the role of specific proteins and DNA sequences in the regulation of gene expression under different cellular conditions
Day 024: Model of gene regulation 24.3 Use your model to predict how changes to gene coding or gene regulatory sequences will affect gene expression
Day 025: DNA Damage and Mutations 25.1 Explain why cells need DNA repair mechanisms and how unrepaired DNA damage affects the DNA of daughter cells
Day 025: DNA Damage and Mutations 25.2 Describe the general process to repair replication errors and DNA damage, including how the cell recognizes which nucleotide(s) to replace
Day 025: DNA Damage and Mutations 25.3 Predict if and how a mutation would affect protein-coding sequences in genes
Day 025: DNA Damage and Mutations 25.4 Predict the effect of a mutation on cellular function
Day 026: Alleles and Phenotypes (Chromosome Connections Model of Mutations and Phenotypes) 26.1 Distinguish between gene and allele and between genotype and phenotype
Day 026: Alleles and Phenotypes (Chromosome Connections Model of Mutations and Phenotypes) 26.2 Use a model of a gene to explain how different gene sequences (alleles, arising from mutations) encode mRNAs and proteins with different phenotypes and functions
Day 026: Alleles and Phenotypes (Chromosome Connections Model of Mutations and Phenotypes) 26.3 Use gene and protein structure models to explain how the presence of certain alleles (genotype) affects cell phenotypes
|
05e9f18211404e11a246aa93c9f5e2dd | Evaluate this writing:
And Yossarian also did not understand why Milo needed so desperately to invest in the letter from Doc Daneeka, which came right to the point. โGive Yossarian all the dried fruit and fruit juices he wants,โ Doc Daneeka had written. โHe says he has a liver condition.โ
โA letter like this,โ Milo mumbled despondently, โcould ruin any mess officer in the world.โ Milo had come to Yossarianโs tent just to read the letter again, following his carton of lost provisions across the squadron like a mourner. โI have to give you as much as you ask for. Why, the letter doesnโt even say you have to eat all of it yourself.โ
โAnd itโs a good thing it doesnโt,โ Yossarian told him, โbecause I never eat any of it. I have a liver condition.โ
โOh, yes, I forgot,โ said Milo, in a voice lowered deferentially. โIs it bad?โ
โJust bad enough,โ Yossarian answered cheerfully.
โI see,โ said Milo. โWhat does that mean?โ
โIt means that it couldnโt be betterโฆโ
โI donโt think I understand.โ
โโฆwithout being worse. Now do you see?โ
โYes, now I see. But I still donโt think I understand.โ
โWell, donโt let it trouble you. Let it trouble me. You see, I donโt really have a liver condition. Iโve just got the symptoms. I have a Garnett-Fleischaker syndrome.โ
โI see,โ said Milo. โAnd what is a Garnett-Fleischaker syndrome?โ
โA liver condition.โ
โI see,โ said Milo, and began massaging his black eyebrows together wearily with an expression of interior pain, as though waiting for some stinging discomfort he was experiencing to go away. โIn that case,โ he continued finally, โI suppose you do have to be very careful about what you eat, donโt you?.
โVery careful indeed,โ Yossarian told him. โA good Garnett-Fleischaker syndrome isnโt easy to come by, and I donโt want to ruin mine. Thatโs why I never eat any fruit.โ
โNow I do see,โ said Milo. โFruit is bad for your liver?โ
โNo, fruit is good for my liver. Thatโs why I never eat any.โ
โThen what do you do with it?โ demanded Milo, plodding along doggedly through his mounting confusion to fling out the question burning on his lips. โDo you sell it?โ
โI give it away.โ
โTo who?โ cried Milo, in a voice cracking with dismay.
โTo anyone who wants it,โ Yossarian shouted back.
Milo let out a long, melancholy wail and staggered back, beads of perspiration popping out suddenly all over his ashen face. He tugged on his unfortunate mustache absently, his whole body trembling.
โI give a great deal of it to Dunbar,โ Yossarian went on.
โDunbar?โ Milo echoed numbly.
โYes. Dunbar can eat all the fruit he wants and it wonโt do him a damned bit of good. I just leave the carton right out there in the open for anyone who wants any to come and help himself. Aarfy comes here to get prunes because he says he never gets enough prunes in the mess hall. You might look into that when youโve got some time because itโs no fun having Aarfy hanging around here. Whenever the supply runs low I just have Corporal Snark fill me up again. Nately always takes a whole load of fruit along with him whenever he goes to Rome. Heโs in love with a whore there who hates me and isnโt at all interested in him. Sheโs got a kid sister who never leaves them alone in bed together, and they live in an apartment with an old man and woman and a bunch of other girls with nice fat thighs who are always kidding around also. Nately brings them a whole cartonful every time he goes.โ
โDoes he sell it to them?โ
โNo, he gives it to them.โ
Milo frowned. โWell, I suppose thatโs very generous of him,โ he remarked with no enthusiasm.
โYes, very generous,โ Yossarian agreed.
โAnd Iโm sure itโs perfectly legal,โ said Milo, โsince the food is yours once you get it from me. I suppose that with conditions as hard as they are, these people are very glad to get it.โ
โYes, very glad,โ Yossarian assured him. โThe two girls sell it all on the black market and use the money to buy flashy costume jewelry and cheap perfume.โ
Milo perked up. โCostume jewelry!โ he exclaimed. โI didnโt know that. How much are they paying for cheap perfume?โ
โThe old man uses his share to buy raw whiskey and dirty pictures. Heโs a lecher.โ
โA lecher?โ
โYouโd be surprised.โ
โIs there much of a market in Rome for dirty pictures?โ Milo asked.
โYouโd be surprised. Take Aarfy, for instance. Knowing him, youโd never suspect, would you?โ
โThat heโs a lecher?โ
โNo, that heโs a navigator. You know Captain Aardvaark, donโt you? Heโs that nice guy who came up to you your first day in the squadron and said, โAardvaarkโs my name, and navigation is my game.โ He wore a pipe in his face and probably asked you what college you went to. Do you know him?โ
Milo was paying no attention. โLet me be your partner,โ he blurted out imploringly.
Yossarian turned him down, even though he had no doubt that the truckloads of fruit would be theirs to dispose of any way they saw fit once Yossarian had requisitioned them from the mess hall with Doc Daneekaโs letter. Milo was crestfallen, but from that moment on he trusted Yossarian with every secret but one, reasoning shrewdly that anyone who would not steal from the country he loved would not steal from anybody. Milo trusted Yossarian with every secret but the location of the holes in the hills in which he began burying his money once he returned from Smyrna with his planeload of figs and learned from Yossarian that a C.I.D. man had come to the hospital. To Milo, who had been gullible enough to volunteer for it, the position of mess officer was a sacred trust.
โI didnโt even realize we werenโt serving enough prunes,โ he had admitted that first day. โI suppose itโs because Iโm still so new. Iโll raise the question with my first chef.โ
Yossarian eyed him sharply. โWhat first chef?โ he demanded. โYou donโt have a first chef.โ
โCorporal Snark,โ Milo explained, looking away a little guiltily. โHeโs the only chef I have, so he really is my first chef, although I hope to move him over to the administrative side. Corporal Snark tends to be a little too creative, I feel. He thinks being a mess sergeant is some sort of art form and is always complaining about having to prostitute his talents. Nobody is asking him to do any such thing! Incidentally, do you happen to know why he was busted to private and is only a corporal now?โ
โYes,โ said Yossarian. โHe poisoned the squadron.โ
Milo went pale again. โHe did what?โ
โHe mashed hundreds of cakes of GI soap into the sweet potatoes just to show that people have the taste of Philistines and donโt know the difference between good and bad. Every man in the squadron was sick. Missions were canceled.โ
โWell!โ Milo exclaimed, with thin-upped disapproval. โHe certainly found out how wrong he was, didnโt he?โ
โOn the contrary,โ Yossarian corrected. โHe found out how right he was. We packed it away by the plateful and clamored for more. We all knew we were sick, but we had no idea weโd been poisoned.โ
Milo sniffed in consternation twice, like a shaggy brown hare. โIn that case, I certainly do want to get him over to the administrative side. I donโt want anything like that happening while Iโm in charge. You see,โ he confided earnestly, โwhat I hope to do is give the men in this squadron the best meals in the whole world. Thatโs really something to shoot at, isnโt it? If a mess officer aims at anything less, it seems to me, he has no right being mess officer. Donโt you agree?โ
Yossarian turned slowly to gaze at Milo with probing distrust. He saw a simple, sincere face that was incapable of subtlety or guile, an honest, frank face with disunited large eyes, rusty hair, black eyebrows and an unfortunate reddish-brown mustache. Milo had a long, thin nose with sniffing, damp nostrils heading sharply off to the right, always pointing away from where the rest of him was looking. It was the face of a man of hardened integrity who could no more consciously violate the moral principles on which his virtue rested than he could transform himself into a despicable toad. One of these moral principles was that it was never a sin to charge as much as the traffic would bear. He was capable of mighty paroxysms of righteous indignation, and he was indignant as could be when he learned that a C.I.D. man was in the area looking for him.
โHeโs not looking for you,โ Yossarian said, trying to placate him. โHeโs looking for someone up in the hospital whoโs been signing Washington Irvingโs name to the letters heโs been censoring.โ
โI never signed Washington Irvingโs name to any letters,โ Milo declared.
โOf course not.โ
โBut thatโs just a trick to get me to confess Iโve been making money in the black market.โ Milo hauled violently at a disheveled hunk of his off-colored mustache. โI donโt like guys like that. Always snooping around people like us. Why doesnโt the government get after ex-P.F.C. Wintergreen, if it wants to do some good? Heโs got no respect for rules and regulations and keeps cutting prices on me.โ
Miloโs mustache was unfortunate because the separated halves never matched. They were like Miloโs disunited eyes, which never looked at the same thing at the same time. Milo could see more things than most people, but he could see none of them too distinctly. In contrast to his reaction to news of the C.I.D. man, he learned with calm courage from Yossarian that Colonel Cathcart had raised the number of missions to fifty-five.
โWeโre at war,โ he said. โAnd thereโs no use complaining about the number of missions we have to fly. If the colonel says we have to fly fifty-five missions, we have to fly them.โ
โWell, I donโt have to fly them,โ Yossarian vowed. โIโll go see Major Major.โ
โHow can you? Major Major never sees anybody.โ
โThen Iโll go back into the hospital.โ
โYou just came out of the hospital ten days ago,โ Milo reminded him reprovingly. โYou canโt keep running into the hospital every time something happens you donโt like. No, the best thing to do is fly the missions. Itโs our duty.โ
Milo had rigid scruples that would not even allow him to borrow a package of pitted dates from the mess hall that day of McWattโs stolen bedsheet, for the food at the mess hall was all still the property of the government.
โBut I can borrow it from you,โ he explained to Yossarian, โsince all this fruit is yours once you get it from me with Doctor Daneekaโs letter. You can do whatever you want to with it, even sell it at a high profit instead of giving it away free. Wouldnโt you want to do that together?โ
โNo.โ
Milo gave up. โThen lend me one package of pitted dates,โ he requested. โIโll give it back to you. I swear I will, and thereโll be a little something extra for you.โ
Milo proved good as his word and handed Yossarian a quarter of McWattโs yellow bedsheet when he returned with the unopened package of dates and with the grinning thief with the sweet tooth who had stolen the bedsheet from McWattโs tent. The piece of bedsheet now belonged to Yossarian. He had earned it while napping, although he did not understand how. Neither did McWatt.
โWhatโs this?โ cried McWatt, staring in mystification at the ripped half of his bedsheet.
โItโs half of the bedsheet that was stolen from your tent this morning,โ Milo explained. โIโll bet you didnโt even know it was stolen.โ
โWhy should anyone want to steal half a bedsheet?โ Yossarian asked.
Milo grew flustered. โYou donโt understand,โ he protested. โHe stole the whole bedsheet, and I got it back with the package of pitted dates you invested. Thatโs why the quarter of the bedsheet is yours. You made a very handsome return on your investment, particularly since youโve gotten back every pitted date you gave me.โ Milo next addressed himself to McWatt. โHalf the bedsheet is yours because it was all yours to begin with, and I really donโt understand what youโre complaining about, since you wouldnโt have any part of it if Captain Yossarian and I hadnโt intervened in your behalf.โ
โWhoโs complaining?โ McWatt exclaimed. โIโm just trying to figure out what I can do with half a bedsheet.โ
โThere are lots of things you can do with half a bedsheet,โ Milo assured him. โThe remaining quarter of the bedsheet Iโve set aside for myself as a reward for my enterprise, work and initiative. Itโs not for myself, you understand, but for the syndicate. Thatโs something you might do with half the bedsheet. You can leave it in the syndicate and watch it grow.โ
โWhat syndicate?โ
โThe syndicate Iโd like to form someday so that I can give you men the good food you deserve.โ
โYou want to form a syndicate?โ
โYes, I do. No, a mart. Do you know what a mart is?โ
โItโs a place where you buy things, isnโt it?โ
โAnd sell things,โ corrected Milo.
โAnd sell things.โ
โAll my life Iโve wanted a mart. You can do lots of things if youโve got a mart. But youโve got to have a mart.โ
โYou want a mart?โ
โAnd every man will have a share.โ
Yossarian was still puzzled, for it was a business matter, and there was much about business matters that always puzzled him.
โLet me try to explain it again,โ Milo offered with growing weariness and exasperation, jerking his thumb toward the thief with the sweet tooth, still grinning beside him. โI knew he wanted the dates more than the bedsheet. Since he doesnโt understand a word of English, I made it a point to conduct the whole transaction in English.โ
โWhy didnโt you just hit him over the head and take the bedsheet away from him?โ Yossarian asked.
Pressing his lips together with dignity, Milo shook his head. โThat would have been most unjust,โ he scolded firmly. โForce is wrong, and two wrongs never make a right. It was much better my way. When I held the dates out to him and reached for the bedsheet, he probably thought I was offering to trade.โ
โWhat were you doing?โ
โActually, I was offering to trade, but since he doesnโt understand English, I can always deny it.โ
โSuppose he gets angry and wants the dates?โ
โWhy, weโll just hit him over the head and take them away from him,โ Milo answered without hesitation. He looked from Yossarian to McWatt and back again. โI really canโt see what everyone is complaining about. Weโre all much better off than before. Everybody is happy but this thief, and thereโs no sense worrying about him, since he doesnโt even speak our language and deserves whatever he gets. Donโt you understand?โ
But Yossarian still didnโt understand either how Milo could buy eggs in Malta for seven cents apiece and sell them at a profit in Pianosa for five cents. |
ed19bec77eab4a95afad1317b7cfa680 | ็ปๆ็ดขๆ ๅขๅ ไธไธชๆธ
้คๅ่ฝใ
```
# combine_split_manager.py
import json, os, subprocess, pypinyin
from PyQt5.QtWidgets import *
from PyQt5.QtCore import Qt, QTimer, pyqtSignal
from bs4 import BeautifulSoup
class FormulaCheckBox(QCheckBox):
stateAboutToChange = pyqtSignal(bool)
def mousePressEvent(self, event):
if event.button() == Qt.LeftButton:
newState = not self.isChecked()
if self.stateAboutToChange.emit(newState):
super().mousePressEvent(event)
else:
super().mousePressEvent(event)
class CombineSplitManager(QWidget):
def __init__(self, db, formula_manager, material_manager):
super().__init__()
self.db = db
self.formula_manager = formula_manager
self.material_manager = material_manager
self.selected_materials = set()
self.selected_formulas = set()
self.combined_ingredients = {}
# ็ผๅญ่ฏๆน่ฏๆๅๅ็งฐไฟกๆฏ
self.formula_data = {}
self.material_names = {}
self.init_ui()
self.material_manager.material_changed.connect(self.load_materials_to_checkboxes)
self.formula_manager.formula_changed.connect(self.load_all_formulas)
def init_ui(self):
layout = QVBoxLayout()
self.search_input = QLineEdit(placeholderText="่พๅ
ฅ่ฏๆนๆ่ฏๆ็ๅ็งฐ๏ผๆฏๆๆผ้ณๆ็ผฉๅๅฟซ้ๆ็ดข")
self.search_input.textChanged.connect(self.on_search_input_changed)
layout.addWidget(self.search_input)
self.formula_scroll = QScrollArea()
self.formula_widget = QWidget()
self.formula_layout = QGridLayout(self.formula_widget)
self.formula_scroll.setWidget(self.formula_widget)
self.formula_scroll.setWidgetResizable(True)
layout.addWidget(self.formula_scroll)
self.combine_split_scroll = QScrollArea()
self.combine_split_widget = QWidget()
self.combine_split_material_layout = QGridLayout(self.combine_split_widget)
self.combine_split_scroll.setWidget(self.combine_split_widget)
self.combine_split_scroll.setWidgetResizable(True)
layout.addWidget(self.combine_split_scroll)
self.result_text = QTextEdit(readOnly=True, acceptRichText=True)
layout.addWidget(self.result_text)
btn_layout = QHBoxLayout()
self.save_button = QPushButton("ไฟๅญ็ปๆ", clicked=self.save_results)
self.clear_button = QPushButton("ๅ
จ้จๆธ
้ค", clicked=self.clear_all_selections)
btn_layout.addStretch(1)
btn_layout.addWidget(self.save_button)
btn_layout.addWidget(self.clear_button)
layout.addLayout(btn_layout)
self.notification_label = QLabel('')
self.notification_label.setStyleSheet('color: red; padding: 5px; border: 1px solid #ddd; border-radius: 3px;')
self.notification_label.setAlignment(Qt.AlignCenter)
self.notification_label.setFixedHeight(30)
layout.addWidget(self.notification_label)
self.setLayout(layout)
self.load_all_formulas()
self.load_materials_to_checkboxes()
def save_results(self):
text = BeautifulSoup(self.result_text.toHtml(), 'html.parser').get_text()
if not text.strip():
self.show_warning("ๆฒกๆๅฏไฟๅญ็็ปๆ")
return
file_name, _ = QFileDialog.getSaveFileName(self, "ไฟๅญ็ปๆ", "", "ๆๆฌๆไปถ (*.txt);;ๆๆๆไปถ (*)")
if not file_name:
return
if not file_name.endswith('.txt'):
file_name += '.txt'
try:
with open(file_name, 'w', encoding='utf-8') as f:
f.write(text)
self.show_warning(f"็ปๆๅทฒไฟๅญๅฐ {os.path.basename(file_name)}", is_warning=False)
self.open_file_location(file_name)
except Exception as e:
self.show_warning(f"ไฟๅญๅคฑ่ดฅ: {str(e)}")
def open_file_location(self, file_path):
folder_path = os.path.dirname(file_path)
if os.name == 'nt':
os.startfile(folder_path)
elif os.name == 'posix':
subprocess.call(['open', folder_path])
def on_search_input_changed(self, text):
keywords = text.strip().lower().split()
# ็ผๅญๆผ้ณ็ปๆ
pinyin_cache = {}
keywords = set(keywords + [''.join(pinyin_cache.setdefault(k, pypinyin.lazy_pinyin(k))[0] for k in keywords)])
self.update_checkboxes_visibility(self.formula_layout, keywords, pinyin_cache)
self.update_checkboxes_visibility(self.combine_split_material_layout, keywords, pinyin_cache)
def update_checkboxes_visibility(self, layout, keywords, pinyin_cache):
for i in range(layout.count()):
checkbox = layout.itemAt(i).widget()
if isinstance(checkbox, QCheckBox):
text = checkbox.text().lower()
pinyin_text = ''.join(pinyin_cache.setdefault(text, pypinyin.lazy_pinyin(text)))
pinyin_initials = ''.join(p[0] for p in pinyin_cache.setdefault(text, pypinyin.lazy_pinyin(text)))
checkbox.setVisible(any(k in text or k in pinyin_text or k in pinyin_initials for k in keywords))
def on_checkbox_state_changed(self, state):
sender = self.sender()
color = "red" if isinstance(sender, FormulaCheckBox) else "green"
sender.setStyleSheet(f"QCheckBox {{ color: {color}; }}") if state == Qt.Checked else sender.setStyleSheet("")
def load_all_formulas(self):
self.clear_layout(self.formula_layout)
self.formula_data.clear()
self.formula_data = {
formula_id: {
'name': formula_name,
'materials': {ing[0] for ing in json.loads(ingredients)},
'ingredients': json.loads(ingredients)
}
for formula_id, formula_name, ingredients in self.db.fetch_all('SELECT id, name, ingredients FROM Formulas ORDER BY id')
}
for i, (formula_id, formula_data) in enumerate(self.formula_data.items()):
checkbox = FormulaCheckBox(formula_data['name'])
checkbox.setProperty("formula_id", formula_id)
checkbox.stateAboutToChange.connect(self.on_formula_state_about_to_change)
checkbox.stateChanged.connect(self.on_checkbox_state_changed)
self.formula_layout.addWidget(checkbox, i // 10, i % 10)
def clear_all_selections(self):
self.selected_formulas.clear()
self.selected_materials.clear()
self.combined_ingredients.clear()
self.reset_checkboxes(self.formula_layout)
self.reset_checkboxes(self.combine_split_material_layout)
self.result_text.setText('')
self.show_warning("ๅทฒๆธ
้คๆๆ้ๆฉ")
def on_formula_state_about_to_change(self, new_state):
checkbox = self.sender()
formula_id = checkbox.property("formula_id")
return self.select_formula(formula_id) if new_state else self.deselect_formula(formula_id)
def select_formula(self, formula_id):
if formula_id in self.selected_formulas or any(self.is_subset(formula_id, f) for f in self.selected_formulas):
return True if formula_id in self.selected_formulas else (self.show_warning("่ฏฅ่ฏๆนๆฏๅทฒ้่ฏๆน็ๅญ้๏ผๆ ๆณๆทปๅ ใ") or False)
new_selected_formulas = self.selected_formulas - {f for f in self.selected_formulas if self.is_subset(f, formula_id)} | {formula_id}
new_selected_materials = self.selected_materials | self.get_formula_materials(formula_id)
self.selected_formulas = new_selected_formulas
self.selected_materials = new_selected_materials
self.update_combined_ingredients_from_formulas(new_selected_formulas)
self.update_formula_selections()
self.update_checkboxes(self.combine_split_material_layout, new_selected_materials, True, False)
self.update_results()
return True
def update_checkboxes(self, layout, items_to_update, checked=True, force=True):
for i in range(layout.count()):
checkbox = layout.itemAt(i).widget()
if isinstance(checkbox, QCheckBox):
item_id = checkbox.property("material_id" if layout == self.combine_split_material_layout else "formula_id")
if item_id in items_to_update and (force or not checkbox.isChecked()):
checkbox.setChecked(checked)
def deselect_formula(self, formula_id):
if formula_id not in self.selected_formulas:
return True
supersets = [f for f in self.selected_formulas if self.is_subset(formula_id, f)]
if supersets:
return self.show_warning(f"ๆ ๆณๅๆถ่ฏฅ่ฏๆน๏ผๅ ไธบๅฎๆฏไปฅไธ่ฏๆน็ๅญ้๏ผ{', '.join(self.get_formula_name(f) for f in supersets)}") or False
formula_materials = self.get_formula_materials(formula_id)
subsets = [f for f in self.selected_formulas if self.is_subset(f, formula_id)]
subset_materials = set().union(*(self.get_formula_materials(f) for f in subsets))
if subset_materials == formula_materials:
formulas_to_remove = set(subsets) | {formula_id}
materials_to_remove = formula_materials
else:
formulas_to_remove = {formula_id}
materials_to_remove = formula_materials - subset_materials
self.selected_formulas -= formulas_to_remove
self.selected_materials -= {m for m in materials_to_remove if m not in self.get_materials_from_formulas(self.selected_formulas)}
self.update_combined_ingredients_from_formulas(self.selected_formulas)
self.update_formula_selections()
self.update_checkboxes(self.combine_split_material_layout, materials_to_remove, False)
self.update_results()
return True
def update_formula_selections(self):
for i in range(self.formula_layout.count()):
checkbox = self.formula_layout.itemAt(i).widget()
if isinstance(checkbox, QCheckBox):
formula_id = checkbox.property("formula_id")
is_selected = formula_id in self.selected_formulas
is_subset = any(self.is_subset(formula_id, f) for f in self.selected_formulas if f != formula_id)
checkbox.setChecked(is_selected)
checkbox.setEnabled(not is_subset or is_selected)
def on_material_selection_changed(self, state):
material_id = self.sender().property("material_id")
if state == Qt.Checked:
self.select_material(material_id)
else:
self.deselect_material(material_id)
def select_material(self, material_id):
self.selected_materials.add(material_id)
new_selected_formulas = self.get_formulas_from_materials(self.selected_materials)
self.update_checkboxes(self.formula_layout, new_selected_formulas - self.selected_formulas, True)
self.selected_formulas = new_selected_formulas
self.update_combined_ingredients_from_formulas(self.selected_formulas)
self.update_results()
def deselect_material(self, material_id):
self.selected_materials.discard(material_id)
new_selected_formulas = self.get_formulas_from_materials(self.selected_materials)
self.update_checkboxes(self.formula_layout, self.selected_formulas - new_selected_formulas, False)
self.selected_formulas = new_selected_formulas
self.update_combined_ingredients_from_formulas(self.selected_formulas)
self.update_results()
def load_materials_to_checkboxes(self):
self.clear_layout(self.combine_split_material_layout)
self.material_names.clear()
self.material_names = {
material_id: material_name
for material_id, material_name in self.db.fetch_all('SELECT id, name FROM Materials ORDER BY id')
}
for i, (material_id, material_name) in enumerate(self.material_names.items()):
checkbox = QCheckBox(material_name)
checkbox.setProperty("material_id", material_id)
checkbox.stateChanged.connect(self.on_material_selection_changed)
checkbox.stateChanged.connect(self.on_checkbox_state_changed)
self.combine_split_material_layout.addWidget(checkbox, i // 20, i % 20)
def reset_checkboxes(self, layout):
for i in range(layout.count()):
checkbox = layout.itemAt(i).widget()
if isinstance(checkbox, QCheckBox):
checkbox.setChecked(False)
checkbox.setEnabled(True)
checkbox.setStyleSheet("")
def get_formula_materials(self, formula_id):
return self.formula_data.get(formula_id, {}).get('materials', set())
def get_formula_ingredients(self, formula_id):
return self.formula_data.get(formula_id, {}).get('ingredients', [])
def get_materials_from_formulas(self, formula_ids):
return set().union(*(self.get_formula_materials(formula_id) for formula_id in formula_ids))
def get_formulas_from_materials(self, material_ids):
return {formula_id for formula_id, formula_data in self.formula_data.items() if formula_data['materials'].issubset(material_ids)}
def update_combined_ingredients(self, new_ingredients):
for ing_id, dosage in new_ingredients:
self.combined_ingredients[ing_id] = max(self.combined_ingredients.get(ing_id, 0), float(dosage))
def update_combined_ingredients_from_formulas(self, formula_ids):
self.combined_ingredients = {}
for formula_id in formula_ids:
if not any(self.is_subset(formula_id, other_id) for other_id in formula_ids if other_id != formula_id):
self.update_combined_ingredients(self.get_formula_ingredients(formula_id))
def is_subset(self, formula_id1, formula_id2):
materials1 = self.get_formula_materials(formula_id1)
materials2 = self.get_formula_materials(formula_id2)
return materials1.issubset(materials2) and materials1 != materials2
def show_warning(self, message, is_warning=True):
self.notification_label.setText(message)
self.notification_label.setStyleSheet(f'color: {"red" if is_warning else "green"}; padding: 5px; border: 1px solid #ddd; border-radius: 3px;')
QTimer.singleShot(5000, self.clear_warning)
def clear_warning(self):
self.notification_label.clear()
def update_results(self):
selected_materials = [(mid, self.material_names.get(mid, "ๆช็ฅ่ฏๆ")) for mid in self.selected_materials]
self.update_combined_ingredients_from_formulas(self.selected_formulas)
matching_formulas = self.find_matching_formulas(self.selected_materials)
result = self.format_results(selected_materials, self.combined_ingredients, matching_formulas, self.selected_formulas)
self.result_text.setHtml(result)
self.save_button.setEnabled(bool(result.strip()))
def find_matching_formulas(self, selected_material_ids):
return [(formula_id, formula_data['name'], json.dumps(formula_data['ingredients']))
for formula_id, formula_data in self.formula_data.items()
if formula_data['materials'].issubset(selected_material_ids)]
def format_results(self, selected_materials, combined_ingredients, matching_formulas, selected_formulas):
result = "<p>ๆจ้ๆฉ็่ฏๆๅ
ฑ่ฎก {} ๅณ๏ผ".format(len(selected_materials))
combined_material_ids = set(combined_ingredients.keys())
in_result = ['<span style="color: green;">{}</span>'.format(material_name) for material_id, material_name in selected_materials if material_id in combined_material_ids]
not_in_result = ['<span style="color: red;">{}</span>'.format(material_name) for material_id, material_name in selected_materials if material_id not in combined_material_ids]
result += ' '.join(in_result)
if not_in_result:
result += ' ๏ผ{}๏ผ'.format('ใ'.join(not_in_result))
result += '</p><p><small>(ไธๆนๆฌๅทไธญ็่ฏๆๆชๅจๅๆนไธญใ)</small></p>'
result += "<p>ๅ
ๅซ็่ฏๆน็ปๅๅ
ฑ่ฎก {} ไธช๏ผ</p>".format(len(matching_formulas))
for formula_id, formula_name, ingredients in matching_formulas:
is_subset = any(self.is_subset(formula_id, other_id) for other_id in selected_formulas if other_id != formula_id)
result += "<p>{}{}: ".format(formula_name, " (ๅญ้)" if is_subset else "")
ingredients = json.loads(ingredients)
for ing_id, dosage in ingredients:
result += '{}: {} '.format(self.material_names.get(ing_id, "ๆช็ฅ่ฏๆ"), dosage)
result += "</p>"
result += "<p>ๅๆน็ปๆ๏ผ</p>"
total_ingredients = len(combined_ingredients)
result += "<p>ๅ
ฑ่ฎก {} ๅณ๏ผ".format(total_ingredients)
result += ' '.join(['<span style="color: green;">{}</span>: <span style="color: orange;">{}</span>'.format(self.material_names.get(material_id, "ๆช็ฅ่ฏๆ"), dosage) for material_id, dosage in combined_ingredients.items()]) + "</p>"
subset_formulas = {formula_id for formula_id in selected_formulas if any(self.is_subset(formula_id, other_id) for other_id in selected_formulas if other_id != formula_id)}
if subset_formulas:
result += "<p><small>ๆณจๆ๏ผไปฅไธ่ฏๆนๆฏๅ
ถไป่ฏๆน็ๅญ้๏ผๅ
ถ่ฏๆๆชๅไธๆ็ปๅๆน็ปๆ็่ฎก็ฎ๏ผ</small></p>"
for formula_id in subset_formulas:
result += f"<p><small>- {self.get_formula_name(formula_id)}</small></p>"
return result
def get_formula_name(self, formula_id):
return self.formula_data.get(formula_id, {}).get('name', "ๆช็ฅ่ฏๆน")
def clear_layout(self, layout):
while layout.count():
item = layout.takeAt(0)
widget = item.widget()
if widget:
widget.setParent(None)
``` |
456cc39343ca4ce7a98e76adb2571030 | export interface AccessPointDialogData {
accessPoint: AccessPointDto;
ngGraceMode: NgGraceOptions;
dataTypeTemplate: DataTypeTemplatesDto | undefined;
}
export interface SubTableDescription {
id: string;
title: string;
}
@Component({
selector: 'app-access-point-dialog',
templateUrl: './access-point-dialog.component.html',
styleUrls: ['./access-point-dialog.component.scss'],
changeDetection: ChangeDetectionStrategy.OnPush
})
export class AccessPointDialogComponent extends DialogComponent<AccessPointDialogData> {
protected readonly addressTabName: SubTableDescription = {
id: 'address',
title: 'Address'
};
protected readonly servicesTabName: SubTableDescription = {
id: 'services',
title: 'Services'
};
protected readonly serverAtTabName: SubTableDescription = {
id: 'server_at',
title: 'Server At'
};
protected readonly gooseSeqTabName: SubTableDescription = {
id: 'goose_security',
title: 'Goose Security'
};
protected readonly smvSeqTabName: SubTableDescription = {
id: 'smv_security',
title: 'SMV Security'
};
protected readonly parametersList = [
this.addressTabName,
this.servicesTabName,
this.serverAtTabName,
this.gooseSeqTabName,
this.smvSeqTabName
];
protected readonly selectedLibrary$ = new BehaviorSubject<SubTableDescription>(this.parametersList[0]);
protected readonly headerLabel$ = new BehaviorSubject<string | undefined>(undefined);
@Output()
protected readonly form: FormGroup = new FormGroup({});
protected readonly readOnly: boolean;
protected readonly accessPoint: AccessPointDto;
protected apName: string;
constructor(dialogRef: DialogRef<AccessPointDialogData>, @Inject(DIALOG_DATA) data: AccessPointDialogData) {
super(dialogRef, data);
this.readOnly = data.ngGraceMode.disableEditing;
this.accessPoint = data.accessPoint;
this.apName = this.accessPoint.name;
this.headerLabel$.next(this.apHeader());
const dataTypeTemplate = data.dataTypeTemplate;
if (this.accessPoint.connectedAP.address.p.length === 0 && dataTypeTemplate) {
this.accessPoint.connectedAP.address = LogicLibraryTemplateBuilder.buildAddress(
dataTypeTemplate.id,
'ConnectedAP'
);
}
if (this.accessPoint.services == undefined && dataTypeTemplate) {
this.accessPoint.services = LogicLibraryTemplateBuilder.buildAccessPointService(dataTypeTemplate);
}
this.addControlsToForm();
}
onAddressChanged(newAddress: AddressDto): void {
this.accessPoint.connectedAP.address = newAddress;
}
override onSubmit(): void {
this.setDataFromForm();
super.onSubmit();
}
override onCancel(): void {
super.onCancel();
}
private addControlsToForm(): void {
this.form.addControl(
'name',
new FormControl({ value: this.accessPoint.name, disabled: this.readOnly }, [Validators.required])
);
this.form.addControl('description', new FormControl({ value: this.accessPoint.desc, disabled: this.readOnly }));
this.form.addControl('router', new FormControl({ value: this.accessPoint.router, disabled: this.readOnly }));
this.form.addControl('clock', new FormControl({ value: this.accessPoint.clock, disabled: this.readOnly }));
this.form.addControl('kdc', new FormControl({ value: this.accessPoint.kdc, disabled: this.readOnly }));
}
private apHeader(): string {
return 'ะะฐัะฐะผะตััั ัะพัะบะธ ะดะพัััะฟะฐ: '.concat(this.apName);
}
private setDataFromForm(): void {
this.accessPoint.name = this.form.controls.name.value;
this.accessPoint.desc = this.form.controls.description.value;
this.accessPoint.router = this.form.controls.router.value;
this.accessPoint.clock = this.form.controls.clock.value;
this.accessPoint.kdc = this.form.controls.kdc.value;
}
protected apNameChange(newName: any): void {
this.apName = newName.target.value;
this.headerLabel$.next(this.apHeader());
}
}
<app-address
*ngIf="panel.id === 'address'"
[address]="accessPoint.connectedAP.address"
[readOnly]="readOnly"
[inputForm]="form"
[macRequired]="false"
[ipRequired]="true"
(addressChanged)="onAddressChanged($event)"></app-address>
export interface AddressType {
name: string;
description: {
RU: string;
EN: string;
};
pattern: string;
hint: string;
}
export interface PExt {
originalP: PDto;
possibleTypes: BehaviorSubject<SelectModel<string>[]>;
typeFormControl: FormControl<string | null | undefined>;
valueFormControl: FormControl<string | null | undefined>;
}
@Component({
selector: 'app-address',
templateUrl: './address.component.html',
styleUrls: ['./address.component.scss'],
changeDetection: ChangeDetectionStrategy.OnPush
})
export class AddressComponent implements OnChanges, OnInit, OnDestroy {
@Input()
address?: AddressDto;
@Input()
readOnly = false;
@Input()
inputForm?: FormGroup;
@Input()
macRequired = false;
@Input()
ipRequired = false;
@Output() readonly addressChanged = new EventEmitter<AddressDto>();
protected readonly tableColumns = ['type', 'deviceDescription', 'value'].map(t => ({ title: t }));
protected readonly pTypeEnumValueMap = (option: string): string => option;
protected readonly pTypeEnumOptionMap = (option: string): string => option;
protected readonly addressTypes = AddressTypesMock as AddressType[];
protected readonly p$ = new BehaviorSubject<PExt[]>([]);
protected readonly lastPControl = new FormControl({ value: false, disabled: this.readOnly }, Validators.requiredTrue);
protected pTypes = this.preparePTypesSelectModel(
['-'].concat(Object.values(AddressTypeEnum).sort((one, two) => one.localeCompare(two)))
);
protected possibleSelectsOf(pExt: PExt): SelectModel<string>[] {
const usedTypes = this.p$.value
.filter(p => p != pExt)
.map(p => p.typeFormControl.value)
.filter(type => type != '-');
return this.pTypes.filter(p => !usedTypes.includes(p.data));
}
get form(): FormGroup {
if (!this.inputForm) {
throw new Error('Form group is undefined');
}
return this.inputForm;
}
private subscription: Subscription | undefined = undefined;
ngOnChanges(changes: SimpleChanges): void {
this.address = changes.address.currentValue as AddressDto;
this.prepareDefaultPType();
if (this.address) {
this.p$.next(this.preparePExt(this.address.p));
}
this.lastPControl.setValue(this.p$.value.find(p => p.typeFormControl.value !== '-') !== undefined);
this.form.addControl('lastPControl', this.lastPControl);
this.setDataFromForm();
}
ngOnInit(): void {
if (this.inputForm) {
this.subscription = this.inputForm.valueChanges.subscribe(() => {
this.setDataFromForm();
});
}
}
private prepareDefaultPType(): void {
if (this.macRequired) {
this.createDefaultP('MAC-Address', '01:0C:CD:01:00:00');
} else if (this.ipRequired) {
this.createDefaultP('IP', '192.168.1.1');
}
}
private createDefaultP(type: string, value: string): void {
if (this.address) {
if (this.address.p.find(p => p.type === type) === undefined) {
this.address.p.push({
id: uuid.v4(),
type: type,
value: value
});
}
}
}
private preparePTypesSelectModel(pTypes: string[]): SelectModel<string>[] {
return [
...pTypes.map(enumValue => ({
data: enumValue,
selected: false,
isDeleting: false,
disabled: false
}))
];
}
private preparePExt(pDto: PDto[]): PExt[] {
const pExtList = pDto.map(p => this.createPExt(p));
pExtList.forEach(p => p.possibleTypes.next(this.possibleSelectsOf(p)));
return pExtList;
}
private createPExt(p: PDto): PExt {
const { id } = p;
const isMacAddress = p.type == 'MAC-Address';
const isMacSource = p.type == 'MAC-Source';
const isIp = p.type == 'IP';
const disabledIp = this.readOnly || isIp;
const disabledMacAddress = this.readOnly || isMacAddress;
if (isMacAddress || isMacSource) {
p.value = p.value?.replaceAll('-', ':');
p.value = p.value?.toUpperCase();
}
const typeFormControl = new FormControl({
value: p.type,
disabled: this.macRequired ? disabledMacAddress : disabledIp
});
const valueFormControl = new FormControl({ value: p.value, disabled: this.readOnly }, [
Validators.required,
Validators.pattern(this.getPattern(p.type))
]);
this.form.addControl(id.concat('_type'), typeFormControl);
this.form.addControl(id.concat('_value'), valueFormControl);
return {
originalP: p,
possibleTypes: new BehaviorSubject<SelectModel<string>[]>([]),
typeFormControl: typeFormControl,
valueFormControl: valueFormControl
};
}
private getPattern(pType: string | undefined): string {
return this.addressTypes.find(p => p.name === pType)?.pattern ?? ' ';
}
setDataFromForm(): void {
if (this.address) {
this.address.p = this.p$.value
.filter(pExt => pExt.typeFormControl.value !== '-')
.map(pExt => this.saveParametersFromExtensionToOriginal(pExt));
this.addressChanged.emit(this.address);
}
}
private saveParametersFromExtensionToOriginal(pExt: PExt): PDto {
const pOriginal = pExt.originalP;
pOriginal.value = pExt.valueFormControl.value!;
return pOriginal;
}
protected removeP(pList: PExt[], p: PExt): void {
if (pList.length > 1) {
const index = pList.indexOf(p, 0);
if (index > -1) {
pList.splice(index, 1);
const { id } = p.originalP;
this.form.removeControl(id.concat('_type'));
this.form.removeControl(id.concat('_value'));
}
}
this.lastPControl.setValue(this.p$.value.find(p => p.typeFormControl.value !== '-') !== undefined);
this.p$.value.forEach(p => p.possibleTypes.next(this.possibleSelectsOf(p)));
}
protected addNewP(pList: PExt[], index: number): void {
const pInstance = this.createPExt({
id: uuid.v4(),
type: '-',
value: ''
});
pInstance.possibleTypes.next(this.possibleSelectsOf(pInstance));
pInstance.valueFormControl.disable();
pList.splice(index + 1, 0, pInstance);
this.lastPControl.setValue(this.p$.value.find(p => p.typeFormControl.value !== '-') !== undefined);
this.p$.value.forEach(p => p.possibleTypes.next(this.possibleSelectsOf(p)));
}
protected pTypeChange(p: PExt): void {
p.originalP = {
id: uuid.v4(),
type: p.typeFormControl.value!,
value: ''
};
p.typeFormControl.setValue(p.typeFormControl.value);
p.valueFormControl.setValue('');
p.valueFormControl.setValidators([
Validators.required,
Validators.pattern(this.getPattern(p.typeFormControl.value!))
]);
if (p.typeFormControl.value == '-') {
p.valueFormControl.disable();
} else {
p.valueFormControl.enable();
}
this.lastPControl.setValue(this.p$.value.find(p => p.typeFormControl.value !== '-') !== undefined);
this.p$.value.forEach(p => p.possibleTypes.next(this.possibleSelectsOf(p)));
}
protected getPDescription(pType: string): string {
return this.addressTypes.find(p => p.name === pType)?.description.RU ?? '';
}
protected sortingDrop(event: CdkDragDrop<any, any>, p: PExt[]): void {
moveItemInArray(p, event.previousIndex, event.currentIndex);
}
protected removeButtonValidity(p: PExt): boolean {
let disable = false;
if (this.macRequired) {
disable = p.typeFormControl.value === 'MAC-Address';
} else if (this.ipRequired) {
disable = p.typeFormControl.value === 'IP';
}
return disable;
}
dashChangeToColon(p: PExt): void {
if (p.typeFormControl.value == 'MAC-Address' || p.typeFormControl.value == 'MAC-Source') {
const macAddress = document.getElementById(p.typeFormControl.value);
const macAddressNode = macAddress?.childNodes[1].childNodes[0];
if (macAddressNode) {
const mac = macAddressNode as HTMLInputElement;
p.valueFormControl.setValue(mac.value.replaceAll('-', ':'));
p.valueFormControl.setValue(mac.value.toUpperCase());
}
}
}
valuePatternHint(p: PExt): string {
const hint = this.addressTypes.find(address => p.typeFormControl.value === address.name)?.hint;
return `ะคะพัะผะฐั: ${hint}`;
}
ngOnDestroy(): void {
if (this.subscription) {
this.subscription.unsubscribe();
}
}
}
ั ะผะตะฝั ะตััั ะบะพะผะฟะพะฝะตะฝั AccessPoint. ะะฝัััะธ ะตะณะพ ัะฐะฑะปะพะฝะฐ ะฒัะทัะฒะฐะตััั Address ะบะพะผะฟะพะฝะตะฝั. ะฃ ะผะตะฝั ะตััั input ะธ output ะฐ ัะฐะบ ะถะต ั ัะดะตะปะฐะป ะฟะพะดะฟะธัะบั ะฝะฐ ะธะทะผะตะฝะตะฝะธะต ัะพัะผั, ััะพะฑั ะฟะตัะตะดะฐะฒะฐัั ะดะฐะฝะฝัะต ะพะฑัะฐัะฝะพ ะฒ ัะพะดะธัะตะปััะบะธะน ะบะพะผะฟะพะฝะตะฝั. ะะพ ัะพัะผะฐ ะผะตะฝัะตััั ัะปะธัะบะพะผ ัะฐััะพ, ะธ ะฟะตัะตะดะฐะฒะฐัั ะดะฐะฝะฝัะต ะบะฐะถะดัะน ัะฐะท ะตะผะบะพ. ะะฐะบ ะฟะตัะตะดะฐะฒะฐัั ะดะฐะฝะฝัะต ะธะท ัะพัะผั, ะฐ ะฟะพัะพะผ ัะตะฐะบัะธะฒะฝะพ ะฒ ัะพะดะธัะตะปััะบะธะน ะบะพะผะฟะพะฝะตะฝั ะฟัะธ ะทะฐะบัััะธะธ ะบะพะผะฟะพะฝะตะฝัะฐ AccessPoint onSubmit? |
b27bb326f8a44e04b7254e326ea3822a | import React, { useState, useEffect } from "react";
import image from "../assets/react.svg";
import SearchIcon from "@mui/icons-material/Search";
import FavoriteIcon from "@mui/icons-material/Favorite";
import axios from 'axios';
function Books() {
const [books, setBooks] = useState([]);
const [searchQuery, setSearchQuery] = useState("");
const [currentPage, setCurrentPage] = useState(1);
const [selectedDepartment, setSelectedDepartment] = useState("All");
const [selectedBook, setSelectedBook] = useState(null);
const booksPerPage = 20;
useEffect(() => {
const getBooks = async () => {
try {
const res = await axios.get('http://localhost:3000/books');
setBooks(res.data);
} catch (error) {
console.log('Error', error);
}
};
getBooks();
}, []);
const handleFavoriteClick = (bookId) => {
const updatedBooks = books.map(book =>
book._id === bookId ? { ...book, isFavorite: !book.isFavorite } : book
);
setBooks(updatedBooks);
};
useEffect(() => {
setCurrentPage(1);
}, [searchQuery, selectedDepartment]);
const filterBooks = () => {
return books.filter(
(book) =>
(selectedDepartment === "All" ||
book.department === selectedDepartment) &&
book.title.toLowerCase().includes(searchQuery.toLowerCase())
);
};
const handleBookClick = (book) => {
setSelectedBook(book);
};
const handleCloseModal = () => {
setSelectedBook(null);
};
const filteredBooks = filterBooks();
// Calculate the books to be displayed on the current page
const indexOfLastBook = currentPage * booksPerPage;
const indexOfFirstBook = indexOfLastBook - booksPerPage;
const currentBooks = filteredBooks.slice(indexOfFirstBook, indexOfLastBook);
const totalPages = Math.ceil(filteredBooks.length / booksPerPage);
const handlePageChange = (event) => {
const pageNumber = Number(event.target.value);
if (pageNumber >= 1 && pageNumber <= totalPages) {
setCurrentPage(pageNumber);
}
};
const goToNextPage = () => {
if (currentPage < totalPages) {
setCurrentPage(currentPage + 1);
}
};
const goToPrevPage = () => {
if (currentPage > 1) {
setCurrentPage(currentPage - 1);
}
};
return (
<div>
<div className="flex items-center justify-between p-3">
<div className="relative w-3/4 sm:w-1/2 p-2">
<input
type="text"
placeholder="Start Searching..."
className="search-bar text-black"
value={searchQuery}
onChange={(e) => setSearchQuery(e.target.value)}
/>
<SearchIcon className="search-icon" />
</div>
<div className="dropdown dropdown-end">
<div
tabIndex={0}
role="button"
className="btn btn-ghost btn-circle avatar"
>
<div className="w-10 rounded-full">
<img
alt="component"
src="https://img.daisyui.com/images/stock/photo-1534528741775-53994a69daeb.jpg"
/>
</div>
</div>
<ul
tabIndex={0}
className="mt-3 z-[1] p-2 shadow menu menu-sm dropdown-content bg-white text-black rounded-box w-52"
>
<li>
<a className="justify-between">Account</a>
</li>
<li>
<a>Settings</a>
</li>
<li>
<a>Logout</a>
</li>
</ul>
</div>
</div>
<div className="flex flex-wrap ml-5 mb-6">
{[
"All",
"Computer Science",
"Electrical Engineering",
"Mechanical Engineering",
"Chemical Engineering",
"Civil Engineering",
"Engineering Physics",
].map((department) => (
<span
key={department}
className={`inline-block px-3 py-1.5 mb-2 mr-2 bg-gray-100 rounded-sm text-black text-sm cursor-pointer leading-4 ${selectedDepartment === department
? "selected bg-gray-600 text-white transition ease-in-out delay-30 -translate-y-0.5 scale-10 duration-150 shadow-md shadow-slate-400 "
: " "
}`}
onClick={() => setSelectedDepartment(department)}
>
{department}
</span>
))}
</div>
<div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 gap-4">
{currentBooks.map((book) => (
<div key={book._id} className="p-4 rounded-md">
<button
type="button"
className="w-full object-cover"
onClick={() => handleBookClick(book)}
>
<img
src={image}
alt={book.title}
className="w-full object-cover"
/>
</button>
<h3 className="text-center mt-2 text-sm truncate">{book.title}</h3>
<div className="flex items-center">
<button
type="button"
className="borrow-button transition duration-150 ease-in-out hover:border-neutral-800 hover:bg-neutral-100 hover:text-white focus:border-neutral-800 focus:bg-neutral-100 focus:text-white focus:ring-0 active:border-neutral-900 active:text-neutral-900 motion-reduce:transition-none dark:text-neutral-600 dark:hover:bg-neutral-900 dark:focus:bg-neutral-900"
data-twe-ripple-init
>
Borrow
</button>
<FavoriteIcon
className={`ml-3 mt-2 cursor-pointer ${book.isFavorite ? "text-red-500" : "text-gray-400"
}`}
onClick={() => handleFavoriteClick(book._id)}
style={{ transition: "color 0.3s" }}
/>
</div>
</div>
))}
</div>
<div className="pagination">
<div className="inline-flex gap-6 bg-slate-100 rounded-md">
<button onClick={goToPrevPage} disabled={currentPage === 1}>
<span className="sr-only">Prev Page</span>
<svg xmlns="http://www.w3.org/2000/svg" className="h-6 w-6" viewBox="0 0 20 20" fill="currentColor">
<path
fillRule="evenodd"
d="M12.707 5.293a1 1 0 010 1.414L9.414 10l3.293 3.293a1 1 0 01-1.414 1.414l-4-4a1 1 0 010-1.414l4-4a1 1 0 011.414 0z"
clipRule="evenodd"
/>
</svg>
</button>
<div>
<label htmlFor="PaginationPage" className="sr-only">
Page
</label>
<input
type="number"
className="h-8 w-12 rounded border border-gray-900 bg-white p-0 text-center text-xl font-bold text-gray-900 [-moz-appearance:_textfield] [&::-webkit-inner-spin-button]:m-0 [&::-webkit-inner-spin-button]:appearance-none [&::-webkit-outer-spin-button]:m-0 [&::-webkit-outer-spin-button]:appearance-none focus:outline-none"
min="1"
max={totalPages}
value={currentPage}
onChange={handlePageChange}
id="PaginationPage"
/>
</div>
<button onClick={goToNextPage} disabled={currentPage === totalPages}>
<span className="sr-only">Next Page</span>
<svg
xmlns="http://www.w3.org/2000/svg"
className="h-6 w-6"
viewBox="0 0 20 20"
fill="currentColor"
>
<path
fillRule="evenodd"
d="M7.293 14.707a1 1 0 010-1.414L10.586 10 7.293 6.707a1 1 0 011.414-1.414l4 4a1 1 0 010 1.414l-4 4a1 1 0 01-1.414 0z"
clipRule="evenodd"
/>
</svg>
</button>
</div>
</div>
{selectedBook && (
<div className="fixed inset-0 z-50 flex items-center justify-center backdrop-blur-md">
<div className="bg-slate-100 p-4 w-3/4 h-3/4 rounded-md relative flex flex-col lg:flex-row">
<button
className="absolute text-3xl top-1 right-3 text-gray-600 hover:text-black"
onClick={handleCloseModal}
>
×
</button>
<img
src={image}
alt={selectedBook.title}
className="size-1/3 lg:w-1/3 h-auto mx-auto lg:mx-0 lg:mr-4"
/>
<div className="mt-4 lg:pb-40 lg:pl-14 flex flex-col justify-center">
<h2 className="text-center lg:text-left font-semibold lg:font-bold text-xl lg:text-3xl text-black">
{selectedBook.title}
</h2>
<p className="text-left mt-2 text-md lg:text-xl text-black">
<span className="text-black font-medium">Author:</span>{" "}
{selectedBook.author}
</p>
<p className="text-left mt-2 text-md lg:text-xl text-black">
<span className="text-black font-medium">Description:</span>{" "}
{selectedBook.description}
</p>
<p className="text-left mt-2 text-md lg:text-xl text-black">
<span className="text-black font-medium">Department:</span>{" "}
{selectedBook.department}
</p>
<p className="text-left mt-2 text-md lg:text-xl text-black">
<span className="text-black font-medium">Genre:</span>{" "}
{selectedBook.genre}
</p>
<p className="text-left mt-2 text-md lg:text-xl text-black">
<span className="text-black font-medium">Publisher:</span>{" "}
{selectedBook.publisher}
</p>
<div className="w-1/2 pt-12">
<button
type="button"
className="borrow-button transition duration-150 ease-in-out hover:border-neutral-800 hover:bg-neutral-100 hover:text-white focus:border-neutral-800 focus:bg-neutral-100 focus:text-white focus:ring-0 active:border-neutral-900 active:text-neutral-900 motion-reduce:transition-none dark:text-neutral-600 dark:hover:bg-neutral-900 dark:focus:bg-neutral-900"
data-twe-ripple-init
>
Borrow
</button>
<FavoriteIcon
className={`ml-2 0 mb-1 cursor-pointer ${selectedBook.isFavorite ? "text-red-500" : "text-gray-400"
}`}
onClick={() =>
handleFavoriteClick(selectedBook._id)
}
style={{ transition: "color 0.3s" }}
/>
</div>
</div>
</div>
</div>
)}
</div>
);
}
export default Books;
when click favorite icon it will add to favorite table
import React from "react";
import { BarChart } from "@mui/x-charts/BarChart";
import { PieChart } from "@mui/x-charts/PieChart";
function Status() {
const borrowedBooks = [
{ title: "Book 1", author: "Author 1", dueDate: "2022-01-01" },
{ title: "Book 2", author: "Author 2", dueDate: "2022-01-01" },
];
const borrowingHistory = [
{ title: "Book 1", author: "Author 1", Status: "Pending", Actions: "Cancel Request" },
{ title: "Book 2", author: "Author 2", Status: "Pending", Actions: "Cancel Request" },
];
const favoriteBooks = [
{ title: "Book 3", author: "Author 3" },
{ title: "Book 4", author: "Author 4" },
];
return (
<div className="w-full">
<div className="mb-10">
<h2 className="text-3xl font-semibold mb-4 border-b pb-2 text-slate-800">Book Request</h2>
<table className="w-full table-auto bg-white shadow-md rounded">
<thead>
<tr className="bg-gray-200">
<th className="p-4 text-center text-slate-600">Book Title</th>
<th className="p-4 text-center text-slate-600">Author</th>
<th className="p-4 text-center text-slate-600">Status</th>
<th className="p-4 text-center text-slate-600">Actions</th>
</tr>
</thead>
<tbody>
{borrowingHistory.map((book, index) => (
<tr key={index} className="border-t hover:bg-gray-100">
<td className="p-4 text-center text-gray-600">{book.title}</td>
<td className="p-4 text-center text-gray-600">{book.author}</td>
<td className="p-4 text-center text-gray-600">{book.Status}</td>
<td className="p-4 text-center text-red-600 cursor-pointer">{book.Actions}</td>
</tr>
))}
</tbody>
</table>
</div>
<div className="flex mb-10">
<div className="w-3/5 pr-4">
<h2 className="text-2xl font-semibold mb-4 border-b pb-2 text-slate-800">Borrowed Books</h2>
<table className="w-full table-auto bg-white shadow-md rounded">
<thead>
<tr className="bg-gray-200">
<th className="p-4 text-center text-slate-600">Book Title</th>
<th className="p-4 text-center text-slate-600">Author</th>
<th className="p-4 text-center text-slate-600">Due Date</th>
</tr>
</thead>
<tbody>
{borrowedBooks.map((book, index) => (
<tr key={index} className="border-t hover:bg-gray-100">
<td className="p-4 text-center text-gray-600">{book.title}</td>
<td className="p-4 text-center text-gray-600">{book.author}</td>
<td className="p-4 text-center text-gray-600">{book.dueDate}</td>
</tr>
))}
</tbody>
</table>
</div>
<PieChart
series={[
{
data: [
{ id: 0, value: 10, label: "Returned" },
{ id: 1, value: 3, label: "Not Returned" },
],
},
]}
width={500}
height={300}
/>
</div>
<div className="flex mb-10">
<BarChart
xAxis={[
{
scaleType: "band",
data: ["group A", "group B", "group C"],
},
]}
series={[
{ data: [4, 3, 5] },
{ data: [1, 6, 3] },
{ data: [2, 5, 6] },
]}
width={400}
height={250}
/>
<div className="w-3/4 pr-4">
<h2 className="text-2xl font-semibold mb-4 border-b pb-2 text-slate-800">My Favorite Books</h2>
<table className="w-full table-auto bg-white shadow-md rounded">
<thead>
<tr className="bg-gray-200">
<th className="p-4 text-center text-slate-600">Book Title</th>
<th className="p-4 text-center text-slate-600">Author</th>
</tr>
</thead>
<tbody>
{favoriteBooks.map((book, index) => (
<tr key={index} className="border-t hover:bg-gray-100">
<td className="p-4 text-center text-gray-600">{book.title}</td>
<td className="p-4 text-center text-gray-600">{book.author}</td>
</tr>
))}
</tbody>
</table>
</div>
</div>
</div>
);
}
export default Status; |
0efc35f6c35e491094c8f399a2520944 | Use the learning objective table at the bottom to align the questions below to the appropriate learning objective(s). Put the results in a table.
Q1: Which functional group is most likely to be polar uncharged under normal cellular conditions? a) Hydroxyl group (-OH) b) Carboxyl group (-COOH) c) Amino group (-NH2) d) Sulfhydryl group (-SH)
Q2: Insulin is a protein produced by cells in the pancreas. If you wanted to permanently change just one amino acid in insulin, what would you need to alter? a) The mRNA sequence coding for insulin b) The tRNA molecules used during translation c) The DNA sequence of the insulin gene d) The ribosomes that synthesize insulin
Learning Objective Table:
Day Designation Objective Code Learning Objective
Day 001: Scientific argumentation and cell model 1.1 Describe your current understanding of how cells work
Day 001: Scientific argumentation and cell model 1.2 Describe the claim-evidence-reasoning (CER) framework and use to make scientific arguments
Day 001: Scientific argumentation and cell model 1.3 Create a concrete plan for your success in BS161
Day 002: Covalent Bonds and Intermolecular Forces 2.1 Compare and contrast covalent bonds and intermolecular forces
Day 002: Covalent Bonds and Intermolecular Forces 2.2 Describe intermolecular forces and their relative strength in aqueous environments
Day 002: Covalent Bonds and Intermolecular Forces 2.3 Given the names or structures of two functional groups, predict the most relevant intermolecular force between them
Day 002: Covalent Bonds and Intermolecular Forces 2.4 Describe one way that you can observe intermolecular forces in your daily life
Day 003: Introduction to Macromolecules 3.1 Identify types of macromolecules and their monomers based on molecular structures
Day 003: Introduction to Macromolecules 3.2 Predict macromolecular shapes and interactions based on molecular structure
Day 003: Introduction to Macromolecules 3.3 Explain the relationship between a molecule's structure and its function in the cell
Day 004: Gene Expression I 4.1 Describe the outcome of gene expression and explain how this relates to cell function
Day 004: Gene Expression I 4.2 Interpret the experimental evidence that identified DNA as the genetic material
Day 004: Gene Expression I 4.3 Describe key features of DNA structure and RNA structure important for the storage and transfer of genetic information
Day 004: Gene Expression I 4.4 Use a model to describe the process of transcription
Day 005: Gene Expression II 5.1 Predict the sequence of an mRNA produced by transcription from a gene diagram and sequence
Day 005: Gene Expression II 5.2 Predict the sequence of a protein produced by translation from a gene diagram/sequence
Day 005: Gene Expression II 5.3 Use a model to describe the process of translation
Day 005: Gene Expression II 5.4 Use a model to explain the overall process of how a cell uses genetic information (DNA) to produce proteins
Day 006: Chromosome Connections Gene Expression and Protein Structure 6.1 Explain how a protein's primary structure is related to its tertiary structure
Day 006: Chromosome Connections Gene Expression and Protein Structure 6.2 Develop a model to show the flow of information in gene expression
Day 006: Chromosome Connections Gene Expression and Protein Structure 6.3 Use your model to explain the flow of information and how different genes produce different proteins
Day 006: Chromosome Connections Gene Expression and Protein Structure 6.4 Explain how a change in a gene can lead to a change in protein function and potentially a disease
Day 007: Model of protein engineering 7.1 Predict amino acids that could interact favorably to create a protein's tertiary structure
Day 007: Model of protein engineering 7.2 Predict amino acids in a binding site that could interact favorably with a specific substrate molecule
Day 007: Model of protein engineering 7.3 Use a model to explain how a change in the tertiary structure of a protein could lead to a different function
Day 008: Exam I 8.1 Recall information on molecular interactions, macromolecules, transcription, and translation
Day 008: Exam I 8.2 Test your mastery of the material covered up to Exam I
Day 008: Exam I 8.3 Refine your plan for success in BS161
Day 009: Bioenergetics and Enzymes 9.1 Use principles of equilibrium to explain the difference between energetically favorable versus energetically unfavorable processes
Day 009: Bioenergetics and Enzymes 9.2 Explain how cells use ATP to drive processes that would otherwise be energetically unfavorable
Day 009: Bioenergetics and Enzymes 9.3 Use a model to explain the role of enzymes in the rate and specificity of favorable chemical reactions
Day 010: Membranes, Compartments, and Transport 10.1 Use the structure and properties of membrane lipids to develop a model of how and why membranes form and use this model to explain:
Day 010: Membranes, Compartments, and Transport 10.1.1 how and why changes in membrane components and/or temperatures affect membrane fluidity
Day 010: Membranes, Compartments, and Transport 10.1.2 what allows membranes to be selectively permeable and why this is important for cellular function
Day 010: Membranes, Compartments, and Transport 10.2 Compare and contrast cellular organization of prokaryotic and eukaryotic cells. Explain why compartmentalization is advantageous for eukaryotic cells.
Day 010: Membranes, Compartments, and Transport 10.3 Based on the properties of a given solute and concentration gradients, predict the type of transport required to move that solute across a membrane
Day 010: Membranes, Compartments, and Transport 10.4 Construct a model to show solutes, concentration gradients, and transporter proteins in a membrane. Use this model to explain how cells use energetic coupling to transport solutes across membranes and why this is important for cellular function
Day 011: Introduction to Energy Metabolism 11.1 Compare and contrast anabolic and catabolic pathways
Day 011: Introduction to Energy Metabolism 11.2 Explain how cells create conditions to couple favorable processes with unfavorable processes and why this is required in metabolic pathways
Day 011: Introduction to Energy Metabolism 11.3 Explain how the same enzyme would catalyze a reaction in opposite directions in different cell types or cell compartments
Day 012: Cellular Respiration 12.1 Describe the principles of cellular respiration, including the transformations of energy and matter that occur in the process
Day 012: Cellular Respiration 12.2 Explain why respiration generates more ATP than fermentation, and why cells produce more ATP from the metabolism of fats compared to the metabolism of sugars
Day 012: Cellular Respiration 12.3 Use a model of cellular respiration to explain how changes to metabolic substrate or product concentrations in one part of the process affect other parts of the process
Day 012: Cellular Respiration 12.4 Use a model of cellular respiration to predict how cellular respiration is affected by mutations in genes encoding cellular respiration proteins or by chemicals
Day 013: Photosynthesis 13.1 Describe the principles of photosynthesis, including the transformations of energy and matter that occur in the process
Day 013: Photosynthesis 13.2 Use a model to explain how changes to metabolic substrate or product concentrations in one part of the process affect other parts of the process
Day 013: Photosynthesis 13.3 Use a model of photosynthesis to predict how photosynthesis is affected by mutations in genes encoding photosynthesis proteins or chemicals
Day 013: Photosynthesis 13.4 Use a model of photosynthesis to explain the connections between photosynthesis and respiration in a plant cell
Day 014: Model of Energy and Matter Transformations 14.1 Use a model to compare and contrast metabolic pathways
Day 014: Model of Energy and Matter Transformations 14.2 Analyze data to formulate hypotheses about metabolic pathways
Day 014: Model of Energy and Matter Transformations 14.3 Use a model to show the connections between photosynthesis in plants and respiration within plant cells and between plants and non-photosynthetic organisms
Day 014: Model of Energy and Matter Transformations 14.4 Use a model to make predictions about the relationship between mutations in genes encoding metabolic enzymes and metabolic pathways
Day 015: Exam II 15.1 Recall information on bioenergetics, membranes and membrane transport, cellular structures, and metabolism
Day 015: Exam II 15.2 Test your mastery of the material covered up to Exam II
Day 015: Exam II 15.3 Refine your plan for success in BS161
Day 016: Cell Communication 16.1 Use the components of signaling pathways to explain why different cells respond differently to the environment
Day 016: Cell Communication 16.2 Explain how the following receptor signaling pathways are activated and terminated: receptor kinase, intracellular receptor, G protein-coupled receptor, and ligand-gated ion channel
Day 016: Cell Communication 16.3 Explain how signal transduction components allow for signal amplification and multiple levels of control, and why this is advantageous to cells
Day 016: Cell Communication 16.4 Using a model of a signal transduction pathway, predict how changes in signaling components will impact cellular responses
Day 017: Cell Cycle: Activity on DNA replication and mitosis (Chromosome Connections Model of DNA Replication, Model of Mitosis) 17.1 List the major phases of the cell cycle and identify key events and features of each phase
Day 017: Cell Cycle: Activity on DNA replication and mitosis (Chromosome Connections Model of DNA Replication, Model of Mitosis) 17.2 Create a model to show how chromosomes with specific genes and sequences change during DNA replication. Use the model to support explanations regarding gene expression
Day 017: Cell Cycle: Activity on DNA replication and mitosis (Chromosome Connections Model of DNA Replication, Model of Mitosis) 17.3 Create a model to show how chromosomes with sister chromatids containing specific genes and sequences are divided during mitosis. Use the model to support explanations of how genetically identical daughter cells are created
Day 017: Cell Cycle: Activity on DNA replication and mitosis (Chromosome Connections Model of DNA Replication, Model of Mitosis) 17.4 Using your models, explain how DNA amount varies across cell cycle stages and relate to DNA synthesis and changes in the mitotic spindle
Day 018: Cell Cycle Regulation 18.1 Use models to explain the roles of cyclins, CDKs and checkpoints in cell cycle control, including mechanisms of how cell cycle regulators are activated or inactivated
Day 018: Cell Cycle Regulation 18.2 Define oncogene and tumor suppressor in terms of their effects on the cell cycle and identify proteins as either oncogenic or anti-tumor in function
Day 018: Cell Cycle Regulation 18.3 Predict how alterations of the processes involved in the cell cycle will impact the cell
Day 019: DNA Replication 19.1 Describe the extracellular and intracellular requirements for DNA replication and identify when DNA replication occurs in the cell cycle
Day 019: DNA Replication 19.2 Construct models to demonstrate the process and outcome of DNA replication
Day 019: DNA Replication 19.3 Use a model of DNA replication to explain why continuous synthesis of both DNA strands is not possible
Day 020: Ras and cancer model 20.1 Use a model of Ras signaling to explain how and why a specific Ras mutation is associated with cancer
Day 020: Ras and cancer model 20.2 Use a model of Ras signaling and your knowledge of the Ras signaling pathway to propose other drug targets that might block the abnormal cell division caused by mutations to Ras.
Day 020: Ras and cancer model 20.3 Use a model of Ras signaling and your knowledge of cell cycle regulation to predict how a specific mutation or drug that binds to a protein in the Ras pathway would impact signaling, cyclins, and cell division
Day 021: Exam III 21.1 Recall information on cell communication, cell division, and DNA replication
Day 021: Exam III 21.2 Test your mastery of the material covered up to Exam III
Day 021: Exam III 21.3 Refine your plan for success in BS161
Day 022: Regulation of Gene Expression I 22.1 Explain what it means for a gene to be 'expressed'
Day 022: Regulation of Gene Expression I 22.2 Use a model to explain the role of DNA sequences, DNA-binding proteins (transcription factors), and their interactions in controlling gene expression.
Day 022: Regulation of Gene Expression I 22.3 Explain the role of epigenetic modifications in the regulation of gene expression.
Day 022: Regulation of Gene Expression I 22.4 Use a model to explain how differences in gene expression account for the diverse cell types present in multicellular organisms.
Day 023: Regulation of Gene Expression II 23.1 Compare and contrast eukaryotic and prokaryotic gene expression
Day 023: Regulation of Gene Expression II 23.2 Use a model to explain how gene expression is affected by changing environmental conditions
Day 023: Regulation of Gene Expression II 23.3 Use a model to predict changes in gene expression resulting from mutations
Day 024: Model of gene regulation 24.1 Interpret data to formulate hypotheses about gene expression
Day 024: Model of gene regulation 24.2 Develop a model to show the role of specific proteins and DNA sequences in the regulation of gene expression under different cellular conditions
Day 024: Model of gene regulation 24.3 Use your model to predict how changes to gene coding or gene regulatory sequences will affect gene expression
Day 025: DNA Damage and Mutations 25.1 Explain why cells need DNA repair mechanisms and how unrepaired DNA damage affects the DNA of daughter cells
Day 025: DNA Damage and Mutations 25.2 Describe the general process to repair replication errors and DNA damage, including how the cell recognizes which nucleotide(s) to replace
Day 025: DNA Damage and Mutations 25.3 Predict if and how a mutation would affect protein-coding sequences in genes
Day 025: DNA Damage and Mutations 25.4 Predict the effect of a mutation on cellular function
Day 026: Alleles and Phenotypes (Chromosome Connections Model of Mutations and Phenotypes) 26.1 Distinguish between gene and allele and between genotype and phenotype
Day 026: Alleles and Phenotypes (Chromosome Connections Model of Mutations and Phenotypes) 26.2 Use a model of a gene to explain how different gene sequences (alleles, arising from mutations) encode mRNAs and proteins with different phenotypes and functions
Day 026: Alleles and Phenotypes (Chromosome Connections Model of Mutations and Phenotypes) 26.3 Use gene and protein structure models to explain how the presence of certain alleles (genotype) affects cell phenotypes
|
cff8b4ec57eb4b8fb24b2ec91b26321c | import sys
import os
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
from src.report_types import ReportTypes
from src.program_report_generator import ProgramCodeExtractor
from src.program_report_generator import MultiProgramReportGenerator
from processors.director_performance_graph import DirectorPerformanceGraphProcessor
from processors.director_summary_report import DirectorSummaryProcessor
from processors.director_report_3 import DirectorReport3Processor
from processors.director_report_2 import DirectorReport2Processor
from processors.director_report_1 import DirectorReport1Processor
from processors.resident_report_2 import ResidentReport2Processor
from processors.resident_report_1 import ResidentReport1Processor
from processors.director_graph import DirectorGraphProcessor
import logging
import argparse
from flask import Flask, render_template, request, redirect, url_for
app = Flask(__name__)
args = argparse.Namespace()
args.report_type = 'CHILD_PRITE'
processors = {
'resident_report_1': ResidentReport1Processor,
'resident_report_2': ResidentReport2Processor,
'director_report_1': DirectorReport1Processor,
'director_report_2': DirectorReport2Processor,
'director_report_3': DirectorReport3Processor,
'director_summary_report': DirectorSummaryProcessor,
'director_performance_graph': DirectorPerformanceGraphProcessor,
'director_graph': DirectorGraphProcessor
}
def load_processors():
for processor_name, processor_class in processors.items():
setattr(app, f'{processor_name}_processor', processor_class(args.report_type))
load_processors()
log = logging.getLogger('werkzeug')
log.setLevel(logging.ERROR)
@app.route("/")
def home():
return f"ยกWorking! report_type: {args.report_type}"
def route(path, template_name):
def decorator(processor_name):
def wrapper(program_code=None):
processor = getattr(app, f'{processor_name}_processor')
data = processor.reports(program_code) if program_code else processor.reports()
return render_template(template_name, **{processor_name: data})
return app.route(path)(wrapper)
return decorator
route('/resident_report_1/<program_code>', 'resident_report_1.html')('resident_report_1')
route('/resident_report_2/<program_code>', 'resident_report_2.html')('resident_report_2')
# ...
@app.route('/generate_reports', methods=['GET', 'POST'])
def generate_reports():
if request.method == 'POST':
options = {
'program_code': request.form.get('program_code'),
'default_type_reports': request.form.getlist('type_report'),
'should_replace_file': request.form.get('should_replace_file') == 'true',
'report_type': request.form['report_type']
}
pdf_generator = MultiProgramReportGenerator(options['report_type'])
pdf_generator.generate_reports_from_options(options)
return redirect(url_for('generate_reports', status='complete'))
# ...
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='Flask app to generate PDFs')
parser.add_argument('--report_type', type=str, help='Type of report', default='CHILD_PRITE')
args = parser.parse_args()
print(f"report_type: {args.report_type}")
app.run(debug=True, use_reloader=True)
โญโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ Traceback (most recent call last) โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโฎ
โ C:\Users\AndresG\Sites\scripts\reports\flask\app.py:57 in <module> โ
โ โ
โ 54 โ return decorator โ
โ 55 โ
โ 56 route('/resident_report_1/<program_code>', 'resident_report_1.html')('resident_report_1' โ
โ โฑ 57 route('/resident_report_2/<program_code>', 'resident_report_2.html')('resident_report_2' โ
โ 58 # ... โ
โ 59 โ
โ 60 @app.route('/generate_reports', methods=['GET', 'POST']) โ
โ โ
โ โญโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ locals โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโฎ โ
โ โ app = <Flask 'app'> โ โ
โ โ argparse = <module 'argparse' from โ โ
โ โ 'C:\\Python311\\Lib\\argparse.py'> โ โ
โ โ args = Namespace(report_type='CHILD_PRITE') โ โ
โ โ DirectorGraphProcessor = <class โ โ
โ โ 'processors.director_graph.DirectorGraphProcessor'> โ โ
โ โ DirectorPerformanceGraphProcessor = <class โ โ
โ โ 'processors.director_performance_graph.DirectorPerformaโฆ โ โ
โ โ DirectorReport1Processor = <class โ โ
โ โ 'processors.director_report_1.DirectorReport1Processor'> โ โ
โ โ DirectorReport2Processor = <class โ โ
โ โ 'processors.director_report_2.DirectorReport2Processor'> โ โ
โ โ DirectorReport3Processor = <class โ โ
โ โ 'processors.director_report_3.DirectorReport3Processor'> โ โ
โ โ DirectorSummaryProcessor = <class โ โ
โ โ 'processors.director_summary_report.DirectorSummaryProcโฆ โ โ
โ โ Flask = <class 'flask.app.Flask'> โ โ
โ โ home = <function home at 0x00000220DB913100> โ โ
โ โ load_processors = <function load_processors at 0x00000220DB305BC0> โ โ
โ โ log = <Logger werkzeug (ERROR)> โ โ
โ โ logging = <module 'logging' from โ โ
โ โ 'C:\\Python311\\Lib\\logging\\__init__.py'> โ โ
โ โ MultiProgramReportGenerator = <class โ โ
โ โ 'src.program_report_generator.MultiProgramReportGeneratโฆ โ โ
โ โ os = <module 'os' (frozen)> โ โ
โ โ processors = { โ โ
โ โ โ 'resident_report_1': <class โ โ
โ โ 'processors.resident_report_1.ResidentReport1Processor'โฆ โ โ
โ โ โ 'resident_report_2': <class โ โ
โ โ 'processors.resident_report_2.ResidentReport2Processor'โฆ โ โ
โ โ โ 'director_report_1': <class โ โ
โ โ 'processors.director_report_1.DirectorReport1Processor'โฆ โ โ
โ โ โ 'director_report_2': <class โ โ
โ โ 'processors.director_report_2.DirectorReport2Processor'โฆ โ โ
โ โ โ 'director_report_3': <class โ โ
โ โ 'processors.director_report_3.DirectorReport3Processor'โฆ โ โ
โ โ โ 'director_summary_report': <class โ โ
โ โ 'processors.director_summary_report.DirectorSummaryProcโฆ โ โ
โ โ โ 'director_performance_graph': <class โ โ
โ โ 'processors.director_performance_graph.DirectorPerformaโฆ โ โ
โ โ โ 'director_graph': <class โ โ
โ โ 'processors.director_graph.DirectorGraphProcessor'> โ โ
โ โ } โ โ
โ โ ProgramCodeExtractor = <class โ โ
โ โ 'src.program_report_generator.ProgramCodeExtractor'> โ โ
โ โ redirect = <function redirect at 0x00000220DB140720> โ โ
โ โ render_template = <function render_template at 0x00000220DB2A09A0> โ โ
โ โ ReportTypes = <class 'src.report_types.ReportTypes'> โ โ
โ โ request = <LocalProxy unbound> โ โ
โ โ ResidentReport1Processor = <class โ โ
โ โ 'processors.resident_report_1.ResidentReport1Processor'> โ โ
โ โ ResidentReport2Processor = <class โ โ
โ โ 'processors.resident_report_2.ResidentReport2Processor'> โ โ
โ โ route = <function route at 0x00000220DB912160> โ โ
โ โ sys = <module 'sys' (built-in)> โ โ
โ โ url_for = <function url_for at 0x00000220DB140400> โ โ
โ โฐโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโฏ โ
โ โ
โ C:\Users\AndresG\Sites\scripts\reports\flask\app.py:53 in decorator โ
โ โ
โ 50 โ โ โ processor = getattr(app, f'{processor_name}_processor') โ
โ 51 โ โ โ data = processor.reports(program_code) if program_code else processor.report โ
โ 52 โ โ โ return render_template(template_name, **{processor_name: data}) โ
โ โฑ 53 โ โ return app.route(path)(wrapper) โ
โ 54 โ return decorator โ
โ 55 โ
โ 56 route('/resident_report_1/<program_code>', 'resident_report_1.html')('resident_report_1' โ
โ โ
โ โญโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ locals โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโฎ โ
โ โ path = '/resident_report_2/<program_code>' โ โ
โ โ processor_name = 'resident_report_2' โ โ
โ โ template_name = 'resident_report_2.html' โ โ
โ โ wrapper = <function route.<locals>.decorator.<locals>.wrapper at 0x00000220DBA29D00> โ โ
โ โฐโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโฏ โ
โ โ
โ C:\Users\AndresG\Sites\scripts\reports\venv\Lib\site-packages\flask\sansio\scaffold.py:364 in โ
โ decorator โ
โ โ
โ 361 โ โ โ
โ 362 โ โ def decorator(f: T_route) -> T_route: โ
โ 363 โ โ โ endpoint = options.pop("endpoint", None) โ
โ โฑ 364 โ โ โ self.add_url_rule(rule, endpoint, f, **options) โ
โ 365 โ โ โ return f โ
โ 366 โ โ โ
โ 367 โ โ return decorator โ
โ โ
โ โญโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ locals โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโฎ โ
โ โ endpoint = None โ โ
โ โ f = <function route.<locals>.decorator.<locals>.wrapper at 0x00000220DBA29D00> โ โ
โ โ options = {} โ โ
โ โ rule = '/resident_report_2/<program_code>' โ โ
โ โ self = <Flask 'app'> โ โ
โ โฐโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโฏ โ
โ โ
โ C:\Users\AndresG\Sites\scripts\reports\venv\Lib\site-packages\flask\sansio\scaffold.py:44 in โ
โ wrapper_func โ
โ โ
โ 41 โ โ
โ 42 โ def wrapper_func(self, *args: t.Any, **kwargs: t.Any) -> t.Any: โ
โ 43 โ โ self._check_setup_finished(f_name) โ
โ โฑ 44 โ โ return f(self, *args, **kwargs) โ
โ 45 โ โ
โ 46 โ return t.cast(F, update_wrapper(wrapper_func, f)) โ
โ 47 โ
โ โ
โ โญโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ locals โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโฎ โ
โ โ args = ( โ โ
โ โ โ '/resident_report_2/<program_code>', โ โ
โ โ โ None, โ โ
โ โ โ <function route.<locals>.decorator.<locals>.wrapper at 0x00000220DBA29D00> โ โ
โ โ ) โ โ
โ โ f = <function App.add_url_rule at 0x00000220DB2A3740> โ โ
โ โ f_name = 'add_url_rule' โ โ
โ โ kwargs = {} โ โ
โ โ self = <Flask 'app'> โ โ
โ โฐโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโฏ โ
โ โ
โ C:\Users\AndresG\Sites\scripts\reports\venv\Lib\site-packages\flask\sansio\app.py:659 in โ
โ add_url_rule โ
โ โ
โ 656 โ โ if view_func is not None: โ
โ 657 โ โ โ old_func = self.view_functions.get(endpoint) โ
โ 658 โ โ โ if old_func is not None and old_func != view_func: โ
โ โฑ 659 โ โ โ โ raise AssertionError( โ
โ 660 โ โ โ โ โ "View function mapping is overwriting an existing" โ
โ 661 โ โ โ โ โ f" endpoint function: {endpoint}" โ
โ 662 โ โ โ โ ) โ
โ โ
โ โญโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ locals โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโฎ โ
โ โ endpoint = 'wrapper' โ โ
โ โ methods = {'OPTIONS', 'GET'} โ โ
โ โ old_func = <function route.<locals>.decorator.<locals>.wrapper at โ โ
โ โ 0x00000220DBA29800> โ โ
โ โ options = {'endpoint': 'wrapper'} โ โ
โ โ provide_automatic_options = True โ โ
โ โ required_methods = {'OPTIONS'} โ โ
โ โ rule = <Rule '/resident_report_2/<program_code>' (OPTIONS, HEAD, GET) โ โ
โ โ -> wrapper> โ โ
โ โ self = <Flask 'app'> โ โ
โ โ view_func = <function route.<locals>.decorator.<locals>.wrapper at โ โ
โ โ 0x00000220DBA29D00> โ โ
โ โฐโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโฏ โ
โฐโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโฏ
AssertionError: View function mapping is overwriting an existing endpoint function: wrapper |
03896239d65348f29a6632d14e609b58 | flesch scores for this text.... In drama, dilemma reigns. What is the one hard choice the protagonist must make? If the muse of screenwriting fluttered down in a goddess-by-machine way and offered me a choice between a 1000-page bio with every detail of a character's life or a succinct 1โ2 sentence description of the character's dilemmaโ-โit wouldn't even be a dilemma. It's a no-brainer. I would pick the latter because it would be more helpful.
Dilemma has a special place in love stories. Romantic comedies and romances use the protagonist's dilemma to create two romantic interests who embody the protagonists' inner conflict.ย
Does the female character want the super handsome, rich, powerful, somewhat superficial guy or the down-to-earth, authentic, generous guy? In Hollywood and Hallmark Land, we know which one she chooses.ย
You want the choice to be equally good or bad. Sleepless in Seattle gives Annie (Meg Ryan) a challenging choice: Walter (Bill Pullman) and Sam (Tom Hanks).ย
Walter: safe, sturdy, practical love.
Sam: exciting, passionate love with an element of surprise and unknown.
Notice the circular process. Finesse the main character's desires, and that clarifies her love interests. Conversely, any changes to the love interests will reflect on the protagonist. The two competing love interests align with the dual sides of the protagonist's dilemma.
Make the dilemma a hardย choice
If the dilemma is the protagonist's toughest choice, what can possibly challenge romantic love and make it a fair fight? Often, it's romantic love versus familial love or the romantic love of two competing, appealing suitors. Alternatively, a story might pit love against something monumentally significant, like honor or duty.ย
Twenty or thirty years ago, if you had gay characters coming out or growing up in a small town, that created enough conflict to tell a gripping story. Nowadays, with the internet and more ubiquitous representation, these characters might find a welcoming community online or in a known liberal city. West Hollywood, anyone?ย
Look at the effort put into the gay love story Brokeback Mountain. The setting (1963 Wyoming), the conservative small-town culture, and the small cowboy subculture that idolizes traditional masculinity combine to create an obstacle significant enough to be a dilemma.ย
In addition to limiting the cultural or historical context, another approach to creating higher stakes in love stories is with hyperbole, like Baz Luhrmann's Romeo + Juliet with warring gangs instead of feuding families, Edward Scissorhands, or Her. (alternate phrasing for last 3 graphs in comment)
Casablanca creates numerous obstacles for Rick. He begins with self-hatred, resentment towards Ilsa, and indifference toward politics and the Nazis. By the end, he has overcome all of them.
Romantic Love and Self-Love: He remembers his love for Ilsa but doesn't need to possess her.
Political Love: He respects Laszlo's mission and supports it, even killing the Nazi antagonist Strasser.
Friendship: His relationship with Renault evolves into a surprise:ย . "Louis, I think this is the beginning of a beautiful friendship."
Rick doesn't take the letters of transit and fade off into the sunset with Ilsa. His ultimate choices transcend mere romantic loveโ-โwhy Casablanca is often considered the greatest love story ever.
Crafting soulmates with the push andย pull
The dilemma frames your characters and drives many of the key scenes.
Our main characters have two sides that align with the dilemma. The choice they are making now and the choice they will eventually makeโ-โtheir pre-character arc and post-character-arc character.
Persona or identity refers to the period before the character's character arc, when they are living a lie, clinging on to fear or defense mechanisms. Essence refers to the period after they grow and embrace their best self.
This duality creates conflict and affinity-the push and the pull-between the romance characters. From the moment they meet, often in a meet-cute, they clash at the superficial persona/identity level and connect at the deeper, often hidden level of essence.
For your lovers to be soulmates, seemingly destined for each other, you make them the only ones who see a glimpse of each other's essence. Only they see beyond the veneer of the persona and identity to something deeperโ-โthe other character's eventual best self. At some point, your character will say, express, or feel a version of this sentiment:
Everybody else thinks you're X, but I see you're Y.
I can't stand that you do X, but I love that you do Y
I'm the only one who can see Y in you.
This works for movie friendships, too. Like in real life, we bond with the people who "get us."
Lethal Weaponโ-โthe friendship version
Lethal Weapon introduces Riggs and Murtaugh separately. Riggs (Mel Gibson) is on the verge of suicideโ-โhe wants to die. Murtaugh (Danny Glover) is counting the days until retirement, playing everything safeโ-โhe wants to live.
When they meet, the scene juxtaposes their identities with a glimpse of their shadow sides. Riggs enters the police station undercover, and from Murtaugh's point of view, he looks dangerous. When Murtaugh spots Riggs's gun, without thinking, he charges to disarm him.
Despite his death wish and ragged appearance, Riggs is a productive member of the police force who handily outmaneuvers Murtaugh. And despite Murtaugh's overly cautious demeanor, he reveals a hint of his heroic risk-taking side.
This establishes the trajectory of their relationship. When Murtaugh's daughter is kidnapped, he must rely on Riggs's dangerous qualities to save her.
In the scene before, Riggs is shot but survives because he is wearing a bulletproof vest. Murtaugh celebrates the vestโ-โit shows through connection with Murtaugh's family that Riggs has found a desire to be alive.
Here is the identity-essence push-pull from Murtaugh's perspective:
I don't like your reckless and self-destructive nature. Can I even trust you? But when you're present and have something to fight for, your intensity and loyalty make you a lethal weapon that I want on my side.
An Officer and a Gentlemanโ-โlove storyย version
An Officer and a Gentleman echoes Casablanca. Zack (Richard Gere) has to learn love, honor, and respect for his job, his commander, his friends, and ultimately his lover and himself. This will make him an officer and a gentleman, leading to a happy ending.
Zack and Paula (Debra Winger) lie in bed, sharing intimate details. He tells her about his mother's suicide.
Paula is the only one who sees through Zack's pessimistic exterior. Debra Winger salvages the cringe-worthy moment with her performance of the surprising reversal. She follows his last line with a smile and a laugh.
๐ฟ๐ฐ๐๐ป๐ฐ
๐ธ ๐๐๐ ๐๐๐๐ ๐๐๐๐๐๐ ๐ ๐๐๐๐ ๐๐๐ข ๐๐๐๐ ๐๐๐๐ ๐ ๐๐๐ ๐ข๐๐ ๐๐๐๐ ๐๐ ๐๐ ๐๐๐๐. ๐ท๐๐? ๐ท๐๐?ย
Then they kiss. All hail Debra Winger.
Meet-cuteย
In the meet-cute, you now know where the chemistry comes from. There is something in their way, but you also reveal a hidden part of each other.
Silver Liningsย Playbook
Tiffany (Jennifer Lawrence) and Pat (Bradley Cooper) meet at Tiffany's sister's house. Tiffany's sister is married to a friend of Pat's. Pat and Tiffany are authentic, in contrast to the more artificial and polished couple.
ย Tiffany's sister encourages small talk, but Pat and Tiffany eventually break through the artificeโ-โgetting excited when they start discussing their meds.
Tiffany immediately declares her desire to leave and for Pat to walk her home. At her house, she cuts through the bullshit.
He plays coy and reminds her he's married. She says, "So am I," and holds up her ring.ย
Why the slap?
She framed them earlier in the sceneโ-โ"We're not liars like they are."
She hates that he's ACTING LIKE A LIARโ-โespecially since she's seen a glimpse of HIS HONEST, AUTHENTIC SIDE.
The throughline ofย lying
The next big scene-maybe the movie's set piece-in the diner continues with the question of him being a liar. You can watch the scene from the point where these reaction shots happen.
These shotsโ-โmy favorite acting moment this century- show Tiffany's disgust at learning Pat thinks she is crazier than him. Her anger comes from the place where he can most aggravate and disappoint her:
๐๐ธ๐ต๐ต๐ฐ๐ฝ๐
โฆ ๐๐๐'๐๐ ๐ ๐๐๐๐๐๐๐๐๐๐. ๐๐๐'๐๐ ๐ ๐๐๐๐. ๐ธ ๐๐๐๐๐๐ ๐๐ ๐๐ ๐ข๐๐ ๐๐๐ ๐ข๐๐ ๐๐๐๐๐๐ ๐๐. ๐๐๐ ๐๐๐ ๐๐ ๐๐๐๐๐๐๐. ๐๐๐ ๐๐๐ ๐๐ ๐๐๐๐๐๐๐!
TV and otherย mediaย
Your narrative medium impacts the stories you can tell and how you tell them. The 12-hour run time of the long-form miniseries "Normal People" allowed for a nuanced depiction of Marianne and Connell's ups and downsโ-โconnections and separationsโ-โcreating a deeper emotional connection with the audience.
Its bittersweet ending where the protagonists, who clearly love each other, decide to separateโ-โat least for the time beingโ-โwouldn't have played as well in a two-hour story. The time constraint alone limits the emotional turns. Assume the characters fall in love at the midpoint, 15โ20 minutes later, they separate, and then 15 or so minutes later, they reconcile. After the series of sharp reversals, a halfway/lukewarm twist to bittersweet would feel anticlimactic or, worse, unearned.
The additional time spent with the characters makes the ending feel less like a contrived plot twist and more like an authentic slice-of-life depiction of the characters' self-discovery and growth.
This dilemma paradigm brings focus to lovers andย friends
You can see it play out in a wide variety of films.
Harold and Maudeโ-โA young kid who stages fake suicides is obsessed with death. At a stranger's funeral, he meets a free-spirited 79-year-old woman. He adopts her joie de vivre and falls in love with her. After she commits suicide on her 80th birthday, he is in his hearse driving full speed toward a cliff's edge. Will he grow or regress? Will he choose life or death?
Super Badโ-โThe two bows must choose between the safe, predictable love of their friendship and the scary risk and uncertainty of their first romantic encounters with girls.
Napoleon Dynamiteโ-โNapoleon wants to be cool and popular more than anything else in the world, yet he chooses to risk looking like a dork to do his dance to support his friend. Vote for Pedro!
Portrait of a Lady on Fireโ-โThis breathtakingly beautiful modern-day masterpiece compares Marianne and Hรฉloรฏse's choice with the myth of Orpheus and Eurydice. Orpheus can rescue Eurydice from the underworld if he doesn't turn around to look at her until they leave the underworld. Otherwise, he will lose her forever. The story frames it as the poet's choice or the lover's choice. Their ultimate choices reflect on them, love, loss, and the idealization of memory.
In practice
During brainstorming and character development, take your character's starting values and sprinkle those characteristics onto one of their love interests. Think about how the character will grow and evolve. Take those eventual values and begin to shape the other love interest.
When you get to the "I can't stand that you do X, but I love that you do Y" moment, get something on the page. Even an ugly first draft will help to jumpstart your character creation/development.ย
Then you can finesse the dialogue to match the character or finesse the character to match the dialogue. Bounce back and forth between your protagonist and their love interests. Every improvement or discovery you make with one of them has a ripple effect on the other.
Room forย mystery
I framed this paradigm with clarity and gave you tidy examples that demonstrated it.
However, there is still room for magic, mystery, and intuition in this process.
If you know why one character is pulled toward another, you have enough to start. If you can't label it or frame it tidily, that's okay. Stick with it.
The Oscar-winning Best Original Screenplay from 2021, A Promising Young Woman, was a pastiche of genresโ-โone of them most certainly a rom-com. In its meet-cute scene, Ryan and Cassandra fall for each other because right in front of each other, she spits in his coffee, and he happily drinks it.
I might be able to bullshit my way through explaining what that means. But it's not necessary. As long as you, the writer, understand what is pulling your characters toward each other, you have a place to start. Your next task is to hide it and create obstacles to it. These principles will serve your love story, allowing you to be as strange, personal, and specific as you want to be. |
End of preview. Expand
in Data Studio
README.md exists but content is empty.
- Downloads last month
- 22