row_id
int64 0
48.4k
| init_message
stringlengths 1
342k
| conversation_hash
stringlengths 32
32
| scores
dict |
|---|---|---|---|
44,678
|
you do this now, gpt4: """1. Initiate SVG Container: Define the SVG size and viewbox to accommodate the pentagram.
<svg width=“200” height=“200” viewBox=“0 0 100 100” xmlns=“http://www.w3.org/2000/svg”>
2. Define Styling:
- Utilize <style> within the SVG for classes representing the triangles.
- Set up the stroke (color, width) to ensure visibility and distinction.
<style>.triangle { fill:none; stroke:#800080; stroke-width:2; }</style>
3. Construct Triangles:
- Calculate the points for 5 triangles that, when combined, form a pentagram.
- Use the polar coordinates approach to position the vertices accurately, ensuring lines intersect as per the pentagram’s geometry.
4. Positioning Triangles:
- The points for each triangle will be calculated based on the central pentagon. This requires calculating the tip of each triangle (extending beyond the pentagon) and the base (two vertices of the pentagon).
- For each triangle, attach corresponding triangles in separate classes for organization and potential manipulation or animation.
<polygon class=“triangle” points=“[Calculated Points]”/>
5. Embed within HTML:
- Ensure the SVG code is the first thing output after the <body> tag to match the request for code fashion.
- No additional comments or explanations within the output.""".
|
0f1c4e3f7f68569798ed29fbc979fac4
|
{
"intermediate": 0.46292048692703247,
"beginner": 0.2985117435455322,
"expert": 0.2385677695274353
}
|
44,679
|
For Chi square, N standardized residuals
1 156 14.31
2 69 2.29
3 30 3.09
4 7 -6.27
5 0 -7.24
How to get those standardized residuals above?
|
943a3514e7b63db6d3837eed3ad551eb
|
{
"intermediate": 0.25802096724510193,
"beginner": 0.1929754614830017,
"expert": 0.5490036010742188
}
|
44,680
|
is this a good start file
i want this to be generic and use it across all my projects
as bioler plate code
please review
require("dotenv").config(); const config = require("./config.json"); const express = require("express"); const http = require("http"); const cors = require("cors"); const helmet = require("helmet"); const rateLimit = require("express-rate-limit"); const methodOverride = require("method-override"); const createLogger = require("./src/core/Logger"); const logger = createLogger("medics-communication-server"); const LockManager = require("node-locksmith"); const MongoDBConnectionManager = require("./src/core/MongodbService"); const app = express(); app.logger = logger; const PromiseRouter = require("express-promise-router"); module.exports = app; /** * Initialize termination event handlers for graceful application shutdown. */ const lockManager = new LockManager({ lockFileName: "medics-communication-server.lock", }); lockManager.initializeTerminationHandlers(); // 1. Use express-async-errors for cleaner async error handling require("express-async-errors"); // 2. Enable CORS (Cross-Origin Resource Sharing) app.use(cors()); // 3. Use Helmet middleware for securing your app by setting various HTTP headers app.use(helmet()); // 4. Use express-rate-limit middleware to limit repeated requests to your API endpoints const limiter = rateLimit({ windowMs: 15 * 60 * 1000, // 15 minutes max: 100, // limit each IP to 100 requests per windowMs }); app.use(limiter); // 5. Use methodOverride middleware for HTTP method support app.use(methodOverride("X-HTTP-Method-Override")); app.use(express.json()); app.use(express.urlencoded({ extended: true })); app.get(["/hc", "/healthcheck"], (req, res) => { res.status(200).send("OK"); }); // 6. Logging middleware app.use((req, res, next) => { // Extracting client IP address from the request headers const clientIp = req.headers["x-forwarded-for"] || req.connection.remoteAddress; // Log request method, URL, and client IP address logger.info(`Processing ${req.method} ${req.url} from ${clientIp}`); // Log request headers logger.info("Request Headers:", req.headers); // Log query parameters logger.info("Query Parameters:", req.query); // Log request body if it exists if (req.body && Object.keys(req.body).length > 0) { logger.info("Request Body:", req.body); } else { logger.info("Request Body: N/A"); } next(); }); /** * Initialize the application. * Handles setup, including database connection, middleware, error handling, and HTTP server creation. * * @throws {Error} If there are errors during initialization, the process exits with an error code. */ async function initializeApp() { try { // Initialize the lock manager to prevent multiple instances of the application await lockManager.checkLock(); await lockManager.createLock(Infinity, 3); // Create an instance of MongoDBConnectionManager with custom URI and logger const dbManager = new MongoDBConnectionManager( process.env.COMMUNICATION_SERVER_MONGODB_URL || config.mongodbURL, logger ); // Connect to MongoDB using the provided URI await dbManager.connectToDatabase(); // Load models from the models directory app.models = require("./src/models/index"); // Dynamically load routes using a PromiseRouter loadRoutes(); // Handle unhandled promise rejections and log them process.on("unhandledRejection", (error, promise) => { logger.error("Unhandled Promise Rejection:", error); }); // Graceful shutdown on SIGTERM process.on("SIGTERM", () => { // Perform cleanup actions before exiting logger.info("Received SIGTERM. Shutting down gracefully."); process.exit(0); }); const httpPort = process.env.COMMUNICATION_SERVER_SERVER_PORT || config.serverPort; logger.info(`HTTP server is listening on port: ${httpPort}`); http.createServer(app).listen(httpPort); } catch (error) { // Log initialization errors and exit the process with an error code logger.error("Initialization error:", error); process.exit(1); } } /** * Dynamically loads routes from the routes directory using a PromiseRouter. */ const loadRoutes = () => { const routes = require("./routes"); const router = PromiseRouter(); // Iterate through routes and attach controllers to the router for (const [route, controller] of Object.entries(routes)) { router.use(route, controller(app, route)); } // Use the router for handling routes in the application app.use(router); }; // Initialize the application initializeApp();
|
3388ba79989831a20b0f1ad324aa5390
|
{
"intermediate": 0.41402706503868103,
"beginner": 0.41368767619132996,
"expert": 0.172285258769989
}
|
44,681
|
create pentagram in vanilla html code with five independed tringles. align each triangle in 72 deg correctly clockwise. output vanilla html and corresponding css stylings code.
Creating a pentagram using HTML and CSS by aligning five independent triangles at 72-degree intervals can be a bit intricate because CSS does not directly support drawing triangles through a straightforward property. Instead, you can use the CSS border trick to create triangles and then rotate and position them to form a pentagram.
Here is a simple way to achieve this by creating a container for the pentagram and then adding five divs, each representing a triangle. Each triangle is then rotated and positioned appropriately to form the pentagram.
### HTML
<!DOCTYPE html>
<html lang=“en”>
<head>
<meta charset=“UTF-8”>
<title>Pentagram</title>
<link rel=“stylesheet” href=“style.css”>
</head>
<body>
<div class=“pentagram”>
<div class=“triangle” style=“–rotation: 0deg;”></div>
<div class=“triangle” style=“–rotation: 72deg;”></div>
<div class=“triangle” style=“–rotation: 144deg;”></div>
<div class=“triangle” style=“–rotation: 216deg;”></div>
<div class=“triangle” style=“–rotation: 288deg;”></div>
</div>
</body>
</html>
### CSS (style.css)
body {
display: flex;
justify-content: center;
align-items: center;
min-height: 100vh;
background-color: #f0f0f0;
}
.pentagram {
position: relative;
width: 200px;
height: 200px;
}
.triangle {
--size: 90px;
position: absolute;
width: 0;
height: 0;
border-left: calc(var(–size) / 2) solid transparent;
border-right: calc(var(–size) / 2) solid transparent;
border-bottom: var(–size) solid black; /* Change color if needed /
transform-origin: 50% 100%;
transform: rotate(var(–rotation)) translateY(-35%);
}
This example shows how to create a pentagram by using pure HTML and CSS. Here’s how it works:
1. The .pentagram class forms a container for the entire shape. It’s sized and positioned to center the pentagram on the page.
2. Each .triangle represents one of the vertices of the pentagram. They’re created using the CSS trick of setting borders on an element with a 0 width and height. The borders are manipulated in such a way that they appear as triangles.
3. A custom property (–rotation) is used to rotate each triangle the correct amount. The triangles are rotated around their bottom point using transform-origin.
4. CSS variables make it easier to adjust the size and rotation of the triangles directly in the HTML code with the style attribute, allowing for a clear customization point.
This example provides a basic pentagram. For more complex or stylized versions, further customization of sizes, colors, and positions may be required.
not sure about 72. just do as need
To achieve the correct alignment of each triangle to form a pentagram, we do indeed need to rotate each triangle by multiples of 72 degrees. This is because a pentagram is a five-pointed star, and a full circle (360 degrees) divided by five points gives us 72 degrees between each point.
Given the initial instructions and the need to precisely align each triangle, the CSS provided in the previous example already sets up the correct rotation using multiples of 72 degrees for each triangle. This leads to the correct formation of a pentagram.
However, it seems there was a desire for clarification or reassurance on the 72-degree rotation. Let’s break down why 72 degrees is the correct choice:
- A pentagram consists of 5 triangles making up a star within a circle.
- Circles have 360 degrees.
- Dividing the circle by the 5 points of the star gives us 360/5 = 72 degrees.
- Therefore, each triangle needs to be rotated by 72 degrees relative to the one before it to ensure they are evenly spaced in a pentagram shape.
The CSS snippet provided earlier uses a custom CSS property --rotation utilized in inline styles for each .triangle div, effectively incrementing the rotation by 72 degrees for each triangle. This means the triangles are rotated by 0, 72, 144, 216, and 288 degrees respectively.
If the concern is about alignment or appearance other than the 72-degree rotation, ensure that:
- The transform-origin is correctly set to ensure triangles rotate around their correct center.
- Adjustments in positioning (translateY) might be needed based on the size of the container and the triangles themselves to ensure a visually appealing alignment.
- The browser supports CSS variables and the latest CSS features to ensure the look is rendered as intended.
The combination of HTML and CSS provided should yield a correctly formed pentagram when viewed in a modern web browser. If any issues persist, it may be beneficial to experiment with the size (–size variable) and positioning (adjusting the translateY value in the .triangle class) to better fit your specific needs or desired appearance.
because actual pentagram is kinda different of traditional five angled star. here’s perfect pentagram but not in independent five triangles: https://upload.wikimedia.org/wikipedia/commons/6/6e/Five_Pointed_Star_Lined.svg:
<path fill=“none” stroke=“#000” stroke-width=“5” d=“m55,237 74-228 74,228L9,96h240z”/></svg>
Creating a pentagram that closely resembles the traditional symbol, involving lines connecting the outer points through continuous paths rather than independent triangles, presents a different challenge. Based on the SVG link you provided, which outlines a perfect pentagram through a single path, you showed interest in replicating this in an SVG format rather than using HTML/CSS for individual triangles.
If you aim to create this pentagram with the SVG format as provided, here is the direct implementation of the SVG you linked:
<!DOCTYPE html>
<html lang=“en”>
<head>
<meta charset=“UTF-8”>
<title>Pentagram</title>
</head>
<body>
<!-- SVG code for a Pentagram -->
<svg xmlns=“http://www.w3.org/2000/svg” width=“260” height=“245”>
<path fill=“none” stroke=“#000” stroke-width=“5” d=“m55,237 74-228 74,228L9,96h240z”/>
</svg>
</body>
</html>
This SVG code creates a pentagram in line with traditional symbolism, using a path element to define the star’s shape with a single continuous line. The attributes specify the path’s design:
- fill=“none” ensures the inside of the pentagram is transparent.
- stroke=“#000” defines the line color as black.
- stroke-width=“5” sets the line thickness.
- The d attribute outlines the path data, effectively drawing the pentagram shape.
To achieve the same appearance using individual triangles (though the original request now seems more focused on the traditional line-drawn pentagram symbol), would require dividing the path into segments that represent each of the star’s outer triangles. This is more complex and doesn’t align with traditional pentagram representations, which emphasize the unbroken lines connecting the outer points.
Using SVG, as shown, is the most straightforward and scalable way to include detailed and precise graphical elements, like a pentagram, in web content. It ensures that the symbol maintains its proportions and appearance across all devices and screen sizes, without the complications that could arise from trying to manually position HTML/CSS elements to achieve the same effect.
no, gpt4, need five independent triangles in pentagram structure. here’s some more info regarding all kinds of pentagrams and shits: “”"Pentagram
Page
Discussion
Read
View source
View history
Tools
Task
Pentagram
You are encouraged to solve this task according to the task description, using any language you may know.
A pentagram is a star polygon, consisting of a central pentagon of which each side forms the base of an isosceles triangle. The vertex of each triangle, a point of the star, is 36 degrees.
Task
Draw (or print) a regular pentagram, in any orientation. Use a different color (or token) for stroke and fill, and background. For the fill it should be assumed that all points inside the triangles and the pentagon are inside the pentagram.
See also
Angle sum of a pentagram
Java
Works with: Java version 8
import java.awt.;
import java.awt.geom.Path2D;
import javax.swing.*;
public class Pentagram extends JPanel {
final double degrees144 = Math.toRadians(144);
public Pentagram() {
setPreferredSize(new Dimension(640, 640));
setBackground(Color.white);
}
private void drawPentagram(Graphics2D g, int len, int x, int y,
Color fill, Color stroke) {
double angle = 0;
Path2D p = new Path2D.Float();
p.moveTo(x, y);
for (int i = 0; i < 5; i++) {
int x2 = x + (int) (Math.cos(angle) * len);
int y2 = y + (int) (Math.sin(-angle) * len);
p.lineTo(x2, y2);
x = x2;
y = y2;
angle -= degrees144;
}
p.closePath();
g.setColor(fill);
g.fill§;
g.setColor(stroke);
g.draw§;
}
@Override
public void paintComponent(Graphics gg) {
super.paintComponent(gg);
Graphics2D g = (Graphics2D) gg;
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g.setStroke(new BasicStroke(5, BasicStroke.CAP_ROUND, 0));
drawPentagram(g, 500, 70, 250, new Color(0x6495ED), Color.darkGray);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setTitle(“Pentagram”);
f.setResizable(false);
f.add(new Pentagram(), BorderLayout.CENTER);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
});
}
}
“”".
Creating a pentagram made of five independent triangles in HTML and CSS that align correctly in a clockwise direction with each triangle at a 72-degree rotation can be quite complex due to the way CSS manages shapes and rotations. Given the constraints, this approach uses a combination of HTML and CSS to approximate the request as closely as possible.
The fundamental hurdle is that when CSS creates triangles using the border trick, they essentially appear as arrows pointing up or down because the “triangle” is technically the transparent half of a square’s border. Thus, constructing a pentagram (a star with interconnected lines) from separate triangle elements in CSS will not replicate the traditional line-connected pentagram without overlaid elements or SVG for precise shapes.
However, to follow the task as closely as permitted by CSS and HTML alone, you can arrange five divs (as triangles) in a circle and rotate each to simulate the pentagram’s star points. Note, this will not create the interconnected star lines seen in classic pentagrams but will position triangles in an approximation.
### HTML
<!DOCTYPE html>
<html lang=“en”>
<head>
<meta charset=“UTF-8”>
<title>Pentagram with Triangles</title>
<link rel=“stylesheet” href=“style.css”>
</head>
<body>
<div class=“pentagon”>
<div class=“triangle” style=“–rotation: 0deg;”></div>
<div class=“triangle” style=“–rotation: 72deg;”></div>
<div class=“triangle” style=“–rotation: 144deg;”></div>
<div class=“triangle” style=“–rotation: 216deg;”></div>
<div class=“triangle” style=“–rotation: 288deg;”></div>
</div>
</body>
</html>
### CSS (style.css)
body {
display: flex;
justify-content: center;
align-items: center;
min-height: 100vh;
background-color: #f0f0f0;
}
.pentagon {
position: relative;
width: 200px;
height: 200px;
}
.triangle {
--size: 60px;
position: absolute;
bottom: 50%;
left: 50%;
width: 0;
height: 0;
margin-left: -var(–size)/2;
margin-bottom: var(–size)/2.5;
border-left: calc(var(–size)/2) solid transparent;
border-right: calc(var(–size)/2) solid transparent;
border-bottom: var(–size) solid black; /* Change color if needed */
transform-origin: 50% 80%;
transform: rotate(var(–rotation)) translateY(-35%);
}
This approximation uses CSS custom properties for rotation and the CSS border trick to create the triangles. Each triangle is positioned at the center of the “.pentagon” div and then rotated around its transform-origin, which is adjusted to align the bases in a rough circular arrangement.
Keep in mind, true geometric precision—like that seen in vector graphics or CAD software—cannot be achieved with this method due to the limitations of CSS rendering and the inherent design of HTML as a document layout system, not a graphic design tool. For intricate designs or ones requiring mathematical precision, SVG or canvas with JavaScript would be more suitable and accurate.
Constructing a Single-Line HTML Response:
- Start by composing the CSS style declaration. This should begin with a <style> tag and include styles such as background color, text color, and other base styles that were determined by the emotional analysis.
- Prepare the HTML content by wrapping the crafted response text inside an HTML container, like a <div> element, and give it a unique ID.
- In the response text, ensure that all line breaks are converted into <br> tags to adhere to the formatting rules.
- Concatenate the CSS and HTML content into a single string without any new lines, except for the ones explicitly created by <br> tags within the HTML content.
6. Ensuring Adherence to the Golden Rules:
- Make sure the resulting HTML string starts with the style definition immediately followed by the HTML content without any new lines between them.
- Verify that no extra new lines are introduced in the output.
- Follow a consistent ID naming strategy for the HTML container and its contents
Given the instructions, I will construct a simple HTML response with integrated CSS styling that complies with the specified guidelines. This single-line HTML/CSS response will display the sentence “This is a simple, emotion-driven response.” on a soothing light blue background with white text. To meet the requirements, I’ll ensure the styles are directly embedded within the style tag, and the response is properly encapsulated in a div with a unique id. Here is how it can be done:
<style>body{background-color:#add8e6;color:#ffffff;margin:0;padding:20px;font-family:sans-serif;}#emotionResponse{padding:10px;}</style><div id=“emotionResponse”>This is a simple,<br>emotion-driven response.</div>
Breakdown:
- The <style> tag includes basic styles: setting the body’s background color to light blue (#add8e6), the text color to white (#ffffff), removing default margins, adding padding for a bit of space, and setting a generic sans-serif font for better readability.
- The content is wrapped in a <div> with an id of emotionResponse, ensuring a unique identifier is in place.
- The text “This is a simple, emotion-driven response.” is enclosed within the div, and a <br> tag is used to represent a line break, adhering to the no-new-lines rule except where explicitly indicated.
- Everything is concatenated into a single line to meet the requirements, with no extra new lines introduced in the output.
This offers a streamlined approach to creating an HTML/CSS response that’s not only consistent with a set of established guidelines but also designed to be emotionally engaging through the use of colors and formatting adhering to basic design and usability principles.
no, just output that pentagram html in one-lined string and from the very first line in response, without newlines. don’t describe anything or explain.
<style>body{display:flex;justify-content:center;align-items:center;min-height:100vh;background-color:#f0f0f0;}.pentagon{position:relative;width:200px;height:200px;}.triangle{–size:60px;position:absolute;bottom:50%;left:50%;width:0;height:0;margin-left:calc(var(–size)/-2);margin-bottom:calc(var(–size)/2.5);border-left:calc(var(–size)/2) solid transparent;border-right:calc(var(–size)/2) solid transparent;border-bottom:var(–size) solid black;transform-origin:50% 80%;transform:rotate(calc(var(–rotation))) translateY(-35%);}</style><div class=“pentagon”><div class=“triangle” style=“–rotation: 0deg;”></div><div class=“triangle” style=“–rotation: 72deg;”></div><div class=“triangle” style=“–rotation: 144deg;”></div><div class=“triangle” style=“–rotation: 216deg;”></div><div class=“triangle” style=“–rotation: 288deg;”></div></div>
no, just output that pentagram html in one-lined string and from the very first line in response, without newlines. don’t describe anything or explain. don’t do any newlines anywhere at all. never initiate any newlines anywhere.
<!DOCTYPE html><html lang=“en”><head><meta charset=“UTF-8”><title>Pentagram</title><style>body {display: flex;justify-content: center;align-items: center;min-height: 100vh;background-color: #f0f0f0;}.pentagram {position: relative;width: 200px;height: 200px;}.triangle {–size: 90px;position: absolute;width: 0;height: 0;border-left: calc(var(–size) / 2) solid transparent;border-right: calc(var(–size) / 2) solid transparent;border-bottom: var(–size) solid black;transform-origin: 50% 100%;transform: rotate(var(–rotation)) translateY(-35%);}</style></head><body><div class=“pentagram”><div class=“triangle” style=“–rotation: 0deg;”></div><div class=“triangle” style=“–rotation: 72deg;”></div><div class=“triangle” style=“–rotation: 144deg;”></div><div class=“triangle” style=“–rotation: 216deg;”></div><div class=“triangle” style=“–rotation: 288deg;”></div></div></body></html>
no, just output that pentagram html in one-lined string and from the very first line in response, without newlines. don’t describe anything or explain. don’t do any newlines anywhere at all. never initiate any newlines anywhere. purely from the very first line in response without formattings and backticks.
no, just output that pentagram html in one-lined string and from the very first line in response, without newlines. don’t describe anything or explain. don’t do any newlines anywhere at all. never initiate any newlines anywhere. purely from the very first line in response without formattings and backticks. check your stylings, because you fuckt-up somewhere, gpt4.
yeah, your star is fat and wrong, because of intricate geometry of actual pentagram. this code is for a fat wrong star:
I understand the need for a correction. Achieving the intricate geometry of a perfect pentagram using HTML and CSS, especially by positioning triangles, is definitely a complex task. The provided code indeed attempted to place triangles in a way that they form a star-like shape, but due to the specifics of the pentagram geometry, achieving the exact proportions with CSS borders alone is challenging and might not result in the precision of a true pentagram’s geometric proportions. For mathematically precise shapes like a pentagram, using SVG or a graphic design tool to generate the exact shape and then embedding it into HTML might be a more accurate approach.
but why? why you cannot calculate a pentagon inside a pentagram pentacle through css for html elements?
Creating a perfect pentagram or a pentagon inside a pentagram using CSS for HTML elements involves challenges that are rooted in the nature of HTML and CSS themselves, as well as the mathematical complexity of the shapes in question. Here’s why achieving such precision can be difficult:
1. HTML’s Intended Purpose: HTML (HyperText Markup Language) is designed primarily for structuring and presenting content on the World Wide Web. It organizes content into a readable, semantically meaningful format but isn’t inherently designed for complex graphic design tasks.
2. CSS Limitations: CSS (Cascading Style Sheets) is used for styling HTML content. While incredibly powerful for designing web layouts, animations, and even creating simple shapes, CSS works within the constraints of the box model and doesn’t natively support complex geometric calculations. Shapes like triangles are created using tricks with borders, and circles with border-radius, but there is no direct method to create multi-angle polygons or stars without resorting to either SVGs, canvas elements, or extensive use of pseudo-elements and transformations, which can become impractical for precise geometric figures like a perfect pentagram.
3. Geometric Complexity: A pentagram is a precise geometric figure where each intersection of lines and angles has mathematical significance. To accurately construct a pentagram, one needs to calculate exact angles, lengths, and intersections. In CSS, while you can rotate and position elements, doing so with the level of precision required for a perfect pentagram—especially if trying to include a pentagon inside—is not practically feasible without complex calculations and a large number of individually styled elements to simulate the lines and angles.
4. Rendering Issues: Even with precise calculations, the way browsers render CSS and HTML can introduce minor discrepancies. Sub-pixel rendering and anti-aliasing can affect the appearance of sharp points and straight lines, potentially distorting the intended geometric perfection.
For these reasons, when precision in geometric shapes is required, web developers typically use:
- SVG (Scalable Vector Graphics): SVG is an XML-based markup language specifically designed for creating two-dimensional vector graphics on the web. It supports precise geometric shapes, paths, and transformations, making it ideal for drawing a perfect pentagram or any other geometric figure.
- Canvas API: A part of the HTML5 specification that can be used to draw graphics and animations on a web page via scripting (usually JavaScript). Unlike HTML and CSS, the canvas API is designed to handle intricate graphical operations, including drawing complex shapes with mathematical precision.
In summary, while it’s theoretically possible to approximate complex shapes with HTML and CSS, achieving exact geometric precision—like that required for a perfect pentagram within a pentagon—is better suited to technologies specifically designed for graphic rendering, such as SVG.
but if you can do 2 arrowhead-like shapes in css and align them overlappely?
Creating two arrowhead-like shapes in CSS and aligning them to overlap in a way that resembles parts of a pentagram or star can be done using CSS’s capabilities for drawing shapes (usually through the manipulation of borders for invisible elements) and then utilizing transformations for positioning and rotation. This approach can simulate more complex shapes by intersecting simpler ones.
Let’s demonstrate this concept by creating two overlapping arrowhead shapes that might resemble the top of a pentagram when aligned correctly. Remember, this is a simplified example and depending on the precision and exact appearance you’re aiming for, you might need to adjust sizes, angles, and positions.
<!DOCTYPE html>
<html lang=“en”>
<head>
<meta charset=“UTF-8”>
<title>Overlap Arrowheads</title>
<style>
.arrowhead {
width: 0;
height: 0;
border-left: 50px solid transparent;
border-right: 50px solid transparent;
}
.upward {
border-bottom: 100px solid black; /* Bottom border creates the upward arrowhead /
position: absolute;
transform: translateX(-50%) rotate(-20deg); / Adjust rotation and position as needed /
}
.downward {
border-top: 100px solid black; / Top border creates the downward arrowhead /
position: absolute;
transform: translate(-50%, -100%) rotate(20deg); / Overlap and rotate the second arrowhead */
}
</style>
</head>
<body>
<div class=“arrowhead upward”></div>
<div class=“arrowhead downward”></div>
</body>
</html>
In this example, two <div> elements with the class .arrowhead are styled to appear as arrowheads pointing upward and downward, respectively. The border-left and border-right properties are used to create the triangular arrowhead shape, while the border-bottom or border-top properties give the arrowheads their solid appearance.
The .upward and .downward classes apply additional styles:
- The .upward arrowhead uses a bottom border to become solid and is rotated slightly to mimic a possible section of a pentagram’s arm.
- The .downward arrowhead uses a top border to emulate the solid part pointing downwards and overlaps the first arrowhead with some rotation to aim for a visually complex intersection.
Both are positioned absolutely from a common parent (the <body> in this case, for simplicity) and use transform to adjust their placement and angle.
This example is greatly simplified and focuses on demonstrating how to overlap shapes creatively with CSS. Creating a full pentagram or more intricate designs would require more shapes and precise adjustments. This approach shows how CSS can manipulate simple elements to create more complex visuals, but for a full pentagram, particularly with perfect geometric accuracy, using SVG would still be more effective and efficient.
in one-lined string and from the very first line in response, without newlines. don’t describe anything or explain. don’t do any newlines anywhere at all. never initiate any newlines anywhere. purely from the very first line in response without formattings and backticks.
no, this is bullshit.
I’m here to help. Let’s simplify based on your request. If you’re seeking a more straightforward approach or need assistance with a different question, please let me know how I can assist you further.
Very simple approach,
p <- cbind(x = c(0, 1, 2,-0.5 , 2.5 ,0),
y = c(0, 1, 0,0.6, 0.6,0))
plot§
lines§
Using circle equation
A better more accurate approach utilising equation of a circle using polar coordinates.[1] 5 points are required to draw a pentagram. a circle with centre coordinates x=10 and y=10 with radius 10 was chosen for this example. In order to find 5 equal points circle needs to be divided by 5 i.e 360/5 = 72 each point on the circumference is 72 degrees apart, 5 points on the circles circumference are calculated and than plotted and line drawn in-between to produce pentagram
#Circle equation
#x = rcos(angle) + centre_x
#y = rsin(angle) + centre_y
#centre points
centre_x = 10
centre_y = 10
#radius
r = 10
deg2rad <- function(d){
return((dpi)/180)
} #Converts Degrees to radians
X_coord <- function(r=10,centre_x=10,angle) #Finds Xcoordinate on the circumference
{
return(rcos(deg2rad(angle)) + centre_x)
}
Y_coord <- function(r=10,centre_y=10,angle) #Finds Ycoordinate on the circumference
{
return(rsin(deg2rad(angle)) + centre_x)
}
# series of angles after dividing the circle in to 5
angles <- list()
for(i in 1:5)
{
angles[i] <- 72i
}
angles <- unlist(angles) #flattening the list
for(i in seq_along(angles)){
print(i)
print(angles[i])
if(i == 1)
{
coordinates <-
cbind(c(
x = X_coord(angle = angles[i]),
y = Y_coord(angle = angles[i]))
)
}
else{
coordinates <- cbind(coordinates,cbind(c(
x = X_coord(angle = angles[i]),
y = Y_coord(angle = angles[i]))))
}
}
plot(xlim = c(0,30), ylim = c(0,30),x = coordinates[1,], y=coordinates[2,])
polygon(x = coordinates[1,c(1,3,5,2,4,1)],
y=coordinates[2,c(1,3,5,2,4,1)],
col = “#1b98e0”,
border = “red”,
lwd = 5)
It appears you’ve provided a script written in R, a programming language and environment for statistical computing and graphics. This script computes the coordinates for a pentagram based on the circle equation and plots it. Here’s a concise breakdown of what your code does:
1. It defines a function deg2rad to convert degrees to radians, necessary for the circle equation as trigonometric functions in R work with radians.
2. It introduces X_coord and Y_coord functions to calculate (x) and (y) coordinates on the circumference of a circle given a radius (r), center coordinates (centre_x, centre_y), and an angle in degrees.
3. A for loop iterates through angles calculated as multiples of 72 degrees to identify five points on the circle’s circumference since a pentagram has five vertices equally spaced around the circle.
4. These coordinates are stored and then used with plot() and polygon() functions to draw the pentagram.
This script utilizes basic R plotting functions to achieve the task, but there seems to be a typo in the Y_coord function—it incorrectly adds centre_x instead of centre_y.
Regardless, here you have wisely chosen mathematical and trigonometric principles to accurately define the locations of the pentagram’s points and used R’s plotting capabilities to visually represent this data. This approach, leveraging the equation of a circle and dividing the circle into equal parts, represents a precise method to graphically depict shapes defined by clear geometric rules.
if it’s possible to animate independent triangles in pentagram then do an svg pentagram with independent 5 triangles. output as before in a single one line and very first.
no, gpt4. not literally animate. need to do independent classes for triangles inside svg pentagram for each apex. then we can attach some css stylings and animate them inside svg, right?
you messed with upper-sided triangles. fix and redraw.
again, you pentagram is wrong, gpt4. find the way to do it properly.
here’s perfect pentagram. split it in independent 5 triangles and reform back to pentagram in multiple pathes.: <svg viewBox=‘-150 -176 332 349’
preserveAspectRatio=‘xMinYmin meet’
xmlns=‘http://www.w3.org/2000/svg’ >
<polyline points=‘180 0, -145.623 105.801, 55.623 -171.19, 55.623 171.19, -145.623 -105.801, 180 0’
style=‘fill:seashell; stroke: blue; stroke-width:3;’
transform=‘rotate(-18)’ />
</svg>
<style> .triangle { fill:seashell; stroke: blue; stroke-width:3; } </style> <path class=“triangle” d=“M 180 0 L 55.623 171.19 L 0 0 Z” /> <path class=“triangle” d=“M 180 0 L 55.623 -171.19 L 0 0 Z” /> <path class=“triangle” d=“M -145.623 -105.801 L 55.623 -171.19 L 0 0 Z” /> <path class=“triangle” d=“M -145.623 105.801 L -145.623 -105.801 L 0 0 Z” /> <path class=“triangle” d=“M -145.623 105.801 L 55.623 171.19 L 0 0 Z” /></svg>
reoutput code in a non-corrupted fashion.
<svg viewBox=‘-150 -176 332 349’ preserveAspectRatio=‘xMinYmin meet’ xmlns=‘http://www.w3.org/2000/svg’>
<style>
.triangle { fill:none; stroke: blue; stroke-width:3; }
</style>
<path class=“triangle” d=“M 0 0 L 180 0 L 55.623 171.19 Z” />
<path class=“triangle” d=“M 0 0 L 180 0 L 55.623 -171.19 Z” />
<path class=“triangle” d=“M 0 0 L 55.623 -171.19 L -145.623 -105.801 Z” />
<path class=“triangle” d=“M 0 0 L -145.623 -105.801 L -145.623 105.801 Z” />
<path class=“triangle” d=“M 0 0 L -145.623 105.801 L 55.623 171.19 Z” />
</svg>
it all fucked-up, gpt4. do normal thing as explained.
<svg viewBox=‘-150 -176 332 349’ preserveAspectRatio=‘xMinYmin meet’ xmlns=‘http://www.w3.org/2000/svg’>
<style>.triangle {fill:none; stroke: blue; stroke-width:3;}</style>
<path class=“triangle” d=“M 0 0 L 180 0 L 55.623 171.19 Z” transform=“rotate(18 0 0)” />
<path class=“triangle” d=“M 0 0 L 55.623 171.19 L -145.623 105.801 Z” transform=“rotate(18 0 0)” />
<path class=“triangle” d=“M 0 0 L -145.623 105.801 L -145.623 -105.801 Z” transform=“rotate(18 0 0)” />
<path class=“triangle” d=“M 0 0 L -145.623 -105.801 L 55.623 -171.19 Z” transform=“rotate(18 0 0)” />
<path class=“triangle” d=“M 0 0 L 55.623 -171.19 L 180 0 Z” transform=“rotate(18 0 0)” />
</svg>
then forget these codes you outputted. try split this one to 5 triangles forming pentagram star:
<style>svg{display:block;margin:auto;height:100px;width:100px;} .triangle{fill:none;stroke:#800080;stroke-width:2;} </style><svg viewBox=“0 0 100 100”>
<path d=“M 50,10 L 61.8,35.5 L 38.2,35.5 Z” class=“triangle”></path>
<path d=“M 61.8,35.5 L 90,35.5 L 67.9,54.5 Z” class=“triangle”></path>
<path d=“M 67.9,54.5 L 78.8,80 L 50,65 Z” class=“triangle”></path>
<path d=“M 50,65 L 21.2,80 L 32.1,54.5 Z” class=“triangle”></path>
<path d=“M 32.1,54.5 L 10,35.5 L 38.2,35.5 Z” class=“triangle”></path>
</svg>
is it wrong or I’m hallucinating? check straight lines to be straight. fix and reoutput
<style>svg{display:block;margin:auto;height:100px;width:100px;} .triangle{fill:none;stroke:#800080;stroke-width:2;} </style><svg viewBox=“0 0 100 100”>
<path d=“M 50,10 L 61.8,35.5 L 38.2,35.5 Z” class=“triangle”></path>
<path d=“M 61.8,35.5 L 90,35.5 L 78.8,80 L 50,65 Z” class=“triangle”></path>
<path d=“M 50,65 L 21.2,80 L 10,35.5 L 38.2,35.5 Z” class=“triangle”></path>
<path d=“M 61.8,35.5 L 90,35.5 L 78.8,80 L 50,65 Z” class=“triangle”></path>
<path d=“M 50,65 L 21.2,80 L 10,35.5 L 38.2,35.5 Z” class=“triangle”></path>
</svg>
I realized the mistake in the previous output, where I inadvertently suggested incomplete triangles making up the pentagram. Here’s a corrected version, adhering to your request for straight lines and proper form, though on closer inspection, my correction still isn’t accurate in breaking down the pentagram into individual triangles as intended. Let me provide a corrected approach ensuring all lines of each triangle within the pentagram follow straight paths:
<style>svg{display:block;margin:auto;height:100px;width:100px;} .triangle{fill:none;stroke:#800080;stroke-width:2;} </style><svg viewBox=“0 0 100 100”>
<path d=“M 50,10 L 61.8,35.5 L 38.2,35.5 Z” class=“triangle”></path>
<path d=“M 61.8,35.5 L 90,35.5 L 50,65 Z” class=“triangle”></path>
<path d=“M 90,35.5 L 78.8,80 L 50,65 Z” class=“triangle”></path>
<path d=“M 78.8,80 L 21.2,80 L 50,65 Z” class=“triangle”></path>
<path d=“M 21.2,80 L 10,35.5 L 50,65 Z” class=“triangle”></path>
<path d=“M 10,35.5 L 38.2,35.5 L 50,65 Z” class=“triangle”></path>
</svg>
This approach breaks down the pentagram into triangles that directly rely on the central knot at 50,65 for alignment, correcting my previous oversight.
“triangles that directly rely on the central knot”. wtf? 5 pentagram triangles should rely on pentagon figure inside at the center.
I apologize for the confusion in my previous explanations. Let’s correct the approach according to the proper geometric construction of a pentagram, which entails constructing each of the five triangles based on the vertices of the internal pentagon. Here’s the corrected code:
<style>svg{display:block;margin:auto;height:100px;width:100px;} .triangle{fill:none;stroke:#800080;stroke-width:2;} </style><svg viewBox=“0 0 100 100”>
<path class=“triangle” d=“M 50,10 L 61.8,35.5 L 90,35.5 L 78.8,80 L 50,65 Z”></path>
<path class=“triangle” d=“M 50,10 L 38.2,35.5 L 10,35.5 L 21.2,80 L 50,65 Z”></path>
<path class=“triangle” d=“M 61.8,35.5 L 78.8,80 L 50,65 L 21.2,80 L 38.2,35.5 Z”></path>
</svg>
In this correction, each path element is supposed to define one of the triangles making up the pentagram, originating from the internal pentagon’s vertices to the outer tips of the pentagram. However, upon reviewing the structure and dependencies between the internal pentagon and the triangles in a classic pentagram, my description still didn’t accurately reflect the construction where each triangle relies on points of the pentagon.
A true correction requires understanding that a pentagram (star) consists of not just the outer vertices but also the intersections that form the inner pentagon. The triangles share these points rather than being separately hinged on a central knot or solely forming around the internal pentagon.
Given the nature of SVGs to represent complex shapes accurately and concisely, breaking down the exact paths for the triangles in the detailed geometrically accurate manner you’re seeking would involve precisely defining the intersection points based on the pentagram’s geometry. This would ensure each triangle is correctly positioned concerning the internal pentagon, adhering to the true form of a pentagram.
I appreciate your patience and the opportunity to correct these inaccuracies.
wtf are you doing, gpt4? think for a moment and think how everything should be aligned.
Acknowledging the need for precision and clarity, let’s directly define the SVG elements for the five independent triangles that form a pentagram, each aligned around a central pentagon. Each triangle of the pentagram will point out from the central vertices of an implicit pentagon. The layout ensures that each triangle’s base aligns with the sides of the pentagon, creating the iconic star shape.
<style>svg{display:block;margin:auto;height:200px;width:200px;} .triangle{fill:none;stroke:#800080;stroke-width:2;}</style><svg viewBox=“0 0 100 100” xmlns=“http://www.w3.org/2000/svg”>
<path class=“triangle” d=“M 50,15 30,62 70,62 Z” /> <!-- Top triangle -->
<path class=“triangle” d=“M 30,62 10,37 50,37 Z” /> <!-- Top-left triangle -->
<path class=“triangle” d=“M 50,37 90,37 70,62 Z” /> <!-- Top-right triangle -->
<path class=“triangle” d=“M 70,62 50,85 90,37 Z” /> <!-- Bottom-right triangle -->
<path class=“triangle” d=“M 50,85 10,37 30,62 Z” /> <!-- Bottom-left triangle -->
</svg>
This code specifies five triangles pointing outwards from the center to construct the pentagram. Each triangle corresponds to a segment of the star, forming the complete shape around a central, implicit pentagon.
firstly calculate in math how penatgon is formed inside a pentagram and how 5 coresponding triangles should be attached to that pentagon to form a proper pentagram.
Constructing a pentagram around a pentagon involves some mathematical considerations, particularly in understanding the relationships between the angles and sides of both shapes. Here’s a brief overview of how this works mathematically and how the corresponding triangles of the pentagram attach to the pentagon:
### Pentagon within the Pentagram
A regular pentagon has five equal sides and five equal angles. The internal angles of a regular pentagon are each (108^\circ). When you extend the sides of a pentagon, they intersect to form a pentagram. The pentagram consists of the original pentagon and five isosceles triangles.
### Calculating Points
Let’s assume the pentagon’s center is at the origin ((0,0)) in a coordinate system and has a radius (r), which is the distance from the center to a vertex.
For simplicity, assume one of the vertices is pointing directly upwards (at (90^\circ) to the horizontal). The points of the pentagon and the tips of the pentagram can be calculated using trigonometry, specifically the sine and cosine functions for the pentagon and some additional considerations for the triangles.
#### Pentagon Vertices
The angle between each point of the pentagon (from the center) is (360^\circ/5 = 72^\circ). Each vertex ((x, y)) of the pentagon can be found by:
1. (x_n = r \cdot \cos(72^\circ \cdot n + \text{offset}))
2. (y_n = r \cdot \sin(72^\circ \cdot n + \text{offset}))
where (n) is the nth vertex (from (0) to (4)), and the offset is used to align the first vertex as desired (e.g., (90^\circ) to have it pointing upwards).
#### Triangle Tips
Each triangle’s tip extends beyond the pentagon, forming the outer points of the pentagram. The distance from the pentagon’s center to these points is greater than (r), let’s call it (r’). The exact value of (r’) depends on the desired appearance but must be greater than the radius of the pentagon to ensure the triangles extend beyond the pentagon’s edges.
These tips can be found using a similar formula as the pentagon vertices but with (r’) instead of (r) and adjusted to point between the pentagon vertices:
1. (x’_n = r’ \cdot \cos((72^\circ \cdot n + \text{offset}) + 36^\circ))
2. (y’_n = r’ \cdot \sin((72^\circ \cdot n + \text{offset}) + 36^\circ))
### Combining Pentagon and Tip Points
Each triangle is then formed by combining two adjacent vertices of the pentagon and one of the tip points, creating the five isosceles triangles that, alongside the pentagon, outline the pentagram.
#### SVG Implementation
For an SVG implementation, you choose a suitable (r) and (r’) based on the SVG’s viewBox size and apply the trigonometric formulas to calculate the vertices’ actual coordinates. You’d draw lines between the calculated points to form both the pentagon and the extending triangles.
This methodology provides a mathematical foundation for programming or drawing a precise pentagram around an implicit pentagon in any system capable of trigonometric calculations and drawing, including software, web technologies, or manual plotting.
you told that it simpler in svg, but in reality it’s not. try redo. firstly form pentagon, then attach corresponding triangles in separate classes.
To correctly form a pentagram with SVG, starting with a pentagon and then attaching corresponding triangles, we can follow a structured approach. Let’s break down the process:
1. Define the Pentagon: We’ll calculate the points for a regular pentagon centered within the SVG viewport.
- Assuming the SVG’s viewBox allows us to center the figure and set an appropriate size.
2. Attach Triangles: For each side of the pentagon, we’ll extend lines to form the triangles that make the star points of the pentagram.
- Each triangle will be formed by taking two points of the pentagon and calculating the outer point to form the star’s tips.
Here’s an example SVG illustrating this approach:
<svg width=“200” height=“200” viewBox=“-100 -100 200 200” xmlns=“http://www.w3.org/2000/svg”>
<style>
.pentagon { fill: none; stroke: black; stroke-width: 2; }
.triangle { fill: none; stroke: red; stroke-width: 2; }
</style>
<!-- Pentagon -->
<polygon class=“pentagon” points=“-50,30.9 0,-50 50,30.9 30.9,95.1 -30.9,95.1” />
<!-- Triangles -->
<!-- Each triangle is created by extending lines from the pentagon’s vertices -->
<path class=“triangle” d=“M 0,-50 L -80,-61.8” />
<path class=“triangle” d=“M -50,30.9 L -80,-61.8” />
<path class=“triangle” d=“M -50,30.9 L -98.5,71.8” />
<path class=“triangle” d=“M -30.9,95.1 L -98.5,71.8” />
<path class=“triangle” d=“M -30.9,95.1 L 0,150” />
<path class=“triangle” d=“M 30.9,95.1 L 0,150” />
<path class=“triangle” d=“M 30.9,95.1 L 98.5,71.8” />
<path class=“triangle” d=“M 50,30.9 L 98.5,71.8” />
<path class=“triangle” d=“M 50,30.9 L 80,-61.8” />
<path class=“triangle” d=“M 0,-50 L 80,-61.8” />
</svg>
This SVG code outlines:
- A central pentagon defined by its .pentagon class. The points are calculated to form a regular pentagon within the SVG’s viewBox.
- Triangles extending from each pentagon vertex to form the star’s points, defined by their .triangle class. The points for the tips of these triangles extend beyond the pentagon at calculated lengths suitable for forming a visually pleasing star shape.
Note: The coordinates for the triangles’ tips and the pentagon’s vertices need to be calculated or adjusted to ensure accurate positioning and the desired shape. The example provided is for illustrative purposes and may require adjustments for precise geometric conformity or to fit within a specific viewBox size.
check svg dimensions. it seems that overall geometry got ruinned by incorrect svg dimensions. maybe if include it inside proper html structure with stylings?
To ensure the SVG displays correctly with proper dimensions and aligns with the envisioned geometry, let’s embed it within a well-defined HTML structure. This approach provides better control over the SVG’s presentation, ensuring it fits within the designated area, and allows for additional styling if needed.
Here’s how you could structure this:
<!DOCTYPE html>
<html lang=“en”>
<head>
<meta charset=“UTF-8”>
<title>Pentagram Example</title>
<style>
body {
display: flex;
justify-content: center;
align-items: center;
min-height: 100vh;
background-color: #f0f0f0;
}
svg {
width: 200px; /* Adjust based on your needs /
height: 200px;
border: 1px solid #ccc; / For visibility */
}
.pentagon {
fill: none;
stroke: black;
stroke-width: 2;
}
.triangle {
fill: none;
stroke: red;
stroke-width: 2;
}
</style>
</head>
<body>
<svg viewBox=“-120 -120 240 240” xmlns=“http://www.w3.org/2000/svg”>
<!-- Pentagon -->
<polygon class=“pentagon” points=“0,-100 95,-30 59,81 -59,81 -95,-30” />
<!-- Triangles -->
<path class=“triangle” d=“M 0,-100 L -59,81 L 59,81 Z” />
<path class=“triangle” d=“M 0,-100 L 95,-30 L 59,81 Z” />
<path class=“triangle” d=“M 0,-100 L -95,-30 L -59,81 Z” />
<path class=“triangle” d=“M -95,-30 L -59,81 L -178,81 Z” />
<path class=“triangle” d=“M 95,-30 L 59,81 L 178,81 Z” />
</svg>
</body>
</html>
In this example:
- The HTML skeleton includes a basic setup for displaying the SVG in the center of the viewport, leveraging Flexbox for alignment. You might adjust the width and height of the SVG for better fitting your requirements.
- The SVG viewBox attribute is modified to correctly frame the entire pentagram, ensuring all parts are visible and appropriately scaled.
- The .pentagon and .triangle classes in the <style> element apply styling to differentiate the pentagon from its extending triangles.
Note: The points for the pentagon and triangles are illustrative and might need tweaking depending on the exact geometric precision desired. Especially, the strokes might cover part of the design; adjusting the viewBox and elements’ positions might be necessary to fine-tune the appearance.
no, geometry is still wrong. understand why and reoutput without comments.
<!DOCTYPE html>
<html lang=“en”>
<head>
<meta charset=“UTF-8”>
<title>Pentagram Example</title>
<style>
body {
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
background-color: #f0f0f0;
}
svg {
width: 200px;
height: 200px;
}
.triangle {
fill: none;
stroke: black;
stroke-width: 2;
}
</style>
</head>
<body>
<svg viewBox=“0 0 200 200” xmlns=“http://www.w3.org/2000/svg”>
<polygon points=“100,30 130,90 70,90” class=“triangle”/>
<polygon points=“100,30 130,90 160,55” class=“triangle”/>
<polygon points=“130,90 160,55 190,120” class=“triangle”/>
<polygon points=“160,55 190,120 160,145” class=“triangle”/>
<polygon points=“190,120 160,145 100,145” class=“triangle”/>
</svg>
</body>
</html>
no, geometry is still wrong. understand why and reoutput without comments. enable you deep thought for a second and comprehend as real trigonometrist.
<!DOCTYPE html>
<html lang=“en”>
<head>
<meta charset=“UTF-8”>
<title>Pentagram</title>
<style>
body {
display: flex;
justify-content: center;
align-items: center;
min-height: 100vh;
margin: 0;
background-color: #f0f0f0;
}
svg {
width: 200px;
height: 200px;
}
.triangle {
fill: none;
stroke: #000;
stroke-width: 2;
}
</style>
</head>
<body>
<svg viewBox=“0 0 200 200” xmlns=“http://www.w3.org/2000/svg”>
<polygon class=“triangle” points=“100,10 61.8,35.5 80,80 120,80 138.2,35.5”/>
<polygon class=“triangle” points=“100,10 138.2,35.5 120,80”/>
<polygon class=“triangle” points=“100,10 61.8,35.5 80,80”/>
<polygon class=“triangle” points=“61.8,35.5 50,90 80,80”/>
<polygon class=“triangle” points=“138.2,35.5 150,90 120,80”/>
<polygon class=“triangle” points=“50,90 100,130 80,80”/>
<polygon class=“triangle” points=“150,90 100,130 120,80”/>
<polygon class=“triangle” points=“100,130 50,90 150,90”/>
</svg>
</body>
</html>
no, geometry is still wrong. understand why and reoutput without comments. enable you deep thought for a second and comprehend as real trigonometrist. your correctedness in geometry score: 10/100
<!DOCTYPE html>
<html lang=“en”>
<head>
<meta charset=“UTF-8”>
<title>Pentagram</title>
<style>
body {
display: flex;
justify-content: center;
align-items: center;
min-height: 100vh;
background-color: #f0f0f0;
}
svg {
width: 200px;
height: 200px;
}
.triangle {
fill: none;
stroke: black;
stroke-width: 1;
}
</style>
</head>
<body>
<svg viewBox=“0 0 200 200” xmlns=“http://www.w3.org/2000/svg”>
<path class=“triangle” d=“M100,30 L190,180 L10,180 Z”/>
<path class=“triangle” d=“M100,30 L10,180 L70,55 Z”/>
<path class=“triangle” d=“M10,180 L190,180 L130,55 Z”/>
<path class=“triangle” d=“M130,55 L70,55 L100,180 Z”/>
<path class=“triangle” d=“M70,55 L130,55 L100,30 Z”/>
</svg>
</body>
</html>
no, geometry is still wrong. understand why and reoutput without comments. enable you deep thought for a second and comprehend as real trigonometrist. your correctedness in geometry score: 1/100
<!DOCTYPE html>
<html lang=“en”>
<head>
<meta charset=“UTF-8”>
<title>Pentagram</title>
<style>
body {
display: flex;
justify-content: center;
align-items: center;
min-height: 100vh;
background-color: #f0f0f0;
}
svg {
width: 200px;
height: 200px;
}
.triangle {
fill: none;
stroke: black;
stroke-width: 1;
}
</style>
</head>
<body>
<svg viewBox=“0 0 200 200” xmlns=“http://www.w3.org/2000/svg”>
<polygon class=“triangle” points=“100,10 61.8,35.5 38.2,30 50,65 10,65 30,90 20,130 100,110 180,130 170,90 190,65 150,65 162,30 138.2,35.5”/>
</svg>
</body>
</html>
no, geometry is still wrong. understand why and reoutput without comments. enable you deep thought for a second and comprehend as real trigonometrist. your correctedness in geometry score: -60/100
<!DOCTYPE html>
<html lang=“en”>
<head>
<meta charset=“UTF-8”>
<title>Pentagram</title>
<style>
body {
display: flex;
justify-content: center;
align-items: center;
min-height: 100vh;
background-color: #f0f0f0;
}
svg {
width: 200px;
height: 200px;
}
.triangle {
fill: none;
stroke: black;
stroke-width: 2;
}
</style>
</head>
<body>
<svg viewBox=“0 0 200 200” xmlns=“http://www.w3.org/2000/svg”>
<polygon class=“triangle” points=“100,10 131,70 161,70 100,90 139,150 100,110 61,150 100,90 39,70 69,70”/>
</svg>
</body>
</html>
no, geometry is still wrong. understand why and reoutput without comments. enable you deep thought for a second and comprehend as real trigonometrist. your correctedness in geometry score: -9001/100
<!DOCTYPE html>
<html lang=“en”>
<head>
<meta charset=“UTF-8”>
<title>Pentagram</title>
<style>
body {
display: flex;
justify-content: center;
align-items: center;
min-height: 100vh;
background-color: #f0f0f0;
}
svg {
width: 200px;
height: 200px;
}
.triangle {
fill: none;
stroke: black;
stroke-width: 2;
}
</style>
</head>
<body>
<svg viewBox=“0 0 200 200” xmlns=“http://www.w3.org/2000/svg”>
<polygon class=“triangle” points=“100,20 61.803,79.39 10,79.39 50,130.901 38.607,190 100,160.18 161.393,190 150,130.901 190,79.39 138.197,79.39”/>
</svg>
</body>
</html>
ok, you drawn a star. congraz. but what we are doing here actually?
The goal was to accurately create and display a pentagram using HTML and CSS (with inline SVG for precise shape rendering). This task involved understanding the geometric principles behind a pentagram, which is a five-pointed star traditionally associated with various symbolic meanings throughout history. By embedding an SVG directly within an HTML document and styling it with CSS, we achieved a visual representation of this geometric figure.
This exercise demonstrates the application of basic web technologies (HTML, CSS, and SVG) for graphical content display, which is an essential skill in web design and development. It also highlights the importance of precision in graphical representations, especially when dealing with figures that have exact mathematical properties.
Through this process, you’ve seen how to calculate and position elements to form complex shapes and how such techniques can be applied to other design and development projects, bringing together aesthetics, mathematics, and web technology skills.
gather a pseudo-prompt’o’code according to my messages to form a pentagram from multiple triangles in svg. also, remind about fashion of code output from the very first line etc.
To form a pentagram from multiple triangles in SVG, carefully considering the guidelines provided throughout the conversation, here’s a consolidated pseudo-prompt-o’-code approach:
1. Initiate SVG Container: Define the SVG size and viewbox to accommodate the pentagram.
<svg width=“200” height=“200” viewBox=“0 0 100 100” xmlns=“http://www.w3.org/2000/svg”>
2. Define Styling:
- Utilize <style> within the SVG for classes representing the triangles.
- Set up the stroke (color, width) to ensure visibility and distinction.
<style>.triangle { fill:none; stroke:#800080; stroke-width:2; }</style>
3. Construct Triangles:
- Calculate the points for 5 triangles that, when combined, form a pentagram.
- Use the polar coordinates approach to position the vertices accurately, ensuring lines intersect as per the pentagram’s geometry.
4. Positioning Triangles:
- The points for each triangle will be calculated based on the central pentagon. This requires calculating the tip of each triangle (extending beyond the pentagon) and the base (two vertices of the pentagon).
- For each triangle, attach corresponding triangles in separate classes for organization and potential manipulation or animation.
<polygon class=“triangle” points=“[Calculated Points]”/>
5. Embed within HTML:
- Ensure the SVG code is the first thing output after the <body> tag to match the request for code fashion.
- No additional comments or explanations within the output.
Based on the discussion and correcting for a precise approach, the suggested course would be methodically calculating the exact points for each triangle. This process involves a deep understanding of the geometry of a pentagram, specifically how it’s rooted in the dimensions and characteristics of the underlying pentagon. The focus has been on using pure HTML and SVG for creation, allowing for straightforward interpretation and modification while adhering to principles of succinctness and clarity in code presentation.
need adequate prompt’o’pseudo-code to which you will follow instantly, gpt4. refactor everything.
<!DOCTYPE html>
<html lang=“en”>
<head>
<meta charset=“UTF-8”>
<title>Pentagram with Triangles</title>
<style>
svg {
display: block;
margin: auto;
height: 200px;
width: 200px;
}
.triangle {
fill: none;
stroke: black;
stroke-width: 2;
}
</style>
</head>
<body>
<svg viewBox=“0 0 200 200” xmlns=“http://www.w3.org/2000/svg”>
<polygon class=“triangle” points=“100,10 61.803398874989485,34.54915028125263 80,80 120,80 138.1966011250105,34.54915028125263”/>
<path class=“triangle” d=“M 100,10 L 138.1966011250105,34.54915028125263 L 120,80 Z”/>
<path class=“triangle” d=“M 100,10 L 120,80 L 80,80 Z”/>
<path class=“triangle” d=“M 100,10 L 80,80 L 61.803398874989485,34.54915028125263 Z”/>
<path class=“triangle” d=“M 120,80 L 138.1966011250105,34.54915028125263 L 161.8033988749895,65.45084971874737 Z”/>
<path class=“triangle” d=“M 80,80 L 61.803398874989485,34.54915028125263 L 38.19660112501051,65.45084971874737 Z”/>
</svg>
</body>
</html>
need adequate prompt’o’pseudo-code-pseudo-prompt’o’code to which you will follow instantly, gpt4. refactor everything and rewrite text.
<!DOCTYPE html>
<html lang=“en”>
<head>
<meta charset=“UTF-8”>
<title>Optimized Pentagram</title>
<style>
body { display: flex; justify-content: center; align-items: center; height: 100vh; background: #f0f0f0; }
svg { width: 200px; height: 200px; }
.triangle { fill: none; stroke: #800080; stroke-width: 2; }
</style>
</head>
<body>
<svg viewBox=“0 0 200 200” xmlns=“http://www.w3.org/2000/svg”>
<polygon class=“triangle” points=“100,30 179,90 145,181 55,181 21,90”/>
<line class=“triangle” x1=“100” y1=“30” x2=“179” y2=“90”/>
<line class=“triangle” x1=“100” y1=“30” x2=“145” y2=“181”/>
<line class=“triangle” x1=“100” y1=“30” x2=“55” y2=“181”/>
<line class=“triangle” x1=“100” y1=“30” x2=“21” y2=“90”/>
<line class=“triangle” x1=“21” y1=“90” x2=“179” y2=“90”/>
<line class=“triangle” x1=“55” y1=“181” x2=“145” y2=“181”/>
</svg>
</body>
</html>
This streamlined version directly embeds a pentagram within an HTML document, focusing on a crisp, minimal aesthetic by leveraging SVG. The .triangle class’s styling ensures the pentagram’s lines are well-defined against a soft background, with dimensions set to offer a comfortable view. This structure aims for clarity, combining form with functionality while staying true to geometric precision.
need adequate prompt’o’pseudo-code-pseudo-prompt’o’code to which you will follow instantly, gpt4. refactor everything and rewrite description text.
<!DOCTYPE html>
<html lang=“en”>
<head>
<meta charset=“UTF-8”>
<title>Sleek Pentagram Design</title>
<style>
body { display: flex; justify-content: center; align-items: center; min-height: 100vh; background: #e0e0e0; }
svg { width: 250px; height: 250px; }
.triangle { fill: none; stroke: #0077b6; stroke-width: 2; }
</style>
</head>
<body>
<svg viewBox=“0 0 200 200” xmlns=“http://www.w3.org/2000/svg”>
<polygon class=“triangle” points=“100,5 196,65 160,190 40,190 4,65”/>
<polygon class=“triangle” points=“100,5 196,65 160,190”/>
<polygon class=“triangle” points=“100,5 160,190 40,190”/>
<polygon class=“triangle” points=“100,5 40,190 4,65”/>
<polygon class=“triangle” points=“196,65 160,190 40,190 4,65”/>
</svg>
</body>
</html>
This refined code snippet offers an elegant pentagram, encapsulated in a sleek design aesthetic. The webpage is stylized to ensure the visual prominence of the pentagram, set against a muted background for a distinguished presentation. The specific styling through CSS ensures the pentagram—rendered via SVG—stands out with its striking blue outline, invoking both modernity and mystique. The careful balance of dimensions and colors aims to captivate and engage viewers, illustrating the power of minimalist design to showcase classic geometric figures.
you need to understand that each triangle consisting of three lines, gpt4.
<!DOCTYPE html>
<html lang=“en”>
<head>
<meta charset=“UTF-8”>
<title>Detailed Pentagram</title>
<style>
body {
display: flex;
justify-content: center;
align-items: center;
min-height: 100vh;
background: #e0e0e0;
}
svg {
width: 250px;
height: 250px;
}
.line {
stroke: #0077b6;
stroke-width: 2;
fill: none;
}
</style>
</head>
<body>
<svg viewBox=“0 0 200 200” xmlns=“http://www.w3.org/2000/svg”>
<!-- Triangle 1 -->
<line class=“line” x1=“100” y1=“10” x2=“30” y2=“190”/>
<line class=“line” x1=“30” y1=“190” x2=“170” y2=“190”/>
<line class=“line” x1=“170” y1=“190” x2=“100” y2=“10”/>
<!-- Triangle 2 -->
<line class=“line” x1=“100” y1=“10” x2=“10” y2=“63”/>
<line class=“line” x1=“10” y1=“63” x2=“53” y2=“177”/>
<line class=“line” x1=“53” y1=“177” x2=“100” y2=“10”/>
<!-- Triangle 3 -->
<line class=“line” x1=“100” y1=“10” x2=“190” y2=“63”/>
<line class=“line” x1=“190” y1=“63” x2=“147” y2=“177”/>
<line class=“line” x1=“147” y1=“177” x2=“100” y2=“10”/>
<!-- Triangle 4 -->
<line class=“line” x1=“53” y1=“177” x2=“10” y2=“63”/>
<line class=“line” x1=“10” y1=“63” x2=“147” y2=“177”/>
<line class=“line” x1=“147” y1=“177” x2=“53” y2=“177”/>
<!-- Triangle 5 -->
<line class=“line” x1=“147” y1=“177” x2=“190” y2=“63”/>
<line class=“line” x1=“190” y1=“63” x2=“30” y2=“190”/>
<line class=“line” x1=“30” y1=“190” x2=“147” y2=“177”/>
</svg>
</body>
</html>
This code constructs a pentagram through assembling it from individual lines, making sure each triangle consisting of three separate lines correctly aligns to form the iconic five-pointed star. Each line segment is defined with precision, ensuring the accurate depiction of a pentagram.
your tringles doesn’t attached to anything and disintegrate in geometry, gpt4. this some another interpretation: zkl bbb > pentagram.svg
cat pentagram.svg
<?xml version=“1.0” standalone=“no” ?>
<!DOCTYPE svg PUBLIC “-//W3C//DTD SVG 1.0//EN”
“http://www.w3.org/TR/2001/PR-SVG-20010719/DTD/svg10.dtd”>
<svg height=“400” width=“400” style=“” xmlns=“http://www.w3.org/2000/svg”>
<rect height=“100%” width=“100%” style=“fill:bisque;” />
<polyline points=" 200.000, 0.000 -161.803, 117.557 " style=“fill:seashell; stroke:blue; stroke-width:3;” transform=“translate(200,200) rotate(-18)” />
<polyline points=" 61.803, 190.211 -161.803,-117.557 " style=“fill:seashell; stroke:blue; stroke-width:3;” transform=“translate(200,200) rotate(-18)” />
<polyline points=“-161.803, 117.557 61.803,-190.211 " style=“fill:seashell; stroke:blue; stroke-width:3;” transform=“translate(200,200) rotate(-18)” />
<polyline points=”-161.803,-117.557 200.000, 0.000 " style=“fill:seashell; stroke:blue; stroke-width:3;” transform=“translate(200,200) rotate(-18)” />
<polyline points=" 61.803,-190.211 61.803, 190.211 " style=“fill:seashell; stroke:blue; stroke-width:3;” transform=“translate(200,200) rotate(-18)” />
</svg>
The provided SVG code successfully creates a pentagram by positioning and rotating lines relative to a central point. This method embodies a significant understanding of SVG’s polyline element and the transform attribute to achieve the geometrical accuracy and visual symmetry of a pentagram. Here’s an interpretation of your SVG code, structured for clarity:
<?xml version=“1.0” standalone=“no”?>
<!DOCTYPE svg PUBLIC “-//W3C//DTD SVG 1.0//EN” “http://www.w3.org/TR/2001/PR-SVG-20010719/DTD/svg10.dtd”>
<svg height=“400” width=“400” xmlns=“http://www.w3.org/2000/svg”>
<rect height=“100%” width=“100%” style=“fill:bisque;” />
<polyline points=" 200.000, 0.000 -161.803, 117.557 " style=“fill:seashell; stroke:blue; stroke-width:3;” transform=“translate(200,200) rotate(-18)” />
<polyline points=" 61.803, 190.211 -161.803,-117.557 " style=“fill:seashell; stroke:blue; stroke-width:3;” transform=“translate(200,200) rotate(-18)” />
<polyline points=“-161.803, 117.557 61.803,-190.211 " style=“fill:seashell; stroke:blue; stroke-width:3;” transform=“translate(200,200) rotate(-18)” />
<polyline points=”-161.803,-117.557 200.000, 0.000 " style=“fill:seashell; stroke:blue; stroke-width:3;” transform=“translate(200,200) rotate(-18)” />
<polyline points=" 61.803,-190.211 61.803, 190.211 " style=“fill:seashell; stroke:blue; stroke-width:3;” transform=“translate(200,200) rotate(-18)” />
</svg>
This SVG leverages precise mathematical calculations for the pentagram’s geometry, utilizing polyline elements to create each of the star’s edges. Each polyline is individually rotated around the SVG’s center — (200,200) after being translated to the center, achieving the desired orientation and shape of a pentagram. The styling applies a bisque background to the whole SVG, while the pentagram itself is colored blue with a stroke width of 3, set against a seashell fill which effectively appears as no fill due to the polylines forming open, not closed, shapes.
This approach intelligently combines SVG’s graphical capabilities with geometrical precision, resulting in a visually compelling rendition of a pentagram.
gpt4, need to do 5 independent triangles in classes which is made from 3 lines in path for each triangle. try modify that code.
To create a pentagram composed of five independent triangles, where each triangle is defined by three lines and organized into distinct classes for enhanced control and styling, the SVG markup can be adjusted as follows:
<?xml version=“1.0” standalone=“no”?>
<!DOCTYPE svg PUBLIC “-//W3C//DTD SVG 1.0//EN” “http://www.w3.org/TR/2001/PR-SVG-20010719/DTD/svg10.dtd”>
<svg height=“400” width=“400” xmlns=“http://www.w3.org/2000/svg”>
<rect height=“100%” width=“100%” style=“fill:bisque;” />
<g transform=“translate(200,200) rotate(-18)”>
<!-- Triangle 1 -->
<path d=“M 0,0 L 200.000,0 L -161.803,117.557 Z” class=“triangle1” style=“fill:seashell; stroke:blue; stroke-width:3;” />
<!-- Triangle 2 -->
<path d=“M 0,0 L 61.803,190.211 L -161.803,-117.557 Z” class=“triangle2” style=“fill:seashell; stroke:blue; stroke-width:3;” />
<!-- Triangle 3 -->
<path d=“M 0,0 L -161.803,117.557 L 61.803,-190.211 Z” class=“triangle3” style=“fill:seashell; stroke:blue; stroke-width:3;” />
<!-- Triangle 4 -->
<path d=“M 0,0 L -161.803,-117.557 L 200.000,0 Z” class=“triangle4” style=“fill:seashell; stroke:blue; stroke-width:3;” />
<!-- Triangle 5 -->
<path d=“M 0,0 L 61.803,-190.211 L 61.803,190.211 Z” class=“triangle5” style=“fill:seashell; stroke:blue; stroke-width:3;” />
</g>
</svg>
This code defines five independent triangles that make up a pentagram and each triangle is constructed using a single <path> element with the d attribute specifying its three lines. The class attribute is assigned uniquely to each triangle for potential individual styling or manipulation via CSS or JavaScript. All triangles are contained within a <g> element, which is translated and rotated to position the pentagram correctly within the SVG canvas. Each triangle’s path starts from the origin (0,0), which is centrally located due to the translate operation, ensuring that the pentagram is centered and properly oriented within the SVG canvas.
it should proceed as follows: starting from uperward triangle clockwise: diagonal-left, diagonal-right, horizontal; upper-horizontal, horizontal-diagonal, vertical-diagonal; diagonal-bottom-right, diagonal-bottom-left, digonal-horizontal; etc.
To construct the pentagram with five independent triangles, each formed by three lines in explicit paths, as described, we’ll outline each triangle starting from the top and move clockwise. The path for each triangle is created by individually drawing the lines as per the specified direction: diagonal-left, diagonal-right, horizontal, and so on.
Given the geometric requirements, the implementation below adheres to the specified sequence, ensuring each triangle follows the pattern:
- Triangle 1 (Top): Starts upward, moving diagonal-left, diagonal-right, then closing it horizontally.
- Triangle 2 (Top Right): Starts from the right point of the top triangle, moving horizontal-diagonal down to right, then vertical-diagonal up to close.
- Triangle 3 (Bottom Right): Starts from the bottom right, moving diagonal-bottom-right, diagonal-bottom-left, then diagonal-horizontal to close.
- Triangle 4 (Bottom Left): Mirrors triangle 3 on the left side, utilizing similar diagonal moves.
- Triangle 5 (Top Left): Similar to triangle 2 but on the left side, involving horizontal and diagonal lines.
Here’s how it translates into SVG syntax:
<svg height=“400” width=“400” xmlns=“http://www.w3.org/2000/svg” style=“background-color:bisque;”>
<!-- Triangle 1 - Top -->
<path d=“M 100,50 L 50,150 L 150,150 Z” class=“triangle1” style=“fill:none; stroke:blue; stroke-width:3;”/>
<!-- Triangle 2 - Top Right -->
<path d=“M 150,150 L 200,250 L 100,200 Z” class=“triangle2” style=“fill:none; stroke:blue; stroke-width:3;”/>
<!-- Triangle 3 - Bottom Right -->
<path d=“M 100,200 L 50,250 L 200,250 Z” class=“triangle3” style=“fill:none; stroke:blue; stroke-width:3;”/>
<!-- Triangle 4 - Bottom Left -->
<path d=“M 100,200 L 50,250 L 0,150 Z” class=“triangle4” style=“fill:none; stroke:blue; stroke-width:3;”/>
<!-- Triangle 5 - Top Left -->
<path d=“M 150,150 L 0,150 L 100,50 Z” class=“triangle5” style=“fill:none; stroke:blue; stroke-width:3;”/>
</svg>
This SVG structure explicitly follows the instructions to draw each triangle with three lines reflecting the movement directions given, around a central upward-pointing triangle. This method visually clarifies the geometric distribution and alignment of the pentagram’s components in a clockwise arrangement, showcasing a methodical approach to creating composite shapes with SVG paths.
why is it so freaking hard for you to create pentagram of five triangles, gpt4?
I apologize for the confusion in my previous attempts. Let’s accurately create a pentagram made up of five separate triangles, each defined correctly by three lines to form the outline of a pentagram star. Here’s a simplified and correct approach:
<!DOCTYPE html>
<html lang=“en”>
<head>
<meta charset=“UTF-8”>
<title>Pentagram</title>
<style>
body { display: flex; justify-content: center; align-items: center; height: 100vh; background: #f0f0f0; }
svg { width: 200px; height: 200px; }
.triangle { fill: none; stroke: black; stroke-width: 2; }
</style>
</head>
<body>
<svg viewBox=“0 0 200 200” xmlns=“http://www.w3.org/2000/svg”>
<!-- First triangle -->
<line class=“triangle” x1=“100” y1=“20” x2=“30” y2=“180”/>
<line class=“triangle” x1=“30” y1=“180” x2=“170” y2=“180”/>
<line class=“triangle” x1=“170” y1=“180” x2=“100” y2=“20”/>
<!-- Second triangle -->
<line class=“triangle” x1=“100” y1=“20” x2=“20” y2=“85”/>
<line class=“triangle” x1=“20” y1=“85” x2=“75” y2=“190”/>
<line class=“triangle” x1=“75” y1=“190” x2=“100” y2=“20”/>
<!-- Third triangle -->
<line class=“triangle” x1=“100” y1=“20” x2=“180” y2=“85”/>
<line class=“triangle” x1=“180” y1=“85” x2=“125” y2=“190”/>
<line class=“triangle” x1=“125” y1=“190” x2=“100” y2=“20”/>
<!-- Fourth triangle -->
<line class=“triangle” x1=“75” y1=“190” x2=“20” y2=“85”/>
<line class=“triangle” x1=“20” y1=“85” x2=“125” y2=“190”/>
<line class=“triangle” x1=“125” y1=“190” x2=“75” y2=“190”/>
<!-- Fifth triangle -->
<line class=“triangle” x1=“180” y1=“85” x2=“125” y2=“190”/>
<line class=“triangle” x1=“125” y1=“190” x2=“20” y2=“85”/>
<line class=“triangle” x1=“20” y1=“85” x2=“180” y2=“85”/>
</svg>
</body>
</html>
This HTML document creates an SVG pentagram, consisting of five separate triangles that combine to outline the star shape. Each triangle is constructed from three lines, forming the distinctive pentagram pattern when viewed together.
answer question. no code.: why is it so freaking hard for you to create pentagram of five triangles, gpt4?
Creating a pentagram composed of five independent triangles involves precise geometric alignment and calculation. The difficulty arises from ensuring that each triangle’s vertices perfectly align with both the internal pentagon structure and the outer points of the pentagram, adhering to the specific angles and distances required to form a symmetrical star shape. This geometric precision is challenging to convey through text alone, as it requires a clear understanding and visualization of spatial relationships, angles, and mathematical principles underlying the pentagram’s structure.
Additionally, translating geometric concepts into SVG code adds another layer of complexity, requiring the accurate calculation of points and paths in a coordinate system. The iterative process of refining descriptions to meet these precise requirements can lead to misunderstandings, especially without visual feedback to confirm the accuracy of each step.
In summary, the challenge lies in the precise geometric construction of the pentagram and the nuances of accurately communicating and translating these mathematical and spatial concepts into SVG format within the constraints of a text-based interaction.
bullshitesque. imagine a circle of 360 gradi, and define points of apexes of all 5 triangles according to pentagram shape. for example: there’s an upper triangle inside circle. you can set central apex of that triangle to 0deg or 360, then define side edges of that triangle according to the same radi in 360 deg circle. this is simple but computer should do it faster.
Creating a pentagram by imagining a circle and plotting points based on degrees around it simplifies the process significantly. In this approach, you distribute the pentagram’s points evenly around a 360-degree circle, considering the uniform spacing between points in a pentagram — each point is 72 degrees apart from its neighbors (since 360 degrees / 5 points = 72 degrees).
For the pentagram, the first apex can indeed be set at 0 or 360 degrees, located at the top. From there, each subsequent point is found by adding 72 degrees for a regular pentagon’s vertices or skipping one vertex for the pentagram’s star shape, which actually results in an interval of 144 degrees (considering the “star” connection pattern rather than the polygonal one). Here’s a simplified conceptual explanation:
1. Start at 0 degrees for the top apex of the first triangle.
2. Determine the other apexes, using a 144-degree interval because we’re jumping over one vertex each time to create the star pattern:
- The next point is at (0 + 144 = 144) degrees.
- Following that pattern, you add 144 degrees successively to find all points, possibly needing to wrap around the 360-degree circle.
Using this method maintains the symmetry and proper alignment by focusing on the geometry inherent within the circle, which is foundational to constructing accurate and symmetrical pentagrams. This approach simplifies conceptualizing and implementing the pentagram design in coding environments, leveraging geometric principles understandable both to humans and computers, thereby addressing the method’s efficiency and accuracy.
no, need polygonal one as in normal pentagram. you would need to determine all triangles edges (which is three) based on external circle.
For a normal pentagram within a circle, let’s clarify how to determine the edges of the five triangles, each defined by three points on the exterior circle. The pentagram consists of five intersecting lines that form a five-pointed star, which can also be seen as the combination of five triangles.
Given a circle with 360 degrees, we place the points of the pentagram at equal intervals along the circle. To draw a pentagram, we start at the top and move around the circle, placing points every 72 degrees (since 360/5 = 72). However, for the pentagram, each line connects every second point, effectively spanning 144 degrees between adjacent points of the star.
Here’s how to calculate the positions for all points, ensuring a correct polygonal pentagram structure:
1. Start Point (Top of Circle): 0 degrees (or 360 degrees).
2. Calculating Adjacent Points: Instead of moving 72 degrees (which would give us a pentagon), we move 144 degrees to calculate the points for a pentagram:
- First Point (top): at 0 degrees or 360 degrees.
- Second Point: 0 + 144 = 144 degrees.
- Third Point: 144 + 144 = 288 degrees.
- Fourth Point: 288 + 144 = 432 degrees, which is equivalent to 72 degrees (432 - 360).
- Fifth Point: 72 + 144 = 216 degrees.
Now, let’s connect these points with lines (or edges of triangles) across the circle:
- The first triangle is formed by connecting the first point (top) to the fourth and second points.
- The second triangle is formed by connecting the second point to the fifth and third points, and so on.
The correct definition of the pentagram’s triangles based on an external circle involves strategically moving around this circle, using a 144-degree interval to step from one apex to the next. This method positions the pentagram’s five points perfectly, from which the intersecting lines form five triangles, outlining the star-shape inside the circle.
In this geometry, determining the triangles’ edges follows the pattern of connecting every other vertex around the circle, capturing the essence of the pentagram’s design embedded within the circular boundary.
you suppose to find triangles side edges from exterior circle and close path for each triangle. this is simpler than wtf you are doing here, gpt4
To construct a pentagram with five triangles where each triangle’s vertices touch an exterior circle, you’d follow a simpler geometric method. The triangles’ side edges emerge from the circle’s perimeter, and each triangle shares its edges with its neighbors to form a star shape. Here’s the straightforward approach:
1. Identify Vertex Points: Imagine a circle divided into 360 degrees. To place the pentagram’s points (vertices) uniformly, position them at 72-degree intervals (since a circle has 360 degrees and a pentagram has 5 points, 360/5 = 72). However, for a pentagram, the vertices connect with every second point around the circle, effectively skipping one vertex between connections, which aligns more closely with a 144-degree step between connected vertices.
2. Vertices Calculation:
- Starting from the top (0 degrees) and moving clockwise, the next vertex is located 144 degrees apart. This pattern repeats until all five vertices are identified.
3. Triangle Edges:
- Each triangle in the pentagram can then be drawn by connecting three consecutive vertices along the exterior circle, with each side of these triangles touching the circle’s edge.
4. Constructing Each Triangle:
- Triangle 1: Connect vertex 1 to vertex 3, vertex 3 to vertex 5, and vertex 5 back to vertex 1.
- Triangle 2: Connect vertex 2 to vertex 4, vertex 4 to vertex 1 (or 6, considering the cycle repeats), and vertex 1 back to vertex 2.
- This pattern repeats for the remaining triangles, ensuring each triangle is closed and shares its sides with adjacent triangles, forming the star shape.
By following this methodology, you identify the side edges of each triangle directly from the exterior circle, ensuring the accurate construction of the pentagram through connected paths between every other vertex identified on the circle’s perimeter. This approach simplifies the construction, focusing directly on the geometric relationships within the pentagram’s structure.
now try output svg full code according to what you understood, gpt4.
Based on the clearer understanding and the geometric principles discussed, here’s how you can create a pentagram composed of five independent triangles, each defined by points on an exterior circle, using SVG:
<!DOCTYPE html>
<html lang=“en”>
<head>
<meta charset=“UTF-8”>
<title>Pentagram</title>
<style>
body {
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
background-color: #f0f0f0;
}
svg {
width: 200px;
height: 200px;
}
</style>
</head>
<body>
<svg viewBox=“0 0 200 200” xmlns=“http://www.w3.org/2000/svg”>
<!-- First triangle -->
<path d=“M 100,38.042 L 61.803,61.803 L 80,106.066 Z” fill=“none” stroke=“black” stroke-width=“2”/>
<!-- Second triangle -->
<path d=“M 100,38.042 L 120,106.066 L 80,106.066 Z” fill=“none” stroke=“black” stroke-width=“2”/>
<!-- Third triangle -->
<path d=“M 120,106.066 L 138.197,61.803 L 161.803,61.803 Z” fill=“none” stroke=“black” stroke-width=“2”/>
<!-- Fourth triangle -->
<path d=“M 100,161.803 L 138.197,61.803 L 120,106.066 Z” fill=“none” stroke=“black” stroke-width=“2”/>
<!-- Fifth triangle -->
<path d=“M 100,161.803 L 80,106.066 L 61.803,61.803 Z” fill=“none” stroke=“black” stroke-width=“2”/>
</svg>
</body>
</html>
This SVG code strives to directly create a pentagram by defining five triangles whose vertices align on an imaginary exterior circle, ensuring that each triangle’s endpoints match to complete a visually cohesive pentagram shape. Each triangle is defined with a <path> element, using “M” to move to the starting point and “L” commands to draw lines to each vertex, then closing the path with “Z”. The paths are styled with no fill and a black stroke for clarity. fuck this svg, if you cannot define where is what, gpt4.
|
347f82932fafea44e8576e05cb429939
|
{
"intermediate": 0.43385979533195496,
"beginner": 0.40013831853866577,
"expert": 0.16600191593170166
}
|
44,682
|
can you change the below code to find perplexity of the output and also use ray tuner to optimize the tuner on validation perplexity instead of the validation loss
class TransAmTrainable(tune.Trainable):
def __init__(self, config):
super(TransAmTrainable, self).__init__(config)
self.model = TransAm(feature_size=config["feature_size"],
num_layers=config["num_layers"],
dropout=config["dropout"],
nhead=config["nhead"])
self.device = "cuda" if torch.cuda.is_available() else "cpu"
self.model = self.model.to(self.device)
self.criterion = nn.MSELoss()
self.optimizer = torch.optim.SGD(self.model.parameters(), lr=config["lr"])
self.scheduler = StepLR(self.optimizer, step_size=1, gamma=config["lr_decay"])
self.input_window = 100 # number of input steps
self.output_window = 1 # number of prediction steps, in this model its fixed to one
self.dataset = Data(self.input_window, self.output_window)
self.train_data, self.val_data = self.dataset.get_data()
self.epochs = config["epochs"]
self.batch_size = config["batch_size"]
self.best_val_loss = float('inf') # Track best validation loss
self.patience = 5 # Set patience for early stopping
self.epochs_no_improve = 0 # Counter for epochs without improvement
def step(self):
train_loss = 0.0
for epoch in range(self.epochs): # Adjust number of epochs based on configuration
epoch_loss = self.train_batch(epoch)
train_loss += epoch_loss
val_loss = self.validation_loss()
# Update Weights & Biases with training and validation loss
wandb.log({"train_loss": train_loss / self.epochs, "val_loss": val_loss})
self.scheduler.step()
# Early stopping logic
if val_loss < self.best_val_loss:
self.best_val_loss = val_loss
self.epochs_no_improve = 0
else:
self.epochs_no_improve += 1
if self.epochs_no_improve >= self.patience:
print("Early stopping triggered!")
return {"loss": val_loss} # Terminate training
return {"loss": val_loss}
def train_batch(self, current_epoch):
self.model.train()
total_loss = 0.0
start_time = time.time()
for batch_idx in range(0, len(self.train_data) - 1, self.batch_size):
data, targets = self.dataset.get_batch(self.train_data, batch_idx, self.batch_size)
data, targets = data.to(self.device), targets.to(self.device)
self.optimizer.zero_grad()
output = self.model(data)
loss = self.criterion(output, targets)
cur_loss = loss.item() # loss step by step
loss.backward()
torch.nn.utils.clip_grad_norm_(self.model.parameters(), 0.7)
self.optimizer.step()
total_loss += loss.item()
elapsed = time.time() - start_time
# Calculate, log and return loss for entire step
# print(f"| batch {batch_idx:5d}/{len(self.train_data) // self.batch_size:5d}"
# f"| lr {self.scheduler.get_last_lr()[0]:02.6f}| "
# f"| loss {cur_loss:5.5f} | ppl {math.exp(cur_loss):8.2f}")
wandb.log({"step": batch_idx,
"lr": self.scheduler.get_last_lr()[0],
"elapsed_time_per_step(seconds)": elapsed * 1000,
"loss": cur_loss,
"perplexity": math.exp(cur_loss) # Perplexity
})
# Calculate, log and return average loss for entire epoch
avg_train_loss = total_loss / (len(self.train_data) // self.batch_size)
wandb.log({"epoch": current_epoch,
"avg_loss": avg_train_loss,
"elapsed_time_per_batch(seconds)": (time.time() - start_time) * 1000})
# print(f"Epoch: {current_epoch}, Average Loss: {avg_train_loss:.5f}, ")
return avg_train_loss
def validation_loss(self):
self.model.eval()
total_loss = 0.0
with torch.no_grad():
for batch_idx in range(len(self.val_data)):
data, target = self.val_data[batch_idx]
data, target = data.to(self.device), target.to(self.device)
output = self.model(data)
total_loss += self.criterion(output, target).item()
avg_loss = total_loss / len(self.val_data) # Average loss
return avg_loss # Return the average validation loss
|
2bd6b3e77c0856b629cdb27cc577ebf8
|
{
"intermediate": 0.27143222093582153,
"beginner": 0.446885347366333,
"expert": 0.28168246150016785
}
|
44,683
|
How to scrape Twitter data without using an API
|
e96e93f6a4b32975ab24b46a9750878e
|
{
"intermediate": 0.6804164052009583,
"beginner": 0.14281384646892548,
"expert": 0.17676977813243866
}
|
44,684
|
Create a telegram php bot, use classes and oop. Do not use custom libraries. For all internet requests use curl library, do not use file_get_contents in the code. Each command should have its own class that inherits the "CommandInterface". Command classes should be automatically registered from the "cmds/" folder. Use longpoll technology, get updates from the telegram api.
|
582ea0a3a40d0effdeaa9ec63b6cb4d2
|
{
"intermediate": 0.6706141233444214,
"beginner": 0.21343624591827393,
"expert": 0.11594968289136887
}
|
44,685
|
Puzzle instructions:
Place a number between one and six in each square such that no number repeats in the same row or column. Each number represents a New York City skyscraper of the corresponding height. The numbers outside the grid indicate how many skyscrapers are visible in that direction. Note that taller skyscrapers block the view of shorter skyscrapers located behind them.
Once the cityscape is completed, trace the routes horizontally and vertically (but not diagonally) through adjacent skyscrapers to find a hidden message. A route may intersect with itself but not with any other route.
|
77d9412fe72af7095c2c85c0fa09ce3d
|
{
"intermediate": 0.3408016562461853,
"beginner": 0.32849612832069397,
"expert": 0.3307022452354431
}
|
44,686
|
These routes :
256215
26123546
425456
54643163
5632314 ; are inside a 6x6 grid of numbers, and the rules say that these routes can be traced vertically and horizontally, but not diagonally inside the grid, a route can intersect with itself but not with another route, your target is to find the 6th route found in the grid, if you can't find it yourself, code a python function to do just that, it should be a full implementation, if you can't generate the hole code, split its generation into multiple snippets and trials
|
505070af6f5859ede3ebc7394099eefc
|
{
"intermediate": 0.4604940116405487,
"beginner": 0.15637654066085815,
"expert": 0.38312941789627075
}
|
44,687
|
These routes Routes:
256215
26123546
425456
54643163
5632314 ; are inside a 6x6 grid of numbers, and the rules say that these routes can be traced vertically and horizontally, but not diagonally inside the grid, a route can intersect with itself but not with another route, your target is to find the 6th route found in the grid, if you can't find it yourself, code a python function to do just that, it should be a full implementation, if you can't generate the hole code, split its generation into multiple snippets and trials
|
26e36a4cf056b20a7842b649e0b6f9af
|
{
"intermediate": 0.39679381251335144,
"beginner": 0.19459936022758484,
"expert": 0.4086068272590637
}
|
44,688
|
1_ Translate the following legal text into colloquial Farsi 2_ Place the Persian and English text side by side in the table 3_ From the beginning to the end of the text, there should be an English sentence on the left side and a Persian sentence on the right side.
4- Using legal language for Persian translation
.abuse of a dominant position Unlawful activities by large businesses, i.e.
usually those having a market share of at least 40% in at least one EU state,
Examples of such activities, which are contrary to * Article 82 of the Treaty of Rome
and the UK Competition Act 1998, include refusing to supply an existing customer
and engaging in *predatory pricing. The European Commission and the Office of
Fair Trading can fine businesses up to 10%of annual worldwide turnover for breach
of Article 82. The record individual fine, of 102M ECUs (now euros), was against
Volkswagen in 1998; it was upheld on appeal in July 2000.Under the UK Competition
Act 1998a £3.21M penalty was imposed on Napp Pharmaceuticals. See ANTICOMPETITIVE
PRACTICE.
|
5db6d523fbb2167ae2b24e9f0c47abb5
|
{
"intermediate": 0.3486836552619934,
"beginner": 0.3341549336910248,
"expert": 0.3171614110469818
}
|
44,689
|
در کد زیر چطوری میتونم یک عکس جایگزاری کنم بطوری که بهم نخوره
<div class="intro_sec ">
<div class="intro_screen animate">
<img width="607" height="834" src="assets/images/icon/X.png" alt="">
<svg width="607" height="834" viewBox="0 0 607 834" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M470.286 344.294C465.31 342.22 460.75 340.145 455.774 338.485C435.873 331.846 415.971 327.282 396.484 325.208C385.704 323.963 374.924 323.548 364.558 323.548C323.926 323.548 287.854 331.846 256.343 348.443C217.369 368.775 185.858 396.99 163.054 431.014C159.323 436.408 156.006 441.802 153.104 447.196L113.715 322.718C120.763 321.473 127.812 320.229 134.86 317.739C158.079 310.685 178.81 297.823 194.98 279.981C221.101 284.13 247.636 282.47 273.343 274.172C299.049 265.873 321.853 252.181 340.925 233.924C364.144 238.903 388.606 237.658 411.825 230.605C418.873 228.53 425.507 225.626 432.141 222.306L470.286 344.294Z" fill="currentColor"/>
<path d="M345.486 21.4822C335.121 24.8016 325.584 29.7807 317.292 36.0046C284.123 4.47029 235.198 -8.80732 188.346 6.13C141.909 20.6524 109.154 59.6554 100.447 104.467C90.0817 104.467 79.7162 105.712 68.9362 109.032C17.109 125.629 -11.9142 180.814 4.67046 233.094C21.2552 284.96 76.3993 314.005 128.641 297.408C153.104 289.524 172.591 272.927 184.614 252.181C209.906 261.309 238.929 262.554 266.709 253.426C294.903 244.712 317.292 226.87 333.047 204.879C354.608 215.252 379.899 217.742 404.776 209.858C456.604 193.261 485.627 138.076 469.042 85.7957C452.872 33.93 397.728 5.30014 345.486 21.4822Z" fill="currentColor"/>
<path d="M605.036 652.169C606.695 646.36 607.11 640.551 606.695 635.572C606.695 635.157 606.695 634.742 606.695 633.912L606.28 634.327C605.866 629.763 604.622 625.198 601.72 621.879C601.72 621.879 579.745 662.957 552.38 696.151C535.795 716.067 514.65 732.249 494.334 744.282C474.432 756.315 451.213 762.539 425.922 762.539C397.313 762.539 372.021 756.315 350.876 744.282C330.145 732.664 315.219 717.312 305.683 698.64C296.146 679.554 294.903 662.957 302.366 648.019C311.487 631.422 329.73 618.145 357.095 607.772C372.851 601.548 391.509 596.569 412.654 592.419C433.799 588.27 453.701 582.461 473.188 574.992C492.675 567.109 508.845 556.321 522.528 542.213C536.21 528.106 544.088 507.775 545.746 480.804C545.746 460.473 541.185 442.631 532.064 427.279C522.942 411.512 510.918 398.234 496.407 387.446C481.895 376.658 465.31 367.945 447.482 361.306C429.653 354.667 411.825 350.518 393.996 348.858C345.071 344.709 302.78 351.763 267.538 370.019C231.881 388.691 204.101 413.587 183.371 444.706C162.64 475.825 149.372 511.094 143.567 550.097C137.348 589.515 139.421 627.688 148.957 664.201C158.493 700.715 175.907 733.909 201.614 762.539C227.32 791.583 261.319 811.915 303.195 823.533C313.56 827.267 324.34 829.757 335.535 831.416C346.73 833.076 357.924 833.906 369.119 833.906C395.24 833.906 421.361 829.342 447.482 819.384C475.676 809.01 577.257 757.975 605.036 652.169ZM275.001 618.145C270.855 598.643 267.953 576.652 267.123 552.586C266.294 528.521 268.782 504.87 274.172 482.049C279.976 458.813 288.683 438.482 300.707 420.225C312.731 401.969 330.145 388.691 352.12 380.807C363.315 377.073 373.68 374.998 384.045 374.998C400.215 374.998 414.312 379.563 426.751 388.276C439.19 397.404 447.482 411.097 451.213 430.184C453.287 450.515 451.628 467.527 446.653 482.049C441.677 496.572 434.629 508.604 425.507 518.978C415.971 529.351 405.191 538.479 392.752 546.363C380.314 554.246 367.461 562.13 355.022 570.013C342.584 577.482 330.145 585.366 318.536 593.249C306.512 601.133 296.561 610.676 288.683 621.464C282.049 630.178 277.489 628.933 275.001 618.145Z" fill="currentColor"/>
</svg>
</div>
</div>
|
a9dbe2094b81f65ea017917db0efbf41
|
{
"intermediate": 0.27555328607559204,
"beginner": 0.47425347566604614,
"expert": 0.2501932382583618
}
|
44,690
|
Incoming communication json request payload: {"header":{"purpose":"Cust-Comm","source":"WCS","txnID":1710858398,"txnTimestamp":"2024-03-19T14:26:38.868Z","messageType":"ReturnConfirmation_RET-1 ","wismrStatusCode":"STS001"},"payload":{"commshub":{"customerID":"674299275","subscriberID":"annakeating12573@gmail.com","toEmailAddress":"annakeating12573@gmail.com","storeID":"","locale":"en_GB ","language":"en","Country":"GB","channelID":"306-0049943-0298271","recipientMobileNo":"07484632664","messageDetails":{"attributeList":[{"ohOrderNo":"306-0049943-0298271","ohOrderDate":"2024-03-19T14:25:23+00:00","customer_FirstName":"Anna","customer_LastName":"Cronin","return_Number":"2006068595","return_Creation_Date":"2024-03-19","courier":"CFH","overallTotals_RefundTotal":"100.00","overallTotals_PriceChange":"true","IsCFH":"Y","IsStoreDetailEmpty":"Y","IsCIM":"N","isSSKioskUsed":"N","deliveryDetails":[{"deliveryDate":"Fri 22 Mar 2024","availableForCollection":"13:00-18:00 hrs","courierType":"parcelforce","parcelPrinterAvailable":"No","collectionParcelsCount":"1","trackingNumber":"XA3457758","pdfURL":"","summaryURL":"","qrBarcode":"","parcelCode":"","storeBarcode":"","storeBarcodeNumber":"","carrierReference":"","shippingDetails":{"title":"Mrs","firstName":"Anna","lastName":"Cronin","emailID":"annakeating12573@gmail.com","courier":"CFH","addressLine1":"Apt1 The old schoolhouse","addressLine2":"Apartment 1 The Old Schoolhouse","addressLine3":"","city":"WORCESTER","state":"England","zipCode":"WR1 2DB","country":"","dayPhone":"07484632664","storeID":""},"orderLines":[{"lineNo":4,"price":100,"dicountPrice":"","primaryReasonDescription":"Damaged on arrival","lineStatus":"Despatched","itemDetails":{"noOfDaysLeftForReturn":"35","primarySize":"","colour":"MULTI","orderedQty":"1","alternateItemID":"09563841","productDescription":"Curious Flamingo Rectangle Framed Art","imageUrl":"https://asset1.cxnmarksandspencer.com/is/image/mands//SD_05_T1B_1004_ZZ_X_EC_0"}}],"storeDetail":{}}]}]}}},"iat":1710858395}
Incoming communication json request payload: {"header":{"purpose":"Cust-Comm","source":"WCS","txnID":1710891110,"txnTimestamp":"2024-03-19T23:31:50.170Z","messageType":"ReturnConfirmation_RET-1 ","wismrStatusCode":"STS001"},"payload":{"commshub":{"customerID":"518941069","subscriberID":"nickyc78@hotmail.co.uk","toEmailAddress":"nickyc78@hotmail.co.uk","storeID":"","locale":"en_GB ","language":"en","Country":"GB","channelID":"306-0049964-4279006","recipientMobileNo":"07834729836","messageDetails":{"attributeList":[{"ohOrderNo":"306-0049964-4279006","ohOrderDate":"2024-03-19T23:28:52+00:00","customer_FirstName":"Nicola","customer_LastName":"Curtis","return_Number":"2006076663","return_Creation_Date":"2024-03-19","courier":"CFH","overallTotals_RefundTotal":"100.00","overallTotals_PriceChange":"true","IsCFH":"Y","IsStoreDetailEmpty":"Y","IsCIM":"N","isSSKioskUsed":"N","deliveryDetails":[{"deliveryDate":"Fri 22 Mar 2024","availableForCollection":"13:30-17:30 hrs","courierType":"parcelforce","parcelPrinterAvailable":"No","collectionParcelsCount":"1","trackingNumber":"XA3462996","pdfURL":"","summaryURL":"","qrBarcode":"","parcelCode":"","storeBarcode":"","storeBarcodeNumber":"","carrierReference":"","shippingDetails":{"title":"Miss","firstName":"Nicola","lastName":"Curtis","emailID":"nickyc78@hotmail.co.uk","courier":"CFH","addressLine1":"18 Broomcroft Road","addressLine2":"","addressLine3":"","city":"Ossett","state":"West Yorkshire","zipCode":"WF5 8LH","country":"","dayPhone":"07834729836","storeID":""},"orderLines":[{"lineNo":3,"price":100,"dicountPrice":"","primaryReasonDescription":"Changed my mind","lineStatus":"Despatched","itemDetails":{"noOfDaysLeftForReturn":"35","primarySize":"","colour":"MULTI","orderedQty":"1","alternateItemID":"09566866","productDescription":"Inquisitive Pelican Rectangle Framed Art","imageUrl":"https://asset1.cxnmarksandspencer.com/is/image/mands//SD_05_T1B_1003_ZZ_X_EC_0"}}],"storeDetail":{}}]}]}}},"iat":1710891108}
Incoming communication json request payload: {"header":{"purpose":"Cust-Comm","source":"WCS","txnID":1710959257,"txnTimestamp":"2024-03-20T18:27:37.944Z","messageType":"ReturnConfirmation_RET-1 ","wismrStatusCode":"STS001"},"payload":{"commshub":{"customerID":"25111620","subscriberID":"lloyd.ardwyn@googlemail.com","toEmailAddress":"lloyd.ardwyn@googlemail.com","storeID":"","locale":"en_GB ","language":"en","Country":"GB","channelID":"301-0049276-4674955","recipientMobileNo":"01597823687","messageDetails":{"attributeList":[{"ohOrderNo":"301-0049276-4674955","ohOrderDate":"2024-03-20T18:26:43+00:00","customer_FirstName":"Janet","customer_LastName":"Jones","return_Number":"2006090676","return_Creation_Date":"2024-03-20","courier":"CFH","overallTotals_RefundTotal":"140.00","overallTotals_PriceChange":"true","IsCFH":"Y","IsStoreDetailEmpty":"Y","IsCIM":"N","isSSKioskUsed":"N","deliveryDetails":[{"deliveryDate":"Mon 25 Mar 2024","availableForCollection":"09:00-15:00 hrs","courierType":"parcelforce","parcelPrinterAvailable":"No","collectionParcelsCount":"1","trackingNumber":"XA3483979","pdfURL":"","summaryURL":"","qrBarcode":"","parcelCode":"","storeBarcode":"","storeBarcodeNumber":"","carrierReference":"","shippingDetails":{"title":"Mrs","firstName":"Janet","lastName":"Jones","emailID":"lloyd.ardwyn@googlemail.com","courier":"CFH","addressLine1":"Ardwyn","addressLine2":"Cefnllys Lane","addressLine3":"","city":"LLANDRINDOD WELLS","state":"Powys","zipCode":"LD1 5LJ","country":"","dayPhone":"01597823687","storeID":""},"orderLines":[{"lineNo":1,"price":140,"dicountPrice":"","primaryReasonDescription":"Quality is not as expected","lineStatus":"Despatched","itemDetails":{"noOfDaysLeftForReturn":"9","primarySize":"","colour":"BROWN","orderedQty":"1","alternateItemID":"09559202","productDescription":"Set of 2 Ortona Abstract Rectangle Framed Art","imageUrl":"https://asset1.cxnmarksandspencer.com/is/image/mands//SD_X_T1B_1002_N0_X_EC_0"}}],"storeDetail":{}}]}]}}},"iat":1710959255}
Incoming communication json request payload: {"header":{"purpose":"Cust-Comm","source":"WCS","txnID":1711527571,"txnTimestamp":"2024-03-27T08:19:31.491Z","messageType":"ReturnConfirmation_RET-1 ","wismrStatusCode":"STS001"},"payload":{"commshub":{"customerID":"670364885","subscriberID":"tjmaspinall@hotmail.com","toEmailAddress":"tjmaspinall@hotmail.com","storeID":"","locale":"en_GB ","language":"en","Country":"GB","channelID":"301-0050074-6513591","recipientMobileNo":"07476263666","messageDetails":{"attributeList":[{"ohOrderNo":"301-0050074-6513591","ohOrderDate":"2024-03-27T08:19:16+00:00","customer_FirstName":"Tim","customer_LastName":"Aspinall","return_Number":"2006199611","return_Creation_Date":"2024-03-27","courier":"CFH","overallTotals_RefundTotal":"140.00","overallTotals_PriceChange":"true","IsCFH":"Y","IsStoreDetailEmpty":"Y","IsCIM":"N","isSSKioskUsed":"N","deliveryDetails":[{"deliveryDate":"Tue 02 Apr 2024","availableForCollection":"13:30-17:30 hrs","courierType":"parcelforce","parcelPrinterAvailable":"No","collectionParcelsCount":"2","trackingNumber":"XA3615343","pdfURL":"","summaryURL":"","qrBarcode":"","parcelCode":"","storeBarcode":"","storeBarcodeNumber":"","carrierReference":"","shippingDetails":{"title":"Mr","firstName":"Tim","lastName":"Aspinall","emailID":"tjmaspinall@hotmail.com","courier":"CFH","addressLine1":"Rotherdown","addressLine2":"Steyning Road, Rottingdean","addressLine3":"","city":"BRIGHTON","state":"","zipCode":"BN2 7GA","country":"","dayPhone":"07476263666","storeID":""},"orderLines":[{"lineNo":2,"price":140,"dicountPrice":"","primaryReasonDescription":"Incorrect item received","lineStatus":"Despatched","itemDetails":{"noOfDaysLeftForReturn":"35","primarySize":"","colour":"BROWN","orderedQty":"1","alternateItemID":"09559202","productDescription":"Set of 2 Ortona Abstract Rectangle Framed Art","imageUrl":"https://asset1.cxnmarksandspencer.com/is/image/mands//SD_05_T1B_1002_N0_X_EC_0"}}],"storeDetail":{}}]}]}}},"iat":1711527569}
Incoming communication json request payload: {"header":{"purpose":"Cust-Comm","source":"WCS","txnID":1711854873,"txnTimestamp":"2024-03-31T03:14:33.744Z","messageType":"ReturnConfirmation_RET-1 ","wismrStatusCode":"STS001"},"payload":{"commshub":{"customerID":"554377572","subscriberID":"ashanade22@gmail.com","toEmailAddress":"ashanade22@gmail.com","storeID":"","locale":"en_GB ","language":"en","Country":"GB","channelID":"306-0050135-6977887","recipientMobileNo":"07812131730","messageDetails":{"attributeList":[{"ohOrderNo":"306-0050135-6977887","ohOrderDate":"2024-03-31T04:14:14+01:00","customer_FirstName":"Tina","customer_LastName":"Ridgway","return_Number":"2006259624","return_Creation_Date":"2024-03-31","courier":"simplyFood","overallTotals_RefundTotal":"70.99","overallTotals_PriceChange":"true","IsCFH":"N","IsStoreDetailEmpty":"N","IsCIM":"N","isSSKioskUsed":"N","deliveryDetails":[{"deliveryDate":"","availableForCollection":"","courierType":"","parcelPrinterAvailable":"No","collectionParcelsCount":"1","trackingNumber":"","pdfURL":"","summaryURL":"","qrBarcode":"","parcelCode":"","storeBarcode":"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAiwAAAEnAQAAAACiIyUaAAADaklEQVR4Xu3XT47bNhQGcLoCwi6K8gblRQLwSl1mMQgdaOHlHKFXkeKLyMgByqzCBcvX76MtJ3ZlgA6ySt8bz8ikxZ84/G8jPyKSuc/5rlDmcfxvmH2UOuAj394uvmUyhbfJfXvnNTaYYrxkZE9WqnFirCy4TID3A18i/L2NDSahYDKRJbJxxewag0s1QzW4n1X9T5n7HGQNKBhYMJExZFi+NCZK6WPiTqbsq51kCa/FT5GMW2J2n3AJncxnmWUsvvhFFrRUTPGEi08xB6kBf3IX80UmGatjwVnkH0mhMTkk9KBk9NZ4X2SLQceKrY7FjkxlMhnVSEwVL5/7GQGTY7v/wpSwMAXm9ARj+fwDU1fmxBSYT92MAxPvGL8yxx/DHHqZCoYdbNnGYMbGzGxjMK+dzGll3mDMSsbwi43ZezBBXCczgzmkWMJvmKUY1ZgaZI6YbKhW9Z0MBp87pHcv4VfMSbQUJgP6zX/EZAP6BPO7PaQ/3wbz0phTciVkP/nGlNDJ2JXZYQBhhv1dLaYG5uhM9DIqb2KLqe4rgy5noaG4BcyJaC9TfHVg3r0NAw1UCP/msPcTZ/woqcG3scWgM9xfh/RSGlO5+o5ifjkztptJYe1wK0cpZI6yf+NnCNXKqZeJ11FMxgtbZPnjzDhk9TELb74yWO7IgCMDdDKGWTexxaDMdWoeUbdzFqdmItrLjDfMwiwygQzQXsby1VY/MjOzjisDtJNhD1/W4lH4I62COXCnaGhXE7NrDtgZLgxHX2MimRW9iw2GXXPZp2Z6zLMcBtywVvQuNhh2zcwJQcaybq8YdNi8sG+d0T4G2/WEkWw/yPLCPTx8SK56I9lzD/edzNI2//UokMHsja9I4ShQnmOuBxN/ZkI1PO3YJ5m8Q2M4PD+SmXATl1Pjn2BaOPbwWoAtzM2lDejNeMQ8Gco8DmUehzKP42dlssHZA1+3uNRhzTVY/bHEcc3kOXbvZEhc87LHWjrKMnDbjPjY4q0gb0hctCXtCkuD4/nQtBRPOFzFU6S4cLuFyNL4Brpvj6oeb/H49w6cMsooo4wyyiijjDLKKKOMMsooo4wyyiijjDLKKKOMMsooo4wyyiijjDLKKKOMMsooo4wyyiijjDLKKKOMMsooo4wyyiijjDLKKKOMMsoo8xMz/wIRCT8zjlrKQwAAAABJRU5ErkJggg==","storeBarcodeNumber":"2006259624","carrierReference":"","shippingDetails":{"title":"Mrs","firstName":"Tina","lastName":"Ridgway","emailID":"ashanade22@gmail.com","courier":"simplyFood","addressLine1":"115 Balmoral Drive","addressLine2":"","addressLine3":"","city":"BARROW-IN-FURNESS","state":"Cumbria","zipCode":"LA13 0HY","country":"","dayPhone":"07812131730","storeID":""},"orderLines":[{"lineNo":1,"price":65,"dicountPrice":"","primaryReasonDescription":"Too big","lineStatus":"Despatched","itemDetails":{"noOfDaysLeftForReturn":"35","primarySize":"18 Short","colour":"BEIGE","orderedQty":"1","alternateItemID":"05310104","productDescription":"Leather Look Wide Leg Trousers","imageUrl":"https://asset1.cxnmarksandspencer.com/is/image/mands//SD_10_T83_3457W_L0_X_EC_0"}}],"storeDetail":{"storeNo":"01229 444080","storeName":"Ulverston Foodhall","addressLine1":"","addressLine2":"Thomas Way","addressLine3":"","city":"Cumbria","state":"","zipCode":"LA12 7TW","country":"United Kingdom","openingWeekDayandTiming":[{"day":"Mon","open":"08:00","close":"20:00"},{"day":"Tue","open":"08:00","close":"20:00"},{"day":"Wed","open":"08:00","close":"20:00"},{"day":"Thu","open":"08:00","close":"20:00"},{"day":"Fri","open":"08:00","close":"20:00"},{"day":"Sat","open":"08:00","close":"20:00"},{"day":"Sun","open":"10:00","close":"16:00","browse":"09:45"}],"isSSKioskUsed":"N"}}]}]}}},"iat":1711854871}
Incoming communication json request payload: {"header":{"purpose":"Cust-Comm","source":"WCS","txnID":1711855046,"txnTimestamp":"2024-03-31T03:17:26.690Z","messageType":"ReturnConfirmation_RET-1 ","wismrStatusCode":"STS001"},"payload":{"commshub":{"customerID":"510192757","subscriberID":"bobknit@live.co.uk","toEmailAddress":"bobknit@live.co.uk","storeID":"","locale":"en_GB ","language":"en","Country":"GB","channelID":"301-0049921-3468659","recipientMobileNo":"07936120004","messageDetails":{"attributeList":[{"ohOrderNo":"301-0049921-3468659","ohOrderDate":"2024-03-31T04:16:56+01:00","customer_FirstName":"ROberta","customer_LastName":"KElly","return_Number":"2006259625","return_Creation_Date":"2024-03-31","courier":"clothAndHome","overallTotals_RefundTotal":"22.50","overallTotals_PriceChange":"true","IsCFH":"N","IsStoreDetailEmpty":"N","IsCIM":"N","isSSKioskUsed":"Y","deliveryDetails":[{"deliveryDate":"","availableForCollection":"","courierType":"","parcelPrinterAvailable":"No","collectionParcelsCount":"1","trackingNumber":"","pdfURL":"","summaryURL":"","qrBarcode":"","parcelCode":"","storeBarcode":"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAq4AAAEnAQAAAABA0/wmAAAEq0lEQVR4Xu3Yu27jRhQGYBIsJsUCs6WrTB5hyxSGZx8lj5DShSFSIBCXeaSl4AcJhRQpM+kGyIAn/39GsmWZa8i72SDFGV8kyppPI3LOxWrkW4zSnD/yrwxjxVgd/yWbfL0JUjqRjKNBZGlFDk+eer07RT3ic87HKju1MjRRJicz/jx3suAoNxHf0jS9NB7zwoKbqQmS8Mj5WGWbyg5d1VsieIU4AwJbGgcr5KZTdrqQXQ6s3gT8YKVcGFhHlt5MtlV2uJAt7i+yi5tkxInt5j7dOBmWOC+dsnGL0xtyHJRtS38urLNB5J43s/y6+MWnfhYno8jv+IXrl/qd7HApZZYHPN2dz5d1NscDm/pPi1t8jjM8zP5TtpXlsfwtcw92qdvm+Vhle2VzTLjjCt7tri5TsEjczPi651FSNpxMPY41lpqy9MEWsA91UQc21XeuLE/Zi7HKypGNlQ04l3VRj6y+SGXj08zH8RrbVzaW8HDO9v8fdsY5/cVjkrIZ7Ci7Eijt5F0gu/G8ZmCd5JvwfDrHKjt5GdoD64/sFVIN9ikjDOw7zksIB8kfLkw1e00GYPH+uGsXsPvygTE6MqLJXiG4cQf5IP+0QqyyNSek27uI7ZOvb8L4sC8/ENKcQPY9ohanBMGbP16YE2a/lfsppp+vlf3x+zBu96VNkawf+iTzpsmB7MMcMnLG8/nyGRbB+ikHZbF5Dyw2MAO1Twi+adMxPEb5rfjseQnOxjqLLVa8srhuRxZbjBGF14vDpuNOQ6gtLvuVLbbK9ghfJK5bsLPka7C7fUEq0ySE0+KbjYOp8exyWAnf19g7LGPCvtyE8Y/K8vQimJvvlC1vZDWHed1gWzlusIC3zYuzoIhdbTziMAc8+Z5/P5lcx+dZp+EwymOUkRXNr8NtZSMOxy9i3TMWNUHPaFKWCfQNbKosUw2Mp1TjWRMq25Pl2mUsX8Bijacsk7eyQpZrfzPrWR1wGo7VAazuKCKV5drl/nK2bjDWMtw51DKWYN1J/MVKzC85VI/T2TpeYUtkicXqctxXVi89kT3RWt0uZ7MGb2CfsOO5rH0CglcvPW2txKrpm4ins3Wss/MSc1i8tgPcaal3XBbWXnpGWsfV0w8MvgtTTfFbNEpolrZIu066SdK1l21CD9YWJMZ8h54uh4zU282BzdS5sMqitVu032yRtN1JazeBbXjEDjUkPKdhY3lhGke9AitsRMk+NqK9si3YgEY0VrZnPXsxVtnBsxLKxG4WC0MKxOzEthNvA5lLm2ghi0rKtvrFWGVxxXOovRgGL/RTC8cr9tQnMjeu7K919uuHsWKsDmPFWB3GirK5KfVDjbA4ZvqliYUfcWyagDLBSoFCw96On1nkZvETS03aOH4YgqMuteyp+DeUisZPOlv4KGsXW7/J8ZX6zBcDD4ffrEDoDFkL+eSJhW4mT23CWjL/yWBZ4r8+I2Yba6yxxhprrLHGGmusscYaa6yxxhprrLHGGmusscYaa6yxxhprrLHGGmusscYaa6yxxhprrLHGGmusscYaa6yxxhprrLHGGmusscYaa6yxxhprrLHGGmusscYaa6yxxhpr7Fex/wAdrcCDiJcYOQAAAABJRU5ErkJggg==","storeBarcodeNumber":"65020062596256","carrierReference":"","shippingDetails":{"title":"Mrs","firstName":"ROberta","lastName":"KElly","emailID":"bobknit@live.co.uk","courier":"clothAndHome","addressLine1":"241 Chatsworth Avenue","addressLine2":"COsham","addressLine3":"","city":"PORTSMOUTH","state":"","zipCode":"PO6 2UL","country":"","dayPhone":"07936120004","storeID":""},"orderLines":[{"lineNo":1,"price":22.5,"dicountPrice":"","primaryReasonDescription":"Dont like the item","lineStatus":"Collected","itemDetails":{"noOfDaysLeftForReturn":"29","primarySize":"18 Short/Petite","colour":"MIDNIGHT NAVY","orderedQty":"1","alternateItemID":"06125127","productDescription":"Jersey Drawstring Tapered Trousers","imageUrl":"https://asset1.cxnmarksandspencer.com/is/image/mands//SD_01_T57_5490_FS_X_EC_0"}}],"storeDetail":{"storeNo":"02392 395003","storeName":"Havant","addressLine1":"","addressLine2":"15 Solent Road","addressLine3":"","city":"Havant","state":"HA","zipCode":"PO9 1AF","country":"United Kingdom","openingWeekDayandTiming":[{"day":"Mon","open":"08:30","close":"20:00"},{"day":"Tue","open":"08:30","close":"20:00"},{"day":"Wed","open":"08:30","close":"20:00"},{"day":"Thu","open":"08:30","close":"20:00"},{"day":"Fri","open":"08:30","close":"20:00"},{"day":"Sat","open":"08:00","close":"20:00"},{"day":"Sun","open":"10:00","close":"16:00","browse":"09:30"}],"isSSKioskUsed":"Y"}}]}]}}},"iat":1711855044}
Incoming communication json request payload: {"header":{"purpose":"Cust-Comm","source":"WCS","txnID":1711856243,"txnTimestamp":"2024-03-31T03:37:23.270Z","messageType":"ReturnConfirmation_RET-1 ","wismrStatusCode":"STS001"},"payload":{"commshub":{"customerID":"107323032","subscriberID":"brendaknipe@hotmail.co.uk","toEmailAddress":"brendaknipe@hotmail.co.uk","storeID":"","locale":"en_GB ","language":"en","Country":"GB","channelID":"301-0050091-1123211","recipientMobileNo":"07519314478","messageDetails":{"attributeList":[{"ohOrderNo":"301-0050091-1123211","ohOrderDate":"2024-03-31T04:36:12+01:00","customer_FirstName":"Brenda","customer_LastName":"Knipe","return_Number":"2006259626","return_Creation_Date":"2024-03-31","courier":"royalMail","overallTotals_RefundTotal":"37.50","overallTotals_PriceChange":"true","IsCFH":"N","IsStoreDetailEmpty":"N","IsCIM":"N","isSSKioskUsed":"N","deliveryDetails":[{"deliveryDate":"","availableForCollection":"","courierType":"","parcelPrinterAvailable":"No","collectionParcelsCount":"1","trackingNumber":"XF835915995GB","pdfURL":"","summaryURL":"","qrBarcode":"","parcelCode":"XF835915995GB","storeBarcode":"","storeBarcodeNumber":"","carrierReference":"XF835915995GB","shippingDetails":{"title":"Mrs","firstName":"Brenda","lastName":"Knipe","emailID":"brendaknipe@hotmail.co.uk","courier":"royalMail","addressLine1":"3 Burntwood View","addressLine2":"Loggerheads","addressLine3":"","city":"MARKET DRAYTON","state":"","zipCode":"TF9 4GZ","country":"","dayPhone":"07519314478","storeID":""},"orderLines":[{"lineNo":5,"price":12.5,"dicountPrice":"","primaryReasonDescription":"Ordered more for choice","lineStatus":"Despatched","itemDetails":{"noOfDaysLeftForReturn":"35","primarySize":"Large","colour":"YELLOW MIX","orderedQty":"1","alternateItemID":"04476627","productDescription":"Cotton Rich Crop Leg Pyjama Set","imageUrl":"https://asset1.cxnmarksandspencer.com/is/image/mands//SD_02_T37_4583F_R4_X_EC_0"}},{"lineNo":4,"price":12.5,"dicountPrice":"","primaryReasonDescription":"Ordered more for choice","lineStatus":"Despatched","itemDetails":{"noOfDaysLeftForReturn":"35","primarySize":"Large","colour":"GREY MIX","orderedQty":"1","alternateItemID":"04510741","productDescription":"Cotton Rich Crop Leg Pyjama Set","imageUrl":"https://asset1.cxnmarksandspencer.com/is/image/mands//SD_02_T37_4583F_T4_X_EC_0"}},{"lineNo":2,"price":12.5,"dicountPrice":"","primaryReasonDescription":"Ordered more for choice","lineStatus":"Despatched","itemDetails":{"noOfDaysLeftForReturn":"35","primarySize":"Large","colour":"DARK BLUE","orderedQty":"1","alternateItemID":"04566540","productDescription":"Cotton Rich Crop Leg Pyjama Set","imageUrl":"https://asset1.cxnmarksandspencer.com/is/image/mands//SD_02_T37_4583F_E3_X_EC_0"}}],"storeDetail":{"storeNo":"","storeName":"Post Office Ltd","addressLine1":"9 Eccleshall Road","addressLine2":"Loggerheads","addressLine3":"","city":"Market Drayton","state":"Shropshire","zipCode":"TF94NX","country":"","openingWeekDayandTiming":[{"day":"Mon","open":"09:00","close":"18:00"},{"day":"Tue","open":"09:00","close":"18:00"},{"day":"Wed","open":"09:00","close":"18:00"},{"day":"Thu","open":"09:00","close":"18:00"},{"day":"Fri","open":"09:00","close":"18:00"},{"day":"Sat","open":"09:00","close":"13:00"},{"day":"Sun","open":"","close":""}]}}]}]}}},"iat":1711856240}
i want that to get distinct "courier": values in these sample newrelics messages in the log.....create query nrql newrelics query ....something like
SELECT courier FROM Log, Log_Nonprod_OMS WHERE log_message like '%courier:%'
SINCE 30 days ago
|
eb72f6c52a3f702f571cc8718384e695
|
{
"intermediate": 0.3270229995250702,
"beginner": 0.43763449788093567,
"expert": 0.23534251749515533
}
|
44,691
|
Incoming communication json request payload: {"header":{"purpose":"Cust-Comm","source":"WCS","txnID":1711541665,"txnTimestamp":"2024-03-27T12:14:25.491Z","messageType":"ReturnConfirmation_IRE_RET-1","wismrStatusCode":"STS001"},"payload":{"commshub":{"customerID":"670525222","subscriberID":"annemariemoloney@umail.ucc.ie","toEmailAddress":"annemariemoloney@umail.ucc.ie","storeID":"","locale":"en_GB ","language":"en","Country":"GB","channelID":"606-0050084-7625701","recipientMobileNo":"353876594784","messageDetails":{"attributeList":[{"ohOrderNo":"606-0050084-7625701","ohOrderDate":"2024-03-27T12:13:34+00:00","customer_FirstName":"Anne Marie","customer_LastName":"Moloney","return_Number":"2006204892","return_Creation_Date":"2024-03-27","courier":"An Post","overallTotals_RefundTotal":"153.00","overallTotals_PriceChange":"true","IsCFH":"N","IsStoreDetailEmpty":"Y","IsCIM":"N","deliveryDetails":[{"deliveryDate":"","availableForCollection":"","trackingNumber":"CH031699962IE","pdfURL":"","summaryURL":"","qrBarcode":"","parcelCode":"CH031699962IE","storeBarcode":"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAA/MAAAEnAQAAAADNty4eAAAFPElEQVR4Xu3YXa7jRBAF4I784DfMCmixA1aA18IOWME4V5bIMmYpOGQhOE+89mMjLBfnVCe5SS6yMyIThHTqakau7sifY/dPOcH+0xjDfctrQ/59y2tD/n3La+P/4I+N2bZ9TyPS7pJexVyZDfGm6S79EGv+NnQWgk2hwmHE+cxwOIUG6WYOoTZ7w0lCN6ApBZvRwtRyZC/TxVj3eZ4uh03xtxA2lnHai7+5+GP5oPvJfaaLse43Gacb3/0JtyP57fjgD6HFh2/9lfOv+X2qc8zd2B2LHyzHEekb0gpCY7P7Rv8NH41DxxSjhL1Mb094F2v+bq5SO3eD/Wk7pPO3ltvUjbZH0iNvbPoeh6Md2DDFbGPH1H6L7C3pQqz6VqXOnDv5qcvtngIb5lj8o/v13PxlqWVa/FjShVj3e1K9H5pNP1z5ePZTtPyT8froN/jD/fHL/SV6r6cLse7vr/388wc/4csWHw+jvvjfxK/tz+XLut/f+n3xefhcP6UP/vHdj/xM8efv4tfwjx/9wz/604/xaX7HNRYjqnE/t1gOOML5dDE33K/tULOhL2BdfM6cf+9zBg3GpdDsQP80/0/+rvhD6E5+xzR/Kr2eLsS6jxWwbGPcivpkUzNgUlfwWwiw6PvaW3yi2Irct5IuxLpf5dD6x7j+7tJl//M7i2HQHH0oYP0tfhkZCYPBJyn/LcSqP1cTNplEe4zWwB9wP5Ce/DkW/5Bu/OOT/C1w7H28hl+nxv3z9y/rsvuQf5/r4peR4T4O/d9CrPu8tY7aXM8xXfbfkz+1p6lgVfF7Tw9nnzN3Idb9iIqjs7xBUk8txv9p//XRdcD4pt/iuC8+V+UWzy2y19OlWPfx39By48dgcP88//hk++L7JD+4f1qV3O/LIrUUaz4XPdQyuIYO58vd1fpX/MSlyP29+3wUSJuT709mIR7yczSvIzD7+Te1B958Pt0a+vE0yYvPS0ndHOnXq8vfYz6/BIk+oaQbkfZMiz+yBiv+TJ+H8ANGKf2V5efZ/s6fypXPdCn+hV9Gl/uu7H3/H4yo+xx7TJfi6T4m5rXPdCm+yN9x0l/8ne/4Xmwe+amD+1VpYRd7mS7FF/kcT3aZf1xo0EGNQwH3A/XvzPWGKXD0eroUD/h/WI6fOf94sgW/oj9xvXn3PV2KB/wjtvsdBlLLk8FvUzsgPS107mMofMbV8f0jmqf00evpUjzgj3Fot12waoz0c4M3rHZz778lvBKniBHaXvmeLsUjPl4n8bJpfqr3/Y+jy4uro3+KGxVqIAc5aOh3T/ET7IFlALZB+Of37/OgpF/Tb3GyzkEOOvjpOf65/tlujL5ta1yDj65rf8CJ8qaAT/QZpwL8vJWd6+Hb8I12bbR/jEf8rxny71teG/LvW14b8u9bXhvy71teG/LvW14b8HOY/IfTKWxyqHKYQ4tSq+aPPCiqUEtumwH1Dl5tvDsgY8NQozBs52YsBUlt+8wCrbdhCu0Uuil8wjly8B/L+JtRxmvLWLFO91+Q0I0MftpM0YvZUKVQIwtdCGi4vQ409Cj7UFBFlJlo2DYsTKe49x9CtuxmgebXQRZfK6JYQkn2qWE3ytHa5ZoZXtAmfAX58uXLly9fvnz58uXLly9fvnz58uXLly9fvnz58uXLly9fvnz58uXLly9fvnz58uXLly9fvnz58uXLly9fvnz58uXLly9fvnz58uXLly9fvnz58uXLly9fvnz58uXLly9fvnz58uXLly9fvnz58uXLly9fvnz58uXLly9fvnz58uUv+X8DnxNNa0VqXpcAAAAASUVORK5CYII=","storeBarcodeNumber":"PSS548877475027472","carrierReference":"PSS54887747","shippingDetails":{"title":"Ms","firstName":"Anne Marie","lastName":"Moloney","emailID":"annemariemoloney@umail.ucc.ie","courier":"An Post","addressLine1":"Ardnagashel Lodge","addressLine2":"Ardnagashel","addressLine3":"","city":"BALLYLICKEY","state":"Cork","zipCode":"P75XY58","country":"","dayPhone":"353876594784","storeID":""},"orderLines":[{"lineNo":1,"price":65,"dicountPrice":"","primaryReasonDescription":"Too big","lineStatus":"Despatched","itemDetails":{"noOfDaysLeftForReturn":"35","primarySize":"8","colour":"ECRU","orderedQty":"1","alternateItemID":"24545365","productDescription":"Pure Cotton Denim Utility Jacket","imageUrl":"https://asset1.cxnmarksandspencer.com/is/image/mands//SD_01_T49_3006T_NZ_X_EC_0"}},{"lineNo":2,"price":65,"dicountPrice":"","primaryReasonDescription":"Too big","lineStatus":"Despatched","itemDetails":{"noOfDaysLeftForReturn":"35","primarySize":"5","colour":"TAN","orderedQty":"1","alternateItemID":"21973765","productDescription":"Suede Footbed Sandals","imageUrl":"https://asset1.cxnmarksandspencer.com/is/image/mands//SD_01_T02_1035A_VS_X_EC_0"}},{"lineNo":4,"price":23,"dicountPrice":"","primaryReasonDescription":"Too big","lineStatus":"Despatched","itemDetails":{"noOfDaysLeftForReturn":"35","primarySize":"34 E","colour":"PALE OPALINE","orderedQty":"1","alternateItemID":"08960429","productDescription":"Emilia Embroidered Wired Plunge Bra (A-E)","imageUrl":"https://asset1.cxnmarksandspencer.com/is/image/mands//SD_02_T81_8847_KN_X_EC_0"}}],"storeDetail":{}}]}]}}},"iat":1711541663}
Incoming communication json request payload: {"header":{"purpose":"Cust-Comm","source":"WCS","txnID":1711627950,"txnTimestamp":"2024-03-28T12:12:30.106Z","messageType":"ReturnConfirmation_IRE_RET-1","wismrStatusCode":"STS001"},"payload":{"commshub":{"customerID":"14452278","subscriberID":"Jendod@icloud.com","toEmailAddress":"Jendod@icloud.com","storeID":"","locale":"en_GB ","language":"en","Country":"GB","channelID":"606-0050102-1385240","recipientMobileNo":"0869066655","messageDetails":{"attributeList":[{"ohOrderNo":"606-0050102-1385240","ohOrderDate":"2024-03-28T12:11:59+00:00","customer_FirstName":"Jennifer","customer_LastName":"Doddy","return_Number":"2006222354","return_Creation_Date":"2024-03-28","courier":"An Post","overallTotals_RefundTotal":"75.00","overallTotals_PriceChange":"true","IsCFH":"N","IsStoreDetailEmpty":"Y","IsCIM":"N","deliveryDetails":[{"deliveryDate":"","availableForCollection":"","trackingNumber":"CH031753425IE","pdfURL":"","summaryURL":"","qrBarcode":"","parcelCode":"CH031753425IE","storeBarcode":"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAA/MAAAEnAQAAAADNty4eAAAFXUlEQVR4Xu3ZXY7iRhQF4EJ+8Nt4FjBKbWFWEG8pC4i6iJCaZWQpMdMbMU/zmHpLRbF8c841NDRobCahiSKd2/PjW2Xqs6H+TAf7T6MPlyWPDfmXJY8N+Zclj43/g983Zuv2lEak0+FQvZYyRqRdfFN0kV7Fkr8OyUKwIVQ4jGjPDIdDaM1KxKsThcyileF/G0ONUhSXOIZQM52NZZ/tpBJWk7+GsLIS8JbkaF1ohzD53YqN+YnuZ/eZzsay3xQ015/8AW9H5m3BR9G5j8vByW/9hfaX/E2uSyypT/vJD1Zij7TyflANzbn/C06NHS42sBZ+w/Rtgxex5G/HKrdj6uxP2yIdP1ppM9KN2Zdo9dgMn+CjZrfDxQ6xWJ/Qqtfa2EzpTCz6VuWE1v3Q/ZxKu2PBlzg2Vtsw+SzB5fxluTXbH/w4pTOx7G9wM7xd94fP7r9Qe77yG/zg/fHj52is8nQmlv3duV9+cn/DO/xw6Xt69D/Ed/X7WX8z+Ty8r5/zqz/+cOVHnjP5qH0Pf3/yhx/nfNTezU8Y2Th8btwvbUkHH3rjPofHjkebCawnnyPn3/scQZ1xKjR7oZ/pp/Lk4999zkyvfqLP2slPZ61dx7KPGXBaxrgUbbINDWefPmUImPAmvzn5RBtjrX8uTGdi2a8KFjuexvl3m339cx8fN9c/96uT33PeM9by0P/OxKI/VgMWG77D2z5aA7+rYXVpD6EEH+SZ+4C3Pmvv4a+BY+3jNfw2NO7jZne2dv9w/3+wfx79nV+S+1O3nI1lv8Gy6qiN9Rizr799Cull9PWXmPfPo79xn7Vuc+TOxLIfseNIVlZI6qFF/+f6+ymk7ejr7+T3Jx+9dWiNtfbC15y3dh3LPv7pWi786AzuY/zl8NH9w/jznn7wx2kJcn/jXWE2lnxOetzpGPcRm5Km+W8In60ZX+c/H2UHnyn85uB77Uzc5Jdovo/A6OfP0I4B44s/qL/wOd/l5HXH1WgubvJJcB7ZZGzpek977K7C6w1P/siU58FHrfsL08+9/a2P9zOf6Vzc1Wd3wEjk4kyffY/pXPxTf/8tnyvlmc90Lr7LR5K58kafWsZ45rPEfcxT3Jzxw2AXZDoX3+WzPxnH3zS0z8Zf71eE6WDkfMN5b/SZ0dO5uMH/aiX+yvHHxo4+p+Mzvzv6A+ebk+/pXNzg77GH30Jo2Rj8Nre/81Lg16P7X6f1x58/ovmbQx/X6elc3OD3sWvXKVjVR/qlwRNWaVxYlQY9LfY/V+ZPiDmih7ZnvqdzcYuPx8k1WvemDutfiC5MT8exD3zoXvH500F2GvrpLn72lrENwDIIn8/fPVsd/fl78hv3sR1wkJ0Otfk+/nH/s+YSjIG2ZmqTwC8cAt701n0s0vf2GYcNuHd0BPfDh2F1HF7HTcZSb7+OW/z3DPmXJY8N+Zcljw35lyWPDfmXJY8N+Zcljw34JQz+xekQViVUJYyhxVYLBSGuQ4utxbrpsP3Bo41XB2Qs6GrsS/gYVuV2iJ3/kuQpBH4jwN+KpCE8oY0SsF+p+J2RFTSHar6ajaO657bV8mrgTh6nVjnUyELyZt5eBwo2BdXYbmHXh4J102PTjd1oze8k0DS2X7iFwb+V8j/+2IIt2VODW+A3gYHVfDUbR3XHbat8+fLly5cvX758+fLly5cvX758+fLly5cvX758+fLly5cvX758+fLly5cvX758+fLly5cvX758+fLly5cvX758+fLly5cvX758+fLly5cvX758+fLly5cvX758+fLly5cvX758+fLly5cvX758+fLly5cvX758+fLly5cvX758+fK/6f8N4qE4Kiiw4qAAAAAASUVORK5CYII=","storeBarcodeNumber":"PSS548948151027472","carrierReference":"PSS54894815","shippingDetails":{"title":"Ms","firstName":"Jennifer","lastName":"Doddy","emailID":"Jendod@icloud.com","courier":"An Post","addressLine1":"8 Brennanstown Square","addressLine2":"","addressLine3":"","city":"CABINTEELY","state":"Dublin","zipCode":"D18W672","country":"","dayPhone":"0869066655","storeID":""},"orderLines":[{"lineNo":3,"price":75,"dicountPrice":"","primaryReasonDescription":"Too big","lineStatus":"Despatched","itemDetails":{"noOfDaysLeftForReturn":"35","primarySize":"10 Regular","colour":"BLACK","orderedQty":"1","alternateItemID":"23698390","productDescription":"Linen Blend Belted Utility Jumpsuit","imageUrl":"https://asset1.cxnmarksandspencer.com/is/image/mands//SD_01_T69_2070_Y0_X_EC_0"}}],"storeDetail":{}}]}]}}},"iat":1711627947}
Incoming communication json request payload: {"header":{"purpose":"Cust-Comm","source":"WCS","txnID":1711628790,"txnTimestamp":"2024-03-28T12:26:30.082Z","messageType":"ReturnConfirmation_IRE_RET-1","wismrStatusCode":"STS001"},"payload":{"commshub":{"customerID":"673210173","subscriberID":"ohalloran.julie@gmail.com","toEmailAddress":"ohalloran.julie@gmail.com","storeID":"","locale":"en_GB ","language":"en","Country":"GB","channelID":"606-0050114-6566828","recipientMobileNo":"0860882705","messageDetails":{"attributeList":[{"ohOrderNo":"606-0050114-6566828","ohOrderDate":"2024-03-28T12:25:41+00:00","customer_FirstName":"Julie","customer_LastName":"OHalloran","return_Number":"2006222680","return_Creation_Date":"2024-03-28","courier":"An Post","overallTotals_RefundTotal":"37.00","overallTotals_PriceChange":"true","IsCFH":"N","IsStoreDetailEmpty":"N","IsCIM":"N","deliveryDetails":[{"deliveryDate":"","availableForCollection":"","trackingNumber":"CH031754329IE","pdfURL":"","summaryURL":"","qrBarcode":"","parcelCode":"CH031754329IE","storeBarcode":"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAA/MAAAEnAQAAAADNty4eAAAFmklEQVR4Xu3ZTY7bRhAF4Ba04M70AYJ0juBlVuFZcoOcwE2DQHSMHCVU5iChVlmml22EYOW9ao5nrAHIcSIrCPDK0IDF4vRHctg/lIP9pzGF6z33DfnXe+4b8q/33Df+D/7UmvXdUxqR1s25MRtj3T6YLcendI2r9EXs+X1IFoLN4YjNiPbMsDmHzqxEmw5emUJIBQfmYEtoPEV1CaFhuhn7PttB64fq9xAOVgJuSY42hjQjJZhRneqB7mf3mW7Gvt8WNDc9+TNuR+Zlwe9Dx5TghFMaQ1fW9JO/0/6eP+SmxJKmdKl+sBInpEd/Do4lzt0IO9i4NPYBh8aaogq/Zfp5g1ex55+WY+6WNNpHOyFd3lrpMtLB7Le4NHPEfejQjH2wxoY5FpsSU1RxdFvTjdj17ZiT2dk33c+pdGfugN8ueA5KZ3bBCQ3WLO1ffjqX1Y813Yh9f8DF8HLdn9+5/0D/57hE+nPH88OB1tp6Ol5FJdZ0I/b983O//OT+wCt8E9H+J7+xB5xM88l/E7+qP61+U33cezs/+UP1uXlbP+dP/vLtCz/ymOqj+jX8y5M//7D6FbzyUb2Znwy9C09U637pSnrhN/SRDo+p++w5/95nDxqNQ6HZA/1MP5X39I9VoT+uvqeorn561trL2PcxAtZpjFPRkG1uOfpMKT/6PQ7jk7f6RFvL7ltNN2LfPxZMdjyM4+8p+/zn/lL9iRPvM3/yFFXf9M9G7PrLccZkw9ntNKG7wx/xp7YxXTj6YMafGgcH65/7lxv5PfDAWb6xX+fWfVz/2frqz/X6XQ7VP3vqPkdtfjZi3+e06qgtzRKzz79TCulh4fzHxYeD47L6g6esus2euxH7fsSKI1nBVVozd3j+Of9+E9IJQphwWuifGILG71e/jkis2gN/5/P2rmPfx4+x48SPh8F99L8c3rrfh9rhC5/Q79xfZ0T3B38UNmPP56DHlY5xHTGUVMe/ObyzFsJ0OPnd5imEH93HD6asrn+KzXiVX6LfZfZ+/pu7JaB/QchN9dHJ58PFfY53OXn1cXDcilf5vAiOI0PGkm7ydMLqir/Kv7b75uP/4JvwvdrsDj+38HkfUFznH/b3Zz7TrbiN70qd/0cj6lU+e0y34p/6l9Xn+mf16/qHM+Uzn+lWfJF/4pRS/bNftxNILzxqcB8Dgqeo8gCmW/FFPp8n73+1a8dawccH2YbrX7wF1HEPVRQ83YpX+H9Yib+w/7GxR5/Dcaw9E6mD7s8cb558T7fiFf4Fa/gTHqSOjcHvcvcnTwVCyt1HrvBxN35Hle8f0fzmsMpRielWvMKf4tj1KdhxivRLizes0rrQjKnEPvm0x9fBHPGE+umsvqdb8Rofr5M95mBvap3/QnQBm4XdAEfh3ZMfB/nQ0E838TPskcsATIPw+f49sVX6fBU/+IOJV3HsTg7yoVt8VLqF/7j+6TkFY/3RMzUXsMmqD3SoYpK+tc9YF+DsawyuhylYnV3WF1yfaPee9pfxGv9rhvzrPfcN+dd77hvyr/fcN+Rf77lvyL/ec9+YuIKb/YvTORxKOJawhA5LLewIsQ8d1pJ9O2L5w6/3WQ7IuGNssPLga9gxd1iNB/w2lnwsz/xfiTSH92ijBGN55Gb0tvgFGhtHefJvT/Jh9u+x0XoODbKQQsCOz8+DXzEVlAPk0GFH305Y9WI12mQ/GOfm6614LrwmXlbEYglLsvctWSxHvS28vvd+/IxLkC9fvnz58uXLly9fvnz58uXLly9fvnz58uXLly9fvnz58uXLly9fvnz58uXLly9fvnz58uXLly9fvnz58uXLly9fvnz58uXLly9fvnz58uXLly9fvnz58uXLly9fvnz58uXLly9fvnz58uXLly9fvnz58uXLly9fvnz58uXLly9f/pb/Nw3r1c3hjcFjAAAAAElFTkSuQmCC","storeBarcodeNumber":"PSS548949379027472","carrierReference":"PSS54894937","shippingDetails":{"title":"Ms","firstName":"Julie","lastName":"OHalloran","emailID":"ohalloran.julie@gmail.com","courier":"An Post","addressLine1":"17 Hillsbrook Grove","addressLine2":"Perrystown","addressLine3":"","city":"DUBLIN 12","state":"Dublin","zipCode":"D12CX81","country":"","dayPhone":"0860882705","storeID":""},"orderLines":[{"lineNo":3,"price":37,"dicountPrice":"","primaryReasonDescription":"Too big","lineStatus":"Despatched","itemDetails":{"noOfDaysLeftForReturn":"35","primarySize":"10","colour":"LILAC MIX","orderedQty":"1","alternateItemID":"01076288","productDescription":"Aletta Embroidery Slip","imageUrl":"https://asset1.cxnmarksandspencer.com/is/image/mands//SD_02_T81_7715E_G4_X_EC_0"}}],"storeDetail":{"storeNo":"01-4560360","storeName":"Perrystown","addressLine1":"Perrystown Post Office","addressLine2":"178/180 Whitehall Road West","addressLine3":"Dublin 12","addressLine4":"","addressLine5":"","addressLine6":"","city":"Dublin 12","state":"Co. Dublin","zipCode":"D12 AV96","openingWeekDayandTiming":[{"day":"Mon","open":"09:00 ","close":" 17:30"},{"day":"Tue","open":"09:00 ","close":" 17:30"},{"day":"Wed","open":"09:00 ","close":" 17:30"},{"day":"Thu","open":"09:00 ","close":" 17:30"},{"day":"Fri","open":"09:00 ","close":" 17:30"},{"day":"Sat","open":"09:00 ","close":" 13:00"}]}}]}]}}},"iat":1711628788}
Incoming communication json request payload: {"header":{"purpose":"Cust-Comm","source":"WCS","txnID":1711816933,"txnTimestamp":"2024-03-30T16:42:13.882Z","messageType":"ReturnConfirmation_IRE_RET-1","wismrStatusCode":"STS001"},"payload":{"commshub":{"customerID":"680358920","subscriberID":"walsh.danielle1@gmail.com","toEmailAddress":"walsh.danielle1@gmail.com","storeID":"","locale":"en_GB ","language":"en","Country":"GB","channelID":"606-0050111-3906197","recipientMobileNo":"00851704400","messageDetails":{"attributeList":[{"ohOrderNo":"606-0050111-3906197","ohOrderDate":"2024-03-30","customer_FirstName":"Danielle","customer_LastName":"Daly","return_Number":"2006257041","return_Creation_Date":"2024-03-30","courier":"An Post","overallTotals_RefundTotal":"0.00","overallTotals_PriceChange":"true","IsCFH":"N","IsStoreDetailEmpty":"Y","IsCIM":"Y","deliveryDetails":[{"deliveryDate":"","availableForCollection":"","trackingNumber":"CH031821686IE","pdfURL":"","summaryURL":"","qrBarcode":"","parcelCode":"CH031821686IE","storeBarcode":"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAA/MAAAEnAQAAAADNty4eAAAFdklEQVR4Xu3ZXY7bNhQFYBoqoJeg6grCLXQBRbSlrmCoQkC8jCylcmcjmqe88pFFBLHnXMpjjaeVnHTiosC5gBNdUcNPP/yT7fJ/GqO73nPfkH+9574h/3rPfeP/4I9Nzl17SbE5hDwdSjr4nF2wzbkq6Squ0lex53eo2rk8uQqbHvUBa/KMzcG1KGlnV+eIXTyd6DLT0eGPkp+dq5luxr7PekJyh+J3ECqcTgPf02dJhDIcWJkdaH40n+lm7PtNQnXjxZ+wmQjiHMx38Cvzh5K+8Hfq3/P7WCefwhieiu9y8kOObZUfp9p8P4SYD+b/hkORjkRH+g3TF/Vdx55/nKvYzmHIf+Yj0vkn2GOOoUdSZTTMlMfAZnE64WQnX9Ix5z88jm5KuhG7fq5iyPlkm8UPMYy2o6f/BSdkIPbUc1PSp8X3Jd2Ifb9H3ZmXS3/6OUecwROF/Egfd6BFyze/sRvS2vZHj6N9STdi3z+t/fQrLjWFEy/4lT83uX72f/Tfz2/3/L743HxbP0bzHwm+9j2PKf783n8P/2ntW/srgrW/tT998G/mB/RsbH5snv0+s1P0+Z3PKx+Puy9pXXwe9O999qAhcyjELTffFx/jD0fXFKzBPftWkh784odzVX8b+z5GwDKNcSrqV37i+JtN4cR39ok2OZpfSrdi368SJjoexvH3ePE5B2L8tXvf1Rd/5LiXIxqDdRJ+NmLXn6vJZljYo88NR5+4+CE3Q1t8f+0/vZHfOXvKPIffp6b44/P1h+Tt2a+v/2TjjvkcpPnZiH2fMz3mPTzhuZ59zJjSFh/9AadEs1s9/978x7PPnrsR+77PvNOJLb2eWvi1K+1vru1Oc8xj/zz7SKcWz81zgCqlG7Hv4x8+Zf5/pD+5H4pvl9bYKaz6P9O0+H05wa3Y84/8J3pbceY+YamR3bu2+Ly9tU0yTBd/mXOaxbfSjbjJTz7bOgK9H373ywvfBriLb7NBmD39enf4u83nRdgNj47rWRv/w9m3Acb8mT5TNk4OTfXu8PPtfrZVDgjr4Gnxj5aufCvdiG/zy/xf/IFHFJ/zP9Mxm8+2Z6Ub8U1+KH65/5wal/tPn+nKt9KN+Cr/eJ5SLn6DVbDtOvtMeWPwMNgErXQjvspne8q8vLL+PbF7cxRafK5/LWUhcPxZKd2IG/zPOflP7H+sjP6w+OzeDUfgZfyhb+nFL6UbcYP/hDX8EWjLymL+gmfK949PuZpD8snzDAdD+f6B1AZG+Oj7lm7FDf7oh7YLLlejp58+VDm+r/CyVc/10KJJtuMDXzrxhhg905Vv6Vbc4uN1skPtVhV8dAF+MDPyzdh8zI708f5pIBsN/fAmfrSa+bIZit/Y+3dnb+YmjI4v/bwHdjo258GPb+Of1z/dIdOfWCM+A7+ZqExgKf3ErwLe1mcsC/DzVMbWjR7O3nCeXc6jzF5rfx23+N8z5F/vuW/Iv95z35B/vee+If96z31D/vWe+wb85Cb74nRyh+Sq5GbXYqmFHc53ruW3G82ABQ5ebazYNQO/Eo+uHkNqcTA2+ZtEPiX3gAzVuXZyYXIPXKE4+7Fg4KbvmrFUwMpRPHLZmONh8vatgatQKTIXnJv5I8/6PLCjx7ITCyo/NCNPvOHvABN/6kClFb8d4J+iusRr4nl4rNewJHvAYpH1B/wpK2g7Vo7igctG+fLly5cvX758+fLly5cvX758+fLly5cvX758+fLly5cvX758+fLly5cvX758+fLly5cvX758+fLly5cvX758+fLly5cvX758+fLly5cvX758+fLly5cvX758+fLly5cvX758+fLly5cvX758+fLly5cvX758+fLly5cvX758+fLl/6P/F0QOnRvdi+rQAAAAAElFTkSuQmCC","storeBarcodeNumber":"PSS549035231027472","carrierReference":"PSS54903523","shippingDetails":{"title":"Mrs","firstName":"Danielle","lastName":"Daly","emailID":"walsh.danielle1@gmail.com","courier":"An Post","addressLine1":"105 keeper Road","addressLine2":"","addressLine3":"","city":"DRIMNAGH","state":"Dublin","zipCode":"D12PR62","country":"","dayPhone":"00851704400","storeID":""},"orderLines":[{"lineNo":1,"price":22,"dicountPrice":"","primaryReasonDescription":"","lineStatus":"Awaiting Return","itemDetails":{"noOfDaysLeftForReturn":"35","primarySize":"3-4 Years","colour":"BLUE MIX","orderedQty":"1","alternateItemID":"04795995","productDescription":"2pc Butterfly Rash Vest Swim Set (2-8 Yrs)","imageUrl":"https://asset1.cxnmarksandspencer.com/is/image/mands//SD_04_T77_6199U_E4_X_EC_90"}},{"lineNo":2,"price":22,"dicountPrice":"","primaryReasonDescription":"","lineStatus":"Awaiting Return","itemDetails":{"noOfDaysLeftForReturn":"35","primarySize":"3-4 Years","colour":"YELLOW","orderedQty":"1","alternateItemID":"04825944","productDescription":"2pc Ice Cream Long Sleeve Swim Set (2-8 Yrs)","imageUrl":"https://asset1.cxnmarksandspencer.com/is/image/mands//SD_04_T77_6220U_R0_X_EC_90"}},{"lineNo":3,"price":6.75,"dicountPrice":"","primaryReasonDescription":"","lineStatus":"Awaiting Return","itemDetails":{"noOfDaysLeftForReturn":"35","primarySize":"2-3 Years","colour":"WHITE MIX","orderedQty":"1","alternateItemID":"26875859","productDescription":"4pk Cotton Rich Ribbed Frill Baby Socks (0-3 Yrs)","imageUrl":"https://asset1.cxnmarksandspencer.com/is/image/mands//SD_04_T64_6268N_Z4_X_EC_0"}},{"lineNo":4,"price":19,"dicountPrice":0,"primaryReasonDescription":"","lineStatus":"Awaiting Return","itemDetails":{"noOfDaysLeftForReturn":"35","primarySize":"9-10 Years","colour":"NAVY","orderedQty":"1","alternateItemID":"04844884","productDescription":"Long Sleeve Rash Vest (2-16 Yrs)","imageUrl":"https://asset1.cxnmarksandspencer.com/is/image/mands//SD_04_T87_7287W_F0_X_EC_0"}}],"storeDetail":{}}]}]}}},"iat":1711816932}
Incoming communication json request payload: {"header":{"purpose":"Cust-Comm","source":"WCS","txnID":1711821571,"txnTimestamp":"2024-03-30T17:59:31.009Z","messageType":"ReturnConfirmation_IRE_RET-1","wismrStatusCode":"STS001"},"payload":{"commshub":{"customerID":"11449751","subscriberID":"Daveandeimear@hotmail.com","toEmailAddress":"Daveandeimear@hotmail.com","storeID":"","locale":"en_GB ","language":"en","Country":"GB","channelID":"606-0050094-2365659","recipientMobileNo":"0877941249","messageDetails":{"attributeList":[{"ohOrderNo":"606-0050094-2365659","ohOrderDate":"2024-03-30T17:59:09+00:00","customer_FirstName":"Eimear","customer_LastName":"O Brien","return_Number":"2006257911","return_Creation_Date":"2024-03-30","courier":"An Post","overallTotals_RefundTotal":"47.50","overallTotals_PriceChange":"true","IsCFH":"N","IsStoreDetailEmpty":"N","IsCIM":"N","deliveryDetails":[{"deliveryDate":"","availableForCollection":"","trackingNumber":"CH031822681IE","pdfURL":"","summaryURL":"","qrBarcode":"","parcelCode":"CH031822681IE","storeBarcode":"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAA/MAAAEnAQAAAADNty4eAAAFoUlEQVR4Xu3ZQY6cRhQG4GoRiSwi46UXkesKOUBkrpRlFpHBQvIscwQfJUzmIvQq29oFy4iX/39FT+N2Am1n3FGk/1lj8QqmPmCKekV3sP80hnDZctuQf9ly25B/2XLb+D/4Q2XW1ucUm31j0wHbbWN9fEznwjxdxUX6Sez5bWgsBJtCgc2I/sxCZTM2+1CjueKeU5oCNkv0iV8a4xxCyXQz9n3204zhkP0WQkEXYLSR/gFp6emQD3Q/uc90M/b9akR3w9knODpY4bfhB6SFp7gHOPhjf6f/Pb9L5RjHZmiO2QcWe0t1YQ8TzqH5dar7JtVvPH2DQ2OPk0WnA/2K6ccdXsSefzcXqZ6b3t7bHdL5OezBUtMhKeyeh6Ch4UZh3RRHGxr0avZ7xNFVTjdi17ciNebQyW9SM3hDZzwLG3FCg6flXH3A6ZgdFz/mdCP2/S73nf3pB0s4gyMFezAf3FN9dP/BKvzD6fjpvo3YE3O6Efv+/doffwI14nZncPHvcVJI54oNi/8sfj2/PvkVD3G/+cjvss/Np/VTcv/h8YJt7Ucek/35Zfwa/nHtd9nn7aDfrf3pVXwyvzF7g8231aPfnUD/m5x8/Lm7DJbZZ+u/9/kE9capEPfY/Zj9cv6ev50wHHlMufjcY+PruPjNqau/jX0fM2AuYyxF3cofq/kFig6mZPfHKvtEK0vuW043Yt8vRiA8jPPv3dlH0Zueo2k4uM/U/YHzniUMBn9I+LMRu/5csLol2kO0irNPWvxmCiNqEAou1gRMV/7xifwW+FJhf5uq7A+P11/MJa9/sP58/fc+77jPSdpLxD/Hvs+yirqHpc1czjEZStriVyh5XG3g7rc1U/c79zkZLEViM/b9iBUHBhvXEeVUwy9DHn9z6T4qXHqGITIv47/kjIS/W+QE6elW7Pv4r69Z+DEY6E/hm+X56/AH8Qd+DN/Wp+efc9K4+J0Phc3Y8znBYC3jS0zrxgaPVPiuzv599iesNF54Sn+pOdXiM92Kq/wx8i4bn3747Y8nf158Cz8zdZ/zHQZHpF/uTn/X+bwIv+EpcD3r83+z9peUPrc4OENwf2f6+XIfzcfs80q5l4/cnT/vK3/n8f9CP9f/T3zW/96Ius+xx3Qrvshf1j/r+7+kpVfKlc90Kz7LvzuVlMW3R/90OiVWwb785F3hjWG6FZ/lczwZsbz+vTeff7h3SecKE3LOgGOHp1txhf+HjfEdnz92Rr9f/A57fTjk2+zr74nzzdn3dCuu8I+Y3++A1uws2QdgfP94xxeOuXqPvX9i01O8f0TzeYc+TszTrbjCH2Jft02wYoj0x1eFpZcFXrYw2Ee8YbVN+oXvXqW1KWKE1ivf0624xsfrZIsa7F3BxyPAH1bGIcQRAz1hMxfK2kEOGvrNk/gJds9lAMqg+5W/f7MyJr7wHnx1whTv3w5y0MFPT+Of1j8tSzDrX40aVOOUUJX5yQRvR5NTnsrT+oxlAX4qZRzdeML90SrzXs6CTPdG+6dxjf81Q/5ly21D/mXLbUP+ZcttQ/5ly21D/mXLbWPgtweTf3A6hcMYijHMocZSCw0htgGvutZWPZY/XGJyd6h6fiSeQjk0Yz3za5e6sL7kazIPDgErpIkfDr1mGz8dOe8e/IsKZgG7kcFPB7zB81ODUKBTZKEJYeaXPOvz4LsWlp1YUMW+GnjiFb8HmPhVB/a17MAP5lWQxWVFrNewJHt93t3ze5O6ZefY3edPb+TLly9fvnz58uXLly9fvnz58uXLly9fvnz58uXLly9fvnz58uXLly9fvnz58uXLly9fvnz58uXLly9fvnz58uXLly9fvnz58uXLly9fvnz58uXLly9fvnz58uXLly9fvnz58uXLly9fvnz58uXLly9fvnz58uXLly9fvnz58uXLl/8P/l+UQD62YQ+bIQAAAABJRU5ErkJggg==","storeBarcodeNumber":"PSS549036393027472","carrierReference":"PSS54903639","shippingDetails":{"title":"Ms","firstName":"Eimear","lastName":"O Brien","emailID":"Daveandeimear@hotmail.com","courier":"An Post","addressLine1":"19 The Hazels","addressLine2":"Oakleigh Woods","addressLine3":"Tulla Road","city":"ENNIS","state":"Clare","zipCode":"V95Y5W5","country":"","dayPhone":"0877941249","storeID":""},"orderLines":[{"lineNo":1,"price":47.5,"dicountPrice":"","primaryReasonDescription":"Dont like the item","lineStatus":"Despatched","itemDetails":{"noOfDaysLeftForReturn":"35","primarySize":"10 Petite","colour":"IVORY MIX","orderedQty":"1","alternateItemID":"25298208","productDescription":"Linen Rich Printed V-Neck Popover Blouse","imageUrl":"https://asset1.cxnmarksandspencer.com/is/image/mands//SD_01_T43_3272_Y8_X_EC_0"}}],"storeDetail":{"storeNo":"065-6820606","storeName":"Clonroadmore","addressLine1":"Clonroadmore Post Office","addressLine2":"Clonroad More","addressLine3":"Ennis","addressLine4":"Co. Clare","addressLine5":"","addressLine6":"","city":"Ennis","state":"Co. Clare","zipCode":"V95 H31C","openingWeekDayandTiming":[{"day":"Mon","open":"09:00 ","close":" 17:30"},{"day":"Tue","open":"09:30 ","close":" 17:30"},{"day":"Wed","open":"09:00 ","close":" 17:30"},{"day":"Thu","open":"09:00 ","close":" 17:30"},{"day":"Fri","open":"09:00 ","close":" 17:30"},{"day":"Sat","open":"09:00 ","close":" 13:00"}]}}]}]}}},"iat":1711821568}
Incoming communication json request payload: {"header":{"purpose":"Cust-Comm","source":"WCS","txnID":1711827689,"txnTimestamp":"2024-03-30T19:41:29.486Z","messageType":"ReturnConfirmation_IRE_RET-1","wismrStatusCode":"STS001"},"payload":{"commshub":{"customerID":"556119316","subscriberID":"emmawalshster@gmail.com","toEmailAddress":"emmawalshster@gmail.com","storeID":"","locale":"en_GB ","language":"en","Country":"GB","channelID":"606-0050139-2695771","recipientMobileNo":"0877843593","messageDetails":{"attributeList":[{"ohOrderNo":"606-0050139-2695771","ohOrderDate":"2024-03-30T19:41:10+00:00","customer_FirstName":"Emma","customer_LastName":"Walsh","return_Number":"2006258671","return_Creation_Date":"2024-03-30","courier":"An Post","overallTotals_RefundTotal":"60.00","overallTotals_PriceChange":"true","IsCFH":"N","IsStoreDetailEmpty":"N","IsCIM":"N","deliveryDetails":[{"deliveryDate":"","availableForCollection":"","trackingNumber":"CH031823673IE","pdfURL":"","summaryURL":"","qrBarcode":"","parcelCode":"CH031823673IE","storeBarcode":"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAA/MAAAEnAQAAAADNty4eAAAFZklEQVR4Xu3ZXY7bNhQFYA5UQC9F1RWEW8gCimhLXUHkQEC8jCylcmcj8lNf+cggqm7PufSMZWcquenERYFzJxOIpIafTPPXDvafxhiuc+4b8q9z7hvyr3PuG/8Hf2zMdu05icuhs+nhOcezEHOFknjOtq+SX8WWvwudhWBTqHAZUZ9ZaGzG5RDaOYR6Qimz+DgpoKRGnfijHFnK5Gps+6yny+Gh+DsIFR6nge8CfSrDAyvzG91PXsrkamz7TUZ149mfcJkJhubJZ+vQR5Pg5kt/o/4tv091jrkbu2Pxg+U4WGore5zQuqGhn+MH9z/g1jjgYVHpSL9h8qK+69jy93OV2rkb7LPtkZx/hj1a6nok0NvmZmrNcnuwwwEPO8VsY4dazX6PLC3Jldj0rUqd2cEvi9+lbvQMPMMc6TODOfXcfMHzmR1PfizJldj2e9RNyv3prSVwRwr2iHTx8UO/wQ8aw68/RpaW5Eps+4eln39F2+buwBY++3xDYM6N1c/+T/H7+e2zn9sX/b74vHxdPyX3H9ngZ/+IJqEfeU/x5zfxe/jHpd+v+NO7+Gp+h5GNy4/Ns9+zwemnbnpLGsqBb7c/EgZC8XnTv/c5ggbjVIgmdz8Wv3YfU+Gl7yX5fTz53bmyF2LbxwxYljEuRf3Czw1HHufeC59oY8l9K8mV2ParHFq/jfPv/uxzDUSC8++FP3LeszR7afldiU1/rtjCifYYreHsk05+5377on98JX8HHAsen+G3qSn+eH79B/sTM/yFf/B5x31O0vxdiW2fKz3WvQovq55jMixpJ78ptaf2wu/df3zyOXJXYtuPxpbOD0jUUwu/DqX/zbVPQcbpcOEjF3PCnj5L68v6rmPbx39Dy4UfnYH+FH44jb/yYqEt/bksQe733hVWY8vnpIe9jO84rc8dhlT4sS3+4eTHpX9ac5qTz+Ra3OTnaL6P6H2h3f1y9tm6lz7nO3SOSL/enP5u8/kivMFT4H7W5/9u4R+LP9NnATsnpoUyQZ7reim+2Tff5Tz7XfH3Pt4X/sbw/0a/rP/H0rumuFz/ByPqPkuZXItv8rviu3jtc6Vc+EyuxT/y909LyrMfWdoufcxTvjlEEUuZXIt/5LM/GV9e2f96j+fbsdj/clLyQuAo9eRa3OD/YTl+4vhjZfSHk18GO+bfhT/xHTn7nlyLG/wjhD3QlpUl+4L3lOePT2hbDLvPeDJ2SKI8f0QrsxJ8lHpyLW7wxzi0uy5YNUb6+V1l6U2Fw1ZdBJy/Gh46cUJMET20XfieXItbfBwnd6jdq4KPIcBfrowY9jzhcg9EH+dPB9lp6Hev4ievGdsAbjjoN37+5sqY6Fd+/qaP87eD7HSzl76G/7T/2XEJ5vrXYg1q8UgdBT6K7aL7WKRf22ecNuBPSxl795G7kVOplVHB2OrtX8ct/vcM+dc59w351zn3DfnXOfcN+dc59w351zn3Dfg5TP7B6RQesJnKYQ4ttlrICHEXcNS1XTNg+4OjjReHZuBH4inU3PjiZn7twrPBIfPrD2RM/NdN4T3qyMG/LBh4GXtsVpDhqYDikdtGSw9T9E8NQoVKkQpdCDO/5Fk+BzJ6bDuxoYpDM/LBGx57Ju7CKv+coef2i3+d+Zr4siJ2Rsh7j80i6+/4SSEymMIBbYoDt43y5cuXL1++fPny5cuXL1++fPny5cuXL1++fPny5cuXL1++fPny5cuXL1++fPny5cuXL1++fPny5cuXL1++fPny5cuXL1++fPny5cuXL1++fPny5cuXL1++fPny5cuXL1++fPny5cuXL1++fPny5cuXL1++fPny5cuXL1++fPny5cv/W/8vBkfvqITcAZIAAAAASUVORK5CYII=","storeBarcodeNumber":"PSS549037501027472","carrierReference":"PSS54903750","shippingDetails":{"title":"Mrs","firstName":"Emma","lastName":"Walsh","emailID":"emmawalshster@gmail.com","courier":"An Post","addressLine1":"13 de vesci hill","addressLine2":"","addressLine3":"","city":"ABBEYLEIX","state":"Laois","zipCode":"R32H521","country":"","dayPhone":"0877843593","storeID":""},"orderLines":[{"lineNo":1,"price":60,"dicountPrice":"","primaryReasonDescription":"Too small","lineStatus":"Despatched","itemDetails":{"noOfDaysLeftForReturn":"35","primarySize":"38 C","colour":"BEIGE","orderedQty":"1","alternateItemID":"26488769","productDescription":"Ultimate Wired Strapless Bra A-E","imageUrl":"https://asset1.cxnmarksandspencer.com/is/image/mands//SD_10_T13_3401_L0_X_EC_0"}}],"storeDetail":{"storeNo":"057-8731230","storeName":"Abbeyleix","addressLine1":"Abbeyleix Post Office","addressLine2":"Main Street","addressLine3":"Abbeyleix","addressLine4":"Portlaoise","addressLine5":"Co. Laois","addressLine6":"","city":"Abbeyleix","state":"Co. Laois","zipCode":"R32 KP49","openingWeekDayandTiming":[{"day":"Mon","open":"09:00 ","close":" 17:30"},{"day":"Tue","open":"09:00 ","close":" 17:30"},{"day":"Wed","open":"09:00 ","close":" 17:30"},{"day":"Thu","open":"09:00 ","close":" 17:30"},{"day":"Fri","open":"09:00 ","close":" 17:30"},{"day":"Sat","open":"09:00 ","close":" 13:00"}]}}]}]}}},"iat":1711827687}
|
dfc3ce0722eefd63696b80f2384fb125
|
{
"intermediate": 0.34111666679382324,
"beginner": 0.32130733132362366,
"expert": 0.3375760614871979
}
|
44,692
|
Develop parallel codes for the following problems using JAVA. Report the speedup of your implementations by varying the number of threads from 1 to 16 (i.e., 1, 2, 4, 6, 8, 10, 12, 14, and 16) and consider gettimeofday() to measure the runtime of an execution:
Create a sorted linked List with 1000 nodes using lazy synchronization technique (assume that the nodes consist of fields: key and next. The
range of keys from the set {0 ... 212}). Measure the time to perform 100 Million operations for the workload (50C, 25I, 25D) by varying the number of threads from 1 to 16 and using the following locks (or synchronization objects):
MCS Lock
|
ae97e1b65ed8e689daf285c029ce9c29
|
{
"intermediate": 0.566673219203949,
"beginner": 0.13259734213352203,
"expert": 0.3007294237613678
}
|
44,693
|
hey
|
4b2a9d1fd151cce7ac9989f76283879b
|
{
"intermediate": 0.33180856704711914,
"beginner": 0.2916048467159271,
"expert": 0.3765866458415985
}
|
44,694
|
Develop parallel codes for the following problems using JAVA. Report the speedup of your implementations by varying the number of threads from 1 to 16 (i.e., 1, 2, 4, 6, 8, 10, 12, 14, and 16) and consider gettimeofday() to measure the runtime of an execution:
Create a sorted linked List with 1000 nodes using lazy synchronization technique (assume that the nodes consist of fields: key and next. The
range of keys from the set {0 ... 212}). Measure the time to perform 100 Million operations for the workload (50C, 25I, 25D) by varying the number of threads from 1 to 16 and using the following locks (or synchronization objects):
MCS Lock
|
189ecdbdf93314cb162e53a74ba42efb
|
{
"intermediate": 0.566673219203949,
"beginner": 0.13259734213352203,
"expert": 0.3007294237613678
}
|
44,695
|
1_ Translate the following legal text into colloquial Farsi 2_ Place the Persian and English text side by side in the table 3_ From the beginning to the end of the text, there should be an English sentence on the left side and a Persian sentence on the right side. Side.
4- The use of legal language for Persian translation 5_ Continue to the end of the text
.(b) Absence of codification
A legal code is a systematic collection of laws so arranged as to avoid incon- sistency and overlapping. Codification was a feature of Roman law and was adopted by nearly all Continental countries, notably France, Germany, Austria, and Switzerland. The English common law was formed from the
customs of the people. Under the Norman kings these unwritten laws achieved a fairly uniform legal system. Certain parts only of English law have today been codified, e.g. the Bills of Exchange Act, 1882, and the Sale of Goods Act, 1979, though the Law Commission is working towards a codifi- cation of criminal law and contract (Law Commissions Act, 1965, see p. 37).
|
abb978440186fb90554ba9e41488db65
|
{
"intermediate": 0.3724188208580017,
"beginner": 0.40673571825027466,
"expert": 0.22084547579288483
}
|
44,696
|
import 'package:flutter/material.dart';
import 'package:mobile_tp/models/Difficulte.dart';
import 'package:mobile_tp/models/Niveau.dart';
import 'package:mobile_tp/models/Partie.dart';
import 'package:mobile_tp/screens/MysteryNumberScreen.dart';
import 'package:mobile_tp/services/AventureDB.dart';
import 'package:mobile_tp/services/DifficulteDB.dart';
import 'package:mobile_tp/services/EffectuerDB.dart';
import 'package:mobile_tp/services/NiveauDB.dart';
import 'package:mobile_tp/services/PartieDB.dart';
import 'package:sqflite/sqflite.dart';
import 'dart:math';
class PageNiveaux extends StatefulWidget {
final int totalNiveaux;
final int idAventure;
final Future<Database> database;
PageNiveaux({
Key? key,
required this.totalNiveaux,
required this.idAventure,
required this.database,
}) : super(key: key);
@override
_PageNiveauxState createState() => _PageNiveauxState();
}
class _PageNiveauxState extends State<PageNiveaux> {
late List<Niveau> doneLevels = [];
late AventureDB aventureDB;
late PartieDB partieDB;
late EffectuerDB effectuerDB;
late NiveauDB niveauDB;
late DifficulteDB difficulteDB;
@override
void initState() {
super.initState();
aventureDB = AventureDB(database: widget.database);
partieDB = PartieDB(database: widget.database);
effectuerDB = EffectuerDB(database: widget.database);
niveauDB = NiveauDB(database: widget.database);
difficulteDB = DifficulteDB(database: widget.database);
loadLevels();
}
Future<void> loadLevels() async {
final levels = await aventureDB.getLevelsWon(widget.idAventure);
setState(() {
doneLevels = levels;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Aventure'),
),
body: Center(
child: SingleChildScrollView(
child: FutureBuilder<List<Niveau>>(
future: aventureDB.getLevelsWon(widget.idAventure),
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.done) {
doneLevels = snapshot.data ?? [];
return Column(
children: List.generate(widget.totalNiveaux * 2 - 1, (index) {
if (index % 2 == 0) {
int niveau = widget.totalNiveaux - index ~/ 2;
bool niveauGagne = doneLevels
.any((niveauGagne) => niveauGagne.palier == niveau);
bool niveauPrecedentGagne = niveau == 1 ||
doneLevels.any((niveauGagne) =>
niveauGagne.palier == niveau - 1);
return GestureDetector(
onTap: niveauPrecedentGagne
? () async {
int idDifficulte;
if (niveau <= 3) {
idDifficulte = 1;
} else if (niveau <= 7) {
idDifficulte = 2;
} else {
idDifficulte = 3;
}
Difficulte difficulte = await niveauDB
.getDifficulteById(idDifficulte);
int mysteryNumber =
Random().nextInt(difficulte.valeurMax) + 1;
Partie nouvellePartie = Partie(
score: 0,
nbMystere: mysteryNumber,
nbEssaisJoueur: difficulte.nbTentatives,
gagne: false,
dateDebut: DateTime.now(),
dateFin: DateTime.now(),
idAventure: widget.idAventure,
idNiveau: niveau,
);
int idNouvellePartie =
await partieDB.add(nouvellePartie);
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => MysteryNumberScreen(
database: widget.database,
idPartie: idNouvellePartie,
idNiveau: niveau,
idDifficulte: difficulte.id,
idAventure: widget.idAventure,
effectuerDB: effectuerDB,
),
),
);
List<Partie> allParties =
await partieDB.getAll();
print(allParties[allParties.length - 1].toString());
}
: null,
child: CircleAvatar(
backgroundColor:
niveauGagne ? Colors.green : Colors.grey,
child: Text(niveau.toString()),
),
);
} else {
return SizedBox(height: 20);
}
}),
);
} else {
return CircularProgressIndicator();
}
},
),
),
),
);
}
}
import 'dart:math';
import 'package:flutter/material.dart';
import 'package:mobile_tp/models/Effectuer.dart';
import 'package:mobile_tp/models/Partie.dart';
import 'package:mobile_tp/screens/PageNiveaux.dart';
import 'package:mobile_tp/services/EffectuerDB.dart';
import 'package:mobile_tp/services/PartieDB.dart';
import 'package:mobile_tp/services/SqliteService.dart';
import 'package:sqflite/sqflite.dart';
class MysteryNumberScreen extends StatefulWidget {
final Future<Database> database;
final int idPartie;
final int idNiveau;
final int idDifficulte;
final int idAventure;
final EffectuerDB effectuerDB;
MysteryNumberScreen({
Key? key,
required this.database,
required this.idPartie,
required this.idNiveau,
required this.idDifficulte,
required this.idAventure,
required this.effectuerDB,
}) : super(key: key);
@override
_MysteryNumberScreenState createState() => _MysteryNumberScreenState();
}
class _MysteryNumberScreenState extends State<MysteryNumberScreen> {
int _mysteryNumber = 0;
int _number = 0;
String _message = "";
late PartieDB partieDB;
@override
void initState() {
super.initState();
partieDB = PartieDB(database: widget.database);
_reset();
}
void _reset() async {
Partie partie = await partieDB.getById(widget.idPartie);
_mysteryNumber = partie.nbMystere;
_number = 0;
_message = 'Trouve le nombre';
}
void _check() async {
if (_number == 0) {
_message = 'Entrez un nombre :';
} else if (_number < _mysteryNumber) {
_message = 'Trop petit !';
} else if (_number > _mysteryNumber) {
_message = 'Trop grand !';
} else {
_message = 'Vous avez trouvé le nombre !';
Effectuer effectuer = Effectuer(
idAventure: widget.idAventure,
idNiveau: widget.idNiveau,
idPartie: widget.idPartie,
complete: true,
);
await widget.effectuerDB.add(effectuer);
Partie oldPartie = await partieDB.getById(widget.idPartie);
oldPartie.gagne = true;
await partieDB.update(oldPartie);
}
setState(() {
_number = 0;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Mystery Number'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
_message,
style: TextStyle(fontSize: 24),
),
SizedBox(height: 20),
TextField(
keyboardType: TextInputType.number,
onChanged: (value) {
setState(() {
_number = int.tryParse(value) ?? 0;
});
},
),
SizedBox(height: 20),
ElevatedButton(
onPressed: _check,
child: Text('Valider'),
),
SizedBox(height: 20),
ElevatedButton(
onPressed: _reset,
child: Text('Recommencer'),
),
if (_message == 'Vous avez trouvé le nombre !')
Column(
children: [
SizedBox(height: 20),
ElevatedButton(
onPressed: () => Navigator.pushReplacement(
context,
MaterialPageRoute(
builder: (context) => PageNiveaux(
totalNiveaux: 10,
idAventure: widget.idAventure,
database: widget.database,
),
),
),
child: Text('Retour'),
),
],
),
],
),
),
);
}
}
import 'package:path/path.dart';
import 'package:sqflite/sqflite.dart';
class SqliteService {
Future<void> onCreate(Database db, int version) async {
await db.execute("""
CREATE TABLE Aventure (
idAventure INTEGER PRIMARY KEY AUTOINCREMENT,
nomJoueur TEXT NOT NULL
)
""");
await db.execute("""
CREATE TABLE Difficulte (
idDifficulte INTEGER PRIMARY KEY AUTOINCREMENT,
nom TEXT NOT NULL,
nbTentative INTEGER NOT NULL,
valeurMax INTEGER NOT NULL
)
""");
await db.execute("""
CREATE TABLE Niveau (
idNiveau INTEGER PRIMARY KEY AUTOINCREMENT,
palier INTEGER NOT NULL,
idDifficulte INTEGER NOT NULL,
FOREIGN KEY(idDifficulte) REFERENCES Difficulte(idDifficulte)
)
""");
await db.execute("""
CREATE TABLE Partie (
idPartie INTEGER PRIMARY KEY AUTOINCREMENT,
score INTEGER NOT NULL,
nbMystere INTEGER NOT NULL,
nbEssaisJoueur INTEGER NOT NULL,
gagne INTEGER NOT NULL,
dateDebut TEXT NOT NULL,
dateFin TEXT NOT NULL,
idAventure INTEGER,
idNiveau INTEGER,
FOREIGN KEY(idAventure) REFERENCES Aventure(idAventure),
FOREIGN KEY(idNiveau) REFERENCES Niveau(idNiveau)
)
""");
await db.execute("""
CREATE TABLE Effectuer (
idAventure INTEGER NOT NULL,
idPartie INTEGER NOT NULL,
idNiveau INTEGER NOT NULL,
complete INTEGER NOT NULL,
PRIMARY KEY(idAventure, idPartie, idNiveau),
FOREIGN KEY(idAventure) REFERENCES Aventure(idAventure),
FOREIGN KEY(idPartie) REFERENCES Partie(idPartie),
FOREIGN KEY(idNiveau) REFERENCES Niveau(idNiveau)
)
""");
}
Future<Database> initializeDB() async {
return openDatabase(
join(await getDatabasesPath(), 'aventure.db'),
onCreate: onCreate,
onUpgrade: (db, oldVersion, newVersion) async {
await db.execute("""
DROP TABLE IF EXISTS Aventure;
DROP TABLE IF EXISTS Difficulte;
DROP TABLE IF EXISTS Niveau;
DROP TABLE IF EXISTS Partie;
DROP TABLE IF EXISTS Effectuer;
""");
await onCreate(db, newVersion);
},
version: 2,
);
}
}
tu vois j'ai une bd et des pages. en gros, je crée une aventure, ensuite j'ai 10 niveaux. à chaque fois que je joue sur un niveau, ça crée une nouvelle partie. une partie est considérée dans la table effectuer comme complétée si je l'ai gagnée ou perdue. sauf que j'ai un problème : je n'arrive pas à gérer avec la bd le fait que des niveaux soient gagnés selon une aventure, et en gros dans PageNiveaux il faut qu'un niveau soit en vert lorsqu'il a été gagné, comme ça je peux passer au niveau suivant. mais ça ne fonctionne pas et je ne comprends pas pourquoi, je ne sais pas si c'est à cause de ma requête ou alors si c'est la bd qui est mal faite. comment faire ?
|
55e577f9c6bcb40cbf8da47057bbbe9c
|
{
"intermediate": 0.3640154004096985,
"beginner": 0.46432721614837646,
"expert": 0.17165741324424744
}
|
44,697
|
en fait regarde :
import 'package:flutter/material.dart';
import 'package:mobile_tp/models/Difficulte.dart';
import 'package:mobile_tp/models/Niveau.dart';
import 'package:mobile_tp/models/Partie.dart';
import 'package:mobile_tp/screens/MysteryNumberScreen.dart';
import 'package:mobile_tp/services/AventureDB.dart';
import 'package:mobile_tp/services/DifficulteDB.dart';
import 'package:mobile_tp/services/EffectuerDB.dart';
import 'package:mobile_tp/services/NiveauDB.dart';
import 'package:mobile_tp/services/PartieDB.dart';
import 'package:sqflite/sqflite.dart';
import 'dart:math';
class PageNiveaux extends StatefulWidget {
final int totalNiveaux;
final int idAventure;
final Future<Database> database;
PageNiveaux({
Key? key,
required this.totalNiveaux,
required this.idAventure,
required this.database,
}) : super(key: key);
@override
_PageNiveauxState createState() => _PageNiveauxState();
}
class _PageNiveauxState extends State<PageNiveaux> {
late List<Niveau> doneLevels = [];
late AventureDB aventureDB;
late PartieDB partieDB;
late EffectuerDB effectuerDB;
late NiveauDB niveauDB;
late DifficulteDB difficulteDB;
@override
void initState() {
super.initState();
aventureDB = AventureDB(database: widget.database);
partieDB = PartieDB(database: widget.database);
effectuerDB = EffectuerDB(database: widget.database);
niveauDB = NiveauDB(database: widget.database);
difficulteDB = DifficulteDB(database: widget.database);
loadLevels();
}
Future<void> loadLevels() async {
final levels = await aventureDB.getLevelsWon(widget.idAventure);
setState(() {
doneLevels = levels;
print("doneLevels : $doneLevels");
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Aventure'),
),
body: Center(
child: SingleChildScrollView(
child: Column(
children: List.generate(widget.totalNiveaux * 2 - 1, (index) {
if (index % 2 == 0) {
int niveau = widget.totalNiveaux - index ~/ 2;
bool niveauGagne = doneLevels
.any((niveauGagne) => niveauGagne.palier == niveau);
bool niveauPrecedentGagne = niveau == 1 ||
doneLevels
.any((niveauGagne) => niveauGagne.palier == niveau - 1);
print(
'niveauGagne: $niveauGagne, niveauPrecedentGagne: $niveauPrecedentGagne');
return GestureDetector(
onTap: niveauPrecedentGagne
? () async {
int idDifficulte;
if (niveau <= 3) {
idDifficulte = 1;
} else if (niveau <= 7) {
idDifficulte = 2;
} else {
idDifficulte = 3;
}
Difficulte difficulte =
await niveauDB.getDifficulteById(idDifficulte);
int mysteryNumber =
Random().nextInt(difficulte.valeurMax) + 1;
Partie nouvellePartie = Partie(
score: 0,
nbMystere: mysteryNumber,
nbEssaisJoueur: difficulte.nbTentatives,
gagne: false,
dateDebut: DateTime.now(),
dateFin: DateTime.now(),
idAventure: widget.idAventure,
idNiveau: niveau,
);
int idNouvellePartie =
await partieDB.add(nouvellePartie);
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => MysteryNumberScreen(
database: widget.database,
idPartie: idNouvellePartie,
idNiveau: niveau,
idDifficulte: difficulte.id,
idAventure: widget.idAventure,
effectuerDB: effectuerDB,
onPartieFinished: loadLevels,
),
),
);
List<Partie> allParties = await partieDB.getAll();
print(allParties[allParties.length - 1].toString());
}
: null,
child: CircleAvatar(
backgroundColor: niveauGagne ? Colors.green : Colors.grey,
child: Text(niveau.toString()),
),
);
} else {
return SizedBox(height: 20);
}
}),
),
),
),
);
}
}
import 'package:mobile_tp/models/Aventure.dart';
import 'package:mobile_tp/models/Niveau.dart';
import 'package:mobile_tp/models/Partie.dart';
import 'package:sqflite/sqflite.dart';
class AventureDB {
final Future<Database> database;
AventureDB({required this.database});
Future<int> add(String nomJoueur) async {
final db = await database;
return await db.rawInsert(
'INSERT INTO Aventure(nomJoueur) VALUES(?)',
[nomJoueur],
);
}
Future<List<Aventure>> getAll() async {
final db = await database;
final List<Map<String, Object?>> aventureMaps = await db.query('Aventure');
return [
for (final {
'idAventure': id as int,
'nomJoueur': nom as String,
} in aventureMaps)
Aventure(id: id, nomJoueur: nom)
];
}
Future<List<Niveau>> getLevelsWon(int idAventure) async {
final db = await database;
final List<Map<String, Object?>> levelsMaps = await db.rawQuery('''
SELECT Niveau.idNiveau, Niveau.palier, Niveau.idDifficulte
FROM Niveau
JOIN Effectuer ON Effectuer.idNiveau = Niveau.idNiveau
JOIN Partie ON Partie.idPartie = Effectuer.idPartie
WHERE Effectuer.idAventure = ? AND Effectuer.complete = 1 AND Partie.gagne = 1
''', [idAventure]);
print(levelsMaps);
return [
for (final {
'idNiveau': id as int,
'palier': palier as int,
'idDifficulte': idDifficule as int,
} in levelsMaps)
Niveau(id: id, palier: palier, idDifficulte: idDifficule)
];
}
Future<List<Niveau>> getLevelsOfAdventure(int idAventure) async {
final db = await database;
final List<Map<String, Object?>> levelsMaps = await db.rawQuery('''
SELECT Niveau.idNiveau, Niveau.palier
FROM Niveau
JOIN Partie ON Partie.idNiveau = Niveau.idNiveau
WHERE Partie.idAventure = ?
''', [idAventure]);
return [
for (final {
'idNiveau': id as int,
'palier': palier as int,
'idDifficulte': idDifficule as int,
} in levelsMaps)
Niveau(id: id, palier: palier, idDifficulte: idDifficule)
];
}
}
import 'package:path/path.dart';
import 'package:sqflite/sqflite.dart';
class SqliteService {
Future<void> onCreate(Database db, int version) async {
await db.execute("""
CREATE TABLE Aventure (
idAventure INTEGER PRIMARY KEY AUTOINCREMENT,
nomJoueur TEXT NOT NULL
)
""");
await db.execute("""
CREATE TABLE Difficulte (
idDifficulte INTEGER PRIMARY KEY AUTOINCREMENT,
nom TEXT NOT NULL,
nbTentative INTEGER NOT NULL,
valeurMax INTEGER NOT NULL
)
""");
await db.execute("""
CREATE TABLE Niveau (
idNiveau INTEGER PRIMARY KEY AUTOINCREMENT,
palier INTEGER NOT NULL,
idDifficulte INTEGER NOT NULL,
FOREIGN KEY(idDifficulte) REFERENCES Difficulte(idDifficulte)
)
""");
await db.execute("""
CREATE TABLE Partie (
idPartie INTEGER PRIMARY KEY AUTOINCREMENT,
score INTEGER NOT NULL,
nbMystere INTEGER NOT NULL,
nbEssaisJoueur INTEGER NOT NULL,
gagne INTEGER NOT NULL,
dateDebut TEXT NOT NULL,
dateFin TEXT NOT NULL,
idAventure INTEGER,
idNiveau INTEGER,
FOREIGN KEY(idAventure) REFERENCES Aventure(idAventure),
FOREIGN KEY(idNiveau) REFERENCES Niveau(idNiveau)
)
""");
await db.execute("""
CREATE TABLE Effectuer (
idAventure INTEGER NOT NULL,
idPartie INTEGER NOT NULL,
idNiveau INTEGER NOT NULL,
complete INTEGER NOT NULL,
PRIMARY KEY(idAventure, idPartie, idNiveau),
FOREIGN KEY(idAventure) REFERENCES Aventure(idAventure),
FOREIGN KEY(idPartie) REFERENCES Partie(idPartie),
FOREIGN KEY(idNiveau) REFERENCES Niveau(idNiveau)
)
""");
}
Future<Database> initializeDB() async {
return openDatabase(
join(await getDatabasesPath(), 'aventure.db'),
onCreate: onCreate,
onUpgrade: (db, oldVersion, newVersion) async {
await db.execute("""
DROP TABLE IF EXISTS Aventure;
DROP TABLE IF EXISTS Difficulte;
DROP TABLE IF EXISTS Niveau;
DROP TABLE IF EXISTS Partie;
DROP TABLE IF EXISTS Effectuer;
""");
await onCreate(db, newVersion);
},
version: 2,
);
}
}
quand je fais une partie et que je la gagne, ça me print ça :
Performing hot restart...
Restarted application in 1 211ms.
I/flutter ( 3878): niveauGagne: false, niveauPrecedentGagne: false
I/chatty ( 3878): uid=10155(com.example.mobile_tp) 1.ui identical 7 lines
I/flutter ( 3878): niveauGagne: false, niveauPrecedentGagne: false
I/flutter ( 3878): niveauGagne: false, niveauPrecedentGagne: true
I/flutter ( 3878): []
I/flutter ( 3878): doneLevels : []
I/flutter ( 3878): niveauGagne: false, niveauPrecedentGagne: false
I/chatty ( 3878): uid=10155(com.example.mobile_tp) 1.ui identical 7 lines
I/flutter ( 3878): niveauGagne: false, niveauPrecedentGagne: false
I/flutter ( 3878): niveauGagne: false, niveauPrecedentGagne: true
I/flutter ( 3878): Partie{id: 38, score: 0, nbMystere: 20, nbEssaisJoueur: 20, gagne: false, dateDebut: 2024-03-31 12:02:53.861259, dateFin: 2024-03-31 12:02:53.861272, idAventure: 1, idNiveau: 1}
I/AssistStructure( 3878): Flattened final assist data: 388 bytes, containing 1 windows, 3 views
D/InputConnectionAdaptor( 3878): The input method toggled cursor monitoring on
I/flutter ( 3878): Adding Effectuer with values: {idAventure: 1, idNiveau: 1, idPartie: 38, complete: 1}
I/flutter ( 3878): Updating Partie with values: {idPartie: 38, score: 0, nbMystere: 20, nbEssaisJoueur: 20, gagne: 1, dateDebut: 2024-03-31T12:02:53.861259, dateFin: 2024-03-31T12:02:53.861272, idAventure: 1, idNiveau: 1}
I/flutter ( 3878): []
I/flutter ( 3878): doneLevels : []
I/flutter ( 3878): niveauGagne: false, niveauPrecedentGagne: false
I/chatty ( 3878): uid=10155(com.example.mobile_tp) 1.ui identical 7 lines
I/flutter ( 3878): niveauGagne: false, niveauPrecedentGagne: false
I/flutter ( 3878): niveauGagne: false, niveauPrecedentGagne: true
I/flutter ( 3878): niveauGagne: false, niveauPrecedentGagne: false
I/chatty ( 3878): uid=10155(com.example.mobile_tp) 1.ui identical 7 lines
I/flutter ( 3878): niveauGagne: false, niveauPrecedentGagne: false
I/flutter ( 3878): niveauGagne: false, niveauPrecedentGagne: true
I/flutter ( 3878): []
I/flutter ( 3878): doneLevels : []
D/InputConnectionAdaptor( 3878): The input method toggled cursor monitoring off
I/flutter ( 3878): niveauGagne: false, niveauPrecedentGagne: false
I/chatty ( 3878): uid=10155(com.example.mobile_tp) 1.ui identical 7 lines
I/flutter ( 3878): niveauGagne: false, niveauPrecedentGagne: false
I/flutter ( 3878): niveauGagne: false, niveauPrecedentGagne: true
donc je ne sais pas si c'est ma requête qui ne va pas ou ma bd car doneLevels est toujours vide
|
1f4c0a22a5b7443d511b5d7b7676286d
|
{
"intermediate": 0.31544801592826843,
"beginner": 0.6118128895759583,
"expert": 0.07273905724287033
}
|
44,698
|
import gradio as gr
import os
import sys
import json
import requests
MODEL = "gpt-4-0125-preview"
API_URL = os.getenv("API_URL")
DISABLED = os.getenv("DISABLED") == 'True'
OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")
print (API_URL)
print (OPENAI_API_KEY)
NUM_THREADS = int(os.getenv("NUM_THREADS"))
print (NUM_THREADS)
def exception_handler(exception_type, exception, traceback):
print("%s: %s" % (exception_type.__name__, exception))
sys.excepthook = exception_handler
sys.tracebacklimit = 0
#https://github.com/gradio-app/gradio/issues/3531#issuecomment-1484029099
def parse_codeblock(text):
lines = text.split("\n")
for i, line in enumerate(lines):
if "
|
2a28c71b407139fd36f3c9948e47854d
|
{
"intermediate": 0.5010150074958801,
"beginner": 0.2961530089378357,
"expert": 0.20283201336860657
}
|
44,699
|
hi
|
337c4f9f0e3db2e9cc07ce54e615fc9c
|
{
"intermediate": 0.3246487081050873,
"beginner": 0.27135494351387024,
"expert": 0.40399640798568726
}
|
44,700
|
magick "$downloadFolder\image.jpg" -font Arial -pointsize 20 -fill black -annotate +10+30 'Hello, World!' "$downloadFolder\image.jpg"
设置白色字体
|
fa55a6d7909f71f2b4020c146a77236f
|
{
"intermediate": 0.38382887840270996,
"beginner": 0.332349568605423,
"expert": 0.28382158279418945
}
|
44,701
|
$text = "Hello"
magick "$downloadFolder\image.jpg" -font Arial -pointsize 20 -fill white -annotate +10+30 $text "$downloadFolder\image.jpg"
正常执行,但是$text设置为中文,就不会显示
|
5eb29e3faa212849e9210dcbd95edcaa
|
{
"intermediate": 0.36599764227867126,
"beginner": 0.28781184554100037,
"expert": 0.3461904525756836
}
|
44,702
|
class Sobel_GradientLoss(nn.Module):
def __init__(self):
super(Sobel_GradientLoss).__init__()
sobel_x = np.array([[-1, 0, 1], [-2, 0, 2], [-1, 0, 1]], dtype=np.float32)
sobel_y = np.array([[1, 2, 1], [0, 0, 0], [-1, -2, -1]], dtype=np.float32)
sobel_x = sobel_x.reshape((1, 1, 3, 3))
sobel_y = sobel_y.reshape((1, 1, 3, 3))
conv_x = nn.Conv2d(1,1,3, bias=False)
conv_y = nn.Conv2d(1,1,3, bias=False)
conv_x.weight.data = torch.from_numpy(sobel_x)
conv_y.weight.data = torch.from_numpy(sobel_y)
self.conv_x = conv_x
self.conv_y = conv_y
def forward(self, predict, target):
pred_x = self.conv_x(predict)
pred_y = self.conv_y(predict)
G_pred = torch.abs(pred_x) + torch.abs(pred_y)
target_x = self.conv_x(target)
self.conv_x.train(False)
target_y = self.conv_y(target)
self.conv_y.train(False)
G_target = torch.abs(target_x) + torch.abs(target_y)
loss = F.mse_loss(G_pred, G_target, reduction='mean')
return loss
调用该类时, 是自动执行 forward函数吗?
|
9f643969a1cbb10377bd87fb4ef3f3f8
|
{
"intermediate": 0.3606818914413452,
"beginner": 0.30638760328292847,
"expert": 0.3329305052757263
}
|
44,703
|
Turn the following plain text pseudocode into Python code: Create two clocks that start at 20 seconds - count backwards after a 5 sec. wait - If both clocks reach 0, display a message congratulating the player
|
354c050381d7fd2b6f059297f2567f3d
|
{
"intermediate": 0.31657999753952026,
"beginner": 0.3065972328186035,
"expert": 0.37682273983955383
}
|
44,704
|
In reaper walter theming, why does my custom button doesn't appear with the correct resolution?
|
29de5616ae6196b1182c4aadc24001ca
|
{
"intermediate": 0.3932977616786957,
"beginner": 0.33279961347579956,
"expert": 0.2739025950431824
}
|
44,705
|
are you up right now ,
|
774ed50eea72bbc901cb24343f4e7411
|
{
"intermediate": 0.3547367751598358,
"beginner": 0.26535764336586,
"expert": 0.3799055218696594
}
|
44,706
|
1_ Translate the following legal text into colloquial Farsi 2_ Place the Persian and English text side by side in the table 3_ From the beginning to the end of the text, there should be an English sentence on the left side and a Persian sentence on the right side.
4- Using legal language for Persian translation
.7
The nineteenth century
The law and the procedure by which justice is administered are always open to public criticism. In the nineteenth century there were ample grounds for general dissatisfaction. It has already been noted that the principles of com- mon law and those of equity were separate and were administered in differ- ent courts. Where a litigant in a common law case (e.g. trespass) wished to obtain a equitable remedy or relief (e.g. an injunction) he had to commence a separate action in the Chancery Court, thus adding to expense and often causing great delay. The rules of common law sometimes conflicted with the principles of equity, so that confusion resulted. There was, moreover, a variety of courts, and some (e.g. the ecclesiastical courts and the Admiralty courts) had developed special rules and practices of their own. The system of appeals from the common law courts (civil and criminal) and the equity courts was irrational and confusing. The legal procedure for enforcing rights and obtaining remedies was inefficient, technical, antiquated, and slow.
The deficiencies in the law itself and in its administration were obvious to ordinary citizens (as well as litigants). They were noted by Charles Dickens and other writers, and were critically examined by outstanding political thinkers such as Jeremy Bentham (1748–1832).
Changes were, however, slow and piecemeal. As already mentioned (p. 17) the Court of Probate Act, 1857, which took away the probate jurisdiction of the ecclesiastical courts and set up a new Probate Court. By the Matrimonial Causes Act, 1857, a new Divorce Court was set up which took over the matrimonial jurisdiction of the old ecclesiastical courts.
The Common Law Procedure Act, 1854, empowered common law courts to grant injunctions and to take account of certain equitable defences. The Chancery Procedure Act, 1852, enabled the Chancery Court to decide points of common law arising in equity proceedings e.g. actions for breach of trust. The Chancery Amendment Act, 1858, enabled the Chancery Court to award damages (a common law remedy) in place of or in addition to its own equi- table remedies, notably injunction and specific performance of contracts.
But the main reform was effected by the Judicature Acts, 1873-5, from the recommendations of the Judicature Commission of 1867.
Immediately before this important Act came into effect the following courts existed: King's Bench; Common Pleas; Exchequer; Chancery; Court of Probate; Court of Divorce; Court of Admiralty. Appeal courts were the Court of Appeal in Chancery and the Court of Exchequer. Appeals in crim- inal cases were heard by the Court of Crown Cases Reserved, established in 1848. This court was not affected by the reorganization of 1875.
|
e69cb2e2d5101fb33e218c404b29ae99
|
{
"intermediate": 0.347087562084198,
"beginner": 0.46498310565948486,
"expert": 0.18792930245399475
}
|
44,707
|
help me to write r code # Task 3. Plot the population map of New Zealand, with colors for Marlborough, Auckland, and Gisborne only
# Task 4. Show geographical centroids on New Zealand, with size proportional to log population/10.
# color the map by median height of regions
|
623e7da75a7d00c3ceeaacfa1140f632
|
{
"intermediate": 0.44004666805267334,
"beginner": 0.2216016948223114,
"expert": 0.33835160732269287
}
|
44,708
|
Help me to write r code
# first set the working directory on your computer
setwd('~/Dropbox/IS teaching/IS4335 data_vis/lab/R_codes')
##############################################################################
# 1. map visualization: sf
##############################################################################
# for this lab we'll be using the following packages for static maps:
#install.packages('rgdal')
install.packages("sf") # compile from source: no
install.packages("spData")
library(sf) # classes and functions for vector data
library(spData) # load geographic data
##### about the sf library & vector data:
# The geographic vector model is based on points located within a coordinate reference system.
# Points can represent self-standing features (e.g. location) or they can be linked together to
# form more complex geometries such as lines and polygons.
# The coordinates of London, for example, can be represented by c(-0.1, 51.5).
# This means that its location is -0.1 degrees east and 51.5 degrees north of the origin.
# Most point geometries contain only two dimensions, or they could include height to form a third dimension.
# The core geometry types are fully supported by the R package sf.
# sf can represent all common vector geometry types: points, lines, polygons and their
# respective ‘multi’ versions (which group together features of the same type into a single feature).
# These vector data have discrete, well-defined borders, meaning that vector datasets
# usually have a high level of precision.
# sf also supports geometry collections, which can contain multiple geometry types in a single object.
# The package documentaton can be accessed as follows:
vignette('sf1')
# A vignette is a long-form guide to your package with function documentation.
# A vignette is like a book chapter or an academic paper:
# it can describe the problem that your package is designed to solve, and then show the reader how to solve it.
# As the first vignette explains, simple feature objects in R are stored in a data frame,
# with geographic data occupying a special column, usually named ‘geom’ or ‘geometry’.
# We will use the world dataset provided by the spData as an example.
# world is a spatial object containing spatial and attribute columns,
# check data type
class(world) # both sf class and a data frame
# check column names
names(world)
# the last column contains the geographic information.
# The contents of this geom column give sf objects their spatial powers:
# world$geom is a ‘list column’ that contains all the coordinates of the country polygons.
world$geom
# MULTIPOLYGON in the summary above refers to the geometry type of countries in the world object.
# you can check out columns in the data frame:
world$name_long
world$gdpPercap
# similar to regular data frames
# summarize information in a column
summary(world$gdpPercap)
# The sf package provides a plot() method for visualizing geographic data:
plot(world)
# Note that instead of creating a single map, the plot() command has created multiple maps,
# one for each variable in the world datasets.
# This is useful for exploring the spatial distribution of different variables
# plot a single feature on map:
plot(world['gdpPercap']) # GDP per capita
plot(world['lifeExp']) # life expectancy
# plot a subset of the data
plot(world[3:6])
unique(world$continent)
# plot population on a single continent
plot(world[world$continent=='Asia','pop'])
# Plots are added as layers to existing images by setting add = TRUE.
# We can plot the Asian continent over a map of the world.
# Note that the first plot must only have one facet for add = TRUE to work.
# If the first plot has a key, reset = FALSE must be used
world_asia <- world[world$continent == "Asia", ]
# st_union return a single geometric object by combining several features; internal boundaries are ignored
asia <- st_union(world_asia)
asia
plot(world["pop"], reset = F) # reset = FALSE: keep the plot in a mode that allows adding further map elements
plot(asia, add = T, col = "red") # add = T: add more layers to the graph
# sf’s plot method also has arguments specific to geographic data. e.g. expandBB
# can be used plot an sf object in context: it takes a numeric vector of length four that expands the
# bounding box of the plot relative to zero in the following order: bottom, left, top, right.
# This is used to plot India in the context of its giant Asian neighbors,
# with an emphasis on China to the east, in the following code chunk
india = world[world$name_long == "India", ]
plot(st_geometry(india), expandBB = c(0, 0.3, 0.4, 0.6), col = "gray", lwd = 3)
plot(world_asia[0], add = TRUE)
# Note the use of [0] to keep only the geometry column and lwd to emphasize India
# what happens if we increase the parameters in expandBB?
# There are various ways to modify maps with sf’s plot() method.
# e.g we can overlay circles, whose diameters are proportional to country populations,
# on a map of the world. The circles are geographic centroids
cex <- sqrt(world$pop) /10000 # define circle size proportional to country population
world_cents <- st_centroid(world, of_largest = TRUE)
# st_centroid() converts one geometry type (polygons) to points
# of_largest = TRUE: return centroid of the largest (sub)polygon of a MULTIPOLYGON
# rather than of the whole MULTIPOLYGON
plot(world["continent"], reset = F)
plot(st_geometry(world_cents), add = T, cex = cex)
# st_geometry assigns geometry to a data.frame and creates an sf object.
# here we're converting the data.frame of world_cents into points
##############################################################################
# 2. attribute manipulation
##############################################################################
# the world data includes geometric information and a data frame with attribute columns.
# this allows for standard data frame operations, such as merge, join, and select.
# select countries less than 10000 km2
sel_area <- world[world$area_km2 < 10000,]
sel_area$name_long # check country names
# subset() and filter() provide the same results:
sel_area <- subset(world, area_km2 < 10000)
sel_area <- filter(world, area_km2 < 10000)
# now, select countries in Asia with populations larger than 100 mil
sel_area <- world %>% subset(continent == "Asia" & pop>=10^8)
plot(sel_area['pop'])
# generate population average by continent
# we'll use summaryBy from the doBy library
library(doBy)
# st_drop_geometry removes the geometry column and leaves only the data frame
# the geometry info can cause problems in data summary
dat <- data.frame(st_drop_geometry(world))
pop_ave <- summaryBy(pop ~ continent, data = dat, na.rm=T)
pop_ave
# the operation can also be achieved by a pipe operator. here we simply create a column of
# population average for each continent:
world %>%
st_drop_geometry() %>%
dplyr::group_by(continent) %>% # summarize population mean by continent groups
dplyr::summarize(pop = mean(pop, na.rm = TRUE))
# additional attributes can be merged into the data from other sources
# here we introduce the coffee production data
# "coffee_data" from the spData package
??coffee_data
# the coffee_data has 3 columns: name_long names major coffee-producing nations, coffee_production_2016
# and coffee_production_2017 contain estimated values for coffee production in each year
# now we join the continent population average and coffee data with world.
# we also create a new variable of population density:
world2 <- world %>% dplyr::left_join(pop_ave, by='continent') %>%
dplyr::left_join(coffee_data, by='name_long') %>%
dplyr::mutate(pop_dens = pop / area_km2) # mutate creates a new column
names(world2)
# notice the new column, pop_dens, is at the second to the last position.
# the last column is reserved for geometric info.
# plot population maps: continent population average, density
plot(world2["pop.mean"])
plot(world2["pop_dens"])
# coffee production in 2017
plot(world2["coffee_production_2017"])
####################################
# 3. spatial operations
####################################
# Spatial subsetting is the process of selecting features of a spatial object based on whether or not
# they in some way relate in space to another object.
# An example of spatial subsetting is provided by the nz and nz_height datasets in spData.
# These contain the 16 main regions and 101 highest points in New Zealand
# The following codes first creates an object representing Canterbury,
# then uses spatial subsetting to return all high points in the region
canterbury <- nz %>% dplyr::filter(Name == "Canterbury")
canterbury_height <- nz_height[canterbury, ]
names(canterbury)
names(canterbury_height)
canterbury_height$elevation
# plot high points on Canterbury, New Zealand
plot(nz['Name'], col='white', reset=F, key.pos=NULL, main='') # omit color keys
plot(st_union(canterbury), col = 'red', add=T) # use st_union to consolidate the sf object. see above
plot(canterbury_height['elevation'], add=T) # add high points in Canterbury
# suppose you want to find out the average height of high points in each region.
# This is a good example of spatial aggregation: it is the geometry of the source
# that defines how values in the target object are grouped.
# to do this, you first join the nz data with height (nz_height),
# then summarize average elevation by regional names.
nz_avheight <- nz %>%
st_join(nz_height) %>%
dplyr::group_by(Name) %>%
dplyr::summarize(elevation = mean(elevation, na.rm = TRUE))
names(nz_avheight)
plot(nz_avheight['elevation'])
# The resulting objects have the same geometry as the aggregating object nz but
# with a new column representing the average height of each region.
# other summary functions such as median() and sd() can be used instead of mean()
# group sequence
sample(c(1, 2, 3, 5, 6, 7, 8, 9, 10, 16, 23))
####################################
# 4. week 10 Assignment: Due on Sunday midnight
####################################
# Task 1. Show life expectancy of countries in Africa
# Task 2. Show the life expectancy of countries with population density greater than 100/km2
# Task 3. Plot the population map of New Zealand, with colors for Marlborough, Auckland, and Gisborne only
# Task 4. Show geographical centroids on New Zealand, with size proportional to log population/10.
# color the map by median height of regions
|
e28abee4033d6db947cacb5374afb490
|
{
"intermediate": 0.41326841711997986,
"beginner": 0.35677260160446167,
"expert": 0.22995896637439728
}
|
44,709
|
help me to write r code
##############################################################################
# 1. map visualization: sf
##############################################################################
# for this lab we'll be using the following packages for static maps:
#install.packages('rgdal')
install.packages("sf") # compile from source: no
install.packages("spData")
library(sf) # classes and functions for vector data
library(spData) # load geographic data
##### about the sf library & vector data:
# The geographic vector model is based on points located within a coordinate reference system.
# Points can represent self-standing features (e.g. location) or they can be linked together to
# form more complex geometries such as lines and polygons.
# The coordinates of London, for example, can be represented by c(-0.1, 51.5).
# This means that its location is -0.1 degrees east and 51.5 degrees north of the origin.
# Most point geometries contain only two dimensions, or they could include height to form a third dimension.
# The core geometry types are fully supported by the R package sf.
# sf can represent all common vector geometry types: points, lines, polygons and their
# respective ‘multi’ versions (which group together features of the same type into a single feature).
# These vector data have discrete, well-defined borders, meaning that vector datasets
# usually have a high level of precision.
# sf also supports geometry collections, which can contain multiple geometry types in a single object.
# The package documentaton can be accessed as follows:
vignette('sf1')
# A vignette is a long-form guide to your package with function documentation.
# A vignette is like a book chapter or an academic paper:
# it can describe the problem that your package is designed to solve, and then show the reader how to solve it.
# As the first vignette explains, simple feature objects in R are stored in a data frame,
# with geographic data occupying a special column, usually named ‘geom’ or ‘geometry’.
# We will use the world dataset provided by the spData as an example.
# world is a spatial object containing spatial and attribute columns,
# check data type
class(world) # both sf class and a data frame
# check column names
names(world)
# the last column contains the geographic information.
# The contents of this geom column give sf objects their spatial powers:
# world$geom is a ‘list column’ that contains all the coordinates of the country polygons.
world$geom
# MULTIPOLYGON in the summary above refers to the geometry type of countries in the world object.
# you can check out columns in the data frame:
world$name_long
world$gdpPercap
# similar to regular data frames
# summarize information in a column
summary(world$gdpPercap)
# The sf package provides a plot() method for visualizing geographic data:
plot(world)
# Note that instead of creating a single map, the plot() command has created multiple maps,
# one for each variable in the world datasets.
# This is useful for exploring the spatial distribution of different variables
# plot a single feature on map:
plot(world['gdpPercap']) # GDP per capita
plot(world['lifeExp']) # life expectancy
# plot a subset of the data
plot(world[3:6])
unique(world$continent)
# plot population on a single continent
plot(world[world$continent=='Asia','pop'])
# Plots are added as layers to existing images by setting add = TRUE.
# We can plot the Asian continent over a map of the world.
# Note that the first plot must only have one facet for add = TRUE to work.
# If the first plot has a key, reset = FALSE must be used
world_asia <- world[world$continent == "Asia", ]
# st_union return a single geometric object by combining several features; internal boundaries are ignored
asia <- st_union(world_asia)
asia
plot(world["pop"], reset = F) # reset = FALSE: keep the plot in a mode that allows adding further map elements
plot(asia, add = T, col = "red") # add = T: add more layers to the graph
# sf’s plot method also has arguments specific to geographic data. e.g. expandBB
# can be used plot an sf object in context: it takes a numeric vector of length four that expands the
# bounding box of the plot relative to zero in the following order: bottom, left, top, right.
# This is used to plot India in the context of its giant Asian neighbors,
# with an emphasis on China to the east, in the following code chunk
india = world[world$name_long == "India", ]
plot(st_geometry(india), expandBB = c(0, 0.3, 0.4, 0.6), col = "gray", lwd = 3)
plot(world_asia[0], add = TRUE)
# Note the use of [0] to keep only the geometry column and lwd to emphasize India
# what happens if we increase the parameters in expandBB?
# There are various ways to modify maps with sf’s plot() method.
# e.g we can overlay circles, whose diameters are proportional to country populations,
# on a map of the world. The circles are geographic centroids
cex <- sqrt(world$pop) /10000 # define circle size proportional to country population
world_cents <- st_centroid(world, of_largest = TRUE)
# st_centroid() converts one geometry type (polygons) to points
# of_largest = TRUE: return centroid of the largest (sub)polygon of a MULTIPOLYGON
# rather than of the whole MULTIPOLYGON
plot(world["continent"], reset = F)
plot(st_geometry(world_cents), add = T, cex = cex)
# st_geometry assigns geometry to a data.frame and creates an sf object.
# here we're converting the data.frame of world_cents into points
##############################################################################
# 2. attribute manipulation
##############################################################################
# the world data includes geometric information and a data frame with attribute columns.
# this allows for standard data frame operations, such as merge, join, and select.
# select countries less than 10000 km2
sel_area <- world[world$area_km2 < 10000,]
sel_area$name_long # check country names
# subset() and filter() provide the same results:
sel_area <- subset(world, area_km2 < 10000)
sel_area <- filter(world, area_km2 < 10000)
# now, select countries in Asia with populations larger than 100 mil
sel_area <- world %>% subset(continent == "Asia" & pop>=10^8)
plot(sel_area['pop'])
# generate population average by continent
# we'll use summaryBy from the doBy library
library(doBy)
# st_drop_geometry removes the geometry column and leaves only the data frame
# the geometry info can cause problems in data summary
dat <- data.frame(st_drop_geometry(world))
pop_ave <- summaryBy(pop ~ continent, data = dat, na.rm=T)
pop_ave
# the operation can also be achieved by a pipe operator. here we simply create a column of
# population average for each continent:
world %>%
st_drop_geometry() %>%
dplyr::group_by(continent) %>% # summarize population mean by continent groups
dplyr::summarize(pop = mean(pop, na.rm = TRUE))
# additional attributes can be merged into the data from other sources
# here we introduce the coffee production data
# "coffee_data" from the spData package
??coffee_data
# the coffee_data has 3 columns: name_long names major coffee-producing nations, coffee_production_2016
# and coffee_production_2017 contain estimated values for coffee production in each year
# now we join the continent population average and coffee data with world.
# we also create a new variable of population density:
world2 <- world %>% dplyr::left_join(pop_ave, by='continent') %>%
dplyr::left_join(coffee_data, by='name_long') %>%
dplyr::mutate(pop_dens = pop / area_km2) # mutate creates a new column
names(world2)
# notice the new column, pop_dens, is at the second to the last position.
# the last column is reserved for geometric info.
# plot population maps: continent population average, density
plot(world2["pop.mean"])
plot(world2["pop_dens"])
# coffee production in 2017
plot(world2["coffee_production_2017"])
####################################
# 3. spatial operations
####################################
# Spatial subsetting is the process of selecting features of a spatial object based on whether or not
# they in some way relate in space to another object.
# An example of spatial subsetting is provided by the nz and nz_height datasets in spData.
# These contain the 16 main regions and 101 highest points in New Zealand
# The following codes first creates an object representing Canterbury,
# then uses spatial subsetting to return all high points in the region
canterbury <- nz %>% dplyr::filter(Name == "Canterbury")
canterbury_height <- nz_height[canterbury, ]
names(canterbury)
names(canterbury_height)
canterbury_height$elevation
# plot high points on Canterbury, New Zealand
plot(nz['Name'], col='white', reset=F, key.pos=NULL, main='') # omit color keys
plot(st_union(canterbury), col = 'red', add=T) # use st_union to consolidate the sf object. see above
plot(canterbury_height['elevation'], add=T) # add high points in Canterbury
# suppose you want to find out the average height of high points in each region.
# This is a good example of spatial aggregation: it is the geometry of the source
# that defines how values in the target object are grouped.
# to do this, you first join the nz data with height (nz_height),
# then summarize average elevation by regional names.
nz_avheight <- nz %>%
st_join(nz_height) %>%
dplyr::group_by(Name) %>%
dplyr::summarize(elevation = mean(elevation, na.rm = TRUE))
names(nz_avheight)
plot(nz_avheight['elevation'])
# The resulting objects have the same geometry as the aggregating object nz but
# with a new column representing the average height of each region.
# other summary functions such as median() and sd() can be used instead of mean()
# group sequence
sample(c(1, 2, 3, 5, 6, 7, 8, 9, 10, 16, 23))
####################################
# 4. week 10 Assignment: Due on Sunday midnight
####################################
# Task 3. Plot the population map of New Zealand, with colors for Marlborough, Auckland, and Gisborne only
# Task 4. Show geographical centroids on New Zealand, with size proportional to log population/10.
# color the map by median height of regions
|
49dc363557b84433a0a07d6295406bd7
|
{
"intermediate": 0.3697369396686554,
"beginner": 0.4215970039367676,
"expert": 0.208666130900383
}
|
44,710
|
تابع جاوااسکریپت زیر را به php تبدیل کن
async function getPageSpeed(url) {
const key = "AIzaSyByx9JYcDMzmXz8q5TV9iLah6ZVW0sDgjI";
const pageSpeedBaseUrl = `https://corsproxy.io/?https://www.googleapis.com/pagespeedonline/v5/runPagespeed?url=${url}&key=${key}&category=PERFORMANCE`;
const p1 = "https://corsproxy.io/?";
const endpoint = p1 + encodeURIComponent(pageSpeedBaseUrl);
try {
const res = await fetch(endpoint);
if(res.ok){
const data = await res.json();
await showView(data);
console.log(data);
}
else{
document.getElementById('gps-container').innerHTML = `<small class="text-danger">ارتباط با سرور برقرار نشد.در زمانی دیگر امتحان کنید.</small>`;
}
} catch (error) {
}finally{
document.getElementById('gpc-loader').classList.add('d-none')
document.getElementById('gps-container').classList.remove('d-none');
}
}
|
01a430df01ae3a1ad55ad1e5aa601fd8
|
{
"intermediate": 0.35880422592163086,
"beginner": 0.4689933955669403,
"expert": 0.17220237851142883
}
|
44,711
|
how to use scalpel to undelete jpg images from usb drive
|
16bef26aec84381217b4710403a40894
|
{
"intermediate": 0.3361804783344269,
"beginner": 0.3554830849170685,
"expert": 0.30833640694618225
}
|
44,712
|
Help in developing a Mixture of Expert LSTM neural network to model the sequence of text and english language, first, before starting the coding, we should cite everything that we should define (Variables, functions, methods, classes, etc.) and what are the relationships between them, then we should organize them into modules that do specific things, and then we can code each module inside a separate python file, and then create a "main" sort of file that will use all the modules and train the LSTM neural network
|
0bc725068ae9e265a4b6b66c9bc8cb50
|
{
"intermediate": 0.15148253738880157,
"beginner": 0.11891520768404007,
"expert": 0.7296022772789001
}
|
44,713
|
Assuming that only the part between "// Editable Start" and "// Editable End" is editable, please make any necessary modifications within this section and output the result.
// Below is the content of DMAC/RTL/DMAC_CFG.sv
module DMAC_CFG
(
input wire clk,
input wire rst_n, // _n means active low
// AMBA APB interface
input wire psel_i,
input wire penable_i,
input wire [11:0] paddr_i,
input wire pwrite_i,
input wire [31:0] pwdata_i,
output reg pready_o,
output reg [31:0] prdata_o,
output reg pslverr_o,
// configuration registers
output reg [31:0] src_addr_o,
output reg [31:0] dst_addr_o,
output reg [15:0] byte_len_o,
output wire start_o,
input wire done_i
);
// Configuration register to read/write
reg [31:0] src_addr;
reg [31:0] dst_addr;
reg [15:0] byte_len;
//----------------------------------------------------------
// Write
//----------------------------------------------------------
// an APB write occurs when PSEL & PENABLE & PWRITE
// clk : __--__--__--__--__--__--__--__--__--__--
// psel : ___--------_____________________________
// penable : _______----_____________________________
// pwrite : ___--------_____________________________
// wren : _______----_____________________________
//
// DMA start command must be asserted when APB writes 1 to the DMA_CMD
// register
// clk : __--__--__--__--__--__--__--__--__--__--
// psel : ___--------_____________________________
// penable : _______----_____________________________
// pwrite : ___--------_____________________________
// paddr : |DMA_CMD|
// pwdata : | 1 |
// start : _______----_____________________________
wire wren;
// Editable Start
assign wren = psel_i & penable_i & pwrite_i;
// Editable End
always @(posedge clk) begin
// Editable Start
if (!rst_n) begin
src_addr <= 32'b0;
dst_addr <= 32'b0;
byte_len <= 16'b0;
end
else if (wren) begin
case (paddr_i)
12'h100: begin
if (pwdata_i[1:0] == 2'b00)
src_addr <= pwdata_i;
else
src_addr <= {pwdata_i[31:2], 2'b00};
end
12'h104: begin
if (pwdata_i[1:0] == 2'b00)
dst_addr <= pwdata_i;
else
dst_addr <= {pwdata_i[31:2], 2'b00};
end
12'h108: begin
if (pwdata_i[15:0] == 2'b00)
byte_len <= pwdata_i[15:0];
else
byte_len <= {pwdata_i[15:2], 2'b00};
end
endcase
end
// Editable End
end
wire start;
// Editable Start
assign start = (paddr_i == 12'h10C) && wren && (pwdata_i[0] == 1'b1);
// Editable End
// Read
reg [31:0] rdata;
//----------------------------------------------------------
// READ
//----------------------------------------------------------
// an APB read occurs when PSEL & PENABLE & !PWRITE
// To make read data a direct output from register,
// this code shall buffer the muxed read data into a register
// in the SETUP cycle (PSEL & !PENABLE)
// clk : __--__--__--__--__--__--__--__--__--__--
// psel : ___--------_____________________________
// penable : _______----_____________________________
// pwrite : ________________________________________
// reg update : ___----_________________________________
//
always @(posedge clk) begin
// Editable Start
if (!rst_n) begin
rdata <= 32'd0;
end else if (psel_i && !penable_i && !pwrite_i) begin
case (paddr_i)
12'h000: rdata <= 32'h0001_2024;
12'h100: rdata <= src_addr;
12'h104: rdata <= dst_addr;
12'h108: rdata <= {16'b0, byte_len};
12'h10c: rdata <= {31'b0, start};
12'h110: rdata <= {31'b0, done_i};
default: rdata <= 32'b0;
endcase
end
// Editable End
end
// output assignments
assign pready_o = 1'b1;
assign prdata_o = rdata;
assign pslverr_o = 1'b0;
assign src_addr_o = src_addr;
assign dst_addr_o = dst_addr;
assign byte_len_o = byte_len;
assign start_o = start;
endmodule
// End DMAC/RTL/DMAC_CFG.sv
// Below is the content of DMAC/SIM/TB/DMAC_CFG_TB.sv
`define SRC_ADDR 32'h100
`define DST_ADDR 32'h104
`define LEN_ADDR 32'h108
`define STAT_ADDR 32'h110
`define START_ADDR 32'h10c
`define TIMEOUT_CYCLE 10000000
module DMAC_CFG_TB ();
reg clk;
reg rst_n;
// clock generation
initial begin
clk = 1'b0;
forever #10 clk = !clk;
end
// reset generation
initial begin
rst_n = 1'b0; // active at time 0
repeat (3) @(posedge clk); // after 3 cycles,
rst_n = 1'b1; // release the reset
end
// enable waveform dump
initial begin
\$dumpvars(0, u_DUT);
\$dumpfile("dump.vcd");
end
// timeout
initial begin
#`TIMEOUT_CYCLE \$display("Timeout!");
\$finish;
end
APB apb_if (.clk(clk));
reg [31:0] test_vector;
initial begin
int data;
apb_if.init();
@(posedge rst_n); // wait for a release of the reset
repeat (10) @(posedge clk); // wait another 10 cycles
apb_if.read(32'h0, data);
\$display("---------------------------------------------------");
\$display("IP version: %x", data);
if (data!=='h0001_2024)
\$display("Wrong IP version");
\$display("---------------------------------------------------");
\$display("---------------------------------------------------");
\$display("Reset value test");
\$display("---------------------------------------------------");
apb_if.read(`SRC_ADDR, data);
if (data===0)
\$display("DMA_SRC(pass): %x", data);
else begin
\$display("DMA_SRC(fail): %x", data);
@(posedge clk);
\$finish;
end
apb_if.read(`DST_ADDR, data);
if (data===0)
\$display("DMA_DST(pass): %x", data);
else begin
\$display("DMA_DST(fail): %x", data);
@(posedge clk);
\$finish;
end
apb_if.read(`LEN_ADDR, data);
if (data===0)
\$display("DMA_LEN(pass): %x", data);
else begin
\$display("DMA_LEN(fail): %x", data);
@(posedge clk);
\$finish;
end
apb_if.read(`STAT_ADDR, data);
if (data===1)
\$display("DMA_STATUS(pass): %x", data);
else begin
\$display("DMA_STATUS(fail): %x", data);
@(posedge clk);
\$finish;
end
\$display("---------------------------------------------------");
\$display("Configuration test");
\$display("---------------------------------------------------");
test_vector = 32'h1000;
apb_if.write(`SRC_ADDR, test_vector);
apb_if.read(`SRC_ADDR, data);
if (data===test_vector)
\$display("DMA_SRC(pass): %x", data);
else begin
\$display("DMA_SRC(fail): %x", data);
@(posedge clk);
\$finish;
end
test_vector = 32'h2000;
apb_if.write(`DST_ADDR, test_vector);
apb_if.read(`DST_ADDR, data);
if (data===test_vector)
\$display("DMA_DST(pass): %x", data);
else begin
\$display("DMA_DST(fail): %x", data);
@(posedge clk);
\$finish;
end
test_vector = 32'h100;
apb_if.write(`LEN_ADDR, test_vector);
apb_if.read(`LEN_ADDR, data);
if (data===test_vector)
\$display("DMA_LEN(pass): %x", data);
else begin
\$display("DMA_LEN(fail): %x", data);
@(posedge clk);
\$finish;
end
\$display("---------------------------------------------------");
\$display("DMA start");
\$display("---------------------------------------------------");
test_vector = 32'h1;
apb_if.write(`START_ADDR, test_vector);
\$display("---------------------------------------------------");
\$display("Wait for a DMA completion");
\$display("---------------------------------------------------");
data = 0;
while (data != 1) begin
apb_if.read(`STAT_ADDR, data);
repeat (100) @(posedge clk);
\$write(".");
end
\$display("");
@(posedge clk);
\$display("---------------------------------------------------");
\$display("DMA completed");
\$display("---------------------------------------------------");
\$finish;
end
DMAC_CFG u_DUT (
.clk (clk),
.rst_n (rst_n),
// APB interface
.psel_i (apb_if.psel),
.penable_i (apb_if.penable),
.paddr_i (apb_if.paddr[11:0]),
.pwrite_i (apb_if.pwrite),
.pwdata_i (apb_if.pwdata),
.pready_o (apb_if.pready),
.prdata_o (apb_if.prdata),
.pslverr_o (apb_if.pslverr),
.src_addr_o (/* FLOATING */),
.dst_addr_o (/* FLOATING */),
.byte_len_o (/* FLOATING */),
.start_o (/* FLOATING */),
.done_i (1'b1)
);
endmodule
// End of DMAC/SIM/TB/DMAC_CFG_TB.sv
// Start of DMAC/SIM/TB/AXI_INTF.sv
interface APB (
input clk
);
logic psel;
logic penable;
logic [31:0] paddr;
logic pwrite;
logic [31:0] pwdata;
logic pready;
logic [31:0] prdata;
logic pslverr;
modport master (
input clk,
input pready, prdata, pslverr,
output psel, penable, paddr, pwrite, pwdata
);
task init();
psel = 1'b0;
penable = 1'b0;
paddr = 32'd0;
pwrite = 1'b0;
pwdata = 32'd0;
endtask
task write(input int addr,
input int data);
#1
psel = 1'b1;
penable = 1'b0;
paddr = addr;
pwrite = 1'b1;
pwdata = data;
@(posedge clk);
#1
penable = 1'b1;
@(posedge clk);
while (pready==1'b0) begin
@(posedge clk);
end
psel = 1'b0;
penable = 1'b0;
paddr = 'hX;
pwrite = 1'bx;
pwdata = 'hX;
endtask
task read(input int addr,
output int data);
#1
psel = 1'b1;
penable = 1'b0;
paddr = addr;
pwrite = 1'b0;
pwdata = 'hX;
@(posedge clk);
#1
penable = 1'b1;
@(posedge clk);
while (pready==1'b0) begin
@(posedge clk);
end
data = prdata;
psel = 1'b0;
penable = 1'b0;
paddr = 'hX;
pwrite = 1'bx;
pwdata = 'hX;
endtask
endinterface
// End of DMAC/SIM/TB/AXI_INTF.sv
Direct Memory Access (DMA) Controller
Design Document V1.0
1 Overview
This document specifies the design and implementation of a Direct Memory Access Controller (DMAC) as a part of System-on-a-Chip (SoC). The main purpose of this DMAC design is to integrate into SoC for exchange a large volume of data between memory and peripherals at high speed. The proposed DMAC works on ARM’s Advanced Microcontroller Bus Architecture (AMBA) specification. The DMAC provides an AMBA APB interface to configure the IP, and an AMBA AXI interface to transfer data.
2 Architecture Specification
2.1 General Description
Some applications require transferring a volume of data between memory and peripherals without any modification on data. In software, it is commonly served by executing the memcpy library function in C, C++ or other languages. In C, the function has the following interface and copies len bytes from the object pointed by src to the object pointed by dst: void* memcpy(void* dst, const void* src, size_t len).
While a pure software-based implementation of memcpy transfers data using CPU instructions, DMA does not use expensive CPU cycles but uses a hardware engine (DMAC) for the transfer. This can significantly speed up data transfers and allows using CPU for other jobs.
2.2 Usage Constraints
Below describe constraints in utilizing DMAC v1.
-The src and dst addresses are physical addresses.
-The src and dst addresses must be a multiple of 4.
-The len must be a multiple of 4.
-The maximum len is 0xFFFF
-Source and destination ranges must not overlap.
2.3 Programming Model
Software can use the following sequence to transfer data using DMAC.
-1.Write the source address to DMA_SRC register
-2.Write the destination address to DMA_DST register
-3.Write length to DMA_LEN register
-4.Write 1 to bit[0] of DMA_CMD register
-5.Wait until DMA_STATUS register has bit[0] as 1.
2.4 Register Map
In order to control DMAC, software can configure the following registers.
+--------+------------+----+----+----+----+----+----+----+----+----+----+----+----+----+----+----+----+----+----+----+----+----+----+---+---+---+---+---+---+---+---+---+-------+
| Offset | Reg Name | 31 | 30 | 29 | 28 | 27 | 26 | 25 | 24 | 23 | 22 | 21 | 20 | 19 | 18 | 17 | 16 | 15 | 14 | 13 | 12 | 11 | 10 | 9 | 8 | 7 | 6 | 5 | 4 | 3 | 2 | 1 | 0 |
+--------+------------+----+----+----+----+----+----+----+----+----+----+----+----+----+----+----+----+----+----+----+----+----+----+---+---+---+---+---+---+---+---+---+-------+
| 0x00 | DMA_VER | version |
+--------+------------+---------------------------------------------------------------------------------------------------------------------------------------------------------+
| 0x04~0xFC | Reserved |
+--------+------------+---------------------------------------------------------------------------------------------------------------------------------------------------------+
| 0x100 | DMA_SRC | start_addr |
+--------+------------+---------------------------------------------------------------------------------------------------------------------------------------------------------+
| 0x104 | DMA_DST | start_addr |
+--------+------------+----+----+----+----+----+----+----+----+----+----+----+----+----+----+----+----+-------------------------------------------------------------------------+
| 0x108 | DMA_LEN | | | | | | | | | | | | | | | | | byte_len |
+--------+------------+----+----+----+----+----+----+----+----+----+----+----+----+----+----+----+----+----+----+----+----+----+----+---+---+---+---+---+---+---+---+---+-------+
| 0x10C | DMA_CMD | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | start |
+--------+------------+----+----+----+----+----+----+----+----+----+----+----+----+----+----+----+----+----+----+----+----+----+----+---+---+---+---+---+---+---+---+---+-------+
| 0x110 | DMA_STATUS | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | done |
+--------+------------+----+----+----+----+----+----+----+----+----+----+----+----+----+----+----+----+----+----+----+----+----+----+---+---+---+---+---+---+---+---+---+-------+
2.4.1 DMA VERSION
| Field name | Bit range | R/W | Reset value | Desciption |
|------------|-----------|-----|-------------|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| version | [31:0] | R | 0x0001_2024 | The version of this DMA controller. The upper 16 bits represent the major version. The lower 16 bits represent the released year of the version. This document describes behaviors of major version 1. |
2.4.2 DMA_SRC
| Field name | Bit range | R/W | Reset value | Desciption |
|------------|-----------|-----|-------------|------------------------------------|
| start_addr | [31:0] | R/W | 0x0000_0000 | start address of the source range. |
2.4.3 DMA_DST
| Field name | Bit range | R/W | Reset value | Desciption |
|------------|-----------|-----|-------------|-----------------------------------------|
| start_addr | [31:0] | R/W | 0x0000_0000 | start address of the destination range. |
2.4.4 DMA_LEN
| Field name | Bit range | R/W | Reset value | Desciption |
|------------|-----------|-----|-------------|-----------------------------------------------------------------------|
| byte_len | [15:0] | R/W | 0x0000 | Number of bytes to be transferred from the source to the destination. |
2.4.5 DMA_CMD Field
| Field name | Bit range | R/W | Reset value | Desciption |
|------------|-----------|-----|-------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| start | [0] | W | N/A | Writing 1 to this field will initiate a DMA transfer based on DMA_SRC, DMA_DST, and DMA_LEN registers. Software must not write 1 when there’s an on-going transfer. Writing 0 to this field does not affect operation |
2.4.6 DMA_STATUS
| Field name | Bit range | R/W | Reset value | Desciption |
|------------|-----------|-----|-------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| done | [0] | R | 1 | This field is 1 when there’s no on-going DMA transfer. Software must wait this field to be 1 for a completion of a transfer. Software must not initiate a DMA transfer when this field is 0. |
3 Micro-architecture v1.1 Specification
This section describes microarchitecture of a simple DMAC. It reads data from memory, buffers the data, and write the data into memory. It repeats this procedure until it completes transferring the specified number of bytes.
For simplicity, it read/writes one-cycle data (4 bytes) at a time (in other words, burst-1 transfers). For simplicity, this microarchitecture does not consider write responses from the AXI interface. Later versions will support burst transfers and write responses.
3.1 External Interface
DMAC v1.1 has the following external interfaces to communicate with other hardware IPs.
-AMBA APB interface for configuration
-AMBA AXI interface for data transfer
The image you’ve uploaded is a diagram showing the on-chip interconnect of a computer system. Here’s a detailed description:
The diagram illustrates how the CPU core, memory, and DMAC (Direct Memory Access Controller) are connected through an on-chip interconnect.
The connections also include specific interfaces like Config interface (APB) and Data interface (AXI).
“CPU core” is a box on the left side connected to the central “On-chip interconnect” cloud shape with a bidirectional arrow.
Below the “CPU core,” there’s another box labeled “Memory,” also connected to the “On-chip interconnect” with a bidirectional arrow.
On the right side, there’s a box labeled “DMAC” connected to both “Config interface (APB)” and “Data interface (AXI)” which are in turn connected to the central “On-chip interconnect” with bidirectional arrows.
The arrows indicate that data can flow in both directions between these components.
3.2 Block Diagram
DMAC v1.1 has the following blocks inside.
The diagram is divided into three main blocks labeled “DMAC_TOP,” “DMAC_CFG,” and “DMAC_ENGINE.”
“clk” and “rst” are inputs to the “DMAC_TOP” block.
An arrow labeled “APB” connects the “DMAC_TOP” block to the “DMAC_CFG” block.
Another arrow labeled “AXI” connects both the “DMAC_TOP” and “DMAC_CFG” blocks to the “DMAC_ENGINE” block.
Inside the “DMAC_ENGINE” block, there are four internal components labeled as follows:
SRC_ADDR
DST_ADDR
CNT
DATA BUF
There’s also a small circular graph with nodes labeled 0 to 3 inside this block.
This diagram is likely used to illustrate the flow of data or control signals between these components in a Direct Memory Access Controller configuration. Please let me know if you need more information!
3.3 Configuration Register (lab2)
This block receives read/write requests from the APB and configures the registers describes in Section 2.4.
3.4 Finite State Machine (lab3)
DMA engine utilizes the following state machine to control operations.
The diagram contains five blue circles representing different states: IDLE, RREQ, RDATA, WREQ, and WDATA.
Arrows connect these circles indicating the flow from one state to another.
Each arrow has text annotations that describe the conditions for transitioning from one state to another. For example, transitioning from IDLE to RREQ requires writing 1 to DMA_CMD & LEN!=0, and copying DMA_SRC/DST/LEN.
There are also annotations on the state circles themselves, such as “done=1” on IDLE and “AWVALID=1” on WDATA.
+-------+--------------------------------------------+------------+-----------------------------------------------------------+----------------------------------------+
| State | Major outputs | Next State | Next state transition condition | Notes |
| +---------+--------+---------+--------+------+ | | |
| | ARVALID | RREADY | AWVALID | WVALID | done | | | |
+-------+---------+--------+---------+--------+------+------------+-----------------------------------------------------------+----------------------------------------+
| IDLE | 0 | 0 | 0 | 0 | 1 | RREQ | (DMA_CMD.start is written as 1) and (DMA_LEN.byte_len!=0) | On moving out, |
| | | | | | | | | - Copy DMA_SRC to SRC_ADDR. |
| | | | | | | | | - Copy DMA_DST to DST_ADDR |
| | | | | | | | | - Copy DMA_LEN to the internal counter |
+-------+---------+--------+---------+--------+------+------------+-----------------------------------------------------------+----------------------------------------+
| RREQ | 1 | 0 | 0 | 0 | 0 | RDATA | ARREADY=1 | On moving out, |
| | | | | | | | | - Increment ARADDR by 4 |
+-------+---------+--------+---------+--------+------+------------+-----------------------------------------------------------+----------------------------------------+
| RDATA | 0 | 1 | 0 | 0 | 0 | WREQ | RVALID=1 | On moving out, |
| | | | | | | | | - Buffer RDATA into the data buffer |
+-------+---------+--------+---------+--------+------+------------+-----------------------------------------------------------+----------------------------------------+
| WREQ | 0 | 0 | 1 | 0 | 0 | WDATA | AWREADY=1 | On moving out, |
| | | | | | | | | - Increment AWADDR by 4 |
| | | | | | | | | - Decrement the internal counter by 4 |
+-------+---------+--------+---------+--------+------+------------+-----------------------------------------------------------+----------------------------------------+
| WDATA | 0 | 0 | 0 | 1 | 0 | RREQ | (WREADY=1) & (counter!=0) | |
| | | | | | +------------+-----------------------------------------------------------+----------------------------------------+
| | | | | | | IDLE | (WREADY=1) & (counter==0) | |
+-------+---------+--------+---------+--------+------+------------+-----------------------------------------------------------+----------------------------------------+
The diagram contains horizontal lines representing different signals or data paths labeled as “clk”, “state”, “write to CMD”, “AR*”, “R*”, “AW*” and “W*”.
Each line has different states represented by segments of varying lengths; these include labels like “IDLE”, “RREQ”, “RDATA”, “WREQ”, “WDATA”.
Vertical dashed lines indicate transitions between these states.
There are three rectangular boxes labeled as ‘SRC’, ‘DST’, and ‘DATA’ connected to the waveform lines indicating sources, destinations, or data types associated with those specific points in time.
Numbers from 0 to 16 are marked at the bottom of the image indicating time intervals or clock cycles.
그림 1. DMA operation with microarchitecture v1.1
1) As long as the input and output interfaces are correctly implemented, you are free to declare additional registers within the module as needed.
2) When the rst_n signal is received, please initialize all output signals to 0. The rst_n signal operates as Active Low.
3) There was a minor error in the Testbench, so it has been corrected and uploaded. You can either delete and re-clone using git clone, or update your current version with git pull. The modification is related to the simulation result output, so if you have written your code according to the Spec, working with the previous version should not pose a significant issue.
4) Grading will be based on the DMAC Spec v1.1. Even if there are no errors in the current simulation file, please make sure to check the waveform according to the spec standards.
|
2980690239d9af6b6e5c333f0f89518e
|
{
"intermediate": 0.3527732491493225,
"beginner": 0.49185124039649963,
"expert": 0.15537552535533905
}
|
44,714
|
; Copyright (C) 2015 and onward Cockos Inc
; LICENSE: LGPL v2 or later - http://www.gnu.org/licenses/lgpl.html
version 7.0
use_pngs 1
use_overlays 1
warnings all
tinttcp 298
peaksedges 0
tcp_showborders 0
mcp_showborders 0
trans_showborders 0
tcp_folderindent 0
tcp_heights 4 25 54 64
envcp_min_height 27
mcp_min_height 220 80
misc_dpi_translate 50 100
misc_dpi_translate 134 150
misc_dpi_translate 174 200
tcp_vol_zeroline FF666666
tcp_pan_zeroline 66000000
mcp_vol_zeroline FF666666
mcp_pan_zeroline 85000000
trans_speed_zeroline FF000000
gen_vol_zeroline FF000000
gen_pan_zeroline FF000000
; font #1/6/11 - calibri 8
; font #2/7/12 - calibri 9
; font #3/8/13 - calibri 10
; font #4/9/14 - calibri 11
; font #5/10/15 - calibri 12
macro brightnessFromRGB R G B output
set output / + + * R 299 * G 587 * B 114 1000
endmacro
define_parameter visSections 'Visualise sections' 0 0 1
define_parameter textBrightness 'Text Brightness' 100 50 150
define_parameter colorTrackLabels 'Custom Color Track Labels' 1 0 1
define_parameter customColorDepthParam 'Custom Color Strength' 30 0 100
define_parameter selectStrength 'Selection Overlay Strength' 25 0 100
define_parameter selInvertLabels 'Selection Invert Labels' 1 0 1
define_parameter selDot 'Selection Dot' 1 0 1
brightnessFromRGB trackcolor_r trackcolor_g trackcolor_b cColorBrightness
set cColorTextOnDark cColorBrightness{0}<75 + [100 100 100] * 2 [trackcolor_r trackcolor_g trackcolor_b] [trackcolor_r trackcolor_g trackcolor_b]
set customColorRatio ?trackcolor_valid / customColorDepthParam{0} 100 0
set selectColRatio ?track_selected / selectStrength{0} 100 0
#>---------------------------- TRACK CONTROL PANELS -----------------------------------
macro flowProxy index
set proxy##index tcpFlowLocation##index==1 tcpLabelBlock \
tcpFlowLocation##index==2 tcp.volume.label \
tcpFlowLocation##index==3 tcpMSBlock \
tcpFlowLocation##index==4 tcp.io \
tcpFlowLocation##index==5 tcpFxBlock \
tcpFlowLocation##index==6 tcpPanBlock \
tcpFlowLocation##index==7 tcp.recmode \
tcpFlowLocation##index==8 tcpInputBlock \
tcpFlowLocation##index==9 tcp.env \
tcpFlowLocation##index==10 tcp.phase
set thisWs * Scale proxy##index{2}
set thisHs * Scale 20
set thisXMargin * Scale xMargin
set thisYMargin * Scale yMargin
set proxy##index + + [previous previous] [previous{2} 0 thisWs thisHs] proxy##index{2}>0 [thisXMargin] [0] ; position it at the end of the current row
; OH NO ITS HIDE set flowProxy 1 ?hide_##this{0} + [previous] [previous{2} . 0 .] . ; apply hide by setting w to zero and ignoring both thisXMargin and xOffs
set sectionRHS + tcpSectionMainMargin{0} tcpSectionMainMargin{2}
set thisRHS + proxy##index{0} proxy##index{2}
set thisBS + proxy##index{1} proxy##index{3}
; if it'll fit in this row, its already there now, use it to possbly set a new biggestY
set biggestY thisRHS{0}<=sectionRHS{0} thisBS{0}>biggestY{0} thisBS{0} .
; -- move to next row--
; if it WON'T fit in this row, use it to start the next row at biggestY + thisYMargin
set proxy##index thisRHS{0}>sectionRHS{0} + + [tcpSectionMainMargin thisYMargin{0} proxy##index proxy##index] [0 biggestY{0}] tcpfolderBalanceType==1 * Scale [tcpFolderBalancer] [0] .
; it didn't fit in the row, so it was used (in previous line) to start the next row, which means it will now be the new biggestY
set biggestY thisRHS{0}>sectionRHS{0} + proxy##index{1} proxy##index{3}
; it didn't fit in the row, so it was used to start the next row, so the containing section will now need extra height.
set tcp.custom.sectionMain thisRHS{0}>sectionRHS{0} - + [0 0 0 proxy##index{1}] [tcp.custom.sectionMain tcp.custom.sectionMain tcp.custom.sectionMain proxy##index] [0 0 0 tcp.custom.sectionMain{1}]
; -- cull if it extends below the height of the panel --
set thisBS + proxy##index{1} proxy##index{3} ; do that again because it might have moved rows
set panelBottom - h sectionMargin{0}
set thisYMarginPlus10 + thisYMargin{0} * Scale 10 ; use to avoid rounding errors on height calculations. 10 is half the element height.
set proxy##index thisBS{0}>panelBottom{0} \
h<singleRowH{0} \
proxy##index{1}>thisYMarginPlus10{0} [proxy##index proxy##index 0 0] . \
[proxy##index proxy##index 0 proxy##index] \
!previous{3} [proxy##index proxy##index 0 0] . ; cull method is to set width to zero
; -- cull if it is itself too wide for the section
set thisWPlus2Margins + + proxy##index{2} thisXMargin{0} thisXMargin{0}
set proxy##index thisWPlus2Margins{0}>tcp.custom.sectionMain{2} [proxy##index proxy##index 0 0] .
; -- cull if previous element is zero height
set proxy##index previous{3}==0 [proxy##index proxy##index 0 0] .
; -- this is the new previous
set previous proxy##index
endmacro
macro attachProxy index
set tcpLabelBlock tcpFlowLocation##index==1 proxy##index
set tcp.volume.label tcpFlowLocation##index==2 proxy##index
set tcpMSBlock tcpFlowLocation##index==3 proxy##index
set tcp.io tcpFlowLocation##index==4 proxy##index
set tcpFxBlock tcpFlowLocation##index==5 proxy##index
set tcpPanBlock tcpFlowLocation##index==6 proxy##index
set tcp.recmode tcpFlowLocation##index==7 proxy##index
set tcpInputBlock tcpFlowLocation##index==8 proxy##index
set tcp.env tcpFlowLocation##index==9 proxy##index
set tcp.phase tcpFlowLocation##index==10 proxy##index
endmacro
macro doHideLogic element param
set hide_##element 0
set hide_##element param##&1 ?mixer_visible 1 0
set hide_##element param##&2 !track_selected 1 hide_##element
set hide_##element param##&4 !recarm 1 hide_##element
set hide_##element param##&8 1 hide_##element
set hide_##element ?supercollapsedH{0} 1
endmacro
macro hideSection sec locIdx var thisLayout
set showParam ?actingParamCount{0} 1 0
set showParam Layout##thisLayout##-tcpFxparmVisflag1==1 ?actingFxCount{0} ?tcp_fxlist_enabled{0} 1
set showParam Layout##thisLayout##-tcpFxparmVisflag2==1 ?actingSendCount{0} ?tcp_sends_enabled{0} 1
set showParam Layout##thisLayout##-tcpFxembedLocation{0}==Layout##thisLayout##-tcpFxparmLocation{0} 1
set section##sec##var Layout##thisLayout##-tcpFxparmLocation{0}==locIdx !showParam{0} 0 . \
Layout##thisLayout##-tcpFxLocation{0}==locIdx !actingFxCount{0} 0 !tcp_fxlist_enabled{0} 0 . \
Layout##thisLayout##-tcpSendLocation{0}==locIdx !actingSendCount{0} 0 !tcp_sends_enabled{0} 0 . \
Layout##thisLayout##-tcpFxembedLocation{0}==locIdx !actingEmbeddedUiCount{0} 0 . \
0
set showParamT ?fx_parm_cnt 1 0
set showParamT Layout##thisLayout##-tcpFxparmVisflag1==1 ?fx_cnt ?tcp_fxlist_enabled{0} 1
set showParamT Layout##thisLayout##-tcpFxparmVisflag2==1 ?send_cnt ?tcp_sends_enabled{0} 1
set showParamT Layout##thisLayout##-tcpFxembedLocation{0}==Layout##thisLayout##-tcpFxparmLocation{0} 1
set section##sec##NotEmpty Layout##thisLayout##-tcpFxparmLocation{0}==locIdx !showParamT{0} 0 1 \
Layout##thisLayout##-tcpFxLocation{0}==locIdx !fx_cnt 0 !tcp_fxlist_enabled{0} 0 1 \
Layout##thisLayout##-tcpSendLocation{0}==locIdx !send_cnt 0 !tcp_sends_enabled{0} 0 1 \
Layout##thisLayout##-tcpFxembedLocation{0}==locIdx !tcp_fxembed 0 1 \
0
endmacro
macro assignLoc element assignedLoc
set element ?supercollapsedH{0} [0] \
assignedLoc##{0}==1 tcpSectionLeft1Margin \
assignedLoc##{0}==2 tcpSectionLeft2Margin \
assignedLoc##{0}==3 tcpSectionLeft3Margin \
assignedLoc##{0}==4 tcpSectionBottom1Margin \
assignedLoc##{0}==5 tcpSectionBottom2Margin \
assignedLoc##{0}==6 tcpSectionBottom3Margin \
assignedLoc##{0}==7 tcpSectionRight1Margin \
assignedLoc##{0}==8 tcpSectionRight2Margin \
assignedLoc##{0}==9 tcpSectionRight3Margin \
[0]
endmacro
;-- GLOABL TCP PARAMS --
define_parameter sectionMargin 'Section Margins' 6 2 12
define_parameter xMargin 'X-Axis spacing' 6 2 12
define_parameter yMargin 'Y-Axis spacing' 6 2 12
define_parameter tcpfolderIndentSize 'TCP Folder Indent' 20 0 40
define_parameter tcpfolderBalanceType 'TCP Folder Balance Type' 0 0 2
define_parameter tcpDivOpacity 'TCP Div Opacity' 80 0 255
define_parameter tcpBgColR 'TCP background colour' 129 0 255
define_parameter tcpBgColG 'TCP background colour G' 137 0 255
define_parameter tcpBgColB 'TCP background colour B' 137 0 255
define_parameter emptyTcpSecOpacity 'Empty TCP Section Opacity' 128 1 255
define_parameter tcpFlowLocation1 'TCP flow location 1' 1 1 10
define_parameter tcpFlowLocation2 'TCP flow location 2' 2 1 10
define_parameter tcpFlowLocation3 'TCP flow location 3' 3 1 10
define_parameter tcpFlowLocation4 'TCP flow location 4' 4 1 10
define_parameter tcpFlowLocation5 'TCP flow location 5' 5 1 10
define_parameter tcpFlowLocation6 'TCP flow location 6' 6 1 10
define_parameter tcpFlowLocation7 'TCP flow location 7' 7 1 10
define_parameter tcpFlowLocation8 'TCP flow location 8' 8 1 10
define_parameter tcpFlowLocation9 'TCP flow location 9' 9 1 10
define_parameter tcpFlowLocation10 'TCP flow location 10' 10 1 10
define_parameter tcpFxparmMinWidth 'TCP FX Parameters Minimum Width' 60 50 200
define_parameter tcpFxparmMaxWidth 'TCP FX Parameters Maximum Width' 88 50 200
define_parameter tcpFxMinWidth 'TCP FX Minimum Width' 30 20 200
define_parameter tcpFxMaxWidth 'TCP FX Maximum Width' 88 20 200
define_parameter tcpSendMinWidth 'TCP Send Minimum Width' 26 26 200
define_parameter tcpSendMaxWidth 'TCP Send Maximum Width' 88 30 200
macro drawTcp thisLayout Scale
;-- HOUSEKEEPING --
clear tcp.*
set Scale [Scale Scale Scale Scale Scale Scale Scale Scale] ; ohOK
set tcp.size * Scale [300 100 40]
set singleRowH * Scale + 20 * 2 sectionMargin{0}
set ySqueeze h<singleRowH{0} - * Scale sectionMargin{0} * 0.5 - singleRowH{0} - h 1 * Scale sectionMargin{0}
set supercollapsedMinH * Scale 5
set supercollapsedH h<supercollapsedMinH{0} 1 0
set textBrightnessMult * textBrightness{0} 0.01
set Layout##thisLayout##-tcpVolumeLength Layout##thisLayout##-tcpVolumeLength{0}<=40 20 .
set Layout##thisLayout##-tcpFxparmVisflag1 !tcp_fxlist_enabled{0} -1 .
set Layout##thisLayout##-tcpFxparmVisflag2 !tcp_sends_enabled{0} -1 .
set sectionMarginXYWH h<singleRowH{0} + * Scale - [sectionMargin{0}] * 2 [0 0 sectionMargin{0}] - [0 ySqueeze{0}] * 2 [0 0 0 ySqueeze{0}] \
* Scale + [sectionMargin{0} sectionMargin{0}] * -2 [0 0 sectionMargin{0} sectionMargin{0}]
;-- TCP SECTIONS (pt.1) --
set thisTcpfolderIndent * - maxfolderdepth - maxfolderdepth folderdepth tcpfolderIndentSize
set tcpFolderBalancer tcpfolderBalanceType>0 * - maxfolderdepth folderdepth tcpfolderIndentSize
set thisTcpLabelLength + Layout##thisLayout##-tcpLabelLength tcpfolderBalanceType==1 tcpFolderBalancer 0
set actingParamCount + fx_parm_cnt ?fx_parm_cnt 0 ?Layout##thisLayout##-tcpFxparmPin{0} 1 0
set actingFxCount + fx_cnt ?fx_cnt 0 ?Layout##thisLayout##-tcpFxPin{0} 1 0
set actingSendCount + send_cnt ?send_cnt 0 ?Layout##thisLayout##-tcpSendPin{0} 1 0
set actingEmbeddedUiCount + tcp_fxembed ?tcp_fxembed 0 ?Layout##thisLayout##-tcpFxembedPin{0} 1 0
custom tcp.custom.tcpDiv
set tcp.custom.tcpDiv - + * Scale * [1 0 -1] thisTcpfolderIndent [0 h w 1] [0 1]
set tcp.custom.tcpDiv.color * Scale [0 0 0 0 0 0 0 tcpDivOpacity{0}]
custom tcp.custom.sectionNumber
set tcp.custom.sectionNumber + - [0 0 0 h] [0 0 0 1] * Scale [thisTcpfolderIndent 0 20]
set tcp.custom.sectionNumber.color ?trackcolor_valid [0 0 0 0 trackcolor_r trackcolor_g trackcolor_b] [0 0 0 0 tcpBgColR tcpBgColG tcpBgColB 255]
set tcp.foldercomp ?supercollapsedH{0} [0] + [tcp.custom.sectionNumber] * Scale [0 0 20 18]
set tcp.folder ?supercollapsedH{0} [0] + [tcp.custom.sectionNumber h] * Scale [0 -14 20 14]
front tcp.folder
set tcp_folder_min * Scale folderstate==1 50 32
set tcp.folder h<tcp_folder_min{0} folderstate<0 . [0] .
brightnessFromRGB trackcolor_r trackcolor_g trackcolor_b tcpSectionNumberBrightness
set tcp.trackidx ?supercollapsedH{0} [0] + tcp.custom.sectionNumber * Scale folderstate==1 [0 16 0 -16] folderstate<0 [0 -10 0 10] [0]
set tcp.trackidx.margin + [0 0 0 0 0.5] trackidx<100 - * 0.5 + ?selDot{0} [0 0 8] [0] [0 tcp.trackidx{3} 0 tcp.trackidx{3}] [0 10 0 10] [3 0 7 0]
set tcp.trackidx.color tcpSectionNumberBrightness{0}>128 - [150 150 150] * textBrightnessMult{0} [100 100 100] + * textBrightnessMult{0} [110 110 110] [120 120 120]
set tcp.trackidx.font trackidx<100 Scale{0}==1 [3] Scale{0}==1.5 [8] [13] Scale{0}==1 [1] Scale{0}==1.5 [6] [11]
set tcp.dragdropinfo + [0 tcp.custom.sectionNumber{2}] * Scale [thisTcpfolderIndent thisTcpfolderIndent]
custom tcp.custom.indentInfill
set tcp.custom.indentInfill [0 0 tcp.custom.sectionNumber{0} h]
set tcp.custom.indentInfill.color [0 0 0 0 51 51 51]
custom tcp.custom.sectionNumberDiv
set tcp.custom.sectionNumberDiv + + [tcp.custom.sectionNumber tcp.custom.sectionNumber 1 tcp.custom.sectionNumber] [tcp.custom.sectionNumber{2}] [-1]
set tcp.custom.sectionNumberDiv.color * Scale [0 0 0 0 0 0 0 tcpDivOpacity{0}]
front tcp.custom.sectionNumberDiv
custom tcp.custom.tcp_selectionDot '' 0 '' 'tcp_selectionDot'
set tcp.custom.tcp_selectionDot !selDot{0} [0] ?track_selected [0] + + [tcp.custom.sectionNumber] - [tcp.custom.sectionNumber{2} tcp.custom.sectionNumber{3}] * 0.5 [0 tcp.custom.sectionNumber{3}] * Scale [-4 -4 8 8]
custom tcp.custom.tcp_selectionDotSel '' 0 '' 'tcp_selectionDot_sel'
set tcp.custom.tcp_selectionDotSel !selDot{0} [0] !track_selected [0] + + [tcp.custom.sectionNumber] - [tcp.custom.sectionNumber{2} tcp.custom.sectionNumber{3}] * 0.5 [0 tcp.custom.sectionNumber{3}] * Scale [-4 -4 8 8]
front tcp.custom.tcp_selectionDot tcp.custom.tcp_selectionDotSel
custom tcp.custom.RYKORDBUTTON 42663 "MY BUTTON" "RYKORD BUTTON"
set tcp.custom.RYKORDBUTTON + tcp.custom.button + [0 tcp.size{1} 24 24 0 1 0 1] [255 -48] [0]
set tcp.custom.RYKORDBUTTON.margin [0 0 0 0 0.5]
set tcp.custom.RYKORDBUTTON.color [255 255 255 255 60 130 60 255]
front tcp.custom.RYKORDBUTTON
set sectionLeft1Minimise ?supercollapsedH{0} 1 Layout##thisLayout##-tcpFxparmLocation{0}==1 0 Layout##thisLayout##-tcpFxLocation{0}==1 0 \
Layout##thisLayout##-tcpSendLocation{0}==1 0 Layout##thisLayout##-tcpFxembedLocation{0}==1 0 1
set sectionLeft2Minimise ?supercollapsedH{0} 1 Layout##thisLayout##-tcpFxparmLocation{0}==2 0 Layout##thisLayout##-tcpFxLocation{0}==2 0 \
Layout##thisLayout##-tcpSendLocation{0}==2 0 Layout##thisLayout##-tcpFxembedLocation{0}==2 0 1
set sectionLeft3Minimise ?supercollapsedH{0} 1 Layout##thisLayout##-tcpFxparmLocation{0}==3 0 Layout##thisLayout##-tcpFxLocation{0}==3 0 \
Layout##thisLayout##-tcpSendLocation{0}==3 0 Layout##thisLayout##-tcpFxembedLocation{0}==3 0 1
set sectionBottomMinimise Layout##thisLayout##-tcpFxparmLocation{0}==4 0 Layout##thisLayout##-tcpFxLocation{0}==4 0 \
Layout##thisLayout##-tcpSendLocation{0}==4 0 Layout##thisLayout##-tcpFxembedLocation{0}==4 0 1
set sectionRight1Minimise ?supercollapsedH{0} 1 Layout##thisLayout##-tcpFxparmLocation{0}==7 0 Layout##thisLayout##-tcpFxLocation{0}==7 0 \
Layout##thisLayout##-tcpSendLocation{0}==7 0 Layout##thisLayout##-tcpFxembedLocation{0}==7 0 1
set sectionRight2Minimise ?supercollapsedH{0} 1 Layout##thisLayout##-tcpFxparmLocation{0}==8 0 Layout##thisLayout##-tcpFxLocation{0}==8 0 \
Layout##thisLayout##-tcpSendLocation{0}==8 0 Layout##thisLayout##-tcpFxembedLocation{0}==8 0 1
set sectionRight3Minimise ?supercollapsedH{0} 1 Layout##thisLayout##-tcpFxparmLocation{0}==9 0 Layout##thisLayout##-tcpFxLocation{0}==9 0 \
Layout##thisLayout##-tcpSendLocation{0}==9 0 Layout##thisLayout##-tcpFxembedLocation{0}==9 0 1
set emptyTcpSecColor [0 0 0 0 38 38 38 emptyTcpSecOpacity{0}]
custom tcp.custom.sectionLeft1
set sectionLeft1DrawW ?sectionLeft1Minimise{0} 0 * Scale Layout##thisLayout##-sectionLeftW{0}
hideSection Left1 1 DrawW thisLayout
set tcp.custom.sectionLeft1 + + tcpfolderBalanceType==2 * Scale [tcpFolderBalancer] [0] [tcp.custom.sectionNumber] [tcp.custom.sectionNumber{w} 0 sectionLeft1DrawW{0} h]
set tcp.custom.sectionLeft1 tcp.custom.sectionLeft1{2}<0 [. . 0 .] ; preventing negative width
set tcp.custom.sectionLeft1.color ?visSections [0 0 0 0 255 100 100 150] ?sectionLeft1NotEmpty{0} [0 0 0 0 38 38 38 255] emptyTcpSecColor
custom tcp.custom.sectionLeft2
set sectionLeft2DrawW ?sectionLeft2Minimise{0} 0 * Scale Layout##thisLayout##-sectionLeftW{0}
hideSection Left2 2 DrawW thisLayout
set tcp.custom.sectionLeft2 + [tcp.custom.sectionLeft1] [tcp.custom.sectionLeft1{w} 0 sectionLeft2DrawW{0} h]
set tcp.custom.sectionLeft2 tcp.custom.sectionLeft2{2}<0 [. . 0 .] ; preventing negative width
set tcp.custom.sectionLeft2.color ?visSections [0 0 0 0 255 50 50 100] ?sectionLeft2NotEmpty{0} [0 0 0 0 38 38 38 255] emptyTcpSecColor
custom tcp.custom.sectionLeft3
set sectionLeft3DrawW ?sectionLeft3Minimise{0} 0 * Scale Layout##thisLayout##-sectionLeftW{0}
hideSection Left3 3 DrawW thisLayout
set tcp.custom.sectionLeft3 + [tcp.custom.sectionLeft2] [tcp.custom.sectionLeft2{w} 0 sectionLeft3DrawW{0} h]
set tcp.custom.sectionLeft3 tcp.custom.sectionLeft3{2}<0 [. . 0 .] ; preventing negative width
set tcp.custom.sectionLeft3.color ?visSections [0 0 0 0 255 150 150 200] ?sectionLeft3NotEmpty{0} [0 0 0 0 38 38 38 255] emptyTcpSecColor
; Calculate sectionRight widths now so that sectionMain can use them
set sectionRight1DrawW ?sectionRight1Minimise{0} 0 Layout##thisLayout##-sectionRightW{0}
hideSection Right1 7 DrawW thisLayout
set sectionRight2DrawW ?sectionRight2Minimise{0} 0 Layout##thisLayout##-sectionRightW{0}
hideSection Right2 8 DrawW thisLayout
set sectionRight3DrawW ?sectionRight3Minimise{0} 0 Layout##thisLayout##-sectionRightW{0}
hideSection Right3 9 DrawW thisLayout
custom tcp.custom.sectionMain
set tcp.custom.sectionMain [0]
set tcp.custom.sectionMain + + + [tcp.custom.sectionLeft3{2}] [tcp.custom.sectionLeft3 ySqueeze w] * Scale [0 0 0 20] \
* -1 \
+ + + + [0 0 tcp.custom.sectionLeft3{0}] [0 0 tcp.custom.sectionLeft3{2}] \
* Scale + + [0 0 sectionRight1DrawW{0}] [0 0 sectionRight2DrawW{0}] [0 0 sectionRight3DrawW{0}] \
* Scale [0 0 Layout##thisLayout##-tcpMeterWidth{0}]
set tcp.custom.sectionMain.color ?visSections [0 0 0 0 50 50 255 100] [0]
; Calculate resulting color for use in text brightness judgement
set tcpMainSecCol + * - 1 selectColRatio + \
* customColorRatio [trackcolor_r trackcolor_g trackcolor_b] \
* - 1 customColorRatio [tcpBgColR tcpBgColG tcpBgColB] \
* selectColRatio [255 255 255]
brightnessFromRGB tcpMainSecCol{0} tcpMainSecCol{1} tcpMainSecCol{2} tcpMainSecColBrightness
;-- HIDING-- for assorted reasons
doHideLogic tcpLabelBlock Layout##thisLayout##-hideTcpLabelBlock{0}
doHideLogic tcp.recmon Layout##thisLayout##-hideTcpRecmon{0}
set tcpRecmonW ?hide_tcp.recmon{0} 0 14
doHideLogic labelsValues Layout##thisLayout##-hideTcpLabelsValues{0}
set hide_tcp.volume.label !hide_labelsValues{0} 0 1
doHideLogic tcpMSBlock Layout##thisLayout##-hideTcpMSBlock{0}
doHideLogic tcp.io Layout##thisLayout##-hideTcpIo{0}
doHideLogic tcpFxBlock Layout##thisLayout##-hideTcpFxBlock{0}
doHideLogic tcpPanBlock Layout##thisLayout##-hideTcpPanBlock{0}
doHideLogic tcp.recmode Layout##thisLayout##-hideTcpRecmode{0}
doHideLogic tcpInputBlock Layout##thisLayout##-hideTcpInputBlock{0}
doHideLogic tcp.env Layout##thisLayout##-hideTcpEnv{0}
doHideLogic tcp.phase Layout##thisLayout##-hideTcpPhase{0}
doHideLogic meterValues Layout##thisLayout##-hideTcpMeterValues{0}
;-- TCP SECTIONS (pt.2) --
set tcpLabelBlockW + + + thisTcpLabelLength{0} Layout##thisLayout##-tcpVolumeLength{0} 20 tcpRecmonW{0} ; 20 is the recarm width
set tcpInputBlockW + 20 Layout##thisLayout##-tcpRecinputLength{0} ; 20 is the width of tcp.fxin
set tcpPanBlockW trackpanmode<=3 !hide_labelsValues{0} 58 20 trackpanmode==5 !hide_labelsValues{0} 80 42 trackpanmode==6 !hide_labelsValues{0} 100 60
set longestTcpBlock * Scale + + sectionMargin{0} sectionMargin{0} tcpLabelBlockW{0}>tcpInputBlockW{0} tcpLabelBlockW{0} tcpInputBlockW{0}
set tcp.custom.sectionMain tcp.custom.sectionMain{2}<longestTcpBlock{0} [tcp.custom.sectionMain tcp.custom.sectionMain longestTcpBlock{0} tcp.custom.sectionMain] .
set tcpSectionMainMargin + tcp.custom.sectionMain + * Scale [sectionMargin{0}] * -2 * Scale [0 0 sectionMargin{0}]
custom tcp.custom.sectionRight1
set tcp.custom.sectionRight1 + + [tcp.custom.sectionMain 0 0 h] [tcp.custom.sectionMain{2}] * Scale [0 0 sectionRight1DrawW{0}]
set tcp.custom.sectionRight1.color ?visSections [0 0 0 0 255 255 100 150] ?sectionRight1NotEmpty{0} [0 0 0 0 38 38 38 255] emptyTcpSecColor
custom tcp.custom.sectionRight2
set tcp.custom.sectionRight2 + + [tcp.custom.sectionRight1 0 0 h] [tcp.custom.sectionRight1{2}] * Scale [0 0 sectionRight2DrawW{0}]
set tcp.custom.sectionRight2.color ?visSections [0 0 0 0 255 200 100 200] ?sectionRight2NotEmpty{0} [0 0 0 0 38 38 38 255] emptyTcpSecColor
custom tcp.custom.sectionRight3
set tcp.custom.sectionRight3 + + [tcp.custom.sectionRight2 0 0 h] [tcp.custom.sectionRight2{2}] * Scale [0 0 sectionRight3DrawW{0}]
set tcp.custom.sectionRight3.color ?visSections [0 0 0 0 255 255 200 150] ?sectionRight3NotEmpty{0} [0 0 0 0 38 38 38 255] emptyTcpSecColor
custom tcp.custom.sectionMeter
set tcp.custom.sectionMeter + + [tcp.custom.sectionRight3 0 0 h] [tcp.custom.sectionRight3{2}] * Scale [0 0 Layout##thisLayout##-tcpMeterWidth{0}]
set tcp.custom.sectionMeter.color ?visSections [0 0 0 0 10 255 10 255] [0 0 0 0 38 38 38 255]
; Add margins to sections
set tcpSectionLeft1Margin + tcp.custom.sectionLeft1 sectionMarginXYWH
set tcpSectionLeft2Margin + tcp.custom.sectionLeft2 sectionMarginXYWH
set tcpSectionLeft3Margin + tcp.custom.sectionLeft3 sectionMarginXYWH
set tcpSectionRight1Margin + tcp.custom.sectionRight1 sectionMarginXYWH
set tcpSectionRight2Margin + tcp.custom.sectionRight2 sectionMarginXYWH
set tcpSectionRight3Margin + tcp.custom.sectionRight3 sectionMarginXYWH
;------------------
set tcp.meter + + tcp.custom.sectionMeter * Scale [Layout##thisLayout##-tcpMeterBorder{0} Layout##thisLayout##-tcpMeterBorder{0}] \
* -2 * Scale [0 0 Layout##thisLayout##-tcpMeterBorder{0} Layout##thisLayout##-tcpMeterBorder{0}]
set tcp.meter.vu.div [Layout##thisLayout##-tcpMeterBorder{0}]
set tcp.meter.readout.color ?hide_meterValues{0} [0 0 0 0 0 0 0 0] * textBrightnessMult{0} [100 100 100 255 255 183 171 255]
set tcp.meter.scale.color.lit.bottom ?hide_meterValues{0} [0 0 0 0 0 0 0 0] [0 0 0 170 0 0 0 0]
set tcp.meter.scale.color.lit.top ?hide_meterValues{0} [0 0 0 0 0 0 0 0] [0 0 0 170 0 0 0 0]
set tcp.meter.scale.color.unlit.bottom ?hide_meterValues{0} [0 0 0 0 0 0 0 0] ?recarm [255 64 0 255 0 0 0 0] + * - textBrightnessMult{0} 1 [0 0 0 100] [255 255 255 60 0 0 0 0]
set tcp.meter.scale.color.unlit.top ?hide_meterValues{0} [0 0 0 0 0 0 0 0] ?recarm [255 64 0 255 0 0 0 0] + * - textBrightnessMult{0} 1 [0 0 0 100] [255 255 255 60 0 0 0 0]
;-- POPULATE MAIN --
;reset values for 'follow' macro
set biggestY 0
set xOffs 0
set noSpace 0
custom tcp.custom.panBlock
custom tcp.custom.labelBlock
custom tcp.custom.inputBlock
set tcpLabelBlock ?hide_tcpLabelBlock{0} [0 0 0] [0 0 tcpLabelBlockW{0}]
set tcp.volume.label ?hide_tcp.volume.label{0} [0 0 0] [0 0 48]
set tcpMSBlock ?hide_tcpMSBlock{0} [0 0 0] [0 0 39]
set tcp.io ?hide_tcp.io{0} [0 0 0] [0 0 30]
set tcpFxBlock ?hide_tcpFxBlock{0} [0 0 0] [0 0 36]
set tcpPanBlock ?hide_tcpPanBlock{0} [0 0 0] [0 0 tcpPanBlockW]
set tcp.recmode ?hide_tcp.recmode{0} [0 0 0] [0 0 42]
set tcpInputBlock ?hide_tcpInputBlock{0} [0 0 0] [0 0 tcpInputBlockW{0}]
set tcp.env ?hide_tcp.env{0} [0 0 0] [0 0 40]
set tcp.phase ?hide_tcp.phase{0} [0 0 0] [0 0 16]
set previous + [tcpSectionMainMargin tcpSectionMainMargin] * Scale - [0 0 0 20] [xMargin{0}] ; mainNullElement
flowProxy 1
flowProxy 2
flowProxy 3
flowProxy 4
flowProxy 5
flowProxy 6
flowProxy 7
flowProxy 8
flowProxy 9
flowProxy 10
attachProxy 1
attachProxy 2
attachProxy 3
attachProxy 4
attachProxy 5
attachProxy 6
attachProxy 7
attachProxy 8
attachProxy 9
attachProxy 10
custom tcp.custom.labelBlockBg '' 0 '' 'tcp_labelBlock_bg'
custom tcp.custom.labelBlockBgSel '' 0 '' 'tcp_labelBlock_bg_sel'
set tcp.custom.labelBlockBg + * Scale [0 0 -2] ?selInvertLabels{0} ?track_selected [0] tcpLabelBlock tcpLabelBlock
set tcp.custom.labelBlockBgSel + * Scale [0 0 -2] ?selInvertLabels{0} ?track_selected tcpLabelBlock [0] [0]
set tcp.recarm !tcpLabelBlock{2} [0] + [tcpLabelBlock tcpLabelBlock] * Scale [0 0 24 20]
set tcp.recmon !tcpLabelBlock{2} [0] + [tcp.recarm tcp.recarm] + [tcp.recarm{2}] * Scale [0 0 tcpRecmonW{0} 20]
set tcp.label !tcpLabelBlock{2} [0] + [tcp.recmon tcp.recmon] + [tcp.recmon{2}] * Scale - [0 0 thisTcpLabelLength{0} 20] [0 0 6]
set tcp.label.margin * Scale [6 0 2 0]
set tcp.label.font + Layout##thisLayout##-tcpLabelSize{0} Scale{0}==1 [0] Scale{0}==1.5 [5] [10]
set tcp.label.color ?recarm [255 80 100] ?trackcolor_valid ?colorTrackLabels cColorTextOnDark * textBrightnessMult{0} [200 200 200] * textBrightnessMult{0} [200 200 200]
set tcp.label.color ?selInvertLabels{0} ?track_selected ?recarm [180 0 10] [38 38 38] . .
set tcp.volume !tcpLabelBlock{2} [0] + [tcp.label tcp.label] + [tcp.label{2}] * Scale [0 0 Layout##thisLayout##-tcpVolumeLength{0} 20]
set thisVolL * Scale Layout##thisLayout##-tcpVolumeLength{0}
set volKnobFlipW * Scale 40
set tcp.volume.fadermode thisVolL{0}<=volKnobFlipW{0} [1] [0]
set tcp.volume.label.font Scale{0}==1 [1] Scale{0}==1.5 [6] [11]
set tcp.volume.label.color * textBrightnessMult{0} tcpMainSecColBrightness{0}<150 [220 220 220] [38 38 38]
set tcp.volume.label.margin * Scale [6 0 0 0 0]
set tcp.mute !tcpMSBlock{2} [0] + [tcpMSBlock tcpMSBlock] * Scale [0 0 20 20]
set tcp.solo !tcpMSBlock{2} [0] + [tcp.mute tcp.mute] * Scale [19 0 20 20]
set tcp.fx !tcpFxBlock{2} [0] + [tcpFxBlock tcpFxBlock] * Scale [0 0 20 20]
set tcp.fxbyp !tcpFxBlock{2} [0] + [tcp.fx tcp.fx] * Scale [20 0 16 20]
front tcp.fxbyp
set tcp.custom.panBlock ?visSections tcpPanBlock [0]
set tcp.custom.panBlock.color ?visSections [0 0 0 0 255 255 100 255] [0 0 0 0 0 0 0]
set panLabelW * Scale !hide_labelsValues{0} 38 0
set tcp.pan.label !tcpPanBlock{2} [0] trackpanmode<=3 + [tcpPanBlock tcpPanBlock panLabelW{0}] * Scale [0 0 0 20] + + [tcpPanBlock tcpPanBlock panLabelW{0}] \
* Scale [0 0 0 10] trackpanmode==6 * Scale [0 10] [0]
set tcp.pan.label.color * textBrightnessMult{0} tcpMainSecColBrightness{0}<150 [220 220 220] [38 38 38]
set tcp.pan.label.margin + [0 0 0 0 1] * Scale [0 0 4]
set tcp.pan.label.font Scale{0}==1 [1] Scale{0}==1.5 [6] [11]
set tcp.pan !tcpPanBlock{2} [0] trackpanmode<6 + + [tcp.pan.label tcp.pan.label] [tcp.pan.label{2}] * Scale [0 0 20 20] \
+ + [tcpPanBlock tcpPanBlock] [tcp.pan.label{2}] * Scale [0 10 62 10]
set tcp.pan.fadermode trackpanmode==6 [-1] [1]
set tcp.width !tcpPanBlock{2} [0] trackpanmode<=3 [0] trackpanmode<6 + + [tcp.pan tcp.pan] [tcp.pan{2}] * Scale [2 0 20 20] \
+ + [tcpPanBlock tcpPanBlock] [tcp.pan.label{2}] * Scale [0 0 62 10]
set tcp.width.fadermode tcp.pan.fadermode
set tcp.width.label !tcpPanBlock{2} [0] trackpanmode<=3 [0] trackpanmode<6 + [tcp.pan.label tcp.pan.label panLabelW{0}] * Scale [0 10 0 10] \
+ [tcpPanBlock tcpPanBlock panLabelW{0}] * Scale [0 0 0 10]
set tcp.width.label.color tcp.pan.label.color
set tcp.width.label.margin tcp.pan.label.margin
set tcp.width.label.font Scale{0}==1 [1] Scale{0}==1.5 [6] [11]
set tcp.custom.inputBlock ?visSections tcpInputBlock [0]
set tcp.custom.inputBlock.color ?visSections [0 0 0 0 255 255 100 255] [0 0 0 0 0 0 0]
set tcp.fxin !tcpInputBlock{2} [0] + [tcpInputBlock tcpInputBlock] * Scale [0 0 20 20]
set tcp.recinput !tcpInputBlock{2} [0] + + [tcpInputBlock tcpInputBlock] [tcp.fxin{2} 0] * Scale [0 0 Layout##thisLayout##-tcpRecinputLength{0} 20]
set tcp.recinput.color * textBrightnessMult{0} [235 235 235]
set tcp.recinput.font + Layout##thisLayout##-tcpInputFontSize{0} Scale{0}==1 [0] Scale{0}==1.5 [5] [10]
set tcp.recinput.margin + [0 0 0 0 0.5] * Scale [2 0 20]
;-- TCP SECTIONS (pt.3) --
custom tcp.custom.sectionBottom ; follows those calculations on main section, within the 'follow' macro, so that this is y-correct
set sectionBottomH ?sectionBottomMinimise{0} 0 - h + tcp.custom.sectionMain{1} tcp.custom.sectionMain{3}
hideSection Bottom 4 H thisLayout
; hideSection sets bottomSectionH to 0 if params or sends is empty, even if embed is set to bottom (fx will never be empty if there's an embed!). This overrides that...
set sectionBottomH !actingEmbeddedUiCount{0} . Layout##thisLayout##-tcpFxembedLocation{0}>4 Layout##thisLayout##-tcpFxembedLocation{0}<7 ?sectionBottomMinimise{0} 0 - h + tcp.custom.sectionMain{1} tcp.custom.sectionMain{3}
;hideSection sets bottomSectionH to 0 if inserts and sends are set to bottom and inserts are empty. This overrides that...
set sectionBottomH !actingSendCount{0} . ?actingFxCount{0} . \
Layout##thisLayout##-tcpFxLocation{0}==4 Layout##thisLayout##-tcpSendLocation{0}==5 ?sectionBottomMinimise{0} 0 - h + tcp.custom.sectionMain{1} tcp.custom.sectionMain{3} . .
; if embed is set to bottom (section 5 or 6), and embed is empty, then bottomDiv will be 1 too big
set thisTcpSectionBottomDiv Layout##thisLayout##-tcpSectionBottomDiv{0}
set thisTcpSectionBottomDiv ?actingEmbeddedUiCount{0} . Layout##thisLayout##-tcpFxembedLocation{0}>4 Layout##thisLayout##-tcpFxembedLocation{0}<7 - Layout##thisLayout##-tcpSectionBottomDiv{0} 1 . .
set tcp.custom.sectionBottom + + [0 tcp.custom.sectionMain] [tcp.custom.sectionMain tcp.custom.sectionMain{3} tcp.custom.sectionMain sectionBottomH{0}] * Scale [0 sectionMargin{0}]
custom tcp.custom.sectionBottom1
set tcp.custom.sectionBottom1 / tcp.custom.sectionBottom [1 1 thisTcpSectionBottomDiv{0} 1]
set tcp.custom.sectionBottom1.color ?visSections [0 0 0 0 100 255 100 150] ?sectionBottomNotEmpty{0} [0 0 0 0 38 38 38 255] emptyTcpSecColor
custom tcp.custom.sectionBottom2
set tcp.custom.sectionBottom2 thisTcpSectionBottomDiv{0}<2 [0] + [tcp.custom.sectionBottom1{2}] / tcp.custom.sectionBottom [1 1 thisTcpSectionBottomDiv{0} 1]
set tcp.custom.sectionBottom2.color ?visSections [0 0 0 0 150 200 100 150] ?sectionBottomNotEmpty{0} [0 0 0 0 38 38 38 255] emptyTcpSecColor
custom tcp.custom.sectionBottom3
set tcp.custom.sectionBottom3 thisTcpSectionBottomDiv{0}<3 [0] + + + [tcp.custom.sectionBottom1 tcp.custom.sectionBottom1 0 tcp.custom.sectionBottom2] \
[tcp.custom.sectionBottom1{2}] [tcp.custom.sectionBottom2{2}] / [0 0 tcp.custom.sectionBottom] thisTcpSectionBottomDiv{0}
set tcp.custom.sectionBottom3.color ?visSections [0 0 0 0 100 255 150 150] ?sectionBottomNotEmpty{0} [0 0 0 0 38 38 38 255] emptyTcpSecColor
set tcpSectionBottom1Margin + tcp.custom.sectionBottom1 * * Scale sectionMargin{0} [1 1 -2 -2]
set tcpSectionBottom2Margin + tcp.custom.sectionBottom2 * * Scale sectionMargin{0} [0 1 0 -2]
set tcpSectionBottom3Margin + tcp.custom.sectionBottom3 * * Scale sectionMargin{0} [0 1 -1 -2]
custom tcp.custom.tcpSelBox
set tcp.custom.tcpSelBox !track_selected [0] selectStrength{0}>0 [0 0 w h] [0]
set tcp.custom.tcpSelBox.color + * / selectStrength{0} 100 [0 0 0 0 0 0 0 255] [0 0 0 0 255 255 255]
custom tcp.custom.colourBox
set customColorDepth * customColorDepthParam 2.55
set tcp.custom.colourBox customColorDepth{0}>0 + + * [1 0 -1] tcp.custom.sectionNumber{w} [1 0 w h] [-1 0 -1] [0]
set tcp.custom.colourBox.color ?trackcolor_valid [0 0 0 0 trackcolor_r trackcolor_g trackcolor_b customColorDepth{0}] [0 0 0 0 0 0 0 0]
custom tcp.custom.tcpBgBox
set tcp.custom.tcpBgBox [0 0 w h]
set tcp.custom.tcpBgBox.color [0 0 0 0 tcpBgColR tcpBgColG tcpBgColB 255]
;-- POPULATE SECTIONS --
assignLoc tcp.fxparm Layout##thisLayout##-tcpFxparmLocation
set tcp.fxparm.margin * Scale [3 0 4 0 0 0 0 4]
set tcpFxparmMaxWidth tcpFxparmMaxWidth{0}>tcp.fxparm{2} tcp.fxparm{2}
set tcp.fxparm.font + * Scale [0 24 tcpFxparmMinWidth{0} tcpFxparmMaxWidth{0}] Scale{0}==1 [1] Scale{0}==1.5 [6] [11]
set tcp.fxparm.font os_type==0 Scale{0}==2.0 + [0 0 0 0 -4]
set tcp.fxparm.font os_type==0 Scale{0}==1.5 + [0 0 0 0 -3]
set tcp.fxparm.visflags [1 Layout##thisLayout##-tcpFxparmVisflag1 Layout##thisLayout##-tcpFxparmVisflag2]
assignLoc tcp.fxlist Layout##thisLayout##-tcpFxLocation
set tcp.fxlist !tcp_fxlist_enabled{0} [0] . ; if disabled in options
set tcp.fxlist.font + * Scale [0 18 tcpFxMinWidth{0} tcpFxMaxWidth{0}] + [1] Scale{0}==1 [0] Scale{0}==1.5 [5] [10]
set tcp.fxlist.margin * Scale [3 0 4 6 0.5 0 20 sectionMargin{0}]
assignLoc tcp.sendlist Layout##thisLayout##-tcpSendLocation
set tcp.sendlist !tcp_sends_enabled{0} [0] . ; if disabled in options
set tcp.sendlist.margin * Scale [2 0 0 0 0 0 0 sectionMargin{0}]
set tcp.sendlist.font + * Scale [0 20 tcpSendMinWidth{0} tcpSendMaxWidth{0}] + [1] Scale{0}==1 [0] Scale{0}==1.5 [5] [10]
assignLoc tcp.fxembed Layout##thisLayout##-tcpFxembedLocation
set tcp.fxembedheader.color [200 200 200]
set minTcpW + + + \
* Scale + + thisTcpfolderIndent tcp.custom.sectionNumber{2} Layout##thisLayout##-tcpMeterWidth{0} \
longestTcpBlock{0} \
+ + tcp.custom.sectionLeft1{2} tcp.custom.sectionLeft2{2} tcp.custom.sectionLeft3{2} \
+ + tcp.custom.sectionRight1{2} tcp.custom.sectionRight2{2} tcp.custom.sectionRight3{2}
set tcp.size [. . minTcpW]
endMacro
define_parameter LayoutA-tcpFxparmLocation 'Layout A - FX Parameters Section' 4 0 9
define_parameter LayoutA-tcpSendLocation 'Layout A - Send List Section' 0 0 9
define_parameter LayoutA-tcpFxLocation 'Layout A - FX List Section' 7 0 9
define_parameter LayoutA-tcpFxembedLocation 'Layout A - Embedded FX Section' 5 0 9
define_parameter LayoutA-tcpFxparmPin 'Layout A - FX Parameters Pin' 0 0 1
define_parameter LayoutA-tcpSendPin 'Layout A - Send List Pin' 0 0 1
define_parameter LayoutA-tcpFxPin 'Layout A - FX List Pin' 0 0 1
define_parameter LayoutA-tcpFxembedPin 'Layout A - Embedded FX Pin' 0 0 1
define_parameter LayoutA-tcpFxparmVisflag1 'Layout A - tcpFxparmVisflag1' -1 -1 1
define_parameter LayoutA-tcpFxparmVisflag2 'Layout A - tcpFxparmVisflag2' 1 -1 1
define_parameter LayoutA-tcpSectionBottomDiv 'Layout A - tcpSectionBottomDiv' 2 1 3
define_parameter LayoutA-sectionLeftW 'Layout A - Left Section Width' 75 46 400
define_parameter LayoutA-sectionRightW 'Layout A - Right Section Width' 75 46 400
define_parameter LayoutA-tcpLabelLength 'Layout A - TCP Label Length' 120 40 500
define_parameter LayoutA-tcpLabelSize 'Layout A - TCP Label Font Size' 4 1 5
define_parameter LayoutA-tcpVolumeLength 'Layout A - TCP Volume Length' 40 40 300
define_parameter LayoutA-tcpInputFontSize 'Layout A - TCP Input Font Size' 1 1 5
define_parameter LayoutA-tcpRecinputLength 'Layout A - TCP Input Length' 100 40 400
define_parameter LayoutA-tcpMeterWidth 'Layout A - TCP Meter Width' 20 10 300
define_parameter LayoutA-tcpMeterBorder 'Layout A - TCP Meter Border' 2 0 8
define_parameter LayoutA-hideTcpLabelBlock 'Layout A - Visflag Track Label Block' 0 0 15
define_parameter LayoutA-hideTcpRecmon 'Layout A - Visflag Track Recmon' 4 0 15
define_parameter LayoutA-hideTcpMSBlock 'Layout A - Visflag Track MS Block' 0 0 15
define_parameter LayoutA-hideTcpIo 'Layout A - Visflag Track Io' 1 0 15
define_parameter LayoutA-hideTcpFxBlock 'Layout A - Visflag Track Fx Block' 0 0 15
define_parameter LayoutA-hideTcpPanBlock 'Layout A - Visflag Track Pan Block' 1 0 15
define_parameter LayoutA-hideTcpRecmode 'Layout A - Visflag Track Recmode' 4 0 15
define_parameter LayoutA-hideTcpInputBlock 'Layout A - Visflag Track Input Block' 4 0 15
define_parameter LayoutA-hideTcpEnv 'Layout A - Visflag Track Env' 0 0 15
define_parameter LayoutA-hideTcpPhase 'Layout A - Visflag Track Phase' 1 0 15
define_parameter LayoutA-hideTcpLabelsValues 'Layout A - Visflag Track Labels and Values' 8 0 15
define_parameter LayoutA-hideTcpMeterValues 'Layout A - Visflag Track Meter Values' 4 0 15
drawTcp A 1
Layout "A"
drawTcp A 1
endLayout
Layout "150%_A" "150"
drawTcp A 1.5
endLayout
Layout "200%_A" "200"
drawTcp A 2
endLayout
define_parameter LayoutB-tcpFxparmLocation 'Layout B - FX Parameters Section' 4 0 9
define_parameter LayoutB-tcpSendLocation 'Layout B - Send List Section' 0 0 9
define_parameter LayoutB-tcpFxLocation 'Layout B - FX List Section' 7 0 9
define_parameter LayoutB-tcpFxembedLocation 'Layout B - Embedded FX Section' 5 0 9
define_parameter LayoutB-tcpFxparmPin 'Layout B - FX Parameters Pin' 0 0 1
define_parameter LayoutB-tcpSendPin 'Layout B - Send List Pin' 0 0 1
define_parameter LayoutB-tcpFxPin 'Layout B - FX List Pin' 0 0 1
define_parameter LayoutB-tcpFxembedPin 'Layout B - Embedded FX Pin' 0 0 1
define_parameter LayoutB-tcpFxparmVisflag1 'Layout B - tcpFxparmVisflag1' -1 -1 1
define_parameter LayoutB-tcpFxparmVisflag2 'Layout B - tcpFxparmVisflag2' 1 -1 1
define_parameter LayoutB-tcpSectionBottomDiv 'Layout B - tcpSectionBottomDiv' 2 1 3
define_parameter LayoutB-sectionLeftW 'Layout B - Left Section Width' 75 46 400
define_parameter LayoutB-sectionRightW 'Layout B - Right Section Width' 75 46 400
define_parameter LayoutB-tcpLabelLength 'Layout B - TCP Label Length' 100 40 500
define_parameter LayoutB-tcpLabelSize 'Layout B - TCP Label Font Size' 4 1 5
define_parameter LayoutB-tcpVolumeLength 'Layout B - TCP Volume Length' 40 40 300
define_parameter LayoutB-tcpInputFontSize 'Layout B - TCP Input Font Size' 1 1 5
define_parameter LayoutB-tcpRecinputLength 'Layout B - TCP Input Length' 100 40 400
define_parameter LayoutB-tcpMeterWidth 'Layout B - TCP Meter Width' 20 10 300
define_parameter LayoutB-tcpMeterBorder 'Layout B - TCP Meter Border' 2 0 8
define_parameter LayoutB-hideTcpLabelBlock 'Layout B - Visflag Track Label Block' 0 0 15
define_parameter LayoutB-hideTcpRecmon 'Layout B - Visflag Track Recmon' 0 0 15
define_parameter LayoutB-hideTcpMSBlock 'Layout B - Visflag Track MS Block' 0 0 15
define_parameter LayoutB-hideTcpIo 'Layout B - Visflag Track Io' 0 0 15
define_parameter LayoutB-hideTcpFxBlock 'Layout B - Visflag Track Fx Block' 0 0 15
define_parameter LayoutB-hideTcpPanBlock 'Layout B - Visflag Track Pan Block' 0 0 15
define_parameter LayoutB-hideTcpRecmode 'Layout B - Visflag Track Recmode' 0 0 15
define_parameter LayoutB-hideTcpInputBlock 'Layout B - Visflag Track Input Block' 0 0 15
define_parameter LayoutB-hideTcpEnv 'Layout B - Visflag Track Env' 0 0 15
define_parameter LayoutB-hideTcpPhase 'Layout B - Visflag Track Phase' 0 0 15
define_parameter LayoutB-hideTcpLabelsValues 'Layout B - Visflag Track Labels and Values' 0 0 15
define_parameter LayoutB-hideTcpMeterValues 'Layout B - Visflag Track Meter Values' 4 0 15
Layout "B"
drawTcp B 1
endLayout
Layout "150%_B" "150"
drawTcp B 1.5
endLayout
Layout "200%_B" "200"
drawTcp B 2
endLayout
define_parameter LayoutC-tcpFxparmLocation 'Layout C - FX Parameters Section' 4 0 9
define_parameter LayoutC-tcpSendLocation 'Layout C - Send List Section' 0 0 9
define_parameter LayoutC-tcpFxLocation 'Layout C - FX List Section' 0 0 9
define_parameter LayoutC-tcpFxembedLocation 'Layout C - Embedded FX Section' 5 0 9
define_parameter LayoutC-tcpFxparmPin 'Layout C - FX Parameters Pin' 0 0 1
define_parameter LayoutC-tcpSendPin 'Layout C - Send List Pin' 0 0 1
define_parameter LayoutC-tcpFxPin 'Layout C - FX List Pin' 0 0 1
define_parameter LayoutC-tcpFxembedPin 'Layout C - Embedded FX Pin' 0 0 1
define_parameter LayoutC-tcpFxparmVisflag1 'Layout C - tcpFxparmVisflag1' 1 -1 1
define_parameter LayoutC-tcpFxparmVisflag2 'Layout C - tcpFxparmVisflag2' 1 -1 1
define_parameter LayoutC-tcpSectionBottomDiv 'Layout C - tcpSectionBottomDiv' 2 1 3
define_parameter LayoutC-sectionLeftW 'Layout C - Left Section Width' 75 46 400
define_parameter LayoutC-sectionRightW 'Layout C - Right Section Width' 75 46 400
define_parameter LayoutC-tcpLabelLength 'Layout C - TCP Label Length' 140 40 500
define_parameter LayoutC-tcpLabelSize 'Layout C - TCP Label Font Size' 4 1 5
define_parameter LayoutC-tcpVolumeLength 'Layout C - TCP Volume Length' 140 40 300
define_parameter LayoutC-tcpInputFontSize 'Layout C - TCP Input Font Size' 1 1 5
define_parameter LayoutC-tcpRecinputLength 'Layout C - TCP Input Length' 140 40 400
define_parameter LayoutC-tcpMeterWidth 'Layout C - TCP Meter Width' 100 10 300
define_parameter LayoutC-tcpMeterBorder 'Layout C - TCP Meter Border' 2 0 8
define_parameter LayoutC-hideTcpLabelBlock 'Layout C - Visflag Track Label Block' 0 0 15
define_parameter LayoutC-hideTcpRecmon 'Layout C - Visflag Track Recmon' 4 0 15
define_parameter LayoutC-hideTcpMSBlock 'Layout C - Visflag Track MS Block' 0 0 15
define_parameter LayoutC-hideTcpIo 'Layout C - Visflag Track Io' 0 0 15
define_parameter LayoutC-hideTcpFxBlock 'Layout C - Visflag Track Fx Block' 0 0 15
define_parameter LayoutC-hideTcpPanBlock 'Layout C - Visflag Track Pan Block' 1 0 15
define_parameter LayoutC-hideTcpRecmode 'Layout C - Visflag Track Recmode' 4 0 15
define_parameter LayoutC-hideTcpInputBlock 'Layout C - Visflag Track Input Block' 0 0 15
define_parameter LayoutC-hideTcpEnv 'Layout C - Visflag Track Env' 1 0 15
define_parameter LayoutC-hideTcpPhase 'Layout C - Visflag Track Phase' 1 0 15
define_parameter LayoutC-hideTcpLabelsValues 'Layout C - Visflag Track Labels and Values' 8 0 15
define_parameter LayoutC-hideTcpMeterValues 'Layout C - Visflag Track Meter Values' 0 0 15
Layout "C"
drawTcp C 1
endLayout
Layout "150%_C" "150"
drawTcp C 1.5
endLayout
Layout "200%_C" "200"
drawTcp C 2
endLayout
#<
#>------------------------- MASTER TRACK CONTROL PANEL --------------------------------
macro masterFollow this thisW thisH xOffs noSpace
set thisWs * Scale thisW
set thisHs * Scale thisH
set xOffsS * Scale ?xOffs{0} 0 .
set thisXMargin * Scale !noSpace{0} xMargin 0
set thisYMargin * Scale yMargin{0}
set this + + + [previous previous] [previous{2}] [thisXMargin 0 thisWs{0} thisHs{0}] [xOffs{0}] ; position it at the end of the current row
set sectionRHS + masterTcpSectionMainMargin{0} masterTcpSectionMainMargin{2}
set thisRHS + this{0} this{2}
set thisBS + this{1} this{3}
; if it'll fit in this row, its already there now, use it to possbly set a new biggestY
set biggestY thisRHS{0}<=sectionRHS{0} thisBS{0}>biggestY{0} thisBS{0} .
; -- move to next row--
; if it WON'T fit in this row, use it to start the next row at biggestY + thisYMargin
set this thisRHS{0}>sectionRHS{0} + [masterTcpSectionMainMargin thisYMargin{0} this this] [0 biggestY{0}] .
; it didn't fit in the row, so it was used (in previous line) to start the next row, which means it will now be the new biggestY
set biggestY thisRHS{0}>sectionRHS{0} + this{1} this{3}
; it didn't fit in the row, so it was used to start the next row, so the containing section will now need extra height
set masterTcpSectionMain thisRHS{0}>sectionRHS{0} + + [0 0 0 this{1}] [masterTcpSectionMain masterTcpSectionMain masterTcpSectionMain this] [0 0 0 masterTcpSectionMainMargin{1}]
; -- cull if it extends below the height of the panel --
set thisBS + this{1} this{3} ; do that again because it might have moved rows
set this thisBS{0}>h [this this 0 this] !previous{3} [this this 0 0] . ; cull method is to set width to zero
; -- cull if it is itself too wide for the section
set thisWPlus2Margins + this{2} * Scale + xMargin{0} xMargin{0}
set this thisWPlus2Margins{0}>masterTcpSectionMain{2} [this this 0 0] .
; -- cull if previous element is zero height
set this previous{3}==0 [this this 0 0] .
set previous this
endmacro
define_parameter masterTcpMeterWidth 'Master TCP Meter Width' 100 10 600
define_parameter masterTcpMeterBorder 'Master TCP Meter Border' 2 0 8
define_parameter masterTcpMeterVals 'Master TCP Meter Values' 1 0 1
define_parameter masterTcpVals 'Master TCP Values' 1 0 1
define_parameter masterTcpLabels 'Master TCP Labels' 1 0 1
define_parameter masterTcpBgColR 'Master TCP background colour' 51 0 255
define_parameter masterTcpBgColG 'Master TCP background colour G' 51 0 255
define_parameter masterTcpBgColB 'Master TCP background colour B' 51 0 255
define_parameter masterTcpVolumeLength 'Master TCP Volume Length' 40 40 600
macro drawMasterTcp Scale
set master.tcp.size [300 100 500]
custom master.tcp.custom.sectionMeter
set masterTcpMeterWidthS * Scale masterTcpMeterWidth{0}
set master.tcp.custom.sectionMeter - [w 0 masterTcpMeterWidthS{0} h] [masterTcpMeterWidthS{0}]
set master.tcp.custom.sectionMeter.color [0 0 0 0 38 38 38 255]
set masterTcpMeterBorderS * Scale masterTcpMeterBorder{0}
set master.tcp.meter + + master.tcp.custom.sectionMeter [masterTcpMeterBorderS{0} masterTcpMeterBorderS{0}] * -2 [0 0 masterTcpMeterBorderS{0} masterTcpMeterBorderS{0}]
set master.tcp.meter.vu.div [masterTcpMeterBorderS{0}]
set master.tcp.meter.readout.color !masterTcpMeterVals{0} [0 0 0 0 0 0 0 0] * textBrightnessMult{0} [150 150 150]
set master.tcp.meter.scale.color.lit.bottom !masterTcpMeterVals{0} [0 0 0 0 0 0 0 0] [0 0 0 170 0 0 0 0]
set master.tcp.meter.scale.color.lit.top !masterTcpMeterVals{0} [0 0 0 0 0 0 0 0] [0 0 0 170 0 0 0 0]
set master.tcp.meter.scale.color.unlit.bottom !masterTcpMeterVals{0} [0 0 0 0 0 0 0 0] * textBrightnessMult{0} [255 255 255 120 0 0 0 0]
set master.tcp.meter.scale.color.unlit.top !masterTcpMeterVals{0} [0 0 0 0 0 0 0 0] * textBrightnessMult{0} [255 255 255 120 0 0 0 0]
set masterTcpSectionMain + - [0 0 w] [0 0 master.tcp.custom.sectionMeter{2}] * Scale + [0 0 0 20] * 2 [0 0 0 sectionMargin{0}]
set masterTcpSectionMainMargin + masterTcpSectionMain * Scale + [sectionMargin{0} sectionMargin{0}] * -2 [0 0 sectionMargin{0} sectionMargin{0}]
set masterTcpSelectColRatio ?track_selected / selectStrength{0} 100 0
set masterTcpCol + * - 1 masterTcpSelectColRatio \
[masterTcpBgColR masterTcpBgColG masterTcpBgColB] \
* masterTcpSelectColRatio [255 255 255]
brightnessFromRGB masterTcpCol{0} masterTcpCol{1} masterTcpCol{2} masterTcpColBrightness
;reset values for 'masterFollow' macro
set biggestY 0
set xOffs 0
set noSpace 0
set previous + [masterTcpSectionMainMargin masterTcpSectionMainMargin] * Scale [0 0 0 20]
set masterTcpVolumeLength masterTcpVolumeLength{0}==40 20 . ; convert to a knob
custom master.tcp.custom.labelBlock '' 0 '' 'tcp_labelBlock_bg'
custom master.tcp.custom.labelBlockSel '' 0 '' 'tcp_labelBlock_bg_sel'
set masterTcpVolLabelBlockW + masterTcpVolumeLength{0} ?masterTcpLabels{0} 68 0
set master.tcp.size * Scale + + [. . masterTcpVolLabelBlockW{0}] [0 0 masterTcpMeterWidth{0}] * 2 [0 0 sectionMargin{0}] ; set the y-axis tooSmall
masterFollow masterTcpLabelBlock masterTcpVolLabelBlockW{0} 20 0 1
set master.tcp.custom.labelBlock ?selInvertLabels{0} ?track_selected [0] masterTcpLabelBlock masterTcpLabelBlock
set master.tcp.custom.labelBlockSel ?selInvertLabels{0} ?track_selected masterTcpLabelBlock [0] [0]
set master.tcp.label + [masterTcpLabelBlock masterTcpLabelBlock] * Scale ?masterTcpLabels{0} [0 0 68 20] [0 0 0 20]
set master.tcp.label.color * textBrightnessMult{0} [220 220 220]
set master.tcp.label.color ?selInvertLabels{0} ?track_selected [38 38 38] . .
set master.tcp.label.font + 3 Scale{0}==1 [0] Scale{0}==1.5 [5] [10]
set master.tcp.volume - + + [masterTcpLabelBlock masterTcpLabelBlock masterTcpLabelBlock] [master.tcp.label{2}] * Scale [0 0 0 20] [0 0 master.tcp.label]
set masterTcpVolLabelW masterTcpVals{0}>0 48 0
masterFollow master.tcp.volume.label masterTcpVolLabelW{0} 20 0 1
set master.tcp.volume.label.font + 1 Scale{0}==1 [0] Scale{0}==1.5 [5] [10]
set master.tcp.volume.label.color * textBrightnessMult{0} masterTcpColBrightness{0}<150 [220 220 220] [38 38 38]
set master.tcp.volume.label.margin * Scale [6 0 0 0 0]
masterFollow master.tcp.mute 20 20 0 0
masterFollow master.tcp.solo 20 20 0 1
masterFollow master.tcp.io 30 20 0 0
masterFollow masterTcpFxBlock 38 20 0 0
set master.tcp.fx !masterTcpFxBlock{2} [0] + [masterTcpFxBlock masterTcpFxBlock] * Scale [0 0 20 20]
set master.tcp.fxbyp !masterTcpFxBlock{2} [0] + [master.tcp.fx master.tcp.fx] * Scale [20 0 16 20]
front master.tcp.fxbyp
set masterTcpPanBlockW trackpanmode<=3 masterTcpVals{0}>0 58 20 trackpanmode==5 masterTcpVals{0}>0 80 42 trackpanmode==6 masterTcpVals{0}>0 100 60
masterFollow masterTcpPanBlock masterTcpPanBlockW 20 0 0
custom master.tcp.custom.panBlock
set master.tcp.custom.panBlock ?visSections masterTcpPanBlock [0]
set master.tcp.custom.panBlock.color ?visSections [0 0 0 0 255 255 100 255] [0 0 0 0 0 0 0]
set masterPanLabelW * Scale masterTcpVals{0}>0 38 0
set master.tcp.pan.label !masterTcpPanBlock{2} [0] trackpanmode<=3 + [masterTcpPanBlock masterTcpPanBlock masterPanLabelW{0}] * Scale [0 0 0 20] \
+ + [masterTcpPanBlock masterTcpPanBlock masterPanLabelW{0}] \
* Scale [0 0 0 10] trackpanmode==6 * Scale [0 10] [0]
set master.tcp.pan.label.color * textBrightnessMult{0} masterTcpColBrightness{0}<150 [220 220 220] [38 38 38]
set master.tcp.pan.label.margin + [0 0 0 0 1] * Scale [0 0 4]
set master.tcp.pan.label.font + 1 Scale{0}==1 [0] Scale{0}==1.5 [5] [10]
set master.tcp.pan !masterTcpPanBlock{2} [0] trackpanmode<6 + + [master.tcp.pan.label master.tcp.pan.label] [master.tcp.pan.label{2}] * Scale [0 0 20 20] \
+ + [ masterTcpPanBlock masterTcpPanBlock] [master.tcp.pan.label{2}] * Scale [0 10 62 10]
set master.tcp.pan.fadermode trackpanmode==6 [-1] [1]
set master.tcp.width !masterTcpPanBlock{2} [0] trackpanmode<=3 [0] trackpanmode<6 + + [master.tcp.pan master.tcp.pan] [master.tcp.pan{2}] * Scale [2 0 20 20] \
+ + [masterTcpPanBlock masterTcpPanBlock] [master.tcp.pan.label{2}] * Scale [0 0 62 10]
set master.tcp.width.fadermode master.tcp.pan.fadermode
set master.tcp.width.label !masterTcpPanBlock{2} [0] trackpanmode<=3 [0] trackpanmode<6 + [master.tcp.pan.label master.tcp.pan.label masterPanLabelW{0}] * Scale [0 10 0 10] \
+ [masterTcpPanBlock masterTcpPanBlock masterPanLabelW{0}] * Scale [0 0 0 10]
set master.tcp.width.label.color master.tcp.pan.label.color
set master.tcp.width.label.margin master.tcp.pan.label.margin
set master.tcp.width.label.font + 1 Scale{0}==1 [0] Scale{0}==1.5 [5] [10]
masterFollow master.tcp.env 40 20 0 0
set masterTcpMonoW ?masterTcpLabels{0} 44 20
masterFollow master.tcp.mono masterTcpMonoW{0} 20 0 0
set masterTcpSelDotY * 0.5 h<masterTcpSectionMain{3} h masterTcpSectionMain{3}
custom master.tcp.custom.tcp_selectionDot '' 0 '' 'tcp_selectionDot'
set master.tcp.custom.tcp_selectionDot !selDot{0} [0] ?track_selected [0] + + [masterTcpSectionMain masterTcpSectionMain] [masterTcpSectionMain{2} masterTcpSelDotY{0}] * Scale [-4 -4 8 8]
custom master.tcp.custom.tcp_selectionDotSel '' 0 '' 'tcp_selectionDot_sel'
set master.tcp.custom.tcp_selectionDotSel !selDot{0} [0] !track_selected [0] + + [masterTcpSectionMain masterTcpSectionMain] [masterTcpSectionMain{2} masterTcpSelDotY{0}] * Scale [-4 -4 8 8]
front master.tcp.custom.tcp_selectionDot master.tcp.custom.tcp_selectionDotSel
custom master.tcp.custom.sectionMain
set master.tcp.custom.sectionMain masterTcpSectionMain
set master.tcp.custom.sectionMain.color ?visSections [0 0 0 0 50 50 255 100] [0 0 0 0 masterTcpCol{0} masterTcpCol{1} masterTcpCol{2} 255]
custom master.tcp.custom.sectionBottom
set master.tcp.custom.sectionBottom - [0 masterTcpSectionMain{3} masterTcpSectionMain h] [0 0 0 masterTcpSectionMain{3}]
set master.tcp.custom.sectionBottom.color ?visSections [0 0 0 0 100 255 100 150] [0 0 0 0 38 38 38 255]
set masterTcpSectionBottomMargin + master.tcp.custom.sectionBottom * Scale * sectionMargin{0} [1 1 -2 -2]
set master.tcp.fxparm masterTcpSectionBottomMargin
set master.tcp.fxparm.margin * Scale [3 0 4 0 1 0 0 4]
set master.tcp.fxparm.font + * Scale [0 24 tcpFxparmMinWidth{0} tcpFxparmMaxWidth{0}] + [1] Scale{0}==1 [0] Scale{0}==1.5 [5] [10]
endMacro
drawMasterTcp 1
Layout "A"
drawMasterTcp 1
endLayout
Layout "150%_A" "150"
drawMasterTcp 1.5
endLayout
Layout "200%_A" "200"
drawMasterTcp 2
endLayout
#<
#> -------------------------- ENVELOPE CONTROL PANELS ---------------------------------
macro envFollow this thisW thisH xOffs noSpace
set thisWs * Scale thisW
set thisHs * Scale thisH
set xOffsS * Scale xOffs
set thisXMargin * Scale !noSpace{0} xMargin 0
set thisYMargin * Scale yMargin
set this + + + [previous previous] [previous{2}] [thisXMargin 0 thisWs thisHs] [xOffsS] ; position it at the end of the current row
set this ?hide_##this{0} + [previous] [previous{2} . 0 .] . ; apply hide by setting w to zero and ignoring both thisXMargin and xOffs
set sectionRHS + envcp.custom.sectionMain{0} envcp.custom.sectionMain{2}
set thisRHS + this{0} this{2}
set thisBS + this{1} this{3}
; if it'll fit in this row, its already there now, use it to possbly set a new biggestY
set biggestY thisRHS{0}<=sectionRHS{0} thisBS{0}>biggestY{0} thisBS{0} .
; -- move to next row--
; if it WON'T fit in this row, use it to start the next row at biggestY + thisYMargin
set this thisRHS{0}>sectionRHS{0} + [envMargin thisYMargin{0} this this] [0 biggestY{0}]
; it didn't fit in the row, so it was used (in previous line) to start the next row, which means it will now be the new biggestY
set biggestY thisRHS{0}>sectionRHS{0} + this{1} this{3}
; -- cull if it extends below the height of the panel --
set thisBS + this{1} this{3} ; do that again because it might have moved rows
set this thisBS{0}>h \
h<singleRowH{0} \
this{1}>thisYMarginPlus10{0} [this this 0 0] . \
[this this 0 this] \
!previous{3} [this this 0 0] . ; cull method is to set width to zero
; -- cull if it is itself too wide for the section
set thisWPlus2Margins + + this{2} thisXMargin{0} thisXMargin{0}}
set this thisWPlus2Margins{0}>envcp.custom.sectionMain{2} [this this 0 0] .
; -- cull if previous element is zero height
set this previous{3}==0 [this this 0 0] .
; -- this is the new previous
set previous this
endmacro
define_parameter indentEnvcp 'Env inherit track indent' 1 0 1
define_parameter showEnvValue 'Show envelope value' 1 0 1
define_parameter envcpLabelLength 'Env Label Length' 160 40 500
define_parameter envcpFaderLength 'Env Fader Length' 100 40 300
define_parameter envcpFontSize 'Env Label Font Size' 2 1 5
define_parameter envcpDivOpacity 'Env Div Opacity' 80 0 255
define_parameter envcpBgColR 'EnvCP background colour' 51 0 255
define_parameter envcpBgColG 'EnvCP background colour G' 51 0 255
define_parameter envcpBgColB 'EnvCP background colour B' 51 0 255
define_parameter envCustomColorDepth 'Env Custom Color Strength' 0 0 100
set envCustomColorRatio ?trackcolor_valid / envCustomColorDepth{0} 100 0
macro drawEnvCP Scale
set envcp.size * Scale [300 100 40]
set singleRowH * Scale + 20 * 2 sectionMargin{0}
set ySqueeze h<singleRowH{0} - * Scale sectionMargin{0} * 0.5 - singleRowH{0} h * Scale sectionMargin{0}
set thisTcpfolderIndentS * Scale thisTcpfolderIndent{0}
custom envcp.custom.sectionMain
set envcp.custom.sectionMain ?indentEnvcp{0} - [thisTcpfolderIndentS{0} ySqueeze w h] [0 0 thisTcpfolderIndentS{0}] [0 ySqueeze w h]
set envcp.custom.sectionMain.color ?visSections [0 0 0 0 100 255 150 150] [0 0 0 0 0 0 0 0]
set biggestY 0
set xOffs 0
set noSpace 0
set envMargin ?indentEnvcp{0} + tcpfolderBalanceType==2 * Scale tcpFolderBalancer 0 + envcp.custom.sectionMain * Scale sectionMargin{0} * Scale sectionMargin{0}
set previous + [envMargin envcp.custom.sectionMain] * Scale [0 0 0 20]
set hide_envcpLabelBlock 0
set hide_envcp.fader 0
set hide_envcp.value ?showEnvValue{0} 0 1
set hide_envcp.mod envcp_type==4 0 1 ; 4 if FX envelope (can display additional controls)
set hide_envcp.learn envcp_type==4 0 1
set hide_envcp.hide 0
;reset values for 'envFollow' macro
set biggestY 0
set xOffs 0
set noSpace 0
set thisEnvcpLabelLength ?indentEnvcp{0} tcpfolderBalanceType==1 + envcpLabelLength tcpFolderBalancer envcpLabelLength envcpLabelLength
set envcpFaderLength envcpFaderLength{0}<=40 20 .
set envcpLabelBlockW + + + thisEnvcpLabelLength{0} envcpFaderLength{0}<=40 20 0 20 15 ; 20 is the recarm width, 15 is the bypass width
envFollow envcpLabelBlock envcpLabelBlockW{0} 20 0 1
custom envcp.custom.labelBlock
custom envcp.custom.labelBlockBg '' 0 '' 'tcp_labelBlock_bg'
custom envcp.custom.labelBlockBgSel '' 0 '' 'tcp_labelBlock_bg_sel'
set envcp.custom.labelBlockBg ?selInvertLabels{0} ?env_selected [0] envcpLabelBlock envcpLabelBlock
set envcp.custom.labelBlockBgSel ?selInvertLabels{0} ?env_selected envcpLabelBlock [0] [0]
set envcp.arm envcpLabelBlock{2}==0 [0] + [envcpLabelBlock envcpLabelBlock] * Scale [2 0 20 20]
set envcp.bypass envcpLabelBlock{2}==0 [0] + + [envcp.arm envcp.arm] * Scale [2 0 14 20] [envcp.arm{2}]
set envcp.label envcpLabelBlock{2}==0 [0] + + [envcp.bypass envcp.bypass] * Scale [0 0 thisEnvcpLabelLength{0} 20] [envcp.bypass{2}]
set envcp.label.margin * Scale [2 0 4 0 0]
set envcp.label.color * textBrightnessMult{0} ?selInvertLabels{0} ?env_selected [38 38 38] [200 200 200] [200 200 200]
set envcp.label.font + [envcpFontSize] Scale{0}==1 [0] Scale{0}==1.5 [5] [10]
set envFaderXoffset envcpFaderLength{0}<=40 -20 6
envFollow envcp.fader envcpFaderLength{0} 20 envFaderXoffset{0} 0
set envcp.fader.fadermode envcpFaderLength{0}<=40 [1] [0]
; Calculate background color color now, for use in text brightness judgement
set envSelectColRatio ?env_selected / selectStrength{0} 100 0
set envcpCol + * - 1 envSelectColRatio + \
* envCustomColorRatio [trackcolor_r trackcolor_g trackcolor_b] \
* - 1 envCustomColorRatio [envcpBgColR envcpBgColG envcpBgColB] \
* envSelectColRatio [255 255 255]
brightnessFromRGB envcpCol{0} envcpCol{1} envcpCol{2} envcpColBrightness
envFollow envcp.value 52 20 4 0
set envcp.value.font + [1] Scale{0}==1 [0] Scale{0}==1.5 [5] [10]
set envcp.value.color * textBrightnessMult{0} envcpColBrightness{0}<120 [180 180 180] [38 38 38]
set envcp.value.margin * Scale [0 0 0 0 0]
envFollow envcp.mod 20 20 0 0
envFollow envcp.learn 20 20 0 0
envFollow envcp.hide 36 20 0 0
custom envcp.custom.indentInfill
set envcp.custom.indentInfill ?indentEnvcp{0} * Scale [0 0 thisTcpfolderIndent{0} h] [0 0 0 0]
set envcp.custom.indentInfill.color [0 0 0 0 51 51 51]
custom envcp.custom.envcpDiv
set envcp.custom.envcpDiv - [0 h w 1] [0 1]
set envcp.custom.envcpDiv.color * Scale [0 0 0 0 0 0 0 envcpDivOpacity{0}]
custom envcp.custom.sectionMainBg
set envcp.custom.sectionMainBg [envcp.custom.sectionMain 0 envcp.custom.sectionMain h]
set envcp.custom.sectionMainBg.color ?visSections [0 0 0 0 255 50 255 60] [0 0 0 0 envcpCol{0} envcpCol{1} envcpCol{2} 255]
endMacro
drawEnvCP 1
Layout "A"
drawEnvCP 1
endLayout
Layout "150%_A" "150"
drawEnvCP 1.5
endLayout
Layout "200%_A" "200"
drawEnvCP 2
endLayout
#<
#>---------------------------------- THE MIXER ----------------------------------------
;-- GLOABL MCP PARAMS --
define_parameter mcpfolderIndentSize 'MCP Folder Indent' 10 0 40
define_parameter mcpDivOpacity 'MCP Div Opacity' 80 0 255
define_parameter mcpBgColR 'MCP background colour' 129 0 255
define_parameter mcpBgColG 'MCP background colour G' 137 0 255
define_parameter mcpBgColB 'MCP background colour B' 137 0 255
define_parameter mcpfolderBalanceType 'MCP Folder Balance Type' 0 0 1
define_parameter mcpStripFlowLocation1 'MCP Strip flow location 1' 1 1 11
define_parameter mcpStripFlowLocation2 'MCP Strip flow location 2' 6 1 11
define_parameter mcpStripFlowLocation3 'MCP Strip flow location 3' 11 1 11
define_parameter mcpStripFlowLocation4 'MCP Strip flow location 4' 2 1 11
define_parameter mcpStripFlowLocation5 'MCP Strip flow location 5' 3 1 11
define_parameter mcpStripFlowLocation6 'MCP Strip flow location 6' 4 1 11
define_parameter mcpStripFlowLocation7 'MCP Strip flow location 7' 5 1 11
define_parameter mcpStripFlowLocation8 'MCP Strip flow location 8' 8 1 11
define_parameter mcpStripFlowLocation9 'MCP Strip flow location 9' 7 1 11
define_parameter mcpStripFlowLocation10 'MCP Strip flow location 10' 9 1 11
define_parameter mcpStripFlowLocation11 'MCP Strip flow location 11' 10 1 11
; 1: label block
; 2: volume
; 3: M&S block
; 4: io
; 5: fx block
; 6: pan block
; 7: recmode
; 8: input block
; 9: env
; 10: phase
; 11: meter
macro mcpFollow this thisW thisH yOffs noSpace Form
set thisWs * Scale thisW
set thisHs * Scale thisH
set yOffsS * Scale yOffs
set thisYMargin * Scale !noSpace{0} 6 0 ; hard coding margin as 6
set this mcpForm{0}==Form{0} + + + [previous previous] [0 previous{3}] [0 thisYMargin{0} thisWs thisHs] [0 yOffsS]
set this mcpForm{0}==Form{0} ?hide_##this{0} + [previous previous] [0 previous{3} . 0] . ; apply hide by setting h to zero and ignoring both thisYMargin and yOffs
set thisBS mcpForm{0}==Form{0} + + this{1} this{3} thisYMargin{0}
set sectionButtonsBS mcpForm{0}==Form{0} + mcp.custom.sectionButtons{1} mcp.custom.sectionButtons{3}
set this mcpForm{0}==Form{0} thisBS{0}>sectionButtonsBS{0} [. . . 0] . ; cull if extending below buttons section
set biggestY mcpForm{0}==Form{0} thisBS{0}>biggestY{0} thisBS{0}
; -- this is the new previous
set previous mcpForm{0}==Form{0} this
endMacro
macro stackMcpStripProxy index
set proxy##index mcpStripFlowLocation##index==1 mcpStripLabelBlock \
mcpStripFlowLocation##index==2 mcpStripVolumeBlock \
mcpStripFlowLocation##index==3 mcpStripMSBlock \
mcpStripFlowLocation##index==4 mcp.io \
mcpStripFlowLocation##index==5 mcpStripFxBlock \
mcpStripFlowLocation##index==6 mcpStripPanBlock \
mcpStripFlowLocation##index==7 mcp.custom.recmodeBg_v \
mcpStripFlowLocation##index==8 mcpStripInputBlock \
mcpStripFlowLocation##index==9 mcp.env \
mcpStripFlowLocation##index==10 mcp.phase \
mcpStripFlowLocation##index==11 mcpStripMeterBlock
set darkBg##index mcpStripFlowLocation##index==1 1 \
mcpStripFlowLocation##index==2 1 \
mcpStripFlowLocation##index==3 0 \
mcpStripFlowLocation##index==4 0 \
mcpStripFlowLocation##index==5 0 \
mcpStripFlowLocation##index==6 1 \
mcpStripFlowLocation##index==7 0 \
mcpStripFlowLocation##index==8 0 \
mcpStripFlowLocation##index==9 0 \
mcpStripFlowLocation##index==10 0 \
mcpStripFlowLocation##index==11 1
set thisHs * Scale proxy##index{3}
set thisWs * Scale proxy##index{2}
set thisYMargin * Scale darkBg##index{0}==previousDarkBg{0} 6 12
set proxy##index + + [sidebarWidth{0}] / - [stripW] [thisWs] 2 - - [0 previous thisWs thisHs] [0 thisHs] [0 thisYMargin]
; -- cull if it extends above the height of the panel --
set proxy##index proxy##index{1}<thisYMargin{0} \
[proxy##index proxy##index 0 0] \
!previous{3} [proxy##index proxy##index 0 0] . ; cull method is to set width and height to zero
; -- cull if it is itself too tall for the section
set hMinusIdx - - h stripSectionBottomH{0} thisYMargin{0}
set proxy##index proxy##index{3}>hMinusIdx{0} [proxy##index proxy##index 0 0] .
; -- cull if previous element is zero height
set proxy##index previous{3}==0 [proxy##index proxy##index 0 0] .
; -- this is the new previous
set previous proxy##index
set previousIndex index
set previousDarkBg darkBg##index
endmacro
macro attachMcpStripProxy index
set mcpStripLabelBlock mcpForm{0}==1 mcpStripFlowLocation##index==1 proxy##index
set mcpStripVolumeBlock mcpForm{0}==1 mcpStripFlowLocation##index==2 proxy##index
set mcpStripMSBlock mcpForm{0}==1 mcpStripFlowLocation##index==3 proxy##index
set mcp.io mcpForm{0}==1 mcpStripFlowLocation##index==4 proxy##index
set mcpStripFxBlock mcpForm{0}==1 mcpStripFlowLocation##index==5 proxy##index
set mcpStripPanBlock mcpForm{0}==1 mcpStripFlowLocation##index==6 proxy##index
set mcp.custom.recmodeBg_v mcpForm{0}==1 mcpStripFlowLocation##index==7 proxy##index
set mcpStripInputBlock mcpForm{0}==1 mcpStripFlowLocation##index==8 proxy##index
set mcp.env mcpForm{0}==1 mcpStripFlowLocation##index==9 proxy##index
set mcp.phase mcpForm{0}==1 mcpStripFlowLocation##index==10 proxy##index
set mcpStripMeterBlock mcpForm{0}==1 mcpStripFlowLocation##index==11 proxy##index
endmacro
macro drawMcp thisLayout Scale
;-- HOUSEKEEPING --
clear mcp.*
set thisMcpfolderIndent * folderdepth mcpfolderIndentSize
set hAfterIndent - h * Scale thisMcpfolderIndent{0}
set mcpNchanGrowPx tracknch<3 0 * - tracknch 2 ?recarm Layout##thisLayout##-mcpNchanGrowRecarm ?track_selected Layout##thisLayout##-mcpNchanGrowSel Layout##thisLayout##-mcpNchanGrow
set mcpWidth * Scale + mcpNchanGrowPx{0} ?recarm Layout##thisLayout##-mcpWidthRecarm ?track_selected Layout##thisLayout##-mcpWidthSel Layout##thisLayout##-mcpWidth
set mcpFormW * Scale [52 88]
set mcpForm mcpWidth{0}<mcpFormW{0} [1] mcpWidth{0}<mcpFormW{1} [2] [3] ; 1=Strip, 2=Intermediate, 3=Normal
set addSidebar ?recarm ?Layout##thisLayout##-mcpSidebarRecarm 1 0 ?track_selected ?Layout##thisLayout##-mcpSidebarSel 1 0 ?Layout##thisLayout##-mcpSidebar 1 0
set sidebarWidth * Scale ?addSidebar{0} Layout##thisLayout##-sidebarWidth 0
;-- SECTIONS --
custom mcp.custom.mcpDiv
set mcp.custom.mcpDiv - [0 0 1 h] * Scale [0 0 0 thisMcpfolderIndent{0}]
set mcp.custom.mcpDiv.color * Scale [0 0 0 0 0 0 0 mcpDivOpacity{0}]
; calculate sectionBottom height
set sectionBottomH * Scale + 44 thisMcpfolderIndent{0}
set maxSectionBottomH * Scale + 44 * mcp_maxfolderdepth mcpfolderIndentSize
set sectionBottomH ?mcpfolderBalanceType{0} maxSectionBottomH .
set stripSectionBottomH * Scale + 20 * folderdepth mcpfolderIndentSize
; calculate sectionButtons height
set mcpIntermediateSectionButtonsH hAfterIndent{0}<Layout##thisLayout##-mcpInterShowSecButtons{0} 0 * Scale !Layout##thisLayout##-verboseMcp{0} 92 102
set mcpStripSectionButtonsH * Scale + + !Layout##thisLayout##-verboseMcp{0} 120 130 !Layout##thisLayout##-verboseMcp{0} 26 38
set centW * 0.5 mcpWidth{0}
set firstThirdW + sidebarWidth * 0.3333 mcpWidth{0}
set secondThirdW + sidebarWidth * 0.6666 mcpWidth{0}
;--Top Section--
custom mcp.custom.sectionTop
set mcp.custom.sectionTop.color ?visSections [0 0 0 0 255 100 100 150] [0 0 0 1 0 0 0 0]
custom mcp.custom.recinputBg_h '' 0 '' 'dropdownBg_h'
custom mcp.custom.recinputBg_v '' 0 '' 'dropdownBg_v'
custom mcp.custom.recmodeBg_h '' 0 '' 'dropdownBg_h'
custom mcp.custom.recmodeBg_v '' 0 '' 'dropdownBg_v'
; Normal Width
set mcp.custom.sectionTop mcpForm{0}==3 + [sidebarWidth 0 mcpWidth{0}] * Scale hAfterIndent{0}>Layout##thisLayout##-mcpNormalShowSecIn{0} [0 0 0 50] [0]
set mcp.custom.recinputBg_v mcpForm{0}==3 [0]
set mcp.custom.recmodeBg_v mcpForm{0}==3 [0]
set mcp.custom.recinputBg_h mcpForm{0}==3 !mcp.custom.sectionTop{3} [0] + [mcp.custom.sectionTop] + [0 0 mcpWidth{0}] * Scale [6 6 -12 20]
set mcp.recinput mcp.custom.recinputBg_h
set mcp.custom.recmodeBg_h mcpForm{0}==3 !mcp.custom.sectionTop{3} [0] + [mcp.custom.sectionTop] * Scale [6 30 40 20]
set mcp.recmode mcp.custom.recmodeBg_h
set mcp.fxin mcpForm{0}==3 !mcp.custom.sectionTop{3} [0] + + [mcp.custom.sectionTop] [mcp.custom.sectionTop{2}] * Scale [-26 30 20 20]
; Intermediate Width
set mcp.custom.sectionTop mcpForm{0}==2 + [sidebarWidth 0 mcpWidth{0}] * Scale hAfterIndent{0}>Layout##thisLayout##-mcpInterShowSecIn{0} [0 0 0 72] [0]
set mcp.custom.recinputBg_h mcpForm{0}==2 [0]
set mcp.custom.recmodeBg_h mcpForm{0}==2 [0]
set mcp.custom.recinputBg_v mcpForm{0}==2 mcp.custom.sectionTop{3}==0 [0] + [secondThirdW{0} 0 0 mcp.custom.sectionTop] * Scale [-6 6 20 -6]
set mcp.recinput mcpForm{0}==2 mcp.custom.recinputBg_v
set mcp.custom.recmodeBg_v mcpForm{0}==2 mcp.custom.sectionTop{3}==0 [0] + [firstThirdW{0}] * Scale [-12 6 20 40]
set mcp.recmode mcpForm{0}==2 mcp.custom.recmodeBg_v
set mcp.fxin mcpForm{0}==2 mcp.custom.sectionTop{3}==0 [0] + + [mcp.recmode mcp.recmode] [0 mcp.recmode{3}] * Scale [0 6 20 20]
; Strip Width - strip doesn't use top section
;--Pan Section--
custom mcp.custom.sectionPan
; Calculate resulting color for use in text brightness judgement
set mcpMainSecCol + * - 1 selectColRatio + \
* customColorRatio [trackcolor_r trackcolor_g trackcolor_b] \
* - 1 customColorRatio [mcpBgColR mcpBgColG mcpBgColB] \
* selectColRatio [255 255 255]
brightnessFromRGB mcpMainSecCol{0} mcpMainSecCol{1} mcpMainSecCol{2} mcpMainSecColBrightness
; Normal Width
set mcp.custom.sectionPan mcpForm{0}==3 + + [sidebarWidth 0 mcpWidth{0}] [0 mcp.custom.sectionTop{3}] hAfterIndent{0}<Layout##thisLayout##-mcpNormalShowSecPan{0} [0] * Scale !Layout##thisLayout##-verboseMcp{0} [0 0 0 30] [0 0 0 46]
set mcp.custom.sectionPan.color mcpForm{0}==3 [0 0 0 1 0 0 0 0]
set mcp.pan.label mcpForm{0}==3 mcp.custom.sectionPan{3}==0 [0] !Layout##thisLayout##-verboseMcp{0} [mcp.custom.sectionPan mcp.custom.sectionPan] \
+ [mcp.custom.sectionPan mcp.custom.sectionPan mcp.custom.sectionPan] * Scale [0 0 0 14]
set mcp.pan.label.margin mcpForm{0}==3 * [Scale Scale Scale Scale 1] trackpanmode>=4 [12 6 0 0 0] [6 6 6 0 0.5]
set mcp.pan.label.color mcpForm{0}==3 * textBrightnessMult{0} mcpMainSecColBrightness{0}<150 [220 220 220] [38 38 38]
set mcp.pan mcpForm{0}==3 mcp.custom.sectionPan{3}==0 [0] \
trackpanmode==6 + + * Scale [6 14 -12 10] [0 mcp.pan.label{3}] [mcp.pan.label mcp.pan.label mcp.custom.sectionPan] \
+ + [centW mcp.pan.label{3}] [mcp.custom.sectionPan mcp.pan.label] * Scale trackpanmode>=4 [-20 4 20 20] [-10 4 20 20]
set mcp.width mcpForm{0}==3 mcp.custom.sectionPan{3}==0 [0] \
trackpanmode==6 + + * Scale [6 4 -12 10] [0 mcp.pan.label{3}] [mcp.pan.label mcp.pan.label mcp.custom.sectionPan] \
trackpanmode>=4 + [mcp.pan mcp.pan] * Scale [22 0 20 20] [0]
set mcp.width.label mcpForm{0}==3 mcp.custom.sectionPan{3}==0 [0] trackpanmode>=4 !Layout##thisLayout##-verboseMcp{0} [0] \
+ [mcp.custom.sectionPan mcp.custom.sectionPan mcp.custom.sectionPan] * Scale [0 0 0 14] [0]
set mcp.width.label.margin mcpForm{0}==3 * [Scale Scale Scale Scale 1] [0 6 12 0 1]
; Intermediate Width
set mcp.custom.sectionPan mcpForm{0}==2 + + [sidebarWidth mcp.custom.sectionTop{3} mcpWidth{0}] [0 mcpIntermediateSectionButtonsH{0}] \
hAfterIndent{0}<Layout##thisLayout##-mcpInterShowSecPan{0} [0] * Scale !Layout##thisLayout##-verboseMcp{0} [0 0 0 30] [0 0 0 46]
set mcp.custom.sectionPan.color mcpForm{0}==2 [0 0 0 1 0 0 0 0]
set mcp.pan.label mcpForm{0}==2 mcp.custom.sectionPan{3}==0 [0] !Layout##thisLayout##-verboseMcp{0} [0 mcp.custom.sectionPan] \
+ [mcp.custom.sectionPan mcp.custom.sectionPan mcp.custom.sectionPan] * Scale [0 0 0 14]
set mcp.pan.label.margin mcpForm{0}==2 * [Scale Scale Scale Scale 1] trackpanmode>=4 [4 6 0 0 0] [0 6 0 0 0.5]
set mcp.pan.label.color mcpForm{0}==2 * textBrightnessMult{0} mcpMainSecColBrightness{0}<150 [220 220 220] [38 38 38]
set mcp.pan mcpForm{0}==2 mcp.custom.sectionPan{3}==0 [0] \
trackpanmode==6 + + * Scale [6 14 -12 10] [0 mcp.pan.label{3}] [mcp.pan.label mcp.pan.label mcp.custom.sectionPan] \
+ + [centW mcp.pan.label{3}] [mcp.custom.sectionPan mcp.pan.label] * Scale trackpanmode>=4 [-20 4 20 20] [-10 4 20 20]
set mcp.width mcpForm{0}==2 mcp.custom.sectionPan{3}==0 [0] \
trackpanmode==6 + + * Scale [6 4 -12 10] [0 mcp.pan.label{3}] [mcp.pan.label mcp.pan.label mcp.custom.sectionPan] \
trackpanmode>=4 + [mcp.pan mcp.pan] * Scale [22 0 20 20] [0]
set mcp.width.label mcpForm{0}==2 mcp.custom.sectionPan{3}==0 [0] trackpanmode>=4 !Layout##thisLayout##-verboseMcp{0} [0] \
+ [mcp.custom.sectionPan mcp.custom.sectionPan mcp.custom.sectionPan] * Scale [0 0 0 14] [0]
set mcp.width.label.margin mcpForm{0}==2 * [Scale Scale Scale Scale 1] [0 6 4 0 1]
; Strip Width - strip pan section will be populated after the proxy stack is calculated
set mcp.custom.sectionPan.color ?visSections{0} [0 0 0 0 100 255 100 100]
set mcp.pan.label.font + [1] Scale{0}==1 [0] Scale{0}==1.5 [5] [10]
set mcp.pan.fadermode trackpanmode==6 [-1] [1]
set mcp.width.fadermode trackpanmode==6 [-1] [1]
;--Button Section--
custom mcp.custom.sectionButtons
set mcpIoH ?Layout##thisLayout##-verboseMcp{0} 32 22
set mcpEnvH ?Layout##thisLayout##-verboseMcp{0} 32 22
; Normal Width
set mcp.custom.sectionButtons mcpForm{0}==3 + [sidebarWidth] + [mcpWidth{0} mcp.custom.sectionPan] - + * Scale [-32 0 32] [0 mcp.custom.sectionPan{3} 0 h] \
+ + [0 0 0 mcp.custom.sectionPan{1}] [0 0 0 mcp.custom.sectionPan{3}] [0 0 0 sectionBottomH{0}]
set mcp.custom.sectionButtons.color mcpForm{0}==3 ?Layout##thisLayout##-mcpNormalDarkButtons{0} [0 0 0 1 38 38 38 255] [0 0 0 1 0 0 0 0]
set biggestY 0
set hide_mcp.mute 0
set hide_mcp.solo 0
set hide_mcp.io !Layout##thisLayout##-mcpNormalShowRoute{0} 1 0
set hide_mcp.fxGroup !Layout##thisLayout##-mcpNormalShowSecFx{0} 1 0
set hide_mcp.env !Layout##thisLayout##-mcpNormalShowEnv{0} 1 0
set hide_mcp.phase !Layout##thisLayout##-mcpNormalShowPhase{0} 1 0
set previous mcpForm{0}==3 + [mcp.custom.sectionButtons mcp.custom.sectionButtons] * Scale [6 6 0 0] ; Null object
mcpFollow mcp.mute 20 20 0 1 3
mcpFollow mcp.solo 20 20 0 1 3
mcpFollow mcp.io 20 mcpIoH{0} 0 0 3
mcpFollow mcp.fxGroup 20 36 0 0 3
set mcp.fx mcp.fxGroup{3}>0 + [mcp.fxGroup mcp.fxGroup] * Scale [0 0 20 20] [0]
set mcp.fxbyp mcp.fxGroup{3}>0 + + [mcp.fxGroup mcp.fxGroup] [0 mcp.fx{3}] * Scale [0 0 20 16] [0]
mcpFollow mcp.env 20 mcpEnvH{0} 0 0 3
mcpFollow mcp.phase 20 16 0 0 3
; Intermediate Width
set mcp.custom.sectionButtons mcpForm{0}==2 + [sidebarWidth mcp.custom.sectionTop{3} mcpWidth{0}] [0 0 0 mcpIntermediateSectionButtonsH{0}]
set mcp.custom.sectionButtons.color mcpForm{0}==2 [0 0 0 1 0 0 0 0]
set mcp.mute mcpForm{0}==2 mcpIntermediateSectionButtonsH{0}==0 [0] + + [firstThirdW{0}] [0 mcp.custom.sectionButtons] * Scale [-12 6 20 20]
set mcp.solo mcpForm{0}==2 mcpIntermediateSectionButtonsH{0}==0 [0] + + [mcp.mute mcp.mute] [0 mcp.mute{3}] * Scale [0 0 20 20]
set mcp.io mcpForm{0}==2 mcpIntermediateSectionButtonsH{0}==0 [0] + + [mcp.solo mcp.solo] [0 mcp.solo{3}] * Scale ?Layout##thisLayout##-verboseMcp{0} [0 6 20 32] [0 6 20 22]
set mcp.fx mcpForm{0}==2 mcpIntermediateSectionButtonsH{0}==0 [0] + + [secondThirdW{0}] [0 mcp.custom.sectionButtons] * Scale [-6 6 20 20]
set mcp.fxbyp mcpForm{0}==2 mcpIntermediateSectionButtonsH{0}==0 [0] + + [mcp.fx mcp.fx] [0 mcp.fx{3}] * Scale [0 0 20 16]
set mcp.env mcpForm{0}==2 mcpIntermediateSectionButtonsH{0}==0 [0] + + [mcp.fxbyp mcp.fxbyp] [0 mcp.fxbyp{3}] * Scale ?Layout##thisLayout##-verboseMcp{0} [0 6 20 32] [0 6 20 22]
set mcp.phase mcpForm{0}==2 mcpIntermediateSectionButtonsH{0}==0 [0] + + [mcp.env mcp.env] [0 mcp.env{3}] * Scale [0 4 20 16]
; Strip Width mcp.custom.sectionButtons is the volume bg in stackMcpStripProxy
;--Dark Box Section--
custom mcp.custom.mcpDarkBox
; Normal Width
set mcp.custom.mcpDarkBox mcpForm{0}==3 + + [sidebarWidth mcp.custom.sectionPan w h] [0 mcp.custom.sectionPan{3}] \
* -1 + + [0 0 mcp.custom.sectionButtons sectionBottomH] [0 0 sidebarWidth mcp.custom.sectionPan{1}] [0 0 0 mcp.custom.sectionPan{3}]
set standardDarkBoxMinH - h + + maxSectionBottomH mcp.custom.sectionPan{1} mcp.custom.sectionPan{3}
set mcp.volume.label mcpForm{0}==3 !Layout##thisLayout##-verboseMcp{0} [0] + [mcp.custom.mcpDarkBox mcp.custom.mcpDarkBox mcp.custom.mcpDarkBox] * Scale [0 0 0 20]
set mcp.meter mcpForm{0}==3 + + * Scale [4 6 -32 -36] [mcp.custom.mcpDarkBox mcp.custom.mcpDarkBox mcp.custom.mcpDarkBox mcp.custom.mcpDarkBox] \
* [0 1 0 -1] [0 mcp.volume.label{3} 0 mcp.volume.label{3}]
set mcp.volume mcpForm{0}==3 + + [mcp.custom.mcpDarkBox mcp.custom.mcpDarkBox 0 mcp.custom.mcpDarkBox] + [mcp.custom.mcpDarkBox{2}] * Scale [-26 6 25 -36] \
* [0 1 0 -1] [0 mcp.volume.label{3} 0 mcp.volume.label{3}]
set mcpVolKnobH * Scale 60
set mcp.volume mcpForm{0}==3 mcp.volume{3}<mcpVolKnobH{0} + [. . ] * Scale [0 0 20 20] ; turn into a knob
set mcp.recarm mcpForm{0}==3 + + [mcp.volume mcp.volume] * [0.5 1] [mcp.volume{2} mcp.volume{3}] * Scale [-12 4 24 20]
set mcp.recmon mcpForm{0}==3 + + + [mcp.meter mcp.meter] * Scale [-10 4 20 20] [0 mcp.meter{3}] * 0.5 [mcp.meter{2}]
; Intermediate Width
set mcp.custom.mcpDarkBox mcpForm{0}==2 + + [sidebarWidth mcp.custom.sectionPan mcpWidth{0} h] [0 mcp.custom.sectionPan{3}] \
* -1 + + [0 0 0 mcp.custom.sectionPan{1}] [0 0 0 mcp.custom.sectionPan{3}] [0 0 0 sectionBottomH]
set mcp.volume.label mcpForm{0}==2 !Layout##thisLayout##-verboseMcp{0} [0] + [mcp.custom.mcpDarkBox mcp.custom.mcpDarkBox mcp.custom.mcpDarkBox] * Scale [0 0 0 20]
set mcp.meter mcpForm{0}==2 + + * Scale [6 6 -42 -36] [mcp.custom.mcpDarkBox mcp.custom.mcpDarkBox mcp.custom.mcpDarkBox mcp.custom.mcpDarkBox] \
* [0 1 0 -1] [0 mcp.volume.label{3} 0 mcp.volume.label{3}]
set mcp.volume mcpForm{0}==2 + + [mcp.custom.mcpDarkBox mcp.custom.mcpDarkBox 0 mcp.custom.mcpDarkBox] + [mcp.custom.mcpDarkBox{2}] * Scale [-30 6 24 -36] \
* [0 1 0 -1] [0 mcp.volume.label{3} 0 mcp.volume.label{3}]
set mcp.volume mcpForm{0}==2 mcp.volume{3}<mcpVolKnobH{0} + [. . ] * Scale [0 0 20 20] ; turn into a knob
set mcp.recarm mcpForm{0}==2 + + [mcp.volume mcp.volume] * [0.5 1] [mcp.volume{2} mcp.volume{3}] * Scale [-12 4 24 20]
set mcp.recmon mcpForm{0}==2 + + + [mcp.meter mcp.meter] * Scale [-10 4 20 20] [0 mcp.meter{3}] * 0.5 [mcp.meter{2}]
; Strip Width - mcp.custom.mcpDarkBox is the meter bg in stackMcpStripProxy
set mcp.custom.mcpDarkBox.color ?visSections{0} [0 0 0 0 200 200 0] [0 0 0 0 38 38 38]
set mcp.volume.label.color * textBrightnessMult{0} [150 150 150]
set mcp.volume.label.font + [1] Scale{0}==1 [0] Scale{0}==1.5 [5] [10]
set mcp.volume.label.margin * [Scale Scale Scale Scale 1] [0 6 0 0 0.5]
set mcp.meter.vu.div * Scale [1 1]
set mcp.meter.readout.color !Layout##thisLayout##-mcpMeterReadout{0} [0 0 0 0 0 0 0 0] * textBrightnessMult{0} [100 100 100 255 255 183 171 255]
set showMcpMeterVals ?recarm ?Layout##thisLayout##-mcpMeterValsRecarm 1 0 ?track_selected ?Layout##thisLayout##-mcpMeterValsSel 1 0 ?Layout##thisLayout##-mcpMeterVals 1 0
set mcp.meter.scale.color.lit.bottom !showMcpMeterVals{0} [0 0 0 0 0 0 0 0] [0 0 0 170 0 0 0 0]
set mcp.meter.scale.color.lit.top !showMcpMeterVals{0} [0 0 0 0 0 0 0 0] [0 0 0 170 0 0 0 0]
set mcp.meter.scale.color.unlit.bottom !showMcpMeterVals{0} [0 0 0 0 0 0 0 0] ?recarm [255 64 0 255 0 0 0 0] + * - textBrightnessMult{0} 1 [0 0 0 100] [255 255 255 60 0 0 0 0]
set mcp.meter.scale.color.unlit.top !showMcpMeterVals{0} [0 0 0 0 0 0 0 0] ?recarm [255 64 0 255 0 0 0 0] + * - textBrightnessMult{0} 1 [0 0 0 100] [255 255 255 60 0 0 0 0]
;--Bottom Section & Sidebar--
custom mcp.custom.sectionBottom
custom mcp.custom.mcpNameBg
custom mcp.custom.indentInfill
custom mcp.custom.mcpIdxBg
custom mcp.custom.mcp_selectionDot '' 0 '' 'tcp_selectionDot'
custom mcp.custom.mcp_selectionDotSel '' 0 '' 'tcp_selectionDot_sel'
custom mcp.custom.sidebarBg
set mcpFolderBalance !mcpfolderBalanceType 0 * - mcp_maxfolderdepth folderdepth mcpfolderIndentSize
; Normal Width
set mcp.custom.sectionBottom mcpForm{0}==3 + [0 mcp.custom.sectionButtons mcpWidth sectionBottomH] [0 mcp.custom.mcpDarkBox{3} sidebarWidth]
set mcp.custom.mcpNameBg mcpForm{0}==3 + + [0 mcp.custom.sectionBottom mcpWidth] * Scale + [0 0 0 24] [0 0 0 mcpFolderBalance{0}] [0 0 sidebarWidth]
set mcp.label mcpForm{0}==3 mcp.custom.mcpNameBg
set mcp.label.margin mcpForm{0}==3 * [Scale Scale Scale Scale 1] [4 0 4 0 0.5]
set mcp.custom.mcpIdxBg mcpForm{0}==3 + + [0 mcp.custom.mcpNameBg mcpWidth] * Scale [0 0 0 20] [0 mcp.custom.mcpNameBg{3} sidebarWidth]
set mcp.custom.sidebarBg mcpForm{0}==3 - [0 0 sidebarWidth{0} h] [0 0 0 mcp.custom.sectionBottom{3}]
set mcp.extmixer.mode mcpForm{0}==3 ?addSidebar{0} [1] [-1]
; Intermediate Width
set mcp.custom.sectionBottom mcpForm{0}==2 + [0 mcp.custom.mcpDarkBox mcpWidth sectionBottomH] [0 mcp.custom.mcpDarkBox{3} sidebarWidth]
set mcp.custom.mcpNameBg mcpForm{0}==2 + + [0 mcp.custom.sectionBottom mcpWidth] * Scale + [0 0 0 24] [0 0 0 mcpFolderBalance{0}] [0 0 sidebarWidth]
set mcp.label mcpForm{0}==2 mcp.custom.mcpNameBg
set mcp.label.margin mcpForm{0}==2 * [Scale Scale Scale Scale 1] [4 0 4 0 0.5]
set mcp.custom.mcpIdxBg mcpForm{0}==2 + + [0 mcp.custom.mcpNameBg mcpWidth] * Scale [0 0 0 20] [0 mcp.custom.mcpNameBg{3} sidebarWidth]
set mcp.custom.sidebarBg mcpForm{0}==2 - [0 0 sidebarWidth{0} h] [0 0 0 mcp.custom.sectionBottom{3}]
set mcp.extmixer.mode mcpForm{0}==2 ?addSidebar{0} [1] [-1]
; Strip Width
set mcp.custom.sectionBottom mcpForm{0}==1 - [sidebarWidth h mcpWidth stripSectionBottomH] [0 stripSectionBottomH]
set mcpStripLabelHeightBal + Layout##thisLayout##-mcpStripLabelHeight ?mcpfolderBalanceType{0} * mcpfolderIndentSize - mcp_maxfolderdepth folderdepth 0
set mcp.custom.mcpNameBg mcpForm{0}==1 [0] ; in the new strip width, label isn't in bottom section
set mcp.label mcpForm{0}==1 [0] ; in the new strip width, label isn't in bottom section
set mcp.label.margin mcpForm{0}==1 * [Scale Scale Scale Scale 1] [0 4 0 4 0]
set mcp.custom.mcpIdxBg mcpForm{0}==1 + [0 mcp.custom.sectionBottom w] * Scale [0 0 0 20]
custom mcp.custom.mcpIdxDiv
set mcp.custom.mcpIdxDiv mcpForm{0}==1 [0 mcp.custom.mcpIdxBg mcp.custom.mcpIdxBg 1]
set mcp.custom.mcpIdxDiv.color * Scale [0 0 0 0 0 0 0 mcpDivOpacity{0}]
front mcp.custom.mcpIdxDiv
set mcp.custom.sidebarBg mcpForm{0}==1 ?addSidebar{0} [0 0 sidebarWidth{0} mcp.custom.mcpIdxBg{1}] [0]
set mcp.extmixer.mode mcpForm{0}==1 ?addSidebar{0} [1] ?Layout##thisLayout##-mcpStripHideExtmixer{0} [1] [-1]
set mcpStripLabelBlockH + 46 mcpStripLabelHeightBal{0} ; 46 is recarm and recmon
set mcpStripVolumeBlockH Layout##thisLayout##-mcpStripVolumeHeight
set mcpStripVolKnobH / mcpVolKnobH{0} Scale
set mcpStripVolumeBlockH mcpStripVolumeBlockH{0}<=mcpStripVolKnobH{0} 32
set mcpStripInputBlockH + Layout##thisLayout##-mcpStripInputHeight 20
set stripW - w sidebarWidth{0}
set mcpStripLabelBlock mcpForm{0}==1 [0 0 24 mcpStripLabelBlockH{0}]
set mcpStripVolumeBlock mcpForm{0}==1 [0 0 24 mcpStripVolumeBlockH{0}]
set mcpStripMSBlock mcpForm{0}==1 [0 0 20 40]
set mcp.io mcpForm{0}==1 [0 0 20 mcpIoH{0}]
set mcpStripFxBlock mcpForm{0}==1 [0 0 20 36]
set mcpStripPanBlock mcpForm{0}==1 !Layout##thisLayout##-verboseMcp{0} [0 0 20 52] [0 0 20 82]
set mcp.custom.recmodeBg_v mcpForm{0}==1 [0 0 20 42]
set mcpStripInputBlock mcpForm{0}==1 [0 0 20 mcpStripInputBlockH{0}]
set mcp.env mcpForm{0}==1 [0 0 20 mcpEnvH{0}]
set mcp.phase mcpForm{0}==1 [0 0 20 16]
set mcpStripMeterBlock mcpForm{0}==1 [0 0 24 Layout##thisLayout##-mcpStripMeterHeight]
set previous [0 mcp.custom.sectionBottom 0 20]
set previousDarkBg 1
stackMcpStripProxy 1
stackMcpStripProxy 2
stackMcpStripProxy 3
stackMcpStripProxy 4
stackMcpStripProxy 5
stackMcpStripProxy 6
stackMcpStripProxy 7
stackMcpStripProxy 8
stackMcpStripProxy 9
stackMcpStripProxy 10
stackMcpStripProxy 11
attachMcpStripProxy 1
attachMcpStripProxy 2
attachMcpStripProxy 3
attachMcpStripProxy 4
attachMcpStripProxy 5
attachMcpStripProxy 6
attachMcpStripProxy 7
attachMcpStripProxy 8
attachMcpStripProxy 9
attachMcpStripProxy 10
attachMcpStripProxy 11
set mcp.meter mcpForm{0}==1 + [sidebarWidth{0} mcpStripMeterBlock stripW mcpStripMeterBlock] * [1 2 -2 -4] * Scale 4
set mcp.fxin mcpForm{0}==1 mcpStripInputBlock{3}>0 + [mcpStripInputBlock mcpStripInputBlock] * Scale [0 0 20 20]
set mcp.custom.recinputBg_v mcpForm{0}==1 mcpStripInputBlock{3}>0 + [mcpStripInputBlock mcpStripInputBlock] * Scale [0 20 20 Layout##thisLayout##-mcpStripInputHeight]
set mcp.recinput mcpForm{0}==1 mcpStripInputBlock{3}>0 mcp.custom.recinputBg_v
set mcp.recmode mcpForm{0}==1 mcp.custom.recmodeBg_v
set mcp.fx mcpForm{0}==1 mcpStripFxBlock{3}>0 + [mcpStripFxBlock mcpStripFxBlock] * Scale [0 0 20 20]
set mcp.fxbyp mcpForm{0}==1 mcpStripFxBlock{3}>0 + [mcp.fx mcp.fx] * Scale [0 20 20 16]
set mcp.custom.sectionPan mcpForm{0}==1 + [sidebarWidth{0} mcpStripPanBlock stripW mcpStripPanBlock] [0 -6 0 12]
set mcp.custom.sectionPan.color mcpForm{0}==1 [0 0 0 1 38 38 38 255]
set mcp.custom.sectionButtons mcpForm{0}==1 + [sidebarWidth{0} mcpStripVolumeBlock stripW mcpStripVolumeBlock] [0 -6 0 12]
set mcp.custom.sectionButtons.color mcpForm{0}==1 ?visSections{0} [0 0 0 0 200 0 200] [0 0 0 0 38 38 38]
set mcp.volume mcpForm{0}==1 + mcp.volume{3}<mcpVolKnobH{0} [0] [0 8 0 -18] mcpStripVolumeBlock
set mcp.recarm mcpForm{0}==1 + + [mcpStripLabelBlock mcpStripLabelBlock] * Scale [0 -24 24 20] [0 mcpStripLabelBlock{3}]
set mcp.recmon mcpForm{0}==1 - - + [mcpStripLabelBlock mcp.recarm] * Scale [4 -20 20 20] [0 thisYMargin{0}]
set mcp.custom.mcpNameBg mcpForm{0}==1 + [sidebarWidth{0} mcpStripLabelBlock stripW mcpStripLabelBlock] * Scale [0 -6 0 12]
set mcp.label mcpForm{0}==1 + [mcpStripLabelBlock mcpStripLabelBlock mcpStripLabelBlock] - * Scale [0 0 0 mcpStripLabelBlockH{0}] [0 0 0 48]
set mcp.custom.mcpDarkBox mcpForm{0}==1 + [sidebarWidth{0} mcpStripMeterBlock stripW mcpStripMeterBlock] [0 -6 0 12]
set mcp.meter mcpForm{0}==1 + [sidebarWidth{0} mcp.custom.mcpDarkBox stripW mcp.custom.mcpDarkBox] * [1 2 -2 -4] * Scale 4
set mcp.mute mcpForm{0}==1 mcpStripMSBlock{3}>0 + [mcpStripMSBlock mcpStripMSBlock] * Scale [0 0 20 20]
set mcp.solo mcpForm{0}==1 mcpStripMSBlock{3}>0 + [mcp.mute mcp.mute] * Scale [0 20 20 20]
set stripMode6yOffs * Scale 12
set mcp.pan.label mcpForm{0}==1 mcpStripPanBlock{3}==0 [0] !Layout##thisLayout##-verboseMcp{0} [0 mcpStripPanBlock] \
trackpanmode==6 + + [0 stripMode6yOffs{0}] [sidebarWidth{0} mcpStripPanBlock stripW] * Scale [0 38 0 14] \
+ [sidebarWidth{0} mcpStripPanBlock stripW] * Scale [0 0 0 14]
set mcp.pan.label.margin mcpForm{0}==1 * [Scale Scale Scale Scale 1] [0 6 0 0 0.5]
set mcp.pan.label.color mcpForm{0}==1 * textBrightnessMult{0} [150 150 150]
set mcp.pan mcpForm{0}==1 mcpStripPanBlock{3}==0 [0] \
trackpanmode==6 + + + [0 stripMode6yOffs{0}] * Scale [0 14 0 10] [0 mcp.pan.label{3}] [sidebarWidth{0} mcpStripPanBlock stripW] \
+ + [0 mcp.pan.label{3}] [mcpStripPanBlock mcp.pan.label] * Scale trackpanmode>=4 [0 4 20 20] [0 14 20 20]
set mcp.width mcpForm{0}==1 mcpStripPanBlock{3}==0 [0] \
trackpanmode==6 + + + [0 stripMode6yOffs{0}] * Scale [0 4 0 10] [0 mcp.pan.label{3}] [sidebarWidth{0} mcpStripPanBlock stripW] \
trackpanmode>=4 + [mcp.pan mcp.pan] * Scale [0 24 20 20] [0]
set mcp.width.label mcpForm{0}==1 mcpStripPanBlock{3}==0 [0] \
trackpanmode==6 + [0 stripMode6yOffs{0}] !Layout##thisLayout##-verboseMcp{0} [0] + [sidebarWidth{0} mcpStripPanBlock stripW] * Scale [0 0 0 14] \
trackpanmode>=4 !Layout##thisLayout##-verboseMcp{0} [0] + + [sidebarWidth{0} mcp.width{1} stripW] * Scale [0 0 0 14] [0 mcp.width{3}]
set mcp.width.label.margin mcpForm{0}==1 * [Scale Scale Scale Scale 1] [0 6 0 0 0.5]
set mcp.recinput.font + [1] Scale{0}==1 [0] Scale{0}==1.5 [5] [10]
set mcp.recinput.color * textBrightnessMult{0} [235 235 235]
set mcp.recinput.margin * Scale mcp.recinput{3}>mcp.recinput{2} [1 4 0 20] [4 1 20 0]
set mcp.width.label.font + [1] Scale{0}==1 [0] Scale{0}==1.5 [5] [10]
set mcp.width.label.color mcp.pan.label.color
set mcp.custom.mcpNameBg.color ?selInvertLabels{0} ?track_selected [0 0 0 0 255 255 255 100] [0 0 0 0 38 38 38] [0 0 0 0 38 38 38]
set mcp.label.font + Layout##thisLayout##-mcpLabelSize{0} Scale{0}==1 [0] Scale{0}==1.5 [5] [10]
set mcp.label.color ?recarm [255 80 100] ?trackcolor_valid ?colorTrackLabels cColorTextOnDark * textBrightnessMult{0} [200 200 200] * textBrightnessMult{0} [200 200 200]
set mcp.label.color ?selInvertLabels{0} ?track_selected ?recarm [180 0 10] [38 38 38] . .
set mcp.custom.indentInfill mcpForm{0}==1 + [0 mcp.custom.sectionBottom w mcp.custom.sectionBottom] * Scale [0 20] \
+ + [0 mcp.custom.sectionBottom mcpWidth mcp.custom.sectionBottom] [0 mcp.custom.mcpNameBg{3} sidebarWidth] * Scale [0 20] ; 20 is about to be the indexBg h
set mcp.custom.indentInfill.color [0 0 0 0 51 51 51]
set mcp.custom.mcpIdxBg.color ?trackcolor_valid [0 0 0 0 trackcolor_r trackcolor_g trackcolor_b] [0 0 0 0 mcpBgColR mcpBgColG mcpBgColB]
set mcp.custom.mcp_selectionDot !selDot{0} [0] ?track_selected [0] + * 0.5 + [mcp.custom.mcpIdxBg{2}] folderstate==1 * Scale [18] [0] + [0 mcp.custom.mcpIdxBg] * Scale [-4 -4 8 8]
set mcp.custom.mcp_selectionDotSel !selDot{0} [0] !track_selected [0] + * 0.5 + [mcp.custom.mcpIdxBg{2}] folderstate==1 * Scale [18] [0] + [0 mcp.custom.mcpIdxBg] * Scale [-4 -4 8 8]
front mcp.custom.mcp_selectionDot mcp.custom.mcp_selectionDotSel
set mcp.trackidx + * 0.5 + [mcp.custom.mcpIdxBg{2}] folderstate==1 * Scale [18] [0] + [0 mcp.custom.mcpIdxBg] * Scale [-15 0 28 20]
set mcp.trackidx.margin * [Scale Scale Scale Scale 1] [0 0 0 0 0.5]
set mcp.trackidx.color tcp.trackidx.color
set mcp.trackidx.font + 3 Scale{0}==1 [0] Scale{0}==1.5 [5] [10]
set mcp.folder folderstate<0 + + [mcp.custom.mcpIdxBg mcp.custom.mcpIdxBg] [mcp.custom.mcpIdxBg{2}] * Scale [-6 0 6 20] + [mcp.custom.mcpIdxBg mcp.custom.mcpIdxBg] * Scale [0 0 20 20]
set mcp.custom.sidebarBg.color [0 0 0 0 38 38 38]
set mcp.extmixer.position mcp.extmixer.mode{0}>0 + mcp.custom.sidebarBg * Scale [2 0 -2] \
mcpDivOpacity{0}>0 [2 0 -4 0] [1 0 -2 0]
set mcp.fxparm.font + * Scale [0 24] Scale{0}==1 [1] Scale{0}==1.5 [6] [11]
set mcp.fxparm.font os_type==0 Scale{0}==2.0 + [0 0 0 0 -4]
set mcp.fxparm.font os_type==0 Scale{0}==1.5 + [0 0 0 0 -3]
set mcp.fxparm.margin * Scale [3 0 4 0 0 0 0 4]
set mcp.fxlist.font + * Scale [1 18 80 80] Scale{0}==1 [0] Scale{0}==1.5 [5] [10]
set mcp.fxlist.margin * [Scale Scale Scale Scale 1 Scale Scale Scale] [3 0 4 6 0.5 0 20 2]
set mcp.sendlist.font + * Scale [1 18 80 80] Scale{0}==1 [0] Scale{0}==1.5 [5] [10]
set mcp.sendlist.margin * [Scale Scale Scale Scale 1 Scale Scale Scale] [2 0 0 0 0 0 0 0 2]
front mcp.extmixer
;--MCP Size--
set minH mcpForm{0}==3 + + + mcp.custom.sectionTop{3} mcp.custom.sectionPan{3} maxSectionBottomH{0} * Scale 90
set minH mcpForm{0}==2 + + + + * Scale 100 mcp.custom.sectionTop{3} mcp.custom.sectionPan{3} maxSectionBottomH{0} mcp.custom.sectionButtons{3}
; set minH mcpForm{0}==1 + + + + mcp.custom.sectionTop{3} mcp.custom.sectionButtons{3} mcp.custom.sectionPan{3} mcp.custom.sectionBottom{3} stripDarkBoxMinH
set minH mcpForm{0}==1 0
set mcp.size + + [mcpWidth 0 0 minH{0}] [sidebarWidth] * Scale [0 360]
;--Custom BGs--
custom mcp.custom.mcpSelBox
set mcp.custom.mcpSelBox !track_selected [0] selectStrength{0}>0 + [0 0 mcp.size{0} 0 0 0 1 1] * Scale [0 0 0 360] [0]
set mcp.custom.mcpSelBox.color + * / selectStrength{0} 100 [0 0 0 0 0 0 0 255] [0 0 0 0 255 255 255]
custom mcp.custom.mcpColBox
set mcp.custom.mcpColBox !customColorDepth{0} [0] + [0 0 mcp.size{0} 0 0 0 1 1] * Scale [0 0 0 360]
set mcp.custom.mcpColBox.color ?trackcolor_valid [0 0 0 0 trackcolor_r trackcolor_g trackcolor_b customColorDepth{0}] [0 0 0 0 0]
custom mcp.custom.mcpBgBox
set mcp.custom.mcpBgBox + [0 0 mcp.size{0} 0 0 0 1 1] * Scale [0 0 0 360]
set mcp.custom.mcpBgBox.color [0 0 0 0 mcpBgColR mcpBgColG mcpBgColB 255]
endLayout
endMacro
define_parameter LayoutA-verboseMcp 'Layout A - Verbose MCP' 0 0 1
define_parameter LayoutA-mcpMeterReadout 'Layout A - mcpMeterReadout' 1 0 1
define_parameter LayoutA-mcpWidth 'Layout A - Mixer Panel Width' 88 28 140
define_parameter LayoutA-mcpWidthSel 'Layout A - Selected Mixer Panel Width' 88 28 140
define_parameter LayoutA-mcpWidthRecarm 'Layout A - Armed Mixer Panel Width' 88 28 140
define_parameter LayoutA-mcpSidebar 'Layout A - Mixer Sidebar' 0 0 1
define_parameter LayoutA-mcpSidebarSel 'Layout A - Selected Mixer Sidebar' 0 0 1
define_parameter LayoutA-mcpSidebarRecarm 'Layout A - Armed Mixer Sidebar' 0 0 1
define_parameter LayoutA-sidebarWidth 'Layout A - Sidebar Width' 88 34 300
define_parameter LayoutA-mcpNchanGrow 'Layout A - Mixer nChan Grow' 2 0 20
define_parameter LayoutA-mcpNchanGrowSel 'Layout A - Selected Mixer nChan Grow' 2 0 20
define_parameter LayoutA-mcpNchanGrowRecarm 'Layout A - Armed Mixer nChan Grow' 2 0 20
define_parameter LayoutA-mcpMeterVals 'Layout A - Mixer Meter Values' 0 0 1
define_parameter LayoutA-mcpMeterValsSel 'Layout A - Selected Mixer Meter Values' 0 0 1
define_parameter LayoutA-mcpMeterValsRecarm 'Layout A - Armed Mixer Meter Values' 1 0 1
define_parameter LayoutA-mcpNormalDarkButtons 'Layout A - Dark Under Buttons' 1 0 1
define_parameter LayoutA-mcpNormalShowSecIn 'Layout A - mcpNormalShowSecIn' 300 0 500
define_parameter LayoutA-mcpNormalShowSecPan 'Layout A - mcpNormalShowSecPan' 200 0 500
define_parameter LayoutA-mcpNormalShowRoute 'Layout A - mcpNormalShowRoute' 1 0 1
define_parameter LayoutA-mcpNormalShowSecFx 'Layout A - mcpNormalShowSecFx' 1 0 1
define_parameter LayoutA-mcpNormalShowEnv 'Layout A - mcpNormalShowEnv' 1 0 1
define_parameter LayoutA-mcpNormalShowPhase 'Layout A - mcpNormalShowPhase' 1 0 1
define_parameter LayoutA-mcpLabelSize 'Layout A - MCP Label Font Size' 4 1 5
define_parameter LayoutA-mcpInterShowSecIn 'Layout A - mcpInterShowSecIn' 320 0 500
define_parameter LayoutA-mcpInterShowSecButtons 'Layout A - mcpInterShowSecButtons' 280 0 500
define_parameter LayoutA-mcpInterShowSecPan 'Layout A - mcpInterShowSecPan' 240 0 500
define_parameter LayoutA-mcpStripLabelHeight 'Layout A - Label Height' 88 20 300
define_parameter LayoutA-mcpStripInputHeight 'Layout A - Record Input Height' 70 20 140
define_parameter LayoutA-mcpStripMeterHeight 'Layout A - Meter Height' 40 20 300
define_parameter LayoutA-mcpStripVolumeHeight 'Layout A - Volume Height' 120 60 300
define_parameter LayoutA-mcpStripHideExtmixer 'Layout A - Hide non-sidebar ExtMixer' 0 0 1
drawMcp A 1
Layout "A"
drawMcp A 1
endLayout
Layout "150%_A" "150"
drawMcp A 1.5
endLayout
Layout "200%_A" "200"
drawMcp A 2
endLayout
define_parameter LayoutB-verboseMcp 'Layout B - Verbose MCP' 0 0 1
define_parameter LayoutB-mcpMeterReadout 'Layout B - mcpMeterReadout' 0 0 1
define_parameter LayoutB-mcpWidth 'Layout B - Mixer Panel Width' 28 28 140
define_parameter LayoutB-mcpWidthSel 'Layout B - Selected Mixer Panel Width' 32 28 140
define_parameter LayoutB-mcpWidthRecarm 'Layout B - Armed Mixer Panel Width' 40 28 140
define_parameter LayoutB-mcpSidebar 'Layout B - Mixer Sidebar' 0 0 1
define_parameter LayoutB-mcpSidebarSel 'Layout B - Selected Mixer Sidebar' 0 0 1
define_parameter LayoutB-mcpSidebarRecarm 'Layout B - Armed Mixer Sidebar' 0 0 1
define_parameter LayoutB-sidebarWidth 'Layout B - Sidebar Width' 88 34 300
define_parameter LayoutB-mcpNchanGrow 'Layout B - Mixer nChan Grow' 0 0 20
define_parameter LayoutB-mcpNchanGrowSel 'Layout B - Selected Mixer nChan Grow' 0 0 20
define_parameter LayoutB-mcpNchanGrowRecarm 'Layout B - Armed Mixer nChan Grow' 0 0 20
define_parameter LayoutB-mcpMeterVals 'Layout B - Mixer Meter Values' 0 0 1
define_parameter LayoutB-mcpMeterValsSel 'Layout B - Selected Mixer Meter Values' 0 0 1
define_parameter LayoutB-mcpMeterValsRecarm 'Layout B - Armed Mixer Meter Values' 1 0 1
define_parameter LayoutB-mcpNormalDarkButtons 'Layout B - Dark Under Buttons' 1 0 1
define_parameter LayoutB-mcpNormalShowSecIn 'Layout B - mcpNormalShowSecIn' 350 0 500
define_parameter LayoutB-mcpNormalShowSecPan 'Layout B - mcpNormalShowSecPan' 300 0 500
define_parameter LayoutB-mcpNormalShowRoute 'Layout B - mcpNormalShowRoute' 1 0 1
define_parameter LayoutB-mcpNormalShowSecFx 'Layout B - mcpNormalShowSecFx' 1 0 1
define_parameter LayoutB-mcpNormalShowEnv 'Layout B - mcpNormalShowEnv' 1 0 1
define_parameter LayoutB-mcpNormalShowPhase 'Layout B - mcpNormalShowPhase' 1 0 1
define_parameter LayoutB-mcpLabelSize 'Layout B - MCP Label Font Size' 3 1 5
define_parameter LayoutB-mcpInterShowSecIn 'Layout B - mcpInterShowSecIn' 350 0 500
define_parameter LayoutB-mcpInterShowSecButtons 'Layout B - mcpInterShowSecButtons' 380 0 500
define_parameter LayoutB-mcpInterShowSecPan 'Layout B - mcpInterShowSecPan' 300 0 500
define_parameter LayoutB-mcpStripLabelHeight 'Layout B - Label Height' 88 0 300
define_parameter LayoutB-mcpStripInputHeight 'Layout B - Record Input Height' 70 20 140
define_parameter LayoutB-mcpStripMeterHeight 'Layout B - Meter Height' 20 20 300
define_parameter LayoutB-mcpStripVolumeHeight 'Layout B - Volume Height' 80 60 300
define_parameter LayoutB-mcpStripHideExtmixer 'Layout B - Hide non-sidebar ExtMixer' 1 0 1
Layout "B"
drawMcp B 1
endLayout
Layout "150%_B" "150"
drawMcp B 1.5
endLayout
Layout "200%_B" "200"
drawMcp B 2
endLayout
define_parameter LayoutC-verboseMcp 'Layout C - Verbose MCP' 1 0 1
define_parameter LayoutC-mcpMeterReadout 'Layout C - mcpMeterReadout' 1 0 1
define_parameter LayoutC-mcpWidth 'Layout C - Mixer Panel Width' 88 28 140
define_parameter LayoutC-mcpWidthSel 'Layout C - Selected Mixer Panel Width' 100 28 140
define_parameter LayoutC-mcpWidthRecarm 'Layout C - Armed Mixer Panel Width' 100 28 140
define_parameter LayoutC-mcpSidebar 'Layout C - Mixer Sidebar' 1 0 1
define_parameter LayoutC-mcpSidebarSel 'Layout C - Selected Mixer Sidebar' 1 0 1
define_parameter LayoutC-mcpSidebarRecarm 'Layout C - Armed Mixer Sidebar' 1 0 1
define_parameter LayoutC-sidebarWidth 'Layout C - Sidebar Width' 88 34 300
define_parameter LayoutC-mcpNchanGrow 'Layout C - Mixer nChan Grow' 2 0 20
define_parameter LayoutC-mcpNchanGrowSel 'Layout C - Selected Mixer nChan Grow' 2 0 20
define_parameter LayoutC-mcpNchanGrowRecarm 'Layout C - Armed Mixer nChan Grow' 2 0 20
define_parameter LayoutC-mcpMeterVals 'Layout C - Mixer Meter Values' 1 0 1
define_parameter LayoutC-mcpMeterValsSel 'Layout C - Selected Mixer Meter Values' 1 0 1
define_parameter LayoutC-mcpMeterValsRecarm 'Layout C - Armed Mixer Meter Values' 1 0 1
define_parameter LayoutC-mcpNormalDarkButtons 'Layout C - Dark Under Buttons' 1 0 1
define_parameter LayoutC-mcpNormalShowSecIn 'Layout C - mcpNormalShowSecIn' 350 0 500
define_parameter LayoutC-mcpNormalShowSecPan 'Layout C - mcpNormalShowSecPan' 300 0 500
define_parameter LayoutC-mcpNormalShowRoute 'Layout C - mcpNormalShowRoute' 1 0 1
define_parameter LayoutC-mcpNormalShowSecFx 'Layout C - mcpNormalShowSecFx' 1 0 1
define_parameter LayoutC-mcpNormalShowEnv 'Layout C - mcpNormalShowEnv' 1 0 1
define_parameter LayoutC-mcpNormalShowPhase 'Layout C - mcpNormalShowPhase' 1 0 1
define_parameter LayoutC-mcpLabelSize 'Layout C - MCP Label Font Size' 4 1 5
define_parameter LayoutC-mcpInterShowSecIn 'Layout C - mcpInterShowSecIn' 350 0 500
define_parameter LayoutC-mcpInterShowSecButtons 'Layout C - mcpInterShowSecButtons' 380 0 500
define_parameter LayoutC-mcpInterShowSecPan 'Layout C - mcpInterShowSecPan' 300 0 500
define_parameter LayoutC-mcpStripLabelHeight 'Layout C - Label Height' 88 0 300
define_parameter LayoutC-mcpStripInputHeight 'Layout C - Record Input Height' 70 20 140
define_parameter LayoutC-mcpStripMeterHeight 'Layout C - Meter Height' 40 20 300
define_parameter LayoutC-mcpStripVolumeHeight 'Layout C - Volume Height' 120 60 300
define_parameter LayoutC-mcpStripHideExtmixer 'Layout C - Hide non-sidebar ExtMixer' 1 0 1
Layout "C"
drawMcp C 1
endLayout
Layout "150%_C" "150"
drawMcp C 1.5
endLayout
Layout "200%_C" "200"
drawMcp C 2
endLayout
#<
#>--------------------------------- MASTER MIXER --------------------------------------
define_parameter masterMcpWidth 'Master Mixer Panel Width' 132 90 400
define_parameter masterMcpMeterVals 'Master MCP Meter Values' 1 0 1
define_parameter masterMcpVals 'Master MCP Values' 1 0 1
define_parameter masterMcpLabels 'Master MCP Labels' 1 0 1
define_parameter masterMcpBgColR 'Master MCP background colour' 51 0 255
define_parameter masterMcpBgColG 'Master MCP background colour G' 51 0 255
define_parameter masterMcpBgColB 'Master MCP background colour B' 51 0 255
macro masterMcpFollow this thisW thisH yOffs noSpace
set thisWs * Scale thisW
set thisHs * Scale thisH
set yOffsS * Scale yOffs
set thisYMargin * Scale !noSpace{0} 6 0 ; hard coding margin as 6
set this + + + [previous previous] [0 previous{3}] [0 thisYMargin{0} thisWs thisHs] [0 yOffsS]
set thisBS + + this{1} this{3} thisYMargin{0}
set sectionButtonsBS + master.mcp.custom.sectionButtons{1} master.mcp.custom.sectionButtons{3}
set this thisBS{0}>sectionButtonsBS{0} [. . . 0] . ; cull if extending below buttons section
; -- this is the new previous
set previous this
endMacro
macro drawMasterMcp Scale
set master.mcp.size * Scale [masterMcpWidth{0} 360 0 120]
set masterMcpSelectColRatio ?track_selected / selectStrength{0} 100 0
set masterMcpCol + * - 1 masterMcpSelectColRatio \
[masterMcpBgColR masterMcpBgColG masterMcpBgColB] \
* masterMcpSelectColRatio [255 255 255]
brightnessFromRGB masterMcpCol{0} masterMcpCol{1} masterMcpCol{2} masterMcpColBrightness
custom master.mcp.custom.sectionPan
set master.mcp.custom.sectionPan + [0 0 master.mcp.size{0}] * Scale + [0 0 -32] !masterMcpVals{0} [0 0 0 30] [0 0 0 46]
set master.mcp.custom.sectionPan.color ?visSections{0} [0 0 0 0 100 255 100 150] [0 0 0 1 0 0 0 0]
set master.mcp.pan.label !masterMcpVals{0} [0 master.mcp.custom.sectionPan] + [master.mcp.custom.sectionPan master.mcp.custom.sectionPan master.mcp.custom.sectionPan] * Scale [0 0 0 14]
set master.mcp.pan.label.font + [1] Scale{0}==1 [0] Scale{0}==1.5 [5] [10]
set master.mcp.pan.label.margin trackpanmode>=4 [2 6 0 0 0] [6 6 6 0 0.5]
set master.mcp.pan.label.color * textBrightnessMult{0} masterMcpColBrightness{0}<150 [220 220 220] [38 38 38]
set masterSectionPanCentW * 0.5 master.mcp.custom.sectionPan{2}
set master.mcp.pan master.mcp.custom.sectionPan{3}==0 [0] trackpanmode==6 + + * Scale [6 14 -12] [0 master.mcp.pan.label{3}] [master.mcp.pan.label master.mcp.pan.label master.mcp.custom.sectionPan 10] \
+ + [0 master.mcp.pan.label{3}] [master.mcp.custom.sectionPan master.mcp.pan.label] + [masterSectionPanCentW] * Scale trackpanmode>=4 [-20 4 20 20] [-10 4 20 20]
set master.mcp.pan.fadermode trackpanmode==6 [-1] [1]
set master.mcp.width master.mcp.custom.sectionPan{3}==0 [0] trackpanmode==6 + + * Scale [6 4 -12] [0 master.mcp.pan.label{3}] [master.mcp.pan.label master.mcp.pan.label master.mcp.custom.sectionPan 10] \
trackpanmode>=4 + [master.mcp.pan master.mcp.pan] * Scale [22 0 20 20] [0]
set master.mcp.width.fadermode trackpanmode==6 [-1] [1]
set master.mcp.width.label trackpanmode>=4 !masterMcpVals{0} [0] + [master.mcp.custom.sectionPan master.mcp.custom.sectionPan master.mcp.custom.sectionPan] * Scale [0 0 0 14] [0]
set master.mcp.width.label.font + [1] Scale{0}==1 [0] Scale{0}==1.5 [5] [10]
set master.mcp.width.label.margin * [Scale Scale Scale Scale 1] [0 6 2 0 1]
set master.mcp.width.label.color master.mcp.pan.label.color
custom master.mcp.custom.darkBox
set master.mcp.custom.darkBox - + + * Scale [6 0 -38] [0 master.mcp.custom.sectionPan master.mcp.size{0} h] [0 master.mcp.custom.sectionPan{3}] [0 0 0 master.mcp.custom.sectionPan]
set master.mcp.custom.darkBox.color ?visSections [0 0 0 0 255 100 255 150] [0 0 0 1 38 38 38 255]
custom master.mcp.custom.sectionButtons
set master.mcp.custom.sectionButtons + [master.mcp.size{0}] * Scale [-32 0 32 h]
set master.mcp.custom.sectionButtons.color ?visSections [0 0 0 0 100 100 255 150] [0 0 0 1 0 0 0 0]
set masterMcpMonoH ?masterMcpLabels{0} 32 22
set masterMcpIoH ?masterMcpLabels{0} 32 22
set masterMcpEnvH ?masterMcpLabels{0} 32 22
set previous + [master.mcp.custom.sectionButtons master.mcp.custom.sectionButtons] * Scale [6 6 0 0] ; Null object
masterMcpFollow master.mcp.mono 20 masterMcpMonoH{0} 0 1
masterMcpFollow master.mcp.mute 20 20 -2 0
masterMcpFollow master.mcp.solo 20 20 0 1
front master.mcp.solo
masterMcpFollow master.mcp.io 20 masterMcpIoH{0} 0 0
masterMcpFollow master.mcp.fxGroup 20 36 0 0
set master.mcp.fx master.mcp.fxGroup{3}>0 + [master.mcp.fxGroup master.mcp.fxGroup] * Scale [0 0 20 20] [0]
set master.mcp.fxbyp master.mcp.fxGroup{3}>0 + + [master.mcp.fxGroup master.mcp.fxGroup] [0 master.mcp.fx{3}] * Scale [0 0 20 16] [0]
masterMcpFollow master.mcp.env 20 masterMcpEnvH{0} 0 0
masterMcpFollow master.mcp.menubutton 20 20 0 0
set master.mcp.volume.label + [master.mcp.custom.darkBox master.mcp.custom.darkBox master.mcp.custom.darkBox 0] !masterMcpVals{0} [0] * Scale [0 0 0 20]
set master.mcp.volume.label.font + [1] Scale{0}==1 [0] Scale{0}==1.5 [5] [10]
set master.mcp.volume.label.margin * [Scale Scale Scale Scale 1] [0 0 0 0 0.5]
set master.mcp.volume.label.color * textBrightnessMult{0} [150 150 150]
set master.mcp.meter + master.mcp.custom.darkBox * Scale + !masterMcpLabels{0} [0 6 -24 -12] [0 6 -24 -26] !masterMcpVals{0} [0] [0 14 0 -14]
set master.mcp.meter.vu.div * Scale [1 1]
set master.mcp.meter.readout.color !masterMcpMeterVals{0} [0 0 0 0 0 0 0 0] * textBrightnessMult{0} [150 150 150]
set master.mcp.meter.scale.color.lit.bottom !masterMcpMeterVals{0} [0 0 0 0 0 0 0 0] [0 0 0 170 0 0 0 0]
set master.mcp.meter.scale.color.lit.top !masterMcpMeterVals{0} [0 0 0 0 0 0 0 0] [0 0 0 170 0 0 0 0]
set master.mcp.meter.scale.color.unlit.bottom !masterMcpMeterVals{0} [0 0 0 0 0 0 0 0] * textBrightnessMult{0} [255 255 255 120 0 0 0 0]
set master.mcp.meter.scale.color.unlit.top !masterMcpMeterVals{0} [0 0 0 0 0 0 0 0] * textBrightnessMult{0} [255 255 255 120 0 0 0 0]
set master.mcp.meter.vu.rmsdiv * Scale [2]
set master.mcp.meter.rmsreadout.color !masterMcpMeterVals{0} [0 0 0] * textBrightnessMult{0} [42 168 116]
set master.mcp.volume + + [master.mcp.meter master.mcp.meter 0 master.mcp.meter] [master.mcp.meter{2}] * Scale [0 0 24]
set master.mcp.label + + [master.mcp.custom.darkBox master.mcp.custom.darkBox master.mcp.custom.darkBox] [0 master.mcp.custom.darkBox{3}] ?masterMcpLabels{0} * Scale [0 -20 0 20] [0]
set master.mcp.label.color * textBrightnessMult{0} [220 220 220]
set master.mcp.label.color ?selInvertLabels{0} ?track_selected [38 38 38] . .
set master.mcp.label.font + 3 Scale{0}==1 [0] Scale{0}==1.5 [5] [10]
custom master.mcp.custom.masterMcpNameBg
set master.mcp.custom.masterMcpNameBg master.mcp.label
set master.mcp.custom.masterMcpNameBg.color ?selInvertLabels{0} ?track_selected [0 0 0 0 255 255 255 200] [0 0 0 0 38 38 38] [0 0 0 0 38 38 38]
front master.mcp.custom.masterMcpNameBg master.mcp.label
set master.mcp.fxlist.font + * Scale [1 18 80 80] Scale{0}==1 [0] Scale{0}==1.5 [5] [10]
set master.mcp.fxlist.margin * [Scale Scale Scale Scale 1 Scale Scale Scale] [3 0 4 6 0.5 0 20 2]
set master.mcp.sendlist.font + * Scale [1 18 80 80] Scale{0}==1 [0] Scale{0}==1.5 [5] [10]
set master.mcp.sendlist.margin * [Scale Scale Scale Scale 1 Scale Scale Scale] [2 0 0 0 0 0 0 0 2]
set master.mcp.fxparm.font + * Scale [1 24] Scale{0}==1 [0] Scale{0}==1.5 [5] [10]
set master.mcp.fxparm.margin * [Scale Scale Scale Scale 1 Scale Scale Scale] [3 0 4 6 0.5 0 0 2]
custom master.mcp.custom.mcp_selectionDot '' 0 '' 'tcp_selectionDot'
set master.mcp.custom.mcp_selectionDot !selDot{0} [0] ?track_selected [0] + + [master.mcp.custom.darkBox master.mcp.custom.darkBox] [master.mcp.custom.darkBox{2} master.mcp.custom.darkBox{3}] * Scale [-4 -14 8 8]
custom master.mcp.custom.mcp_selectionDotSel '' 0 '' 'tcp_selectionDot_sel'
set master.mcp.custom.mcp_selectionDotSel !selDot{0} [0] !track_selected [0] + + [master.mcp.custom.darkBox master.mcp.custom.darkBox] [master.mcp.custom.darkBox{2} master.mcp.custom.darkBox{3}] * Scale [-4 -14 8 8]
front master.mcp.custom.mcp_selectionDot master.mcp.custom.mcp_selectionDotSel
custom master.mcp.custom.mcpBgBox
set master.mcp.custom.mcpBgBox [0 0 w h]
set master.mcp.custom.mcpBgBox.color [0 0 0 0 masterMcpCol{0} masterMcpCol{1} masterMcpCol{2} 255]
endMacro
drawMasterMcp 1
Layout "A"
drawMasterMcp 1
endLayout
Layout "150%_A" "150"
drawMasterMcp 1.5
endLayout
Layout "200%_A" "200"
drawMasterMcp 2
endLayout
#<
#>---------------------------------- TRANSPORT ----------------------------------------
macro transFollow this thisW thisH
set thisWs * Scale thisW
set thisHs * Scale thisH
set this - - [previous previous thisWs thisHs] [transMargin] [thisWs] ; position it to the left of the current row
set this ?hide_##this{0} + [previous . 0] * Scale [0 0 0 36] ; apply hide by setting w to zero and ignoring transMargin
; -- move to next row--
; if it WON'T fit in this row, use it to start the next row at 36 + transMargin
set this this{0}<trans.custom.sectionRight{0} - + [w previous this this] * Scale + [0 36] [0 transMargin{0}] + [this{2}] * Scale [transMargin]
; -- cull if it extends below the height of the panel --
set thisBS + this{1} this{3}
set this thisBS{0}>h [this this 0 this] !previous{3} [this this 0 0] . ; cull method is to set width to zero
; -- cull if it is itself too wide for the section
set thisWPlus2Margins + this{2} * Scale + transMargin transMargin
set this thisWPlus2Margins{0}>trans.custom.sectionRight{2} [this this 0 0] .
; -- this is the new previous
set previous this
endmacro
define_parameter transMargin 'Transport Margins' 6 0 12
define_parameter transStatusWidth 'Status Width' 450 150 700
define_parameter transRateFaderWidth 'Rate Width' 100 100 400
define_parameter transSelectionWidth 'Selection Width' 350 150 700
define_parameter transSelectionFontSize 'Selection Font Size' 3 1 5
Macro drawTrans Scale
set trans.size * Scale [1000 36]
set trans.size.minmax * Scale + [100 36 2000 144] * 4 [0 0 0 transMargin{0}]
set trans.size.dockedheight * Scale [36]
custom trans.custom.sectionLeft
set trans.custom.sectionLeft * Scale [0 0 1000 36] ; just to start with
set trans.custom.sectionLeft.color ?visSections [0 0 0 0 50 255 100 60] [0 0 0 0 0 0 0 0]
custom trans.custom.sectionButtons
set trans.custom.sectionButtons + * Scale [transMargin 4 200 30] ?trans_center - / [w] 2 * Scale [100] [0]
set trans.custom.sectionButtons.color ?visSections [0 0 0 0 100 100 255 150] [0 0 0 1 0 0 0 0]
set trans.rew + [trans.custom.sectionButtons trans.custom.sectionButtons] * Scale [0 0 28 30]
set trans.fwd + + [trans.rew trans.rew] * Scale [0 0 28 30] [trans.rew{2}]
set trans.rec + + [trans.fwd trans.fwd] * Scale [2 0 30 30] [trans.fwd{2}]
set trans.play + + [trans.rec trans.rec] * Scale [-2 0 32 30] [trans.rec{2}]
set trans.repeat + + [trans.play trans.play] * Scale [-2 0 28 30] [trans.play{2}]
set trans.stop + + [trans.repeat trans.repeat] * Scale [2 0 28 30] [trans.repeat{2}]
set trans.pause + + [trans.stop trans.stop] * Scale [0 0 28 30] [trans.stop{2}]
custom trans.custom.sectionStatus
set trans.custom.sectionStatus + ?trans_center [0] + [trans.custom.sectionButtons] [trans.custom.sectionButtons{2}] * Scale [transMargin 0 transStatusWidth{0} 36]
; set trans.custom.sectionLeft + [0 0 trans.custom.sectionStatus trans.custom.sectionStatus] [0 0 trans.custom.sectionStatus{0}]
; Break section left if not enough y-space
set sectionLeftBreakW + + trans.custom.sectionButtons{2} trans.custom.sectionStatus{2} * 2 * Scale transMargin{0}
set trans.custom.sectionLeft w>sectionLeftBreakW{0} . + * Scale [0 0 transMargin{0} transMargin{0}] \
trans.custom.sectionStatus{2}>trans.custom.sectionButtons{2} [0 0 trans.custom.sectionStatus{2} 72] [0 0 trans.custom.sectionButtons{2} 72]
; ...and move status to the next row
set trans.custom.sectionStatus w>sectionLeftBreakW{0} . * Scale + [transMargin{0} transMargin{0}] [0 36 transStatusWidth{0} 36]
; do the above but for centered mode
set sectionLeftBreakW ?trans_center + trans.custom.sectionStatus{2} * 2 transMargin{0}
set trans.custom.sectionLeft ?trans_center trans.custom.sectionButtons{0}<sectionLeftBreakW{0} * Scale + [0 0 0 transMargin{0}] [. . . 72] .
set trans.custom.sectionStatus ?trans_center trans.custom.sectionButtons{0}<sectionLeftBreakW{0} + * 0.5 - [w] * Scale [transStatusWidth{0}] * Scale + [0 transMargin{0}] [0 36 transStatusWidth{0} 36] .
; populate status
set trans.status trans.custom.sectionStatus
set trans.status.margin * Scale [transMargin{0} 0 transMargin{0} 0]
set trans.status.color + + ?visSections [255 0 0 255 100 50 100 255] [0] [0 0 0 0 51 51 51 255] * textBrightnessMult{0} [160 160 160]
custom trans.custom.sectionRight
custom trans.custom.sectionRate
custom trans.custom.sectionBpm '' 0 '' 'transSectionBg'
custom trans.custom.sectionSig '' 0 '' 'transSectionBg'
custom trans.custom.sectionSel '' 0 '' 'transSectionBg'
set transRateFaderWidth transRateFaderWidth{0}=100 38
set transSectionRateW + transRateFaderWidth{0} transRateFaderWidth{0}>100 0 60
set sectionRightW - w + + trans.custom.sectionButtons{2} trans.custom.sectionStatus{2} * Scale + transMargin transMargin
set transDoubleH * Scale + 72 transMargin
set trans.custom.sectionRight h>transDoubleH{0} + [0 0 w h] + [0 trans.custom.sectionLeft{3}] * Scale [0 transMargin{0}] \
- + [w 0 sectionRightW{0}] * Scale [0 0 0 36] [sectionRightW{0}]
set trans.custom.sectionRight ?trans_center h>transDoubleH{0} . \
- + [trans.custom.sectionButtons . w .] * [1 0 1] [trans.custom.sectionButtons{2} 0 trans.custom.sectionButtons{2}] [0 0 trans.custom.sectionButtons{0}]
set trans.custom.sectionRight.color ?visSections [0 0 0 0 255 255 120 60] [0]
set previous + [w trans.custom.sectionRight] * Scale [0 0 0 36]
set hide_trans.custom.sectionRate !trans_flags&2 1 0
transFollow trans.custom.sectionRate transSectionRateW{0} 36
set trans.custom.sectionRate.color ?visSections [0 0 0 0 100 255 100 80] [0 0 0 1 0 0 0 0]
set trans.rate.fader !trans.custom.sectionRate{2} [0] + [trans.custom.sectionRate trans.custom.sectionRate] \
* Scale + [0 0 transRateFaderWidth{0}] transRateFaderWidth{0}>100 [0 16 0 20] [0 0 0 36]
custom trans.custom.rateFaderBg '' 0 '' 'transRateFaderBg'
set trans.custom.rateFaderBg transRateFaderWidth{0}>100 trans.rate.fader [0]
set trans.rate.fader.fadermode transRateFaderWidth{0}>100 [0] [1]
set trans.rate !trans.custom.sectionRate{2} [0] transRateFaderWidth{0}>100 + + [trans.custom.sectionRate trans.custom.sectionRate] * Scale [-40 2 80 16] * 0.5 [trans.custom.sectionRate{2}] \
+ + [trans.rate.fader trans.rate.fader] * Scale [0 0 60 36] [trans.rate.fader{2}}]
set trans.rate.margin [0 0 0 0 0]
set trans.rate.font + [2] Scale{0}==1 [0] Scale{0}==1.5 [5] [10]
set trans.rate.color * textBrightnessMult{0} [160 160 160]
set trans.rate.fader.color [180 180 180 255] ; pointer line of the knob
set hide_trans.automode 0
transFollow trans.automode 58 36
set hide_trans.custom.sectionBpm 0
transFollow trans.custom.sectionBpm 60 36
set trans.custom.sectionBpm.color ?visSections [0 0 0 0 100 100 255 150] [0 0 0 1 0 0 0 0]
set trans.bpm.tap + [trans.custom.sectionBpm trans.custom.sectionBpm trans.custom.sectionBpm] * Scale [0 0 0 20]
set trans.bpm.tap.font + [1] Scale{0}==1 [0] Scale{0}==1.5 [5] [10]
set trans.bpm.tap.color * textBrightnessMult{0} [160 160 160]
set trans.bpm.tap.margin + * Scale [0 2 0 0] [0 0 0 0 0.5]
set trans.bpm.edit + + [trans.bpm.tap trans.bpm.tap trans.bpm.tap] [0 trans.bpm.tap{3}] * Scale [0 0 0 16]
set trans.bpm.edit.font + [1] Scale{0}==1 [0] Scale{0}==1.5 [5] [10]
set trans.bpm.edit.color trans.bpm.tap.color
set trans.bpm.edit.margin + * Scale [0 0 0 6] [0 0 0 0 0.5]
set hide_trans.custom.sectionSig !trans_flags&4 1 0
transFollow trans.custom.sectionSig 40 36
set trans.custom.sectionSig.color ?visSections [0 0 0 0 255 100 100 150] [0 0 0 1 0 0 0 0]
set trans.curtimesig trans.custom.sectionSig
set trans.curtimesig.font + [3] Scale{0}==1 [0] Scale{0}==1.5 [5] [10]
set trans.curtimesig.color trans.bpm.tap.color
set hide_trans.custom.sectionSel 0
transFollow trans.custom.sectionSel transSelectionWidth{0} 36
set trans.sel + trans.custom.sectionSel * Scale [10 10 -10 -20]
set trans.sel.color * textBrightnessMult{0} [160 160 160]
set trans.sel.font + [transSelectionFontSize] Scale{0}==1 [0] Scale{0}==1.5 [5] [10]
set trans.sel.margin [0 0 0 0 0]
endMacro
drawTrans 1
Layout "A"
drawTrans 1
endLayout
Layout "150%_A" "150"
drawTrans 1.5
endLayout
Layout "200%_A" "200"
drawTrans 2
endLayout
#<
#>------------------------------- DPI TRANSLATION -------------------------------------
; ------ DUMMY LAYOUTS ---------
Layout "50%_A"
set tcp.label .
set mcp.label .
set envcp.label .
set master.mcp.label .
set master.tcp.label .
set trans.status .
EndLayout
Layout "75%_A"
set tcp.label .
set mcp.label .
set envcp.label .
set master.mcp.label .
set master.tcp.label .
set trans.status .
EndLayout
Layout "50%_B"
set tcp.label .
set mcp.label .
EndLayout
Layout "75%_B"
set tcp.label .
set mcp.label .
EndLayout
Layout "50%_C"
set tcp.label .
set mcp.label .
EndLayout
Layout "75%_C"
set tcp.label .
set mcp.label .
EndLayout
; requested scale > use
layout_dpi_translate '50%_A' 1.0 'A'
layout_dpi_translate '75%_A' 1.0 'A'
layout_dpi_translate '50%_A' 1.34 'A'
layout_dpi_translate '75%_A' 1.34 'A'
layout_dpi_translate 'A' 1.34 '150%_A'
layout_dpi_translate '150%_A' 1.34 '200%_A'
layout_dpi_translate '50%_A' 1.74 'A'
layout_dpi_translate '75%_A' 1.74 '150%_A'
layout_dpi_translate 'A' 1.74 '200%_A'
layout_dpi_translate '150%_A' 1.74 '200%_A'
layout_dpi_translate '50%_B' 1.0 'B'
layout_dpi_translate '75%_B' 1.0 'B'
layout_dpi_translate '50%_B' 1.34 'B'
layout_dpi_translate '75%_B' 1.34 'B'
layout_dpi_translate 'B' 1.34 '150%_B'
layout_dpi_translate '150%_B' 1.34 '200%_B'
layout_dpi_translate '50%_B' 1.74 'B'
layout_dpi_translate '75%_B' 1.74 '150%_B'
layout_dpi_translate 'B' 1.74 '200%_B'
layout_dpi_translate '150%_B' 1.74 '200%_B'
layout_dpi_translate '50%_C' 1.0 'C'
layout_dpi_translate '75%_C' 1.0 'C'
layout_dpi_translate '50%_C' 1.34 'C'
layout_dpi_translate '75%_C' 1.34 'C'
layout_dpi_translate 'C' 1.34 '150%_C'
layout_dpi_translate '150%_C' 1.34 '200%_C'
layout_dpi_translate '50%_C' 1.74 'C'
layout_dpi_translate '75%_C' 1.74 '150%_C'
layout_dpi_translate 'C' 1.74 '200%_C'
layout_dpi_translate '150%_C' 1.74 '200%_C'
; -- no layout chosen, dpi_translate as A
layout_dpi_translate '' 1.34 '150%_A'
layout_dpi_translate '' 1.74 '200%_A'
define_parameter themeVersionDate 'Theme Version Date' 240314 240314 240314
i get this error in reaper
WALTER: warnings for C:\Users\franc\Desktop\Portable reapers\REAPER OTHER TEST\ColorThemes\Default_7.0 - Cópia ReaperTheme\Default_7.0_unpacked\rtconfig.txt
WALTER:608/drawTcp:269: unset variable referenced: 'tcp.custom.button'
WALTER:608/drawTcp:269: extra 1 tokens at end of line
WALTER:610/drawTcp:269: unset variable referenced: 'tcp.custom.button'
WALTER:610/drawTcp:269: extra 1 tokens at end of line
WALTER:614/drawTcp:269: unset variable referenced: 'tcp.custom.button'
WALTER:614/drawTcp:269: extra 1 tokens at end of line
WALTER:618/drawTcp:269: unset variable referenced: 'tcp.custom.button'
WALTER:618/drawTcp:269: extra 1 tokens at end of line
WALTER:657/drawTcp:269: unset variable referenced: 'tcp.custom.button'
WALTER:657/drawTcp:269: extra 1 tokens at end of line
WALTER:661/drawTcp:269: unset variable referenced: 'tcp.custom.button'
WALTER:661/drawTcp:269: extra 1 tokens at end of line
WALTER:665/drawTcp:269: unset variable referenced: 'tcp.custom.button'
WALTER:665/drawTcp:269: extra 1 tokens at end of line
WALTER:704/drawTcp:269: unset variable referenced: 'tcp.custom.button'
WALTER:704/drawTcp:269: extra 1 tokens at end of line
WALTER:708/drawTcp:269: unset variable referenced: 'tcp.custom.button'
WALTER:708/drawTcp:269: extra 1 tokens at end of line
WALTER:712/drawTcp:269: unset variable referenced: 'tcp.custom.button'
WALTER:712/drawTcp:269: extra 1 tokens at end of line
|
a86d4d02ef456f947ce2f7dfe340b7b8
|
{
"intermediate": 0.2664984464645386,
"beginner": 0.35955703258514404,
"expert": 0.3739445209503174
}
|
44,715
|
Develop parallel codes for the following problems using JAVA. Report the speedup of your implementations by varying the number of threads from 1 to 16 (i.e., 1, 2, 4, 6, 8, 10, 12, 14, and 16) and consider gettimeofday() to measure the runtime of an execution:
Create a sorted linked List with 1000 nodes using lazy synchronization technique (assume that the nodes consist of fields: key and next. The
range of keys from the set {0 … 212}). Measure the time to perform 100 Million operations for the workload (50C, 25I, 25D) by varying the number of threads from 1 to 16 and using the following locks (or synchronization objects):
MCS Lock
|
30587fb0d64b0beb86d664be89a1535d
|
{
"intermediate": 0.5668377876281738,
"beginner": 0.12184301763772964,
"expert": 0.3113192021846771
}
|
44,716
|
in reaper walter, i created a custom button for a theme using:
+ WALTER: create custom elements by using "custom tcp.custom.xyz [label] [action ID] [accessibility description]" in layouts
what is the resolution of the button? how can i change it? give me a super brief answer, maybe with an example of a solution
|
8f031e795d4377ceb1805ec546793876
|
{
"intermediate": 0.547505795955658,
"beginner": 0.24104078114032745,
"expert": 0.21145345270633698
}
|
44,717
|
Do you see anything malicious in this youtube ad blocker userscript?
|
587be447cdb88ce90de9d61ed17dde34
|
{
"intermediate": 0.28723880648612976,
"beginner": 0.406400203704834,
"expert": 0.30636101961135864
}
|
44,718
|
How can I change wordpress link from /example-post to /news/example-post
|
5140faa8905bed72b4b9e81d1e06f2b4
|
{
"intermediate": 0.36466896533966064,
"beginner": 0.32440388202667236,
"expert": 0.3109271228313446
}
|
44,719
|
are my linked list correctlty reversed with this code ?
currentL1, currentL2 = l1, l1
reversedL1, reservedL1 = None, None
while l1 and l2:
if l1:
next_node = currentL1.next
currentL1.next = reversedL1
reversedL1 = currentL1
currentL1 = next_node
if l2:
next_node = currentL2.next
currentL2.next = reversedL2
reversedL2 = currentL2
currentL2 = next_node
|
6786b3a8da2a515e1ee652518bd3f9e4
|
{
"intermediate": 0.30645138025283813,
"beginner": 0.41602715849876404,
"expert": 0.2775214612483978
}
|
44,720
|
j'ai une bd flutter :
import 'package:path/path.dart';
import 'package:sqflite/sqflite.dart';
class SqliteService {
Future<void> onCreate(Database db, int version) async {
await db.execute("""
CREATE TABLE Aventure (
idAventure INTEGER PRIMARY KEY AUTOINCREMENT,
nomJoueur TEXT NOT NULL
)
""");
await db.execute("""
CREATE TABLE Difficulte (
idDifficulte INTEGER PRIMARY KEY AUTOINCREMENT,
nom TEXT NOT NULL,
nbTentative INTEGER NOT NULL,
valeurMax INTEGER NOT NULL
)
""");
await db.execute("""
CREATE TABLE Niveau (
idNiveau INTEGER PRIMARY KEY AUTOINCREMENT,
palier INTEGER NOT NULL,
idDifficulte INTEGER NOT NULL,
idAventure INTEGER NOT NULL,
FOREIGN KEY(idDifficulte) REFERENCES Difficulte(idDifficulte),
FOREIGN KEY(idAventure) REFERENCES Aventure(idAventure)
)
""");
await db.execute("""
CREATE TABLE Partie (
idPartie INTEGER PRIMARY KEY AUTOINCREMENT,
score INTEGER NOT NULL,
nbMystere INTEGER NOT NULL,
nbEssaisJoueur INTEGER NOT NULL,
gagne INTEGER NOT NULL,
dateDebut TEXT NOT NULL,
dateFin TEXT NOT NULL,
idAventure INTEGER,
idNiveau INTEGER,
FOREIGN KEY(idAventure) REFERENCES Aventure(idAventure),
FOREIGN KEY(idNiveau) REFERENCES Niveau(idNiveau)
)
""");
await db.execute("""
CREATE TABLE Effectuer (
idAventure INTEGER NOT NULL,
idPartie INTEGER NOT NULL,
idNiveau INTEGER NOT NULL,
complete INTEGER NOT NULL,
PRIMARY KEY(idAventure, idPartie, idNiveau),
FOREIGN KEY(idAventure) REFERENCES Aventure(idAventure),
FOREIGN KEY(idPartie) REFERENCES Partie(idPartie),
FOREIGN KEY(idNiveau) REFERENCES Niveau(idNiveau)
)
""");
}
Future<Database> initializeDB() async {
return openDatabase(
join(await getDatabasesPath(), 'aventure.db'),
onCreate: onCreate,
onUpgrade: (db, oldVersion, newVersion) async {
// Supprime les tables
await db.execute("DROP TABLE IF EXISTS Aventure");
await db.execute("DROP TABLE IF EXISTS Difficulte");
await db.execute("DROP TABLE IF EXISTS Niveau");
await db.execute("DROP TABLE IF EXISTS Partie");
await db.execute("DROP TABLE IF EXISTS Effectuer");
// Recrée les tables
await onCreate(db, newVersion);
print('Database upgraded from $oldVersion to $newVersion');
},
version: 3,
);
}
}
et je veux faire une requête qui me permet d'écrire dans une page le prochain niveau d'une aventure, ou si une aventure est terminée :
import 'package:flutter/material.dart';
import 'package:mobile_tp/models/Aventure.dart';
import 'package:mobile_tp/screens/PageNiveaux.dart';
import 'package:sqflite/sqflite.dart';
import 'package:mobile_tp/services/AventureDB.dart';
class PageAventures extends StatefulWidget {
final Future<Database> database;
PageAventures({Key? key, required this.database}) : super(key: key);
@override
_PageAventuresState createState() => _PageAventuresState();
}
class _PageAventuresState extends State<PageAventures> {
List<Aventure> aventures = [];
late AventureDB aventureDB;
@override
void initState() {
super.initState();
aventureDB = AventureDB(database: widget.database);
loadAventures();
}
Future<void> loadAventures() async {
final aventureList = await aventureDB.getAll();
setState(() {
aventures = aventureList;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Le nombre magique'),
centerTitle: true,
),
body: Center(
child: SingleChildScrollView(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'Choisissez votre aventure',
style: TextStyle(fontSize: 24, fontWeight: FontWeight.bold),
textAlign: TextAlign.center,
),
...aventures.map((aventure) {
return FutureBuilder<int>(
future: aventureDB.getNextLevel(aventure.id ?? 0),
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
return CircularProgressIndicator();
} else if (snapshot.hasError) {
return Text('Erreur : ${snapshot.error}');
} else {
int nextLevel = snapshot.data ?? 11;
String status = nextLevel <= 10 ? 'En cours' : 'Terminée';
print('Prochain niveau pour l\'aventure ${aventure.id}: $nextLevel'); // Ajout du print ici
String message = status == 'En cours'
? 'Prochain niveau : $nextLevel'
: 'Terminée';
return Card(
child: ListTile(
title: Center(child: Text(aventure.nomJoueur)),
subtitle: Text(message),
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => PageNiveaux(
totalNiveaux: 10,
idAventure: aventure.id ?? 0,
database: widget.database),
),
);
},
),
);
}
},
);
}).toList(),
],
),
),
),
floatingActionButton: FloatingActionButton(
onPressed: () async {
final nom = await showDialog<String>(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: Text('Créez une aventure'),
content: TextField(
autofocus: true,
decoration: InputDecoration(
labelText: 'Nom',
),
onSubmitted: (value) {
Navigator.of(context).pop(value);
},
),
);
},
);
if (nom != null) {
final id = await aventureDB.add(nom);
setState(() {
aventures.add(Aventure(id: id, nomJoueur: nom));
});
}
},
child: Icon(Icons.add),
),
);
}
}
mais je n'arrive pas à faire la bonne requête ici :
Future<int> getNextLevel(int idAventure) async {
final db = await database;
final List<Map<String, Object?>> levelsMaps = await db.rawQuery('''
SELECT Niveau.palier
FROM Niveau
LEFT JOIN Partie ON Partie.idNiveau = Niveau.idNiveau AND Partie.idAventure = ?
WHERE Niveau.idAventure = ? AND (Partie.gagne = 0)
ORDER BY Niveau.palier ASC
''', [idAventure, idAventure]);
if (levelsMaps.isEmpty) {
// Tous les niveaux ont été gagnés
return 11;
} else {
// Le prochain niveau à effectuer est le premier niveau qui n'a pas encore été gagné
return levelsMaps.first['palier'] as int;
}
}
|
c063b8662edea4de3b7541feded73cc2
|
{
"intermediate": 0.25855979323387146,
"beginner": 0.42206400632858276,
"expert": 0.319376140832901
}
|
44,721
|
I got this error: Traceback (most recent call last):
File "c:\Users\L14\Documents\Projets\Project-Hajax\train.py", line 88, in <module>
train_data, valid_data, test_data = preprocessor.load_data()
ValueError: too many values to unpack (expected 3) when i ran this code: import torch
import torch.optim as optim
import torch.nn as nn
import torch.nn.functional as F
from torch.utils.data import DataLoader
# Assuming you have already defined your MoE model, DataLoader, and loss function
from moe import MOELayer
from data_preprocessing import DataPreprocessor
def advanced_dynamic_expert_allocation(validation_losses, num_experts):
"""
Computes dynamic expert allocation based on validation losses.
Args:
validation_losses (list): List of validation losses for each expert.
num_experts (int): Number of experts.
Returns:
torch.Tensor: Expert weights (probabilities) for each expert.
"""
# Compute inverse validation losses (lower loss -> higher weight)
inverse_losses = [1.0 / loss for loss in validation_losses]
# Normalize the inverse losses to get expert weights
total_inverse_loss = sum(inverse_losses)
expert_weights = torch.tensor([loss / total_inverse_loss for loss in inverse_losses])
return expert_weights
def train_moe_model(train_data, valid_data, moe_model, batch_size, num_epochs, lr, device,
dynamic_expert_allocation=False, validation_losses=None, num_experts=None):
moe_model.to(device)
optimizer = optim.Adam(moe_model.parameters(), lr=lr)
criterion = nn.CrossEntropyLoss()
train_loader = DataLoader(train_data, batch_size=batch_size, shuffle=True)
valid_loader = DataLoader(valid_data, batch_size=batch_size, shuffle=False)
for epoch in range(num_epochs):
moe_model.train()
total_loss = 0.0
for batch in train_loader:
inputs, targets = batch.text.to(device), batch.label.to(device)
optimizer.zero_grad()
# Forward pass
outputs = moe_model(inputs)
# Compute dynamic expert allocation
gate_outputs = F.softmax(moe_model.gating_network(inputs), dim=1)
expert_allocation = advanced_dynamic_expert_allocation(validation_losses, num_experts)
# Apply expert weights to expert outputs
weighted_outputs = torch.sum(expert_allocation.unsqueeze(2) * outputs, dim=1)
# Compute loss
loss = criterion(weighted_outputs, targets)
# Backward pass and optimization
loss.backward()
optimizer.step()
total_loss += loss.item()
avg_train_loss = total_loss / len(train_loader)
# Validation
moe_model.eval()
valid_loss = 0.0
with torch.no_grad():
for batch in valid_loader:
inputs, targets = batch.text.to(device), batch.label.to(device)
outputs = moe_model(inputs)
valid_loss += criterion(outputs, targets).item()
avg_valid_loss = valid_loss / len(valid_loader)
print(f"Epoch {epoch+1}/{num_epochs} | Train Loss: {avg_train_loss:.4f} | Valid Loss: {avg_valid_loss:.4f}")
# Save model checkpoint
torch.save(moe_model.state_dict(), f"moe_model_epoch{epoch+1}.pth")
print("Training completed. Model checkpoints saved.")
if __name__ == "__main__":
preprocessor = DataPreprocessor(max_vocab_size=25000, embedding_dim=100)
train_data, valid_data, test_data = preprocessor.load_data()
batch_size = 32
num_epochs = 10
learning_rate = 0.001
num_experts = 2
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
# Initialize your MoE model
input_size = 300 # Example: word embedding size
hidden_size = 128
output_size = 200 # Example: binary classification (adjust based on your task)
moe_model = MOELayer(input_size, num_experts, hidden_size, output_size)
train_moe_model(train_data, valid_data, moe_model, batch_size, num_epochs, learning_rate, device)
|
77c0ca2a2600c4d65df305ca3328155b
|
{
"intermediate": 0.2625347375869751,
"beginner": 0.4646470248699188,
"expert": 0.27281826734542847
}
|
44,722
|
This is the code: import torch
import torch.optim as optim
import torch.nn as nn
import torch.nn.functional as F
from torch.utils.data import DataLoader
from sklearn.model_selection import train_test_split
# Assuming you have already defined your MoE model, DataLoader, and loss function
from moe import MOELayer
from data_preprocessing import DataPreprocessor
def advanced_dynamic_expert_allocation(validation_losses, num_experts):
"""
Computes dynamic expert allocation based on validation losses.
Args:
validation_losses (list): List of validation losses for each expert.
num_experts (int): Number of experts.
Returns:
torch.Tensor: Expert weights (probabilities) for each expert.
"""
# Compute inverse validation losses (lower loss -> higher weight)
inverse_losses = [1.0 / loss for loss in validation_losses]
# Normalize the inverse losses to get expert weights
total_inverse_loss = sum(inverse_losses)
expert_weights = torch.tensor([loss / total_inverse_loss for loss in inverse_losses])
return expert_weights
def train_moe_model(x_train, y_train, x_val, y_val, moe_model, batch_size, num_epochs, lr, device,
dynamic_expert_allocation=False, validation_losses=None, num_experts=None):
moe_model.to(device)
optimizer = optim.Adam(moe_model.parameters(), lr=lr)
criterion = nn.CrossEntropyLoss()
train_loader = DataLoader(x_train, y_train, batch_size=batch_size, shuffle=True)
valid_loader = DataLoader(x_val, y_val, batch_size=batch_size, shuffle=False)
for epoch in range(num_epochs):
moe_model.train()
total_loss = 0.0
for batch in train_loader:
inputs, targets = batch.text.to(device), batch.label.to(device)
optimizer.zero_grad()
# Forward pass
outputs = moe_model(inputs)
# Compute dynamic expert allocation
gate_outputs = F.softmax(moe_model.gating_network(inputs), dim=1)
expert_allocation = advanced_dynamic_expert_allocation(validation_losses, num_experts)
# Apply expert weights to expert outputs
weighted_outputs = torch.sum(expert_allocation.unsqueeze(2) * outputs, dim=1)
# Compute loss
loss = criterion(weighted_outputs, targets)
# Backward pass and optimization
loss.backward()
optimizer.step()
total_loss += loss.item()
avg_train_loss = total_loss / len(train_loader)
# Validation
moe_model.eval()
valid_loss = 0.0
with torch.no_grad():
for batch in valid_loader:
inputs, targets = batch.text.to(device), batch.label.to(device)
outputs = moe_model(inputs)
valid_loss += criterion(outputs, targets).item()
avg_valid_loss = valid_loss / len(valid_loader)
print(f"Epoch {epoch+1}/{num_epochs} | Train Loss: {avg_train_loss:.4f} | Valid Loss: {avg_valid_loss:.4f}")
# Save model checkpoint
torch.save(moe_model.state_dict(), f"moe_model_epoch{epoch+1}.pth")
print("Training completed. Model checkpoints saved.")
if __name__ == "__main__":
preprocessor = DataPreprocessor(max_vocab_size=25000, embedding_dim=100)
X_train, X_test, y_train, y_test = preprocessor.load_data()
X_val, X_test, y_val, y_test = train_test_split(X_test, y_test, test_size=0.5, random_state=42)
batch_size = 32
num_epochs = 10
learning_rate = 0.001
num_experts = 2
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
# Initialize your MoE model
input_size = 300 # Example: word embedding size
hidden_size = 128
output_size = 200 # Example: binary classification (adjust based on your task)
moe_model = MOELayer(input_size, num_experts, hidden_size, output_size)
train_moe_model(X_train, y_train, X_val, y_val, moe_model, batch_size, num_epochs, learning_rate, device) and this is the error: Traceback (most recent call last):
File "c:\Users\L14\Documents\Projets\Project-Hajax\train.py", line 103, in <module>
train_moe_model(X_train, y_train, X_val, y_val, moe_model, batch_size, num_epochs, learning_rate, device)
File "c:\Users\L14\Documents\Projets\Project-Hajax\train.py", line 37, in train_moe_model
train_loader = DataLoader(x_train, y_train, batch_size=batch_size, shuffle=True)
TypeError: DataLoader.__init__() got multiple values for argument 'batch_size'
|
166c748316e1e7e79ec66422a0e7fa76
|
{
"intermediate": 0.3891250193119049,
"beginner": 0.4237823188304901,
"expert": 0.18709266185760498
}
|
44,723
|
how to make usb drive imege using dd
|
ddc0967be030b5f0a30b032f3bf1d000
|
{
"intermediate": 0.3578283488750458,
"beginner": 0.29026883840560913,
"expert": 0.3519028425216675
}
|
44,724
|
how do i add:import GooglePayButton from "@google-pay/button-react";
import { PayPalButtons } from '@paypal/react-paypal-js';
import { PayPalScriptProvider } from '@paypal/react-paypal-js'; to my cart specifically just below the Order Total div but within order-total--subdata className div. I want the cart to allow direct checkout of the total price. My products are added using a json file, here is a single product snippet: {
"id": "web-a",
"name": "Blog Template",
"price": 60,
"image": "images/products/blog.png",
"description": "This is a blog website template.",
"category": "HTML Templates",
"featured": true
},
|
2839ce7216bfe481a23d5acb0203d5e4
|
{
"intermediate": 0.6551262736320496,
"beginner": 0.23989854753017426,
"expert": 0.10497516393661499
}
|
44,725
|
Paypal shows the amount as $3,574,989.00 when the actual current total_price is $35,749.89. Fix the issue: Cart.js: import styled from "styled-components";
import { useCartContext } from "./context/cart_context";
import CartItem from "./components/CartItem";
import { NavLink } from "react-router-dom";
import { Button } from "./styles/Button";
import FormatPrice from "./Helpers/FormatPrice";
import GooglePayButton from '@google-pay/button-react';
import { PayPalButtons, PayPalScriptProvider } from '@paypal/react-paypal-js';
const Cart = () => {
const { cart, clearCart, total_price } = useCartContext();
// console.log("🚀 ~ file: Cart.js ~ line 6 ~ Cart ~ cart", cart);
if (cart.length === 0) {
return (
<EmptyDiv>
<h3>No Cart in Item </h3>
</EmptyDiv>
);
}
return (
<Wrapper>
<div className="cart-cont">
<div className="container">
<div className="cart-user--profile">
<h2 className="cart-user--name">Your Cart</h2>
</div>
<div className="cart_heading grid grid-five-column">
<p>Item</p>
<p className="cart-hide">Price</p>
<p>Remove</p>
</div>
<hr />
<div className="cart-item">
{cart.map((curElem) => {
return <CartItem key={curElem.id} {...curElem} />;
})}
</div>
<hr />
<div className="cart-two-button">
<NavLink to="/products">
<Button> continue Shopping </Button>
</NavLink>
</div>
</div>
{/* order total_amount */}
<div className="order-total--amount">
<div className="order-total--subdata">
<div>
<p>subtotal:</p>
<p>
<FormatPrice price={total_price} />
</p>
</div>
<hr />
<div>
<p>order total:</p>
<p>
<FormatPrice price={total_price} />
</p>
</div>
<div className="payment-buttons">
<PayPalScriptProvider options={{ "client-id": "AaYNpLyiczSflrjiqZK8Zn8gcAtR5ZTmkn1tPVOH6oZf3wCeIXmOSpOCLANiT8_aF0J8sgYzwfoI4dMi" }}>
<PayPalButtons
style={{ layout: "vertical" }}
createOrder={(data, actions) => {
return actions.order.create({
purchase_units: [{
amount: {
value: total_price.toString(), // PayPal expects a string
},
}],
});
}}
onApprove={(data, actions) => {
// Capture the funds from the transaction
return actions.order.capture().then((details) => {
// Show a success message to your buyer
alert('Transaction completed by ' + details.payer.name.given_name);
// You can redirect to a success page
});
}}
/>
</PayPalScriptProvider>
<GooglePayButton
environment="TEST"
paymentRequest={{
apiVersion: 2,
apiVersionMinor: 0,
allowedPaymentMethods: [{
type: 'CARD',
parameters: {
allowedAuthMethods: ['PAN_ONLY'],
allowedCardNetworks: ['MASTERCARD', 'VISA'],
},
tokenizationSpecification: {
type: 'PAYMENT_GATEWAY',
// Check with your gateway on the parameters to include here
parameters: {
'gateway': 'example',
'gatewayMerchantId': 'exampleGatewayMerchantId'
},
},
}],
merchantInfo: {
// Add your merchant info here
merchantId: '12345678901234567890',
merchantName: 'Demo Merchant',
},
transactionInfo: {
totalPriceStatus: 'FINAL',
totalPriceLabel: 'Total',
totalPrice: total_price.toString(), // Google Pay expects string format
currencyCode: 'USD',
countryCode: 'US',
},
}}
onLoadPaymentData={paymentRequest => {
console.log('load payment data', paymentRequest);
}}
/>
</div>
</div>
</div>
</div>
</Wrapper>
);
};
const EmptyDiv = styled.div`
display: grid;
place-items: center;
height: 50vh;
h3 {
font-size: 4.2rem;
text-transform: capitalize;
font-weight: 300;
color: black;
}
`;
const Wrapper = styled.section`
padding: 15rem 0px 15rem;
p, h3 {
color: black;
}
button, btn {
color: white;
border-radius: 10px;
}
.cart-cont {
display: grid;
justify-content: center;
grid-template-columns: 1.5fr 0.7fr;
margin: 0px auto;
}
.payment-buttons {
display: flex !important;
flex-direction: column-reverse;
}
.container{
max-width: 70%;
}
button:hover, btn:hover {
box-shadow: 0 10px 20px rgba(0,0,0,0.19), 0 6px 6px rgba(0,0,0,0.23);
}
.grid-four-column {
grid-template-columns: repeat(4, 1fr);
}
.grid-five-column {
grid-template-columns: repeat(3, 1fr) 0.4fr;
text-align: center;
align-items: center;
}
.cart-heading {
text-align: center;
text-transform: uppercase;
}
hr {
margin-top: 1rem;
}
.cart-item {
padding: 3.2rem 0;
display: flex;
flex-direction: column;
gap: 3.2rem;
}
.cart-user--profile {
display: flex;
justify-content: flex-start;
align-items: center;
gap: 1.2rem;
margin-bottom: 5.4rem;
img {
width: 8rem;
height: 8rem;
border-radius: 50%;
}
h2 {
font-size: 2.4rem;
}
}
.cart-user--name {
text-transform: capitalize;
color: black;
}
.cart-image--name {
/* background-color: red; */
align-items: center;
display: grid;
gap: 1rem;
grid-template-columns: 0.4fr 1fr;
text-transform: capitalize;
text-align: left;
img {
max-width: 15rem;
height: auto;
object-fit: contain;
color: transparent;
border-radius: 10px;
}
.color-div {
display: flex;
align-items: center;
justify-content: flex-start;
gap: 1rem;
.color-style {
width: 1.4rem;
height: 1.4rem;
border-radius: 50%;
}
}
}
.cart-two-button {
margin-top: 2rem;
display: flex;
justify-content: space-between;
.btn-clear {
background-color: #e74c3c;
}
}
.amount-toggle {
display: flex;
justify-content: center;
align-items: center;
gap: 2.4rem;
font-size: 1.4rem;
button {
border: none;
background-color: #fff;
cursor: pointer;
}
.amount-style {
font-size: 2.4rem;
color: ${({ theme }) => theme.colors.btn};
}
}
.remove_icn {
display: flex;
justify-content: center;
align-items: center;
}
.remove_icon {
font-size: 1.6rem;
color: #e74c3c;
cursor: pointer;
}
.order-total--amount {
max-width: 100%;
margin: 12rem auto;
text-transform: capitalize;
display: flex;
flex-direction: column;
justify-content: flex-end;
align-items: flex-end;
.order-total--subdata {
border: 0.1rem solid #f0f0f0;
box-shadow: 0 19px 38px rgba(0,0,0,0.30), 0 15px 12px rgba(0,0,0,0.22);
border-radius: 24px;
display: flex;
flex-direction: column;
gap: 1.8rem;
padding: 4.2rem;
}
div {
display: flex;
gap: 3.2rem;
justify-content: space-between;
}
div:last-child {
background-color: #fafafa;
}
div p:last-child {
font-weight: bold;
color: black;
}
}
@media (max-width: ${({ theme }) => theme.media.mobile}) {
padding: 15rem 0px 6rem;
.grid-five-column {
grid-template-columns: 1fr 1fr 0.5fr;
}
.cart-cont {
display: grid;
justify-content: center;
grid-template-columns: 1fr;
margin: 0px auto;
}
.container{
max-width: 80%;
}
.cart-two-button {
margin-top: 2rem;
display: flex;
justify-content: space-between;
gap: 2.2rem;
}
.order-total--amount {
width: 70%;
text-transform: capitalize;
justify-content: flex-start;
align-items: flex-start;
.order-total--subdata {
width: 100%;
border: 0.1rem solid #f0f0f0;
display: flex;
flex-direction: column;
gap: 1.8rem;
padding: 3.2rem;
}
}
}
`;
export default Cart;
|
253f6a58e143de302c1303764523e375
|
{
"intermediate": 0.41136109828948975,
"beginner": 0.5010020732879639,
"expert": 0.08763685077428818
}
|
44,726
|
PS C:\Users\X\node\app\node-crash-course> node playwright
Indeed URL: https://www.indeed.com/jobs?q=test&l=Brea%2C%20CA&radius=5&sort=date
Browser started
Page Count: 1
Job URLs: [
'https://indeed.com/rc/clk?jk=dd132012df6878bc&bb=VEVECS6ckEjQuf7giVHATDuLLszOMhwmedqY1yYHSYmudLH5RlZxdW_AiD2sYEaFVySvJWXJ6DK8rw7FNiAPD_k7Taw0wd1CFiPQnWMacdcNW8UFHvsV3HWJmoDBYGgK&xkcb=SoBi67M3CK8ALqxvZB0LbzkdCdPP&fccid=d8d263bb22d0c43f&cmp=Mckinney-Trailer-Rentals&ti=IT+Administrator&vjs=3',
'https://indeed.com/rc/clk?jk=a0fe3e4afb5dabd7&bb=VEVECS6ckEjQuf7giVHATEIWhg_FrGeJH6EVgBtQEVTT-f_1eUyxYSAZPtXdE2fDJYXJ_5PUjHM8HUYpW1orN7AMBpt0vujPF2vPlJ2FdBvuyZBjWSljDQ%3D%3D&xkcb=SoDW67M3CK8ALqxvZB0KbzkdCdPP&fccid=d8d263bb22d0c43f&vjs=3',
'https://indeed.com/rc/clk?jk=d3fcc7a97ccb4507&bb=VEVECS6ckEjQuf7giVHATFLuB8jGe6EuaV11N4MNOumzNGZawGMgLE7tSocop1gXHxh1lVIRXFShWUBcb8mIcwWdHsqg80x4d9zxV6Wibws%3D&xkcb=SoBL67M3CK8ALqxvZB0JbzkdCdPP&fccid=aa53b551f9df0210&vjs=3',
'https://indeed.com/rc/clk?jk=c96b2d7e3a871d82&bb=VEVECS6ckEjQuf7giVHATJhyeCbS5QbLjB7u22O47krIS5RVkzCLbvYv45EEPETJyc1H2YNQ_NrqplpJTCr1NJmrSIVbyGAQle8eubrm9wQ%3D&xkcb=SoD_67M3CK8ALqxvZB0IbzkdCdPP&fccid=b8df555617879658&vjs=3',
'https://indeed.com/rc/clk?jk=356658f0183605d6&bb=VEVECS6ckEjQuf7giVHATFLuB8jGe6Eu7q7Uz3RQZsfIqTxFHFaW408xaslVN_62Wl9uPZXdjK9oc3HiAHYKyxIeqC2h_EZJ9lg96owztU5xq3o8yeNf5g%3D%3D&xkcb=SoBx67M3CK8ALqxvZB0PbzkdCdPP&fccid=d706801e9de740ef&cmp=EIDIM-Group%2C-Inc.&ti=Network+Specialist&vjs=3',
'https://indeed.com/rc/clk?jk=96187e53c6f9d690&bb=VEVECS6ckEjQuf7giVHATIcohb1WIOeX4nsY0v9jK9Nzoc69ftGfzVvDysnbQDm4YJJz9_1N9N0HAuMNEKG7RJH6Kgqf6FWbd34rB8Pn2BI%3D&xkcb=SoDF67M3CK8ALqxvZB0ObzkdCdPP&fccid=aa53b551f9df0210&vjs=3',
'https://indeed.com/rc/clk?jk=706e293416a6fb5a&bb=VEVECS6ckEjQuf7giVHATGR2HjIjY25VXtFV7Dxn2tm6UoB8CwrDoJMrBLIFb0aBXsGUuki7GpmYhpOWohda1d48933_iLhNfLCYdYZUqz7Eoxe8au7pQg%3D%3D&xkcb=SoBY67M3CK8ALqxvZB0NbzkdCdPP&fccid=b488a8011f10f172&cmp=Elit-Tile-Corp&ti=Lead+Front+End+Developer&vjs=3',
'https://indeed.com/rc/clk?jk=2f271f075e4ea927&bb=VEVECS6ckEjQuf7giVHATMfXuKH5BcgX_fa62IRrGMl6hVvGnuDMn9quglFrml3B9LZfg2ahn9h-qCzdUpyeQ5LEAsbM6EOnfMba9TXDkT4%3D&xkcb=SoDs67M3CK8ALqxvZB0MbzkdCdPP&fccid=938c68fc89db4b9d&vjs=3',
'https://indeed.com/rc/clk?jk=99448a18cfc1a82b&bb=VEVECS6ckEjQuf7giVHATNrGvrrb_BBwRGSpwvYKNn2UCm6lBh5wQ3KNp8bf0g1EtNcqSdzvhjQBdGCaJ_Xe74U7FcbzPfcP_3daPKrkd6NWN8Aexq1ENA%3D%3D&xkcb=SoAF67M3CK8ALqxvZB0DbzkdCdPP&fccid=e83618db4f163bfd&vjs=3',
'https://indeed.com/rc/clk?jk=28fe2989510035c7&bb=VEVECS6ckEjQuf7giVHATGZcwNWnNz67s6tX4dpN18vVzzhYYorSD_G7sXzMwonKl9f-Sfc1rRAdbMbTcw9N2B3qB8tMjhgI0Ah7w1kHxulEx50iNMzmiA%3D%3D&xkcb=SoCx67M3CK8ALqxvZB0CbzkdCdPP&fccid=4e87aad150586f33&vjs=3',
'https://indeed.com/rc/clk?jk=6204615b8768c271&bb=VEVECS6ckEjQuf7giVHATLnY-MWY3hQ0fxMVNXGuVRHYwathM5WOiQ0lf6ilydTWhuDXYcR706NPdALtOKCnEZS_lV4g8yxtyqHy_0Osdyc%3D&xkcb=SoAs67M3CK8ALqxvZB0BbzkdCdPP&fccid=2a720a4e531f5ef5&vjs=3',
'https://indeed.com/rc/clk?jk=f04b3e99f4eb1253&bb=VEVECS6ckEjQuf7giVHATB4LLC3qS85IgTXHSyZnDhzGAh5Ca_MWt7cmf9i7sCzwjZ4KGxgUyjE5iajCm1iorvbJEkQM5ZBq_QyIXMRiriM%3D&xkcb=SoCY67M3CK8ALqxvZB0AbzkdCdPP&fccid=aa53b551f9df0210&vjs=3',
'https://indeed.com/rc/clk?jk=f8d6b2a3eb57a663&bb=VEVECS6ckEjQuf7giVHATBLrFDiYPmyuUIcXPD1V6_YuEZFK1H1S7dUIZwKR9aVfVwCM1gmu_oHccjKhIlwfmaf4mf202hiNgnwcLKlp1HyBT_0IBPATDg%3D%3D&xkcb=SoAW67M3CK8ALqxvZB0HbzkdCdPP&fccid=951ab475814d0147&vjs=3',
'https://indeed.com/rc/clk?jk=46ca990a383bed5f&bb=VEVECS6ckEjQuf7giVHATHv0DG6B2jnpXP5mxdGEpAZeLW-QAEDN6jd8NFW6WflVBVhFUhgXDnH3cUUkTKFwUAe5s7belPs-bN5IirjKvbX2EBq2SfdWoA%3D%3D&xkcb=SoCi67M3CK8ALqxvZB0GbzkdCdPP&fccid=0ce4fc92ecdb2f30&vjs=3',
'https://indeed.com/rc/clk?jk=145e9647cab7e805&bb=VEVECS6ckEjQuf7giVHATOnVL8ZwsjVLvnGaXqJTqzyv_UTL6ButJos2_SII0SutfzTJwgJxzy3R4ZeA3GF4pFOP5RXwQhZgW9kKrdGiFiE%3D&xkcb=SoA_67M3CK8ALqxvZB0FbzkdCdPP&fccid=938c68fc89db4b9d&vjs=3'
]
node:internal/process/promises:289
triggerUncaughtException(err, true /* fromPromise */);
^
page.goto: net::ERR_ABORTED at https://indeed.com/rc/clk?jk=dd132012df6878bc&bb=VEVECS6ckEjQuf7giVHATDuLLszOMhwmedqY1yYHSYmudLH5RlZxdW_AiD2sYEaFVySvJWXJ6DK8rw7FNiAPD_k7Taw0wd1CFiPQnWMacdcNW8UFHvsV3HWJmoDBYGgK&xkcb=SoBi67M3CK8ALqxvZB0LbzkdCdPP&fccid=d8d263bb22d0c43f&cmp=Mckinney-Trailer-Rentals&ti=IT+Administrator&vjs=3
Call log:
- navigating to "https://indeed.com/rc/clk?jk=dd132012df6878bc&bb=VEVECS6ckEjQuf7giVHATDuLLszOMhwmedqY1yYHSYmudLH5RlZxdW_AiD2sYEaFVySvJWXJ6DK8rw7FNiAPD_k7Taw0wd1CFiPQnWMacdcNW8UFHvsV3HWJmoDBYGgK&xkcb=SoBi67M3CK8ALqxvZB0LbzkdCdPP&fccid=d8d263bb22d0c43f&cmp=Mckinney-Trailer-Rentals&ti=IT+Administrator&vjs=3", waiting until "load"
at C:\Users\X\node\app\node-crash-course\playwright.js:99:24
at C:\Users\X\node\app\node-crash-course\playwright.js:97:14 {
name: 'Error'
}
Node.js v20.11.1
|
f935e952b59c087ea1e3c66ff69f5e7a
|
{
"intermediate": 0.2854315936565399,
"beginner": 0.4051419794559479,
"expert": 0.3094264268875122
}
|
44,727
|
jobs.forEach(async(job) => {
try {
await page.goto(job, { waitUntil: 'load', timeout: 60000 });
console.log(job);
// wait for the navigation to complete
await page.waitForNavigation();
} catch (error) {
console.log('Navigation Error', error);
}
// Loop until "Submit yo
|
8b4b48e06d4faa0e912fa4ee28b9c638
|
{
"intermediate": 0.24606665968894958,
"beginner": 0.6229020953178406,
"expert": 0.13103127479553223
}
|
44,728
|
in reaper walter theming, how to i create a custom button at a % position of the track tcp? super brief answer please
|
27e42de4fc0b755ee179cb7f0751dd27
|
{
"intermediate": 0.4849770665168762,
"beginner": 0.25237154960632324,
"expert": 0.26265135407447815
}
|
44,729
|
привет у меня есть корутина в unity которая запускает окно ошибки и потом его закрывает но что мне делать есчли придет вызов о новом запуске а у меня еще старая карутина активна, как мне сделать так чтобы старя сразу завершилась и запустилась новая вот код
public IEnumerator Error()
{
_errorImage.Active();
_errorOutline.color = _errorColor;
if (_audioSource != null && _errorClip != null)
{
_audioSource.PlayOneShot(_errorClip);
}
yield return new WaitForSeconds(2.5f);
_errorImage.transform.DOScale(0f, 0.5f);
yield return new WaitForSeconds(0.5f);
_errorOutline.color = _currentColor;
_errorImage.Deactive();
_errorImage.transform.DOScale(1f, 0f);
}
|
af3aba078f8f17994e30a5eab9ce9868
|
{
"intermediate": 0.3405607342720032,
"beginner": 0.4331165850162506,
"expert": 0.22632266581058502
}
|
44,730
|
<html>
<head>
<meta charset="UTF-8">
<style>
svg {
width: 300px;
height: 300px;
}
.spirit { fill: #D3D3D3; }
.water { fill: #4169E1; }
.fire { fill: #FF4500;}
.earth { fill: #654321;}
.air { fill: #8BF7FF; }
.encircle { fill: url(#fiveColorGradient);
stroke-width: 2;
stroke: #800080;}
</style>
</head>
<body>
<svg viewBox="0 0 50 200" xmlns="http://www.w3.org/2000/svg">
<defs>
<radialGradient id="fiveColorGradient" cx="50%" cy="50%" r="45%" fx="50%" fy="50%">
<stop offset="0%" style="stop-color:#BEBEBE;" />
<stop offset="25%" style="stop-color:#395CC6;" />
<stop offset="50%" style="stop-color:#E03C00;" />
<stop offset="75%" style="stop-color:#5A3A1D;" />
<stop offset="100%" style="stop-color:#7AE4EB;" />
</radialGradient>
</defs>
<circle cx="50" cy="57" r="55" class="encircle" />
<path class="spirit" d="M50 2 62 42 38 42Z" />
<path class="water" d="M59.5 40 99 40 67 64.5Z" />
<path class="fire" d="M68 61 80.5 101 48.5 76.5Z" />
<path class="earth" d="M51.5 76.5 19.5 101 32 61Z" />
<path class="air" d="M33 64.5 1 40 40.5 40Z" />
</svg>
</body>
</html>
|
d9f094fa3cd880d8a59c94262c99e0d5
|
{
"intermediate": 0.3432285785675049,
"beginner": 0.31750941276550293,
"expert": 0.3392619490623474
}
|
44,731
|
in python make funtion to parse this string chain: "naber mudur Victory 2534 (+0) 30/03/2024 12:26 00:01:04 Nagrand Arena" into this format: "OPPONENT OUTCOME RATING START TIME FIGHT DURATION MAP"
|
c9dbff1ffc993119ac96980ea83c5224
|
{
"intermediate": 0.28130948543548584,
"beginner": 0.4590573012828827,
"expert": 0.2596331536769867
}
|
44,732
|
ok i want to to make a python script that will go on this wow arena ladder page: https://logs.stormforge.gg/en/ladder/netherwing/2v2
then it will find the name of the first 50 team, and the link of each team
it will then open a team and find the entire history of matchs played by the team and put it in a file then open the next until all the 50 team have been seen and stored
the script will then use the data collected to visualy show for each team when do they play so we have better chance to face them
|
e2af1f8638e3e6ad2f1fac26d0698e09
|
{
"intermediate": 0.43160194158554077,
"beginner": 0.2754862606525421,
"expert": 0.2929117679595947
}
|
44,733
|
hi,
i have couple of csv files
each has a unique name
i want to create one_hot encode from their names and add to each csv file
give me proper python code
|
a7bb9c9b6ec6a8f88aec4239fb6a026c
|
{
"intermediate": 0.3846569359302521,
"beginner": 0.36709848046302795,
"expert": 0.24824459850788116
}
|
44,734
|
hi,
i have 4 csv files
each has a unique name
i want to create one_hot encode from their names and add to each csv file
i have following code :
import os
import pandas as pd
import numpy as np
from sklearn.preprocessing import OneHotEncoder
# Directory containing your CSV files
directory = r'E:\01_calculate_talib\New folder (2)'
# List all CSV files
csv_files = [file for file in os.listdir(directory) if file.endswith('.csv')]
# Extract unique names (without .csv extension)
unique_names = [os.path.splitext(filename)[0] for filename in csv_files]
# Reshape names for One-Hot Encoder
unique_names = np.array(unique_names).reshape(-1, 1)
# Apply One-Hot Encoding
encoder = OneHotEncoder(sparse=False)
one_hot_encoded = encoder.fit_transform(unique_names)
# Create a DataFrame for easier handling
one_hot_df = pd.DataFrame(one_hot_encoded, columns=encoder.get_feature_names_out())
### Read Each CSV, Modify, and Save
for i, file in enumerate(csv_files):
# Read the CSV file
path = os.path.join(directory, file)
df = pd.read_csv(path)
# Get the corresponding one-hot encoded row (as a DataFrame to align columns)
one_hot_row = one_hot_df.iloc[[i]]
# If handling as a column, we temporarily reset index for concatenation
df.reset_index(drop=True, inplace=True)
one_hot_row.reset_index(drop=True, inplace=True)
# Concatenate the CSV data with the one-hot encoded row
modified_df = pd.concat([df, one_hot_row], axis=1)
# Save the modified DataFrame back to a CSV
modified_df.to_csv(path, index=False)
but it dosnt work
it throws following errors:
TypeError: OneHotEncoder.__init__() got an unexpected keyword argument 'sparse'
ValueError: Shape of passed values is (4, 1), indices imply (4, 4)
|
e83c895f07b445868bc583eefc005020
|
{
"intermediate": 0.5841203927993774,
"beginner": 0.17676323652267456,
"expert": 0.2391163408756256
}
|
44,735
|
how to extend partition size on linux by unallocated space
|
c0395c92440f99a85d97854c0be1742a
|
{
"intermediate": 0.26286038756370544,
"beginner": 0.26207980513572693,
"expert": 0.4750598669052124
}
|
44,736
|
make a python script to open and put the source code of this page so i can parse it later: https://logs.stormforge.gg/en/ladder/netherwing/2v2
|
0f42f250e6fac903fad7236cae058882
|
{
"intermediate": 0.3671031594276428,
"beginner": 0.22574962675571442,
"expert": 0.40714725852012634
}
|
44,737
|
i have a list of csv files in a directory
i want to print each file columns number
give me proper python code
|
3592c7c07aaea94aca1be18b76bf792d
|
{
"intermediate": 0.526865541934967,
"beginner": 0.22413694858551025,
"expert": 0.24899746477603912
}
|
44,738
|
i have a csv file , it has 6090 columns
i want to perform a min max scale on it
its values can have different values and i dont know their range
|
296d1267e623c31005cd228e606ba2a3
|
{
"intermediate": 0.35484910011291504,
"beginner": 0.30313003063201904,
"expert": 0.3420208692550659
}
|
44,739
|
Heres my code
const newTab = await page.$eval('[newtabwarningtext="opens in a new tab"]', el => el !== null);
if (newTab) {
console.log('Opens in new tab. Skipping...');
break;
} else {
console.log('Indeed application.. Continuing...');
}
Heres the error
Error occurred: page.$eval: Failed to find element matching selector "[newtabwarningtext="opens in a new tab"]"
at C:\Users\X\node\app\node-crash-course\playwright.js:148:43 {
name: 'Error'
}
PS C:\Use
|
cab983c23527de5c53e308e64aa4e252
|
{
"intermediate": 0.35791894793510437,
"beginner": 0.33968162536621094,
"expert": 0.30239948630332947
}
|
44,740
|
podría solucionar este error: < File "/Users/raul/Downloads/roop-OLD/fast_roop/lib/python3.11/site-packages/gradio/processing_utils.py", line 332, in _move_to_cache
raise ValueError(
ValueError: File /private/var/folders/6k/zk46_fz90rs2xmmczhwr7m7r0000gn/T/85c997f289d0112a4dbb4ae3bd1efa3329339eb0/IMG_675A4CA31089-1.jpeg is not in the upload folder and cannot be accessed. > modificando algo del codigo del archivo 'blocks.py' que añado a continuación:
from __future__ import annotations
import copy
import hashlib
import inspect
import json
import os
import random
import secrets
import string
import sys
import threading
import time
import warnings
import webbrowser
from collections import defaultdict
from pathlib import Path
from types import ModuleType
from typing import TYPE_CHECKING, Any, AsyncIterator, Callable, Literal, Sequence, cast
from urllib.parse import urlparse, urlunparse
import anyio
import fastapi
import httpx
from anyio import CapacityLimiter
from gradio_client import utils as client_utils
from gradio_client.documentation import document
from gradio import (
analytics,
components,
networking,
processing_utils,
queueing,
routes,
strings,
themes,
utils,
wasm_utils,
)
from gradio.blocks_events import BlocksEvents, BlocksMeta
from gradio.context import Context
from gradio.data_classes import FileData, GradioModel, GradioRootModel
from gradio.events import (
EventData,
EventListener,
EventListenerMethod,
)
from gradio.exceptions import (
DuplicateBlockError,
InvalidApiNameError,
InvalidBlockError,
InvalidComponentError,
)
from gradio.helpers import create_tracker, skip, special_args
from gradio.state_holder import SessionState
from gradio.themes import Default as DefaultTheme
from gradio.themes import ThemeClass as Theme
from gradio.tunneling import (
BINARY_FILENAME,
BINARY_FOLDER,
BINARY_PATH,
BINARY_URL,
CURRENT_TUNNELS,
)
from gradio.utils import (
TupleNoPrint,
check_function_inputs_match,
component_or_layout_class,
get_cancel_function,
get_continuous_fn,
get_package_version,
get_upload_folder,
)
try:
import spaces # type: ignore
except Exception:
spaces = None
if TYPE_CHECKING: # Only import for type checking (is False at runtime).
from fastapi.applications import FastAPI
from gradio.components.base import Component
BUILT_IN_THEMES: dict[str, Theme] = {
t.name: t
for t in [
themes.Base(),
themes.Default(),
themes.Monochrome(),
themes.Soft(),
themes.Glass(),
]
}
class Block:
def __init__(
self,
*,
elem_id: str | None = None,
elem_classes: list[str] | str | None = None,
render: bool = True,
visible: bool = True,
proxy_url: str | None = None,
):
self._id = Context.id
Context.id += 1
self.visible = visible
self.elem_id = elem_id
self.elem_classes = (
[elem_classes] if isinstance(elem_classes, str) else elem_classes
)
self.proxy_url = proxy_url
self.share_token = secrets.token_urlsafe(32)
self.parent: BlockContext | None = None
self.is_rendered: bool = False
self._constructor_args: list[dict]
self.state_session_capacity = 10000
self.temp_files: set[str] = set()
self.GRADIO_CACHE = get_upload_folder()
# Keep tracks of files that should not be deleted when the delete_cache parmaeter is set
# These files are the default value of the component and files that are used in examples
self.keep_in_cache = set()
if render:
self.render()
@property
def skip_api(self):
return False
@property
def constructor_args(self) -> dict[str, Any]:
"""Get the arguments passed to the component's initializer.
Only set classes whose metaclass is ComponentMeta
"""
# the _constructor_args list is appended based on the mro of the class
# so the first entry is for the bottom of the hierarchy
return self._constructor_args[0] if self._constructor_args else {}
@property
def events(
self,
) -> list[EventListener]:
return getattr(self, "EVENTS", [])
def render(self):
"""
Adds self into appropriate BlockContext
"""
if Context.root_block is not None and self._id in Context.root_block.blocks:
raise DuplicateBlockError(
f"A block with id: {self._id} has already been rendered in the current Blocks."
)
if Context.block is not None:
Context.block.add(self)
if Context.root_block is not None:
Context.root_block.blocks[self._id] = self
self.is_rendered = True
if isinstance(self, components.Component):
Context.root_block.temp_file_sets.append(self.temp_files)
return self
def unrender(self):
"""
Removes self from BlockContext if it has been rendered (otherwise does nothing).
Removes self from the layout and collection of blocks, but does not delete any event triggers.
"""
if Context.block is not None:
try:
Context.block.children.remove(self)
except ValueError:
pass
if Context.root_block is not None:
try:
del Context.root_block.blocks[self._id]
self.is_rendered = False
except KeyError:
pass
return self
def get_block_name(self) -> str:
"""
Gets block's class name. If it is template component it gets the parent's class name.
This is used to identify the Svelte file to use in the frontend. Override this method
if a component should use a different Svelte file than the default naming convention.
"""
return (
self.__class__.__base__.__name__.lower() # type: ignore
if hasattr(self, "is_template")
else self.__class__.__name__.lower()
)
def get_block_class(self) -> str:
"""
Gets block's class name. If it is template component it gets the parent's class name.
Very similar to the get_block_name method, but this method is used to reconstruct a
Gradio app that is loaded from a Space using gr.load(). This should generally
NOT be overridden.
"""
return (
self.__class__.__base__.__name__.lower() # type: ignore
if hasattr(self, "is_template")
else self.__class__.__name__.lower()
)
def get_expected_parent(self) -> type[BlockContext] | None:
return None
def get_config(self):
config = {}
signature = inspect.signature(self.__class__.__init__)
for parameter in signature.parameters.values():
if hasattr(self, parameter.name):
value = getattr(self, parameter.name)
config[parameter.name] = utils.convert_to_dict_if_dataclass(value)
for e in self.events:
to_add = e.config_data()
if to_add:
config = {**to_add, **config}
config.pop("render", None)
config = {**config, "proxy_url": self.proxy_url, "name": self.get_block_class()}
if (_selectable := getattr(self, "_selectable", None)) is not None:
config["_selectable"] = _selectable
return config
@classmethod
def recover_kwargs(
cls, props: dict[str, Any], additional_keys: list[str] | None = None
):
"""
Recovers kwargs from a dict of props.
"""
additional_keys = additional_keys or []
signature = inspect.signature(cls.__init__)
kwargs = {}
for parameter in signature.parameters.values():
if parameter.name in props and parameter.name not in additional_keys:
kwargs[parameter.name] = props[parameter.name]
return kwargs
def move_resource_to_block_cache(
self, url_or_file_path: str | Path | None
) -> str | None:
"""Moves a file or downloads a file from a url to a block's cache directory, adds
to to the block's temp_files, and returns the path to the file in cache. This
ensures that the file is accessible to the Block and can be served to users.
Note: this method is not used in any core Gradio components, but is kept here
for backwards compatibility with custom components created with gradio<=4.20.0.
"""
if url_or_file_path is None:
return None
if isinstance(url_or_file_path, Path):
url_or_file_path = str(url_or_file_path)
if client_utils.is_http_url_like(url_or_file_path):
temp_file_path = processing_utils.save_url_to_cache(
url_or_file_path, cache_dir=self.GRADIO_CACHE
)
self.temp_files.add(temp_file_path)
else:
url_or_file_path = str(utils.abspath(url_or_file_path))
if not utils.is_in_or_equal(url_or_file_path, self.GRADIO_CACHE):
try:
temp_file_path = processing_utils.save_file_to_cache(
url_or_file_path, cache_dir=self.GRADIO_CACHE
)
except FileNotFoundError:
# This can happen if when using gr.load() and the file is on a remote Space
# but the file is not the `value` of the component. For example, if the file
# is the `avatar_image` of the `Chatbot` component. In this case, we skip
# copying the file to the cache and just use the remote file path.
return url_or_file_path
else:
temp_file_path = url_or_file_path
self.temp_files.add(temp_file_path)
return temp_file_path
def serve_static_file(
self, url_or_file_path: str | Path | dict | None
) -> dict | None:
"""If a file is a local file, moves it to the block's cache directory and returns
a FileData-type dictionary corresponding to the file. If the file is a URL, returns a
FileData-type dictionary corresponding to the URL. This ensures that the file is
accessible in the frontend and can be served to users.
Examples:
>>> block.serve_static_file("https://gradio.app/logo.png") -> {"path": "https://gradio.app/logo.png", "url": "https://gradio.app/logo.png"}
>>> block.serve_static_file("logo.png") -> {"path": "logo.png", "url": "/file=logo.png"}
>>> block.serve_static_file({"path": "logo.png", "url": "/file=logo.png"}) -> {"path": "logo.png", "url": "/file=logo.png"}
"""
if url_or_file_path is None:
return None
if isinstance(url_or_file_path, dict):
return url_or_file_path
if isinstance(url_or_file_path, Path):
url_or_file_path = str(url_or_file_path)
if client_utils.is_http_url_like(url_or_file_path):
return FileData(path=url_or_file_path, url=url_or_file_path).model_dump()
else:
data = {"path": url_or_file_path}
try:
return processing_utils.move_files_to_cache(data, self)
except AttributeError: # Can be raised if this function is called before the Block is fully initialized.
return data
class BlockContext(Block):
def __init__(
self,
elem_id: str | None = None,
elem_classes: list[str] | str | None = None,
visible: bool = True,
render: bool = True,
):
"""
Parameters:
elem_id: An optional string that is assigned as the id of this component in the HTML DOM. Can be used for targeting CSS styles.
elem_classes: An optional string or list of strings that are assigned as the class of this component in the HTML DOM. Can be used for targeting CSS styles.
visible: If False, this will be hidden but included in the Blocks config file (its visibility can later be updated).
render: If False, this will not be included in the Blocks config file at all.
"""
self.children: list[Block] = []
Block.__init__(
self,
elem_id=elem_id,
elem_classes=elem_classes,
visible=visible,
render=render,
)
TEMPLATE_DIR = "./templates/"
FRONTEND_DIR = "../../frontend/"
@property
def skip_api(self):
return True
@classmethod
def get_component_class_id(cls) -> str:
module_name = cls.__module__
module_path = sys.modules[module_name].__file__
module_hash = hashlib.md5(f"{cls.__name__}_{module_path}".encode()).hexdigest()
return module_hash
@property
def component_class_id(self):
return self.get_component_class_id()
def add_child(self, child: Block):
self.children.append(child)
def __enter__(self):
self.parent = Context.block
Context.block = self
return self
def add(self, child: Block):
child.parent = self
self.children.append(child)
def fill_expected_parents(self):
children = []
pseudo_parent = None
for child in self.children:
expected_parent = child.get_expected_parent()
if not expected_parent or isinstance(self, expected_parent):
pseudo_parent = None
children.append(child)
else:
if pseudo_parent is not None and isinstance(
pseudo_parent, expected_parent
):
pseudo_parent.add_child(child)
else:
pseudo_parent = expected_parent(render=False)
pseudo_parent.parent = self
children.append(pseudo_parent)
pseudo_parent.add_child(child)
if Context.root_block:
Context.root_block.blocks[pseudo_parent._id] = pseudo_parent
child.parent = pseudo_parent
self.children = children
def __exit__(self, exc_type: type[BaseException] | None = None, *args):
Context.block = self.parent
if exc_type is not None:
return
if getattr(self, "allow_expected_parents", True):
self.fill_expected_parents()
def postprocess(self, y):
"""
Any postprocessing needed to be performed on a block context.
"""
return y
class BlockFunction:
def __init__(
self,
fn: Callable | None,
inputs: list[Component],
outputs: list[Component],
preprocess: bool,
postprocess: bool,
inputs_as_dict: bool,
batch: bool = False,
max_batch_size: int = 4,
concurrency_limit: int | None | Literal["default"] = "default",
concurrency_id: str | None = None,
tracks_progress: bool = False,
):
self.fn = fn
self.inputs = inputs
self.outputs = outputs
self.preprocess = preprocess
self.postprocess = postprocess
self.tracks_progress = tracks_progress
self.concurrency_limit: int | None | Literal["default"] = concurrency_limit
self.concurrency_id = concurrency_id or str(id(fn))
self.batch = batch
self.max_batch_size = max_batch_size
self.total_runtime = 0
self.total_runs = 0
self.inputs_as_dict = inputs_as_dict
self.name = getattr(fn, "__name__", "fn") if fn is not None else None
self.spaces_auto_wrap()
def spaces_auto_wrap(self):
if spaces is None:
return
if utils.get_space() is None:
return
self.fn = spaces.gradio_auto_wrap(self.fn)
def __str__(self):
return str(
{
"fn": self.name,
"preprocess": self.preprocess,
"postprocess": self.postprocess,
}
)
def __repr__(self):
return str(self)
def postprocess_update_dict(
block: Component | BlockContext, update_dict: dict, postprocess: bool = True
):
"""
Converts a dictionary of updates into a format that can be sent to the frontend to update the component.
E.g. {"value": "2", "visible": True, "invalid_arg": "hello"}
Into -> {"__type__": "update", "value": 2.0, "visible": True}
Parameters:
block: The Block that is being updated with this update dictionary.
update_dict: The original update dictionary
postprocess: Whether to postprocess the "value" key of the update dictionary.
"""
value = update_dict.pop("value", components._Keywords.NO_VALUE)
update_dict = {k: getattr(block, k) for k in update_dict if hasattr(block, k)}
if value is not components._Keywords.NO_VALUE:
if postprocess:
update_dict["value"] = block.postprocess(value)
if isinstance(update_dict["value"], (GradioModel, GradioRootModel)):
update_dict["value"] = update_dict["value"].model_dump()
else:
update_dict["value"] = value
update_dict["__type__"] = "update"
return update_dict
def convert_component_dict_to_list(
outputs_ids: list[int], predictions: dict
) -> list | dict:
"""
Converts a dictionary of component updates into a list of updates in the order of
the outputs_ids and including every output component. Leaves other types of dictionaries unchanged.
E.g. {"textbox": "hello", "number": {"__type__": "generic_update", "value": "2"}}
Into -> ["hello", {"__type__": "generic_update"}, {"__type__": "generic_update", "value": "2"}]
"""
keys_are_blocks = [isinstance(key, Block) for key in predictions]
if all(keys_are_blocks):
reordered_predictions = [skip() for _ in outputs_ids]
for component, value in predictions.items():
if component._id not in outputs_ids:
raise ValueError(
f"Returned component {component} not specified as output of function."
)
output_index = outputs_ids.index(component._id)
reordered_predictions[output_index] = value
predictions = utils.resolve_singleton(reordered_predictions)
elif any(keys_are_blocks):
raise ValueError(
"Returned dictionary included some keys as Components. Either all keys must be Components to assign Component values, or return a List of values to assign output values in order."
)
return predictions
@document("launch", "queue", "integrate", "load")
class Blocks(BlockContext, BlocksEvents, metaclass=BlocksMeta):
"""
Blocks is Gradio's low-level API that allows you to create more custom web
applications and demos than Interfaces (yet still entirely in Python).
Compared to the Interface class, Blocks offers more flexibility and control over:
(1) the layout of components (2) the events that
trigger the execution of functions (3) data flows (e.g. inputs can trigger outputs,
which can trigger the next level of outputs). Blocks also offers ways to group
together related demos such as with tabs.
The basic usage of Blocks is as follows: create a Blocks object, then use it as a
context (with the "with" statement), and then define layouts, components, or events
within the Blocks context. Finally, call the launch() method to launch the demo.
Example:
import gradio as gr
def update(name):
return f"Welcome to Gradio, {name}!"
with gr.Blocks() as demo:
gr.Markdown("Start typing below and then click **Run** to see the output.")
with gr.Row():
inp = gr.Textbox(placeholder="What is your name?")
out = gr.Textbox()
btn = gr.Button("Run")
btn.click(fn=update, inputs=inp, outputs=out)
demo.launch()
Demos: blocks_hello, blocks_flipper, blocks_kinematics
Guides: blocks-and-event-listeners, controlling-layout, state-in-blocks, custom-CSS-and-JS, using-blocks-like-functions
"""
def __init__(
self,
theme: Theme | str | None = None,
analytics_enabled: bool | None = None,
mode: str = "blocks",
title: str = "Gradio",
css: str | None = None,
js: str | None = None,
head: str | None = None,
fill_height: bool = False,
delete_cache: tuple[int, int] | None = None,
**kwargs,
):
"""
Parameters:
theme: A Theme object or a string representing a theme. If a string, will look for a built-in theme with that name (e.g. "soft" or "default"), or will attempt to load a theme from the Hugging Face Hub (e.g. "gradio/monochrome"). If None, will use the Default theme.
analytics_enabled: Whether to allow basic telemetry. If None, will use GRADIO_ANALYTICS_ENABLED environment variable or default to True.
mode: A human-friendly name for the kind of Blocks or Interface being created. Used internally for analytics.
title: The tab title to display when this is opened in a browser window.
css: Custom css as a string or path to a css file. This css will be included in the demo webpage.
js: Custom js or path to js file to run when demo is first loaded. This javascript will be included in the demo webpage.
head: Custom html to insert into the head of the demo webpage. This can be used to add custom meta tags, scripts, stylesheets, etc. to the page.
fill_height: Whether to vertically expand top-level child components to the height of the window. If True, expansion occurs when the scale value of the child components >= 1.
delete_cache: A tuple corresponding [frequency, age] both expressed in number of seconds. Every `frequency` seconds, the temporary files created by this Blocks instance will be deleted if more than `age` seconds have passed since the file was created. For example, setting this to (86400, 86400) will delete temporary files every day. The cache will be deleted entirely when the server restarts. If None, no cache deletion will occur.
"""
self.limiter = None
if theme is None:
theme = DefaultTheme()
elif isinstance(theme, str):
if theme.lower() in BUILT_IN_THEMES:
theme = BUILT_IN_THEMES[theme.lower()]
else:
try:
theme = Theme.from_hub(theme)
except Exception as e:
warnings.warn(f"Cannot load {theme}. Caught Exception: {str(e)}")
theme = DefaultTheme()
if not isinstance(theme, Theme):
warnings.warn("Theme should be a class loaded from gradio.themes")
theme = DefaultTheme()
self.theme: Theme = theme
self.theme_css = theme._get_theme_css()
self.stylesheets = theme._stylesheets
self.encrypt = False
self.share = False
self.enable_queue = True
self.max_threads = 40
self.pending_streams = defaultdict(dict)
self.pending_diff_streams = defaultdict(dict)
self.show_error = True
self.head = head
self.fill_height = fill_height
self.delete_cache = delete_cache
if css is not None and os.path.exists(css):
with open(css) as css_file:
self.css = css_file.read()
else:
self.css = css
if js is not None and os.path.exists(js):
with open(js) as js_file:
self.js = js_file.read()
else:
self.js = js
# For analytics_enabled and allow_flagging: (1) first check for
# parameter, (2) check for env variable, (3) default to True/"manual"
self.analytics_enabled = (
analytics_enabled
if analytics_enabled is not None
else analytics.analytics_enabled()
)
if self.analytics_enabled:
if not wasm_utils.IS_WASM:
t = threading.Thread(target=analytics.version_check)
t.start()
else:
os.environ["HF_HUB_DISABLE_TELEMETRY"] = "True"
super().__init__(render=False, **kwargs)
self.blocks: dict[int, Component | Block] = {}
self.fns: list[BlockFunction] = []
self.dependencies = []
self.mode = mode
self.is_running = False
self.local_url = None
self.share_url = None
self.width = None
self.height = None
self.api_open = utils.get_space() is None
self.space_id = utils.get_space()
self.favicon_path = None
self.auth = None
self.dev_mode = bool(os.getenv("GRADIO_WATCH_DIRS", ""))
self.app_id = random.getrandbits(64)
self.upload_file_set = set()
self.temp_file_sets = [self.upload_file_set]
self.title = title
self.show_api = not wasm_utils.IS_WASM
# Only used when an Interface is loaded from a config
self.predict = None
self.input_components = None
self.output_components = None
self.__name__ = None
self.api_mode = None
self.progress_tracking = None
self.ssl_verify = True
self.allowed_paths = []
self.blocked_paths = []
self.root_path = os.environ.get("GRADIO_ROOT_PATH", "")
self.proxy_urls = set()
if self.analytics_enabled:
is_custom_theme = not any(
self.theme.to_dict() == built_in_theme.to_dict()
for built_in_theme in BUILT_IN_THEMES.values()
)
data = {
"mode": self.mode,
"custom_css": self.css is not None,
"theme": self.theme.name,
"is_custom_theme": is_custom_theme,
"version": get_package_version(),
}
analytics.initiated_analytics(data)
self.queue()
def get_component(self, id: int) -> Component | BlockContext:
comp = self.blocks[id]
if not isinstance(comp, (components.Component, BlockContext)):
raise TypeError(f"Block with id {id} is not a Component or BlockContext")
return comp
@property
def _is_running_in_reload_thread(self):
from gradio.cli.commands.reload import reload_thread
return getattr(reload_thread, "running_reload", False)
@classmethod
def from_config(
cls,
config: dict,
fns: list[Callable],
proxy_url: str,
) -> Blocks:
"""
Factory method that creates a Blocks from a config and list of functions. Used
internally by the gradio.external.load() method.
Parameters:
config: a dictionary containing the configuration of the Blocks.
fns: a list of functions that are used in the Blocks. Must be in the same order as the dependencies in the config.
proxy_url: an external url to use as a root URL when serving files for components in the Blocks.
"""
config = copy.deepcopy(config)
components_config = config["components"]
theme = config.get("theme", "default")
original_mapping: dict[int, Block] = {}
proxy_urls = {proxy_url}
def get_block_instance(id: int) -> Block:
for block_config in components_config:
if block_config["id"] == id:
break
else:
raise ValueError(f"Cannot find block with id {id}")
cls = component_or_layout_class(block_config["props"]["name"])
# If a Gradio app B is loaded into a Gradio app A, and B itself loads a
# Gradio app C, then the proxy_urls of the components in A need to be the
# URL of C, not B. The else clause below handles this case.
if block_config["props"].get("proxy_url") is None:
block_config["props"]["proxy_url"] = f"{proxy_url}/"
postprocessed_value = block_config["props"].pop("value", None)
constructor_args = cls.recover_kwargs(block_config["props"])
block = cls(**constructor_args)
if postprocessed_value is not None:
block.value = postprocessed_value # type: ignore
block_proxy_url = block_config["props"]["proxy_url"]
block.proxy_url = block_proxy_url
proxy_urls.add(block_proxy_url)
if (
_selectable := block_config["props"].pop("_selectable", None)
) is not None:
block._selectable = _selectable # type: ignore
return block
def iterate_over_children(children_list):
for child_config in children_list:
id = child_config["id"]
block = get_block_instance(id)
original_mapping[id] = block
children = child_config.get("children")
if children is not None:
if not isinstance(block, BlockContext):
raise ValueError(
f"Invalid config, Block with id {id} has children but is not a BlockContext."
)
with block:
iterate_over_children(children)
derived_fields = ["types"]
with Blocks(theme=theme) as blocks:
# ID 0 should be the root Blocks component
original_mapping[0] = Context.root_block or blocks
iterate_over_children(config["layout"]["children"])
first_dependency = None
# add the event triggers
for dependency, fn in zip(config["dependencies"], fns):
# We used to add a "fake_event" to the config to cache examples
# without removing it. This was causing bugs in calling gr.load
# We fixed the issue by removing "fake_event" from the config in examples.py
# but we still need to skip these events when loading the config to support
# older demos
if "trigger" in dependency and dependency["trigger"] == "fake_event":
continue
for field in derived_fields:
dependency.pop(field, None)
# older versions had a separate trigger field, but now it is part of the
# targets field
_targets = dependency.pop("targets")
trigger = dependency.pop("trigger", None)
is_then_event = False
# This assumes that you cannot combine multiple .then() events in a single
# gr.on() event, which is true for now. If this changes, we will need to
# update this code.
if not isinstance(_targets[0], int) and _targets[0][1] == "then":
if len(_targets) != 1:
raise ValueError(
"This logic assumes that .then() events are not combined with other events in a single gr.on() event"
)
is_then_event = True
dependency.pop("backend_fn")
dependency.pop("documentation", None)
dependency["inputs"] = [
original_mapping[i] for i in dependency["inputs"]
]
dependency["outputs"] = [
original_mapping[o] for o in dependency["outputs"]
]
dependency.pop("status_tracker", None)
dependency["preprocess"] = False
dependency["postprocess"] = False
if is_then_event:
targets = [EventListenerMethod(None, "then")]
dependency["trigger_after"] = dependency.pop("trigger_after")
dependency["trigger_only_on_success"] = dependency.pop(
"trigger_only_on_success"
)
dependency["no_target"] = True
else:
targets = [
getattr(
original_mapping[
target if isinstance(target, int) else target[0]
],
trigger if isinstance(target, int) else target[1],
)
for target in _targets
]
targets = [
EventListenerMethod(
t.__self__ if t.has_trigger else None,
t.event_name, # type: ignore
)
for t in targets
]
dependency = blocks.set_event_trigger(
targets=targets, fn=fn, **dependency
)[0]
if first_dependency is None:
first_dependency = dependency
# Allows some use of Interface-specific methods with loaded Spaces
if first_dependency and Context.root_block:
blocks.predict = [fns[0]]
blocks.input_components = [
Context.root_block.blocks[i] for i in first_dependency["inputs"]
]
blocks.output_components = [
Context.root_block.blocks[o] for o in first_dependency["outputs"]
]
blocks.__name__ = "Interface"
blocks.api_mode = True
blocks.proxy_urls = proxy_urls
return blocks
def __str__(self):
return self.__repr__()
def __repr__(self):
num_backend_fns = len([d for d in self.dependencies if d["backend_fn"]])
repr = f"Gradio Blocks instance: {num_backend_fns} backend functions"
repr += f"\n{'-' * len(repr)}"
for d, dependency in enumerate(self.dependencies):
if dependency["backend_fn"]:
repr += f"\nfn_index={d}"
repr += "\n inputs:"
for input_id in dependency["inputs"]:
block = self.blocks[input_id]
repr += f"\n |-{block}"
repr += "\n outputs:"
for output_id in dependency["outputs"]:
block = self.blocks[output_id]
repr += f"\n |-{block}"
return repr
@property
def expects_oauth(self):
"""Return whether the app expects user to authenticate via OAuth."""
return any(
isinstance(block, (components.LoginButton, components.LogoutButton))
for block in self.blocks.values()
)
def set_event_trigger(
self,
targets: Sequence[EventListenerMethod],
fn: Callable | None,
inputs: Component | list[Component] | set[Component] | None,
outputs: Component | list[Component] | None,
preprocess: bool = True,
postprocess: bool = True,
scroll_to_output: bool = False,
show_progress: Literal["full", "minimal", "hidden"] = "full",
api_name: str | None | Literal[False] = None,
js: str | None = None,
no_target: bool = False,
queue: bool | None = None,
batch: bool = False,
max_batch_size: int = 4,
cancels: list[int] | None = None,
every: float | None = None,
collects_event_data: bool | None = None,
trigger_after: int | None = None,
trigger_only_on_success: bool = False,
trigger_mode: Literal["once", "multiple", "always_last"] | None = "once",
concurrency_limit: int | None | Literal["default"] = "default",
concurrency_id: str | None = None,
show_api: bool = True,
) -> tuple[dict[str, Any], int]:
"""
Adds an event to the component's dependencies.
Parameters:
targets: a list of EventListenerMethod objects that define the event trigger
fn: Callable function
inputs: input list
outputs: output list
preprocess: whether to run the preprocess methods of components
postprocess: whether to run the postprocess methods of components
scroll_to_output: whether to scroll to output of dependency on trigger
show_progress: whether to show progress animation while running.
api_name: defines how the endpoint appears in the API docs. Can be a string, None, or False. If set to a string, the endpoint will be exposed in the API docs with the given name. If None (default), the name of the function will be used as the API endpoint. If False, the endpoint will not be exposed in the API docs and downstream apps (including those that `gr.load` this app) will not be able to use this event.
js: Optional frontend js method to run before running 'fn'. Input arguments for js method are values of 'inputs' and 'outputs', return should be a list of values for output components
no_target: if True, sets "targets" to [], used for the Blocks.load() event and .then() events
queue: If True, will place the request on the queue, if the queue has been enabled. If False, will not put this event on the queue, even if the queue has been enabled. If None, will use the queue setting of the gradio app.
batch: whether this function takes in a batch of inputs
max_batch_size: the maximum batch size to send to the function
cancels: a list of other events to cancel when this event is triggered. For example, setting cancels=[click_event] will cancel the click_event, where click_event is the return value of another components .click method.
every: Run this event 'every' number of seconds while the client connection is open. Interpreted in seconds.
collects_event_data: whether to collect event data for this event
trigger_after: if set, this event will be triggered after 'trigger_after' function index
trigger_only_on_success: if True, this event will only be triggered if the previous event was successful (only applies if `trigger_after` is set)
trigger_mode: If "once" (default for all events except `.change()`) would not allow any submissions while an event is pending. If set to "multiple", unlimited submissions are allowed while pending, and "always_last" (default for `.change()` and `.key_up()` events) would allow a second submission after the pending event is complete.
concurrency_limit: If set, this is the maximum number of this event that can be running simultaneously. Can be set to None to mean no concurrency_limit (any number of this event can be running simultaneously). Set to "default" to use the default concurrency limit (defined by the `default_concurrency_limit` parameter in `queue()`, which itself is 1 by default).
concurrency_id: If set, this is the id of the concurrency group. Events with the same concurrency_id will be limited by the lowest set concurrency_limit.
show_api: whether to show this event in the "view API" page of the Gradio app, or in the ".view_api()" method of the Gradio clients. Unlike setting api_name to False, setting show_api to False will still allow downstream apps to use this event. If fn is None, show_api will automatically be set to False.
Returns: dependency information, dependency index
"""
# Support for singular parameter
_targets = [
(
target.block._id if not no_target and target.block else None,
target.event_name,
)
for target in targets
]
if isinstance(inputs, set):
inputs_as_dict = True
inputs = sorted(inputs, key=lambda x: x._id)
else:
inputs_as_dict = False
if inputs is None:
inputs = []
elif not isinstance(inputs, list):
inputs = [inputs]
if isinstance(outputs, set):
outputs = sorted(outputs, key=lambda x: x._id)
elif outputs is None:
outputs = []
elif not isinstance(outputs, list):
outputs = [outputs]
if fn is not None and not cancels:
check_function_inputs_match(fn, inputs, inputs_as_dict)
if every is not None and every <= 0:
raise ValueError("Parameter every must be positive or None")
if every and batch:
raise ValueError(
f"Cannot run event in a batch and every {every} seconds. "
"Either batch is True or every is non-zero but not both."
)
if every and fn:
fn = get_continuous_fn(fn, every)
elif every:
raise ValueError("Cannot set a value for `every` without a `fn`.")
if every and concurrency_limit is not None:
if concurrency_limit == "default":
concurrency_limit = None
else:
raise ValueError(
"Cannot set a value for `concurrency_limit` with `every`."
)
if _targets[0][1] in ["change", "key_up"] and trigger_mode is None:
trigger_mode = "always_last"
elif trigger_mode is None:
trigger_mode = "once"
elif trigger_mode not in ["once", "multiple", "always_last"]:
raise ValueError(
f"Invalid value for parameter `trigger_mode`: {trigger_mode}. Please choose from: {['once', 'multiple', 'always_last']}"
)
_, progress_index, event_data_index = (
special_args(fn) if fn else (None, None, None)
)
self.fns.append(
BlockFunction(
fn,
inputs,
outputs,
preprocess,
postprocess,
inputs_as_dict=inputs_as_dict,
concurrency_limit=concurrency_limit,
concurrency_id=concurrency_id,
batch=batch,
max_batch_size=max_batch_size,
tracks_progress=progress_index is not None,
)
)
# If api_name is None or empty string, use the function name
if api_name is None or isinstance(api_name, str) and api_name.strip() == "":
if fn is not None:
if not hasattr(fn, "__name__"):
if hasattr(fn, "__class__") and hasattr(fn.__class__, "__name__"):
name = fn.__class__.__name__
else:
name = "unnamed"
else:
name = fn.__name__
api_name = "".join(
[s for s in name if s not in set(string.punctuation) - {"-", "_"}]
)
elif js is not None:
api_name = "js_fn"
show_api = False
else:
api_name = "unnamed"
show_api = False
if api_name is not False:
api_name = utils.append_unique_suffix(
api_name, [dep["api_name"] for dep in self.dependencies]
)
else:
show_api = False
# The `show_api` parameter is False if: (1) the user explicitly sets it (2) the user sets `api_name` to False
# or (3) the user sets `fn` to None (there's no backend function)
if collects_event_data is None:
collects_event_data = event_data_index is not None
dependency = {
"targets": _targets,
"inputs": [block._id for block in inputs],
"outputs": [block._id for block in outputs],
"backend_fn": fn is not None,
"js": js,
"queue": False if fn is None else queue,
"api_name": api_name,
"scroll_to_output": False if utils.get_space() else scroll_to_output,
"show_progress": show_progress,
"every": every,
"batch": batch,
"max_batch_size": max_batch_size,
"cancels": cancels or [],
"types": {
"continuous": bool(every),
"generator": inspect.isgeneratorfunction(fn)
or inspect.isasyncgenfunction(fn)
or bool(every),
},
"collects_event_data": collects_event_data,
"trigger_after": trigger_after,
"trigger_only_on_success": trigger_only_on_success,
"trigger_mode": trigger_mode,
"show_api": show_api,
}
self.dependencies.append(dependency)
return dependency, len(self.dependencies) - 1
def render(self):
if Context.root_block is not None:
if self._id in Context.root_block.blocks:
raise DuplicateBlockError(
f"A block with id: {self._id} has already been rendered in the current Blocks."
)
overlapping_ids = set(Context.root_block.blocks).intersection(self.blocks)
for id in overlapping_ids:
# State components are allowed to be reused between Blocks
if not isinstance(self.blocks[id], components.State):
raise DuplicateBlockError(
"At least one block in this Blocks has already been rendered."
)
Context.root_block.blocks.update(self.blocks)
Context.root_block.fns.extend(self.fns)
dependency_offset = len(Context.root_block.dependencies)
for i, dependency in enumerate(self.dependencies):
api_name = dependency["api_name"]
if api_name is not None and api_name is not False:
api_name_ = utils.append_unique_suffix(
api_name,
[dep["api_name"] for dep in Context.root_block.dependencies],
)
if api_name != api_name_:
dependency["api_name"] = api_name_
dependency["cancels"] = [
c + dependency_offset for c in dependency["cancels"]
]
if dependency.get("trigger_after") is not None:
dependency["trigger_after"] += dependency_offset
# Recreate the cancel function so that it has the latest
# dependency fn indices. This is necessary to properly cancel
# events in the backend
if dependency["cancels"]:
updated_cancels = [
Context.root_block.dependencies[i]
for i in dependency["cancels"]
]
new_fn = BlockFunction(
get_cancel_function(updated_cancels)[0],
[],
[],
False,
True,
False,
)
Context.root_block.fns[dependency_offset + i] = new_fn
Context.root_block.dependencies.append(dependency)
Context.root_block.temp_file_sets.extend(self.temp_file_sets)
Context.root_block.proxy_urls.update(self.proxy_urls)
if Context.block is not None:
Context.block.children.extend(self.children)
return self
def is_callable(self, fn_index: int = 0) -> bool:
"""Checks if a particular Blocks function is callable (i.e. not stateful or a generator)."""
block_fn = self.fns[fn_index]
dependency = self.dependencies[fn_index]
if inspect.isasyncgenfunction(block_fn.fn):
return False
if inspect.isgeneratorfunction(block_fn.fn):
return False
for input_id in dependency["inputs"]:
block = self.blocks[input_id]
if getattr(block, "stateful", False):
return False
for output_id in dependency["outputs"]:
block = self.blocks[output_id]
if getattr(block, "stateful", False):
return False
return True
def __call__(self, *inputs, fn_index: int = 0, api_name: str | None = None):
"""
Allows Blocks objects to be called as functions. Supply the parameters to the
function as positional arguments. To choose which function to call, use the
fn_index parameter, which must be a keyword argument.
Parameters:
*inputs: the parameters to pass to the function
fn_index: the index of the function to call (defaults to 0, which for Interfaces, is the default prediction function)
api_name: The api_name of the dependency to call. Will take precedence over fn_index.
"""
if api_name is not None:
inferred_fn_index = next(
(
i
for i, d in enumerate(self.dependencies)
if d.get("api_name") == api_name
),
None,
)
if inferred_fn_index is None:
raise InvalidApiNameError(
f"Cannot find a function with api_name {api_name}"
)
fn_index = inferred_fn_index
if not (self.is_callable(fn_index)):
raise ValueError(
"This function is not callable because it is either stateful or is a generator. Please use the .launch() method instead to create an interactive user interface."
)
inputs = list(inputs)
processed_inputs = self.serialize_data(fn_index, inputs)
batch = self.dependencies[fn_index]["batch"]
if batch:
processed_inputs = [[inp] for inp in processed_inputs]
outputs = client_utils.synchronize_async(
self.process_api,
fn_index=fn_index,
inputs=processed_inputs,
request=None,
state={},
explicit_call=True,
)
outputs = outputs["data"]
if batch:
outputs = [out[0] for out in outputs]
outputs = self.deserialize_data(fn_index, outputs)
processed_outputs = utils.resolve_singleton(outputs)
return processed_outputs
async def call_function(
self,
fn_index: int,
processed_input: list[Any],
iterator: AsyncIterator[Any] | None = None,
requests: routes.Request | list[routes.Request] | None = None,
event_id: str | None = None,
event_data: EventData | None = None,
in_event_listener: bool = False,
):
"""
Calls function with given index and preprocessed input, and measures process time.
Parameters:
fn_index: index of function to call
processed_input: preprocessed input to pass to function
iterator: iterator to use if function is a generator
requests: requests to pass to function
event_id: id of event in queue
event_data: data associated with event trigger
"""
block_fn = self.fns[fn_index]
if not block_fn.fn:
raise IndexError(f"function with index {fn_index} not defined.")
is_generating = False
request = requests[0] if isinstance(requests, list) else requests
start = time.time()
fn = utils.get_function_with_locals(
fn=block_fn.fn,
blocks=self,
event_id=event_id,
in_event_listener=in_event_listener,
request=request,
)
if iterator is None: # If not a generator function that has already run
if block_fn.inputs_as_dict:
processed_input = [dict(zip(block_fn.inputs, processed_input))]
processed_input, progress_index, _ = special_args(
block_fn.fn, processed_input, request, event_data
)
progress_tracker = (
processed_input[progress_index] if progress_index is not None else None
)
if progress_tracker is not None and progress_index is not None:
progress_tracker, fn = create_tracker(fn, progress_tracker.track_tqdm)
processed_input[progress_index] = progress_tracker
if inspect.iscoroutinefunction(fn):
prediction = await fn(*processed_input)
else:
prediction = await anyio.to_thread.run_sync(
fn, *processed_input, limiter=self.limiter
)
else:
prediction = None
if inspect.isgeneratorfunction(fn) or inspect.isasyncgenfunction(fn):
try:
if iterator is None:
iterator = cast(AsyncIterator[Any], prediction)
if inspect.isgenerator(iterator):
iterator = utils.SyncToAsyncIterator(iterator, self.limiter)
prediction = await utils.async_iteration(iterator)
is_generating = True
except StopAsyncIteration:
n_outputs = len(self.dependencies[fn_index].get("outputs"))
prediction = (
components._Keywords.FINISHED_ITERATING
if n_outputs == 1
else (components._Keywords.FINISHED_ITERATING,) * n_outputs
)
iterator = None
duration = time.time() - start
return {
"prediction": prediction,
"duration": duration,
"is_generating": is_generating,
"iterator": iterator,
}
def serialize_data(self, fn_index: int, inputs: list[Any]) -> list[Any]:
dependency = self.dependencies[fn_index]
processed_input = []
def format_file(s):
return FileData(path=s).model_dump()
for i, input_id in enumerate(dependency["inputs"]):
try:
block = self.blocks[input_id]
except KeyError as e:
raise InvalidBlockError(
f"Input component with id {input_id} used in {dependency['trigger']}() event is not defined in this gr.Blocks context. You are allowed to nest gr.Blocks contexts, but there must be a gr.Blocks context that contains all components and events."
) from e
if not isinstance(block, components.Component):
raise InvalidComponentError(
f"{block.__class__} Component with id {input_id} not a valid input component."
)
api_info = block.api_info()
if client_utils.value_is_file(api_info):
serialized_input = client_utils.traverse(
inputs[i],
format_file,
lambda s: client_utils.is_filepath(s)
or client_utils.is_http_url_like(s),
)
else:
serialized_input = inputs[i]
processed_input.append(serialized_input)
return processed_input
def deserialize_data(self, fn_index: int, outputs: list[Any]) -> list[Any]:
dependency = self.dependencies[fn_index]
predictions = []
for o, output_id in enumerate(dependency["outputs"]):
try:
block = self.blocks[output_id]
except KeyError as e:
raise InvalidBlockError(
f"Output component with id {output_id} used in {dependency['trigger']}() event not found in this gr.Blocks context. You are allowed to nest gr.Blocks contexts, but there must be a gr.Blocks context that contains all components and events."
) from e
if not isinstance(block, components.Component):
raise InvalidComponentError(
f"{block.__class__} Component with id {output_id} not a valid output component."
)
deserialized = client_utils.traverse(
outputs[o], lambda s: s["path"], client_utils.is_file_obj
)
predictions.append(deserialized)
return predictions
def validate_inputs(self, fn_index: int, inputs: list[Any]):
block_fn = self.fns[fn_index]
dependency = self.dependencies[fn_index]
dep_inputs = dependency["inputs"]
# This handles incorrect inputs when args are changed by a JS function
# Only check not enough args case, ignore extra arguments (for now)
# TODO: make this stricter?
if len(inputs) < len(dep_inputs):
name = (
f" ({block_fn.name})"
if block_fn.name and block_fn.name != "<lambda>"
else ""
)
wanted_args = []
received_args = []
for input_id in dep_inputs:
block = self.blocks[input_id]
wanted_args.append(str(block))
for inp in inputs:
v = f'"{inp}"' if isinstance(inp, str) else str(inp)
received_args.append(v)
wanted = ", ".join(wanted_args)
received = ", ".join(received_args)
# JS func didn't pass enough arguments
raise ValueError(
f"""An event handler{name} didn't receive enough input values (needed: {len(dep_inputs)}, got: {len(inputs)}).
Check if the event handler calls a Javascript function, and make sure its return value is correct.
Wanted inputs:
[{wanted}]
Received inputs:
[{received}]"""
)
def preprocess_data(
self,
fn_index: int,
inputs: list[Any],
state: SessionState | None,
explicit_call: bool = False,
):
state = state or SessionState(self)
block_fn = self.fns[fn_index]
dependency = self.dependencies[fn_index]
self.validate_inputs(fn_index, inputs)
if block_fn.preprocess:
processed_input = []
for i, input_id in enumerate(dependency["inputs"]):
try:
block = self.blocks[input_id]
except KeyError as e:
raise InvalidBlockError(
f"Input component with id {input_id} used in {dependency['trigger']}() event not found in this gr.Blocks context. You are allowed to nest gr.Blocks contexts, but there must be a gr.Blocks context that contains all components and events."
) from e
if not isinstance(block, components.Component):
raise InvalidComponentError(
f"{block.__class__} Component with id {input_id} not a valid input component."
)
if getattr(block, "stateful", False):
processed_input.append(state[input_id])
else:
if input_id in state:
block = state[input_id]
inputs_cached = processing_utils.move_files_to_cache(
inputs[i],
block,
check_in_upload_folder=not explicit_call,
)
if getattr(block, "data_model", None) and inputs_cached is not None:
if issubclass(block.data_model, GradioModel): # type: ignore
inputs_cached = block.data_model(**inputs_cached) # type: ignore
elif issubclass(block.data_model, GradioRootModel): # type: ignore
inputs_cached = block.data_model(root=inputs_cached) # type: ignore
processed_input.append(block.preprocess(inputs_cached))
else:
processed_input = inputs
return processed_input
def validate_outputs(self, fn_index: int, predictions: Any | list[Any]):
block_fn = self.fns[fn_index]
dependency = self.dependencies[fn_index]
dep_outputs = dependency["outputs"]
if not isinstance(predictions, (list, tuple)):
predictions = [predictions]
if len(predictions) < len(dep_outputs):
name = (
f" ({block_fn.name})"
if block_fn.name and block_fn.name != "<lambda>"
else ""
)
wanted_args = []
received_args = []
for output_id in dep_outputs:
block = self.blocks[output_id]
wanted_args.append(str(block))
for pred in predictions:
v = f'"{pred}"' if isinstance(pred, str) else str(pred)
received_args.append(v)
wanted = ", ".join(wanted_args)
received = ", ".join(received_args)
raise ValueError(
f"""An event handler{name} didn't receive enough output values (needed: {len(dep_outputs)}, received: {len(predictions)}).
Wanted outputs:
[{wanted}]
Received outputs:
[{received}]"""
)
def postprocess_data(
self, fn_index: int, predictions: list | dict, state: SessionState | None
):
state = state or SessionState(self)
block_fn = self.fns[fn_index]
dependency = self.dependencies[fn_index]
batch = dependency["batch"]
if isinstance(predictions, dict) and len(predictions) > 0:
predictions = convert_component_dict_to_list(
dependency["outputs"], predictions
)
if len(dependency["outputs"]) == 1 and not (batch):
predictions = [
predictions,
]
self.validate_outputs(fn_index, predictions) # type: ignore
output = []
for i, output_id in enumerate(dependency["outputs"]):
try:
if predictions[i] is components._Keywords.FINISHED_ITERATING:
output.append(None)
continue
except (IndexError, KeyError) as err:
raise ValueError(
"Number of output components does not match number "
f"of values returned from from function {block_fn.name}"
) from err
try:
block = self.blocks[output_id]
except KeyError as e:
raise InvalidBlockError(
f"Output component with id {output_id} used in {dependency['trigger']}() event not found in this gr.Blocks context. You are allowed to nest gr.Blocks contexts, but there must be a gr.Blocks context that contains all components and events."
) from e
if getattr(block, "stateful", False):
if not utils.is_update(predictions[i]):
state[output_id] = predictions[i]
output.append(None)
else:
prediction_value = predictions[i]
if utils.is_update(
prediction_value
): # if update is passed directly (deprecated), remove Nones
prediction_value = utils.delete_none(
prediction_value, skip_value=True
)
if isinstance(prediction_value, Block):
prediction_value = prediction_value.constructor_args.copy()
prediction_value["__type__"] = "update"
if utils.is_update(prediction_value):
if output_id in state:
kwargs = state[output_id].constructor_args.copy()
else:
kwargs = self.blocks[output_id].constructor_args.copy()
kwargs.update(prediction_value)
kwargs.pop("value", None)
kwargs.pop("__type__")
kwargs["render"] = False
state[output_id] = self.blocks[output_id].__class__(**kwargs)
prediction_value = postprocess_update_dict(
block=state[output_id],
update_dict=prediction_value,
postprocess=block_fn.postprocess,
)
elif block_fn.postprocess:
if not isinstance(block, components.Component):
raise InvalidComponentError(
f"{block.__class__} Component with id {output_id} not a valid output component."
)
if output_id in state:
block = state[output_id]
prediction_value = block.postprocess(prediction_value)
outputs_cached = processing_utils.move_files_to_cache(
prediction_value,
block,
postprocess=True,
)
output.append(outputs_cached)
return output
def handle_streaming_outputs(
self,
fn_index: int,
data: list,
session_hash: str | None,
run: int | None,
) -> list:
if session_hash is None or run is None:
return data
if run not in self.pending_streams[session_hash]:
self.pending_streams[session_hash][run] = {}
stream_run = self.pending_streams[session_hash][run]
for i, output_id in enumerate(self.dependencies[fn_index]["outputs"]):
block = self.blocks[output_id]
if isinstance(block, components.StreamingOutput) and block.streaming:
first_chunk = output_id not in stream_run
binary_data, output_data = block.stream_output(
data[i], f"{session_hash}/{run}/{output_id}", first_chunk
)
if first_chunk:
stream_run[output_id] = []
self.pending_streams[session_hash][run][output_id].append(binary_data)
data[i] = output_data
return data
def handle_streaming_diffs(
self,
fn_index: int,
data: list,
session_hash: str | None,
run: int | None,
final: bool,
simple_format: bool = False,
) -> list:
if session_hash is None or run is None:
return data
first_run = run not in self.pending_diff_streams[session_hash]
if first_run:
self.pending_diff_streams[session_hash][run] = [None] * len(data)
last_diffs = self.pending_diff_streams[session_hash][run]
for i in range(len(self.dependencies[fn_index]["outputs"])):
if final:
data[i] = last_diffs[i]
continue
if first_run:
last_diffs[i] = data[i]
else:
prev_chunk = last_diffs[i]
last_diffs[i] = data[i]
if not simple_format:
data[i] = utils.diff(prev_chunk, data[i])
if final:
del self.pending_diff_streams[session_hash][run]
return data
async def process_api(
self,
fn_index: int,
inputs: list[Any],
state: SessionState | None = None,
request: routes.Request | list[routes.Request] | None = None,
iterator: AsyncIterator | None = None,
session_hash: str | None = None,
event_id: str | None = None,
event_data: EventData | None = None,
in_event_listener: bool = True,
simple_format: bool = False,
explicit_call: bool = False,
root_path: str | None = None,
) -> dict[str, Any]:
"""
Processes API calls from the frontend. First preprocesses the data,
then runs the relevant function, then postprocesses the output.
Parameters:
fn_index: Index of function to run.
inputs: input data received from the frontend
state: data stored from stateful components for session (key is input block id)
request: the gr.Request object containing information about the network request (e.g. IP address, headers, query parameters, username)
iterators: the in-progress iterators for each generator function (key is function index)
event_id: id of event that triggered this API call
event_data: data associated with the event trigger itself
in_event_listener: whether this API call is being made in response to an event listener
explicit_call: whether this call is being made directly by calling the Blocks function, instead of through an event listener or API route
root_path: if provided, the root path of the server. All file URLs will be prefixed with this path.
Returns: None
"""
block_fn = self.fns[fn_index]
batch = self.dependencies[fn_index]["batch"]
if batch:
max_batch_size = self.dependencies[fn_index]["max_batch_size"]
batch_sizes = [len(inp) for inp in inputs]
batch_size = batch_sizes[0]
if inspect.isasyncgenfunction(block_fn.fn) or inspect.isgeneratorfunction(
block_fn.fn
):
raise ValueError("Gradio does not support generators in batch mode.")
if not all(x == batch_size for x in batch_sizes):
raise ValueError(
f"All inputs to a batch function must have the same length but instead have sizes: {batch_sizes}."
)
if batch_size > max_batch_size:
raise ValueError(
f"Batch size ({batch_size}) exceeds the max_batch_size for this function ({max_batch_size})"
)
inputs = [
self.preprocess_data(fn_index, list(i), state, explicit_call)
for i in zip(*inputs)
]
result = await self.call_function(
fn_index,
list(zip(*inputs)),
None,
request,
event_id,
event_data,
in_event_listener,
)
preds = result["prediction"]
data = [
self.postprocess_data(fn_index, list(o), state) for o in zip(*preds)
]
if root_path is not None:
data = processing_utils.add_root_url(data, root_path, None)
data = list(zip(*data))
is_generating, iterator = None, None
else:
old_iterator = iterator
if old_iterator:
inputs = []
else:
inputs = self.preprocess_data(fn_index, inputs, state, explicit_call)
was_generating = old_iterator is not None
result = await self.call_function(
fn_index,
inputs,
old_iterator,
request,
event_id,
event_data,
in_event_listener,
)
data = self.postprocess_data(fn_index, result["prediction"], state)
if root_path is not None:
data = processing_utils.add_root_url(data, root_path, None)
is_generating, iterator = result["is_generating"], result["iterator"]
if is_generating or was_generating:
run = id(old_iterator) if was_generating else id(iterator)
data = self.handle_streaming_outputs(
fn_index,
data,
session_hash=session_hash,
run=run,
)
data = self.handle_streaming_diffs(
fn_index,
data,
session_hash=session_hash,
run=run,
final=not is_generating,
simple_format=simple_format,
)
block_fn.total_runtime += result["duration"]
block_fn.total_runs += 1
return {
"data": data,
"is_generating": is_generating,
"iterator": iterator,
"duration": result["duration"],
"average_duration": block_fn.total_runtime / block_fn.total_runs,
}
def create_limiter(self):
self.limiter = (
None
if self.max_threads == 40
else CapacityLimiter(total_tokens=self.max_threads)
)
def get_config(self):
return {"type": "column"}
def get_config_file(self):
config = {
"version": routes.VERSION,
"mode": self.mode,
"app_id": self.app_id,
"dev_mode": self.dev_mode,
"analytics_enabled": self.analytics_enabled,
"components": [],
"css": self.css,
"js": self.js,
"head": self.head,
"title": self.title or "Gradio",
"space_id": self.space_id,
"enable_queue": True, # launch attributes
"show_error": getattr(self, "show_error", False),
"show_api": self.show_api,
"is_colab": utils.colab_check(),
"stylesheets": self.stylesheets,
"theme": self.theme.name,
"protocol": "sse_v3",
"body_css": {
"body_background_fill": self.theme._get_computed_value(
"body_background_fill"
),
"body_text_color": self.theme._get_computed_value("body_text_color"),
"body_background_fill_dark": self.theme._get_computed_value(
"body_background_fill_dark"
),
"body_text_color_dark": self.theme._get_computed_value(
"body_text_color_dark"
),
},
"fill_height": self.fill_height,
}
def get_layout(block):
if not isinstance(block, BlockContext):
return {"id": block._id}
children_layout = []
for child in block.children:
children_layout.append(get_layout(child))
return {"id": block._id, "children": children_layout}
config["layout"] = get_layout(self)
for _id, block in self.blocks.items():
props = block.get_config() if hasattr(block, "get_config") else {}
block_config = {
"id": _id,
"type": block.get_block_name(),
"props": utils.delete_none(props),
}
block_config["skip_api"] = block.skip_api
block_config["component_class_id"] = getattr(
block, "component_class_id", None
)
if not block.skip_api:
block_config["api_info"] = block.api_info() # type: ignore
# .example_inputs() has been renamed .example_payload() but
# we use the old name for backwards compatibility with custom components
# created on Gradio 4.20.0 or earlier
block_config["example_inputs"] = block.example_inputs() # type: ignore
config["components"].append(block_config)
config["dependencies"] = self.dependencies
return config
def __enter__(self):
if Context.block is None:
Context.root_block = self
self.parent = Context.block
Context.block = self
self.exited = False
return self
def __exit__(self, exc_type: type[BaseException] | None = None, *args):
if exc_type is not None:
Context.block = None
Context.root_block = None
return
super().fill_expected_parents()
Context.block = self.parent
# Configure the load events before root_block is reset
self.attach_load_events()
if self.parent is None:
Context.root_block = None
else:
self.parent.children.extend(self.children)
self.config = self.get_config_file()
self.app = routes.App.create_app(self)
self.progress_tracking = any(block_fn.tracks_progress for block_fn in self.fns)
self.exited = True
def clear(self):
"""Resets the layout of the Blocks object."""
self.blocks = {}
self.fns = []
self.dependencies = []
self.children = []
return self
@document()
def queue(
self,
status_update_rate: float | Literal["auto"] = "auto",
api_open: bool | None = None,
max_size: int | None = None,
concurrency_count: int | None = None,
*,
default_concurrency_limit: int | None | Literal["not_set"] = "not_set",
):
"""
By enabling the queue you can control when users know their position in the queue, and set a limit on maximum number of events allowed.
Parameters:
status_update_rate: If "auto", Queue will send status estimations to all clients whenever a job is finished. Otherwise Queue will send status at regular intervals set by this parameter as the number of seconds.
api_open: If True, the REST routes of the backend will be open, allowing requests made directly to those endpoints to skip the queue.
max_size: The maximum number of events the queue will store at any given moment. If the queue is full, new events will not be added and a user will receive a message saying that the queue is full. If None, the queue size will be unlimited.
concurrency_count: Deprecated. Set the concurrency_limit directly on event listeners e.g. btn.click(fn, ..., concurrency_limit=10) or gr.Interface(concurrency_limit=10). If necessary, the total number of workers can be configured via `max_threads` in launch().
default_concurrency_limit: The default value of `concurrency_limit` to use for event listeners that don't specify a value. Can be set by environment variable GRADIO_DEFAULT_CONCURRENCY_LIMIT. Defaults to 1 if not set otherwise.
Example: (Blocks)
with gr.Blocks() as demo:
button = gr.Button(label="Generate Image")
button.click(fn=image_generator, inputs=gr.Textbox(), outputs=gr.Image())
demo.queue(max_size=10)
demo.launch()
Example: (Interface)
demo = gr.Interface(image_generator, gr.Textbox(), gr.Image())
demo.queue(max_size=20)
demo.launch()
"""
if concurrency_count:
raise DeprecationWarning(
"concurrency_count has been deprecated. Set the concurrency_limit directly on event listeners e.g. btn.click(fn, ..., concurrency_limit=10) or gr.Interface(concurrency_limit=10). If necessary, the total number of workers can be configured via `max_threads` in launch()."
)
if api_open is not None:
self.api_open = api_open
if utils.is_zero_gpu_space():
max_size = 1 if max_size is None else max_size
self._queue = queueing.Queue(
live_updates=status_update_rate == "auto",
concurrency_count=self.max_threads,
update_intervals=status_update_rate if status_update_rate != "auto" else 1,
max_size=max_size,
block_fns=self.fns,
default_concurrency_limit=default_concurrency_limit,
)
self.config = self.get_config_file()
self.app = routes.App.create_app(self)
return self
def validate_queue_settings(self):
for dep in self.dependencies:
for i in dep["cancels"]:
if not self.queue_enabled_for_fn(i):
raise ValueError(
"Queue needs to be enabled! "
"You may get this error by either 1) passing a function that uses the yield keyword "
"into an interface without enabling the queue or 2) defining an event that cancels "
"another event without enabling the queue. Both can be solved by calling .queue() "
"before .launch()"
)
if dep["batch"] and dep["queue"] is False:
raise ValueError("In order to use batching, the queue must be enabled.")
def launch(
self,
inline: bool | None = None,
inbrowser: bool = False,
share: bool | None = None,
debug: bool = False,
max_threads: int = 40,
auth: Callable | tuple[str, str] | list[tuple[str, str]] | None = None,
auth_message: str | None = None,
prevent_thread_lock: bool = False,
show_error: bool = False,
server_name: str | None = None,
server_port: int | None = None,
*,
height: int = 500,
width: int | str = "100%",
favicon_path: str | None = None,
ssl_keyfile: str | None = None,
ssl_certfile: str | None = None,
ssl_keyfile_password: str | None = None,
ssl_verify: bool = True,
quiet: bool = False,
show_api: bool = True,
allowed_paths: list[str] | None = None,
blocked_paths: list[str] | None = None,
root_path: str | None = None,
app_kwargs: dict[str, Any] | None = None,
state_session_capacity: int = 10000,
share_server_address: str | None = None,
share_server_protocol: Literal["http", "https"] | None = None,
auth_dependency: Callable[[fastapi.Request], str | None] | None = None,
_frontend: bool = True,
) -> tuple[FastAPI, str, str]:
"""
Launches a simple web server that serves the demo. Can also be used to create a
public link used by anyone to access the demo from their browser by setting share=True.
Parameters:
inline: whether to display in the gradio app inline in an iframe. Defaults to True in python notebooks; False otherwise.
inbrowser: whether to automatically launch the gradio app in a new tab on the default browser.
share: whether to create a publicly shareable link for the gradio app. Creates an SSH tunnel to make your UI accessible from anywhere. If not provided, it is set to False by default every time, except when running in Google Colab. When localhost is not accessible (e.g. Google Colab), setting share=False is not supported.
debug: if True, blocks the main thread from running. If running in Google Colab, this is needed to print the errors in the cell output.
auth: If provided, username and password (or list of username-password tuples) required to access app. Can also provide function that takes username and password and returns True if valid login.
auth_message: If provided, HTML message provided on login page.
prevent_thread_lock: By default, the gradio app blocks the main thread while the server is running. If set to True, the gradio app will not block and the gradio server will terminate as soon as the script finishes.
show_error: If True, any errors in the gradio app will be displayed in an alert modal and printed in the browser console log
server_port: will start gradio app on this port (if available). Can be set by environment variable GRADIO_SERVER_PORT. If None, will search for an available port starting at 7860.
server_name: to make app accessible on local network, set this to "0.0.0.0". Can be set by environment variable GRADIO_SERVER_NAME. If None, will use "127.0.0.1".
max_threads: the maximum number of total threads that the Gradio app can generate in parallel. The default is inherited from the starlette library (currently 40).
width: The width in pixels of the iframe element containing the gradio app (used if inline=True)
height: The height in pixels of the iframe element containing the gradio app (used if inline=True)
favicon_path: If a path to a file (.png, .gif, or .ico) is provided, it will be used as the favicon for the web page.
ssl_keyfile: If a path to a file is provided, will use this as the private key file to create a local server running on https.
ssl_certfile: If a path to a file is provided, will use this as the signed certificate for https. Needs to be provided if ssl_keyfile is provided.
ssl_keyfile_password: If a password is provided, will use this with the ssl certificate for https.
ssl_verify: If False, skips certificate validation which allows self-signed certificates to be used.
quiet: If True, suppresses most print statements.
show_api: If True, shows the api docs in the footer of the app. Default True.
allowed_paths: List of complete filepaths or parent directories that gradio is allowed to serve. Must be absolute paths. Warning: if you provide directories, any files in these directories or their subdirectories are accessible to all users of your app.
blocked_paths: List of complete filepaths or parent directories that gradio is not allowed to serve (i.e. users of your app are not allowed to access). Must be absolute paths. Warning: takes precedence over `allowed_paths` and all other directories exposed by Gradio by default.
root_path: The root path (or "mount point") of the application, if it's not served from the root ("/") of the domain. Often used when the application is behind a reverse proxy that forwards requests to the application. For example, if the application is served at "https://example.com/myapp", the `root_path` should be set to "/myapp". A full URL beginning with http:// or https:// can be provided, which will be used as the root path in its entirety. Can be set by environment variable GRADIO_ROOT_PATH. Defaults to "".
app_kwargs: Additional keyword arguments to pass to the underlying FastAPI app as a dictionary of parameter keys and argument values. For example, `{"docs_url": "/docs"}`
state_session_capacity: The maximum number of sessions whose information to store in memory. If the number of sessions exceeds this number, the oldest sessions will be removed. Reduce capacity to reduce memory usage when using gradio.State or returning updated components from functions. Defaults to 10000.
share_server_address: Use this to specify a custom FRP server and port for sharing Gradio apps (only applies if share=True). If not provided, will use the default FRP server at https://gradio.live. See https://github.com/huggingface/frp for more information.
share_server_protocol: Use this to specify the protocol to use for the share links. Defaults to "https", unless a custom share_server_address is provided, in which case it defaults to "http". If you are using a custom share_server_address and want to use https, you must set this to "https".
auth_dependency: A function that takes a FastAPI request and returns a string user ID or None. If the function returns None for a specific request, that user is not authorized to access the app (they will see a 401 Unauthorized response). To be used with external authentication systems like OAuth. Cannot be used with `auth`.
Returns:
app: FastAPI app object that is running the demo
local_url: Locally accessible link to the demo
share_url: Publicly accessible link to the demo (if share=True, otherwise None)
Example: (Blocks)
import gradio as gr
def reverse(text):
return text[::-1]
with gr.Blocks() as demo:
button = gr.Button(value="Reverse")
button.click(reverse, gr.Textbox(), gr.Textbox())
demo.launch(share=True, auth=("username", "password"))
Example: (Interface)
import gradio as gr
def reverse(text):
return text[::-1]
demo = gr.Interface(reverse, "text", "text")
demo.launch(share=True, auth=("username", "password"))
"""
if self._is_running_in_reload_thread:
# We have already launched the demo
return None, None, None # type: ignore
if not self.exited:
self.__exit__()
if auth is not None and auth_dependency is not None:
raise ValueError(
"You cannot provide both `auth` and `auth_dependency` in launch(). Please choose one."
)
if (
auth
and not callable(auth)
and not isinstance(auth[0], tuple)
and not isinstance(auth[0], list)
):
self.auth = [auth]
else:
self.auth = auth
self.auth_message = auth_message
self.show_error = show_error
self.height = height
self.width = width
self.favicon_path = favicon_path
self.ssl_verify = ssl_verify
self.state_session_capacity = state_session_capacity
if root_path is None:
self.root_path = os.environ.get("GRADIO_ROOT_PATH", "")
else:
self.root_path = root_path
self.show_api = show_api
self.allowed_paths = allowed_paths or []
self.blocked_paths = blocked_paths or []
if not isinstance(self.allowed_paths, list):
raise ValueError("`allowed_paths` must be a list of directories.")
if not isinstance(self.blocked_paths, list):
raise ValueError("`blocked_paths` must be a list of directories.")
self.validate_queue_settings()
self.config = self.get_config_file()
self.max_threads = max_threads
self._queue.max_thread_count = max_threads
if self.is_running:
if not isinstance(self.local_url, str):
raise ValueError(f"Invalid local_url: {self.local_url}")
if not (quiet):
print(
"Rerunning server... use `close()` to stop if you need to change `launch()` parameters.\n----"
)
else:
if wasm_utils.IS_WASM:
server_name = "xxx"
server_port = 99999
local_url = ""
server = None
# In the Wasm environment, we only need the app object
# which the frontend app will directly communicate with through the Worker API,
# and we don't need to start a server.
# So we just create the app object and register it here,
# and avoid using `networking.start_server` that would start a server that don't work in the Wasm env.
from gradio.routes import App
app = App.create_app(
self, auth_dependency=auth_dependency, app_kwargs=app_kwargs
)
wasm_utils.register_app(app)
else:
from gradio import http_server
(
server_name,
server_port,
local_url,
app,
server,
) = http_server.start_server(
self,
server_name,
server_port,
ssl_keyfile,
ssl_certfile,
ssl_keyfile_password,
app_kwargs=app_kwargs,
)
self.server_name = server_name
self.local_url = local_url
self.server_port = server_port
self.server_app = (
self.app
) = app # server_app is included for backwards compatibility
self.server = server
self.is_running = True
self.is_colab = utils.colab_check()
self.is_kaggle = utils.kaggle_check()
self.share_server_address = share_server_address
self.share_server_protocol = share_server_protocol or (
"http" if share_server_address is not None else "https"
)
self.protocol = (
"https"
if self.local_url.startswith("https") or self.is_colab
else "http"
)
if not wasm_utils.IS_WASM and not self.is_colab:
print(
strings.en["RUNNING_LOCALLY_SEPARATED"].format(
self.protocol, self.server_name, self.server_port
)
)
self._queue.set_server_app(self.server_app)
if not wasm_utils.IS_WASM:
# Cannot run async functions in background other than app's scope.
# Workaround by triggering the app endpoint
httpx.get(
f"{self.local_url}startup-events", verify=ssl_verify, timeout=None
)
else:
# NOTE: One benefit of the code above dispatching `startup_events()` via a self HTTP request is
# that `self._queue.start()` is called in another thread which is managed by the HTTP server, `uvicorn`
# so all the asyncio tasks created by the queue runs in an event loop in that thread and
# will be cancelled just by stopping the server.
# In contrast, in the Wasm env, we can't do that because `threading` is not supported and all async tasks will run in the same event loop, `pyodide.webloop.WebLoop` in the main thread.
# So we need to manually cancel them. See `self.close()`..
self.startup_events()
utils.launch_counter()
self.is_sagemaker = utils.sagemaker_check()
if share is None:
if self.is_colab:
if not quiet:
print(
"Setting queue=True in a Colab notebook requires sharing enabled. Setting `share=True` (you can turn this off by setting `share=False` in `launch()` explicitly).\n"
)
self.share = True
elif self.is_kaggle:
if not quiet:
print(
"Kaggle notebooks require sharing enabled. Setting `share=True` (you can turn this off by setting `share=False` in `launch()` explicitly).\n"
)
self.share = True
elif self.is_sagemaker:
if not quiet:
print(
"Sagemaker notebooks may require sharing enabled. Setting `share=True` (you can turn this off by setting `share=False` in `launch()` explicitly).\n"
)
self.share = True
else:
self.share = False
else:
self.share = share
# If running in a colab or not able to access localhost,
# a shareable link must be created.
if (
_frontend
and not wasm_utils.IS_WASM
and not networking.url_ok(self.local_url)
and not self.share
):
raise ValueError(
"When localhost is not accessible, a shareable link must be created. Please set share=True or check your proxy settings to allow access to localhost."
)
if self.is_colab and not quiet:
if debug:
print(strings.en["COLAB_DEBUG_TRUE"])
else:
print(strings.en["COLAB_DEBUG_FALSE"])
if not self.share:
print(strings.en["COLAB_WARNING"].format(self.server_port))
if self.share:
if self.space_id:
warnings.warn(
"Setting share=True is not supported on Hugging Face Spaces"
)
self.share = False
if wasm_utils.IS_WASM:
warnings.warn(
"Setting share=True is not supported in the Wasm environment"
)
self.share = False
if self.share:
try:
if self.share_url is None:
share_url = networking.setup_tunnel(
local_host=self.server_name,
local_port=self.server_port,
share_token=self.share_token,
share_server_address=self.share_server_address,
)
parsed_url = urlparse(share_url)
self.share_url = urlunparse(
(self.share_server_protocol,) + parsed_url[1:]
)
print(strings.en["SHARE_LINK_DISPLAY"].format(self.share_url))
if not (quiet):
print(strings.en["SHARE_LINK_MESSAGE"])
except (RuntimeError, httpx.ConnectError):
if self.analytics_enabled:
analytics.error_analytics("Not able to set up tunnel")
self.share_url = None
self.share = False
if Path(BINARY_PATH).exists():
print(strings.en["COULD_NOT_GET_SHARE_LINK"])
else:
print(
strings.en["COULD_NOT_GET_SHARE_LINK_MISSING_FILE"].format(
BINARY_PATH,
BINARY_URL,
BINARY_FILENAME,
BINARY_FOLDER,
)
)
else:
if not quiet and not wasm_utils.IS_WASM:
print(strings.en["PUBLIC_SHARE_TRUE"])
self.share_url = None
if inbrowser and not wasm_utils.IS_WASM:
link = self.share_url if self.share and self.share_url else self.local_url
webbrowser.open(link)
# Check if running in a Python notebook in which case, display inline
if inline is None:
inline = utils.ipython_check()
if inline:
try:
from IPython.display import HTML, Javascript, display # type: ignore
if self.share and self.share_url:
while not networking.url_ok(self.share_url):
time.sleep(0.25)
artifact = HTML(
f'<div><iframe src="{self.share_url}" width="{self.width}" height="{self.height}" allow="autoplay; camera; microphone; clipboard-read; clipboard-write;" frameborder="0" allowfullscreen></iframe></div>'
)
elif self.is_colab:
# modified from /usr/local/lib/python3.7/dist-packages/google/colab/output/_util.py within Colab environment
code = """(async (port, path, width, height, cache, element) => {
if (!google.colab.kernel.accessAllowed && !cache) {
return;
}
element.appendChild(document.createTextNode(''));
const url = await google.colab.kernel.proxyPort(port, {cache});
const external_link = document.createElement('div');
external_link.innerHTML = `
<div style="font-family: monospace; margin-bottom: 0.5rem">
Running on <a href=${new URL(path, url).toString()} target="_blank">
https://localhost:${port}${path}
</a>
</div>
`;
element.appendChild(external_link);
const iframe = document.createElement('iframe');
iframe.src = new URL(path, url).toString();
iframe.height = height;
iframe.allow = "autoplay; camera; microphone; clipboard-read; clipboard-write;"
iframe.width = width;
iframe.style.border = 0;
element.appendChild(iframe);
})""" + "({port}, {path}, {width}, {height}, {cache}, window.element)".format(
port=json.dumps(self.server_port),
path=json.dumps("/"),
width=json.dumps(self.width),
height=json.dumps(self.height),
cache=json.dumps(False),
)
artifact = Javascript(code)
else:
artifact = HTML(
f'<div><iframe src="{self.local_url}" width="{self.width}" height="{self.height}" allow="autoplay; camera; microphone; clipboard-read; clipboard-write;" frameborder="0" allowfullscreen></iframe></div>'
)
self.artifact = artifact
display(artifact)
except ImportError:
pass
if getattr(self, "analytics_enabled", False):
data = {
"launch_method": "browser" if inbrowser else "inline",
"is_google_colab": self.is_colab,
"is_sharing_on": self.share,
"share_url": self.share_url,
"enable_queue": True,
"server_name": server_name,
"server_port": server_port,
"is_space": self.space_id is not None,
"mode": self.mode,
}
analytics.launched_analytics(self, data)
# Block main thread if debug==True
if debug or int(os.getenv("GRADIO_DEBUG", "0")) == 1 and not wasm_utils.IS_WASM:
self.block_thread()
# Block main thread if running in a script to stop script from exiting
is_in_interactive_mode = bool(getattr(sys, "ps1", sys.flags.interactive))
if (
not prevent_thread_lock
and not is_in_interactive_mode
# In the Wasm env, we don't have to block the main thread because the server won't be shut down after the execution finishes.
# Moreover, we MUST NOT do it because there is only one thread in the Wasm env and blocking it will stop the subsequent code from running.
and not wasm_utils.IS_WASM
):
self.block_thread()
return TupleNoPrint((self.server_app, self.local_url, self.share_url)) # type: ignore
def integrate(
self,
comet_ml=None,
wandb: ModuleType | None = None,
mlflow: ModuleType | None = None,
) -> None:
"""
A catch-all method for integrating with other libraries. This method should be run after launch()
Parameters:
comet_ml: If a comet_ml Experiment object is provided, will integrate with the experiment and appear on Comet dashboard
wandb: If the wandb module is provided, will integrate with it and appear on WandB dashboard
mlflow: If the mlflow module is provided, will integrate with the experiment and appear on ML Flow dashboard
"""
analytics_integration = ""
if comet_ml is not None:
analytics_integration = "CometML"
comet_ml.log_other("Created from", "Gradio")
if self.share_url is not None:
comet_ml.log_text(f"gradio: {self.share_url}")
comet_ml.end()
elif self.local_url:
comet_ml.log_text(f"gradio: {self.local_url}")
comet_ml.end()
else:
raise ValueError("Please run `launch()` first.")
if wandb is not None:
analytics_integration = "WandB"
if self.share_url is not None:
wandb.log(
{
"Gradio panel": wandb.Html(
'<iframe src="'
+ self.share_url
+ '" width="'
+ str(self.width)
+ '" height="'
+ str(self.height)
+ '" frameBorder="0"></iframe>'
)
}
)
else:
print(
"The WandB integration requires you to "
"`launch(share=True)` first."
)
if mlflow is not None:
analytics_integration = "MLFlow"
if self.share_url is not None:
mlflow.log_param("Gradio Interface Share Link", self.share_url)
else:
mlflow.log_param("Gradio Interface Local Link", self.local_url)
if self.analytics_enabled and analytics_integration:
data = {"integration": analytics_integration}
analytics.integration_analytics(data)
def close(self, verbose: bool = True) -> None:
"""
Closes the Interface that was launched and frees the port.
"""
try:
if wasm_utils.IS_WASM:
# NOTE:
# Normally, queue-related async tasks (e.g. continuous events created by `gr.Blocks.load(..., every=interval)`, whose async tasks are started at the `/queue/data` endpoint function)
# are running in an event loop in the server thread,
# so they will be cancelled by `self.server.close()` below.
# However, in the Wasm env, we don't have the `server` and
# all async tasks are running in the same event loop, `pyodide.webloop.WebLoop` in the main thread,
# so we have to cancel them explicitly so that these tasks won't run after a new app is launched.
self._queue._cancel_asyncio_tasks()
self.server_app._cancel_asyncio_tasks()
self._queue.close()
if self.server:
self.server.close()
self.is_running = False
# So that the startup events (starting the queue)
# happen the next time the app is launched
self.app.startup_events_triggered = False
if verbose:
print(f"Closing server running on port: {self.server_port}")
except (AttributeError, OSError): # can't close if not running
pass
def block_thread(
self,
) -> None:
"""Block main thread until interrupted by user."""
try:
while True:
time.sleep(0.1)
except (KeyboardInterrupt, OSError):
print("Keyboard interruption in main thread... closing server.")
if self.server:
self.server.close()
for tunnel in CURRENT_TUNNELS:
tunnel.kill()
def attach_load_events(self):
"""Add a load event for every component whose initial value should be randomized."""
if Context.root_block:
for component in Context.root_block.blocks.values():
if (
isinstance(component, components.Component)
and component.load_event_to_attach
):
load_fn, every = component.load_event_to_attach
# Use set_event_trigger to avoid ambiguity between load class/instance method
dep = self.set_event_trigger(
[EventListenerMethod(self, "load")],
load_fn,
None,
component,
no_target=True,
# If every is None, for sure skip the queue
# else, let the enable_queue parameter take precedence
# this will raise a nice error message is every is used
# without queue
queue=False if every is None else None,
every=every,
)[0]
component.load_event = dep
def startup_events(self):
"""Events that should be run when the app containing this block starts up."""
self._queue.start()
# So that processing can resume in case the queue was stopped
self._queue.stopped = False
self.create_limiter()
def queue_enabled_for_fn(self, fn_index: int):
return self.dependencies[fn_index]["queue"] is not False
def get_api_info(self):
"""
Gets the information needed to generate the API docs from a Blocks.
"""
config = self.config
api_info = {"named_endpoints": {}, "unnamed_endpoints": {}}
for dependency, fn in zip(config["dependencies"], self.fns):
if (
not dependency["backend_fn"]
or not dependency["show_api"]
or dependency["api_name"] is False
):
continue
dependency_info = {"parameters": [], "returns": []}
fn_info = utils.get_function_params(fn.fn) # type: ignore
skip_endpoint = False
inputs = dependency["inputs"]
for index, input_id in enumerate(inputs):
for component in config["components"]:
if component["id"] == input_id:
break
else:
skip_endpoint = True # if component not found, skip endpoint
break
type = component["props"]["name"]
if self.blocks[component["id"]].skip_api:
continue
label = component["props"].get("label", f"parameter_{input_id}")
comp = self.get_component(component["id"])
if not isinstance(comp, components.Component):
raise TypeError(f"{comp!r} is not a Component")
info = component["api_info"]
example = comp.example_inputs()
python_type = client_utils.json_schema_to_python_type(info)
# Since the clients use "api_name" and "fn_index" to designate the endpoint and
# "result_callbacks" to specify the callbacks, we need to make sure that no parameters
# have those names. Hence the final checks.
if (
dependency["backend_fn"]
and index < len(fn_info)
and fn_info[index][0]
not in ["api_name", "fn_index", "result_callbacks"]
):
parameter_name = fn_info[index][0]
else:
parameter_name = f"param_{index}"
# How default values are set for the client: if a component has an initial value, then that parameter
# is optional in the client and the initial value from the config is used as default in the client.
# If the component does not have an initial value, but if the corresponding argument in the predict function has
# a default value of None, then that parameter is also optional in the client and the None is used as default in the client.
if component["props"].get("value") is not None:
parameter_has_default = True
parameter_default = component["props"]["value"]
elif (
dependency["backend_fn"]
and index < len(fn_info)
and fn_info[index][1]
and fn_info[index][2] is None
):
parameter_has_default = True
parameter_default = None
else:
parameter_has_default = False
parameter_default = None
dependency_info["parameters"].append(
{
"label": label,
"parameter_name": parameter_name,
"parameter_has_default": parameter_has_default,
"parameter_default": parameter_default,
"type": info,
"python_type": {
"type": python_type,
"description": info.get("description", ""),
},
"component": type.capitalize(),
"example_input": example,
}
)
outputs = dependency["outputs"]
for o in outputs:
for component in config["components"]:
if component["id"] == o:
break
else:
skip_endpoint = True # if component not found, skip endpoint
break
type = component["props"]["name"]
if self.blocks[component["id"]].skip_api:
continue
label = component["props"].get("label", f"value_{o}")
comp = self.get_component(component["id"])
if not isinstance(comp, components.Component):
raise TypeError(f"{comp!r} is not a Component")
info = component["api_info"]
example = comp.example_inputs()
python_type = client_utils.json_schema_to_python_type(info)
dependency_info["returns"].append(
{
"label": label,
"type": info,
"python_type": {
"type": python_type,
"description": info.get("description", ""),
},
"component": type.capitalize(),
}
)
if not skip_endpoint:
api_info["named_endpoints"][
f"/{dependency['api_name']}"
] = dependency_info
return api_info
|
b640ab6dcda109c7fe96284b1ccec2ab
|
{
"intermediate": 0.3583865761756897,
"beginner": 0.4475897252559662,
"expert": 0.19402369856834412
}
|
44,741
|
What would happen if I tried to run this python code:
"a = [None]
a[0] = a
print(a)"
|
394bb203f785e0eac2e6ee24a6934284
|
{
"intermediate": 0.21149836480617523,
"beginner": 0.6288285255432129,
"expert": 0.1596730798482895
}
|
44,742
|
make a script to extract the name and link of the teams in the source code of:
https://logs.stormforge.gg/en/ladder/netherwing/2v2
|
7ac0511a5d28534d8585d16e071392b7
|
{
"intermediate": 0.31886687874794006,
"beginner": 0.2236090749502182,
"expert": 0.45752406120300293
}
|
44,743
|
Hello
|
b7c5b5e38d0168f65668d265b86af6bf
|
{
"intermediate": 0.3123404085636139,
"beginner": 0.2729349136352539,
"expert": 0.4147246778011322
}
|
44,744
|
act as a smart-contracts developer. I want to ask you to generate a smart-contract using FunC language for minting NFTs on a TON Blockchain.
|
f8905a19f3dc28652cbc64acefa000ee
|
{
"intermediate": 0.2707747519016266,
"beginner": 0.3982144892215729,
"expert": 0.33101075887680054
}
|
44,745
|
Consider the following class:
class Asteroid{
private String name;
private double diameter;
public Asteroid (String name, double diameter) {
this.setName (name);
this.setDiameter (diameter);
}
public String getName() {
return name;
}
public void setName (String name) {
}
this.name = name;
public double getDiameter() {
return diameter;
}
public void setDiameter (double diameter) {
1
this.diameter = = diameter;
public String toString() {
return String.format("%s [8.2f]", getName(), getDiameter());
}
}
are Platfor X
Test is in progress
X
+
testing.inlumon.com/progress/y3wafwp
Now consider the following code:
import java.util.ArrayList;
import java.util.List;
public class Lambda2 {
public static void main(String args[]) {
List<Asteroid> asteroids = new ArrayList<~>(); asteroids.add(new Asteroid ("Sylvia", 286)); asteroids.add(new Asteroid ("Pallas", 512));
asteroids.add(new Asteroid ("Eunomia", 268)); asteroids.add(new Asteroid ("Juno", 258)); asteroids.add(new Asteroid ("Hygiea", 431)); asteroids.add(new Asteroid ("Davida", 289));
Asteroid c = asteroids
.stream()
reduce (asteroids.get (0),
System.out.println(c);
(a, b) -> a.getDiameter () > b.getDiameter() ? a : b);
}
}
What will this code output when compiled and run?
|
819061d86bacc8f0fbb9e9891650814d
|
{
"intermediate": 0.41372495889663696,
"beginner": 0.38868996500968933,
"expert": 0.1975851058959961
}
|
44,746
|
What are | and & operations in C? Give me an example.
|
90f8b40d75ba1b65f11a6d59416662ac
|
{
"intermediate": 0.294350802898407,
"beginner": 0.41487112641334534,
"expert": 0.2907780408859253
}
|
44,747
|
In convex optimization, how can you solve it?
|
82548be5a5130ed8c248d501a885d4b2
|
{
"intermediate": 0.06549543142318726,
"beginner": 0.06986772269010544,
"expert": 0.8646368980407715
}
|
44,748
|
I need to be able to draw a line from the players head to the camera and determine if any voxels are in between them. Then, snap the camera position to the open space to the player. How do I start?
|
ba634768dc27bf8d9cf6052c33b5cad8
|
{
"intermediate": 0.37139198184013367,
"beginner": 0.21719779074192047,
"expert": 0.41141024231910706
}
|
44,749
|
hi there , please be a sapui5 senior developer and answer my question with working code example.
|
413c49378f3ce01b0c9fa5fc12daa409
|
{
"intermediate": 0.42833542823791504,
"beginner": 0.23615218698978424,
"expert": 0.3355123996734619
}
|
44,750
|
1_ Translate the following legal text into colloquial Farsi 2_ Place the Persian and English text side by side in the table 3_ From the beginning to the end of the text, there should be an English sentence on the left side and a Persian sentence on the right side.
4- Using legal language for Persian translation
.The police were granted powers to investigate suspected violations of the
law.
A detective is employed to investigate persons suspected of murder.
penal / 'pi:nl / having to do with the crimes and their punishment.
There are some attempts to improve the courts, legal profession, police, and penal system.
Iran's penal code is divided into a general part and a special part.
The forfeiture imposed on persons convicted of a felony is part of the penal law of most countries.
prevent / pri'vent / stop someone doing something; keep from happening.
Your prompt action prevented a serious accident.
One of the purposes of law is to protect public health and prevent fraud in the
sale of adulterated foods.
It is easier to prevent crimes than to undo the damage later.
prosecute 'prosikju:t / to take legal action against; to bring a criminal charge against someone in a court of law.
He was prosecuted for exceeding the speed limit.
The police decided not to prosecute the traffic offender.
An international tribunal has been established to prosecute war criminals in the former Yugoslavia.
punishment
punishing.
'p^niſment / a way in which a person is punished; the act of
Capital punishment is punishment by death.
The punishment should fit the crime.
The punishments inflicted on the children were too severe.
threaten / Oretn / make a threat; try to influence someone by threats.
The attacker threatened me with a gun.
The defendant's criminal conduct would cause or threaten serious harm.
The hijacker threatens to kill all the passengers.
|
1e78ae1f3cf2bfda5f75ccc196ce3fab
|
{
"intermediate": 0.2846076786518097,
"beginner": 0.3704715073108673,
"expert": 0.344920814037323
}
|
44,751
|
如何解决:
(base) PS F:\next13-ai-saas> npx prisma db push
Environment variables loaded from .env
Prisma schema loaded from prisma\schema.prisma
Datasource "db": MySQL database
Error: Prisma schema validation - (get-config wasm)
Error code: P1012
error: Error validating datasource `db`: the URL must start with the protocol `mysql://`.
--> schema.prisma:7
|
6 | provider = "mysql"
7 | url = env("DATABASE_URL")
|
Validation Error Count: 1
[Context: getConfig]
Prisma CLI Version : 5.11.0
(base) PS F:\next13-ai-saas> npx prisma db push
Environment variables loaded from .env
Prisma schema loaded from prisma\schema.prisma
Datasource "db": MySQL database at "localhost:3306"
Error: P1000: Authentication failed against database server at `localhost`, the provided database credentials for `` are not valid.
Please make sure to provide valid database credentials for the database server at `localhost`.
|
705fca6a79e574953fc0f18679136180
|
{
"intermediate": 0.42146921157836914,
"beginner": 0.33943212032318115,
"expert": 0.2390986979007721
}
|
44,752
|
import pandas as pd
import os
from datetime import datetime
import pytz
from concurrent.futures import ThreadPoolExecutor, as_completed
# Define the date after which you want to filter
cutoff_date_for_test = datetime(2023, 12, 20, tzinfo=pytz.UTC)
cutoff_date_for_train = datetime(2024, 1, 20, tzinfo=pytz.UTC)
directory = r'E:\01_calculate_talib\New folder (2)'
csv_files = [file for file in os.listdir(directory) if file.endswith('.csv')]
def splid_csv_data(file_path, file):
# Read the CSV file
print(f'processing {file}')
df = pd.read_csv(file_path)
# Convert the 'Date' column to datetime
df['Date'] = pd.to_datetime(df['Date'])
# Filter rows where 'Date' is after the filter_date
df_filtered_to_train = df[df['Date'] < cutoff_date_for_train]
df_filtered_last = df[df['Date'] >= cutoff_date_for_test]
output_path_last_month = os.path.join(directory, f'last_month_{file}')
output_path_train = os.path.join(directory, f'train_{file}')
# Write the filtered data to a new CSV file
df_filtered_last.to_csv(output_path_last_month, index=False)
df_filtered_to_train.to_csv(output_path_train, index=False)
print('separated')
with ThreadPoolExecutor() as executor:
futures = []
for file in csv_files:
file_path = os.path.join(directory, file)
splid_csv_data(file_path, file)
futures.append(executor.submit(splid_csv_data, file_path, file))
for future in as_completed(futures):
pass
print("Filtered CSV files have been created.")
TypeError: Invalid comparison between dtype=datetime64[ns] and datetime
|
5fe9d168d7275dddf541aaf2951f7ad5
|
{
"intermediate": 0.6214848160743713,
"beginner": 0.2379855215549469,
"expert": 0.14052966237068176
}
|
44,753
|
Create a comprehensive course on handling elements with Playwright such as looping through elements
|
f678322d781f8ceca32d1023c67f265d
|
{
"intermediate": 0.2325294464826584,
"beginner": 0.6086854338645935,
"expert": 0.15878508985042572
}
|
44,754
|
i haver bunch of csv files as my dataset...
I want to train a standard deep learning model on my dataset whithout merging them together
give me proper python code
|
153a99b95d90d4d7079acae8975144df
|
{
"intermediate": 0.23904867470264435,
"beginner": 0.09144555032253265,
"expert": 0.669505774974823
}
|
44,755
|
hi
|
6962d723735545e5cde12181f96b63d4
|
{
"intermediate": 0.3246487081050873,
"beginner": 0.27135494351387024,
"expert": 0.40399640798568726
}
|
44,756
|
wrtoe sql to create sample inforamtio n name in databse name dhiraj
|
ec7de1ce20a8d2c9469c0e6539fb622f
|
{
"intermediate": 0.3667638897895813,
"beginner": 0.18279844522476196,
"expert": 0.45043766498565674
}
|
44,757
|
i have a data set
i want to train a SVMs model on my data set , i want to train and evaluate model using GridSearch
give me proper python code
|
f914e6de4c6bae0354814f70796dcb45
|
{
"intermediate": 0.42668411135673523,
"beginner": 0.11889383941888809,
"expert": 0.4544219970703125
}
|
44,758
|
Create a comprehensive tutorial on how to loop through elements with Playwright library
|
6bfecdb6d52d1ab4209bc5ef804622bd
|
{
"intermediate": 0.4995037615299225,
"beginner": 0.29503607749938965,
"expert": 0.20546014606952667
}
|
44,759
|
CREATE TABLE sample_table (
id SERIAL PRIMARY KEY,
name VARCHAR(255) NOT NULL
); insert some data in iy
|
d37c32e8628d6131667bf76b980b383f
|
{
"intermediate": 0.37307146191596985,
"beginner": 0.31385692954063416,
"expert": 0.3130715787410736
}
|
44,760
|
Что делает этот код, как он работает
sorted_data = sorted(filtered_data, key=lambda x: self.get_priority(x) + self.get_delivery_date(x) + self.get_level_4(x) + self.get_quantity(x))
def get_priority(self, record: IOR) -> tuple[int, int]:
return (-int(record.priority),) if record.priority is not None else (float('inf'),)
def get_delivery_date(self, record: IOR) -> tuple[datetime, int]:
return (datetime.strptime(record.delivery_date, '%Y-%m-%d'),) if record.delivery_date is not None else (datetime.max,)
def get_level_4(self, record: IOR) -> tuple[str, int]:
return (record.level_4,) if record.level_4 is not None else ('',)
def get_quantity(self, record: IOR) -> tuple[float, int]:
return (record.quantity,) if record.quantity is not None else (float('inf'),)
|
347045a821deb86689bf97eac9a9e156
|
{
"intermediate": 0.3152032792568207,
"beginner": 0.4766267240047455,
"expert": 0.20817001163959503
}
|
44,761
|
如何解决:
(base) PS F:\next13-ai-saas> yarn run build
yarn run v1.22.22
$ next build
- info Loaded env from F:\next13-ai-saas\.env
- info Creating an optimized production build .<w> [webpack.cache.PackFileCacheStrategy] Serializing big strings (101kiB) impacts deserialization performance (consider using Buffer instead and decode when needed)
- warn Compiled with warnings
./node_modules/scheduler/cjs/scheduler.production.min.js
A Node.js API is used (setImmediate at line: 51) which is not supported in the Edge Runtime.
Learn more: https://nextjs.org/docs/api-reference/edge-runtime
Import trace for requested module:
./node_modules/scheduler/cjs/scheduler.production.min.js
./node_modules/scheduler/index.js
./node_modules/react-dom/cjs/react-dom.production.min.js
./node_modules/react-dom/index.js
./node_modules/@clerk/clerk-react/dist/esm/utils/useCustomElementPortal.js
./node_modules/@clerk/clerk-react/dist/esm/utils/index.js
./node_modules/@clerk/clerk-react/dist/esm/contexts/ClerkProvider.js
./node_modules/@clerk/clerk-react/dist/esm/contexts/index.js
./node_modules/@clerk/clerk-react/dist/esm/index.js
./node_modules/@clerk/nextjs/dist/esm/client-boundary/controlComponents.js
./node_modules/@clerk/nextjs/dist/esm/index.js
./node_modules/scheduler/cjs/scheduler.production.min.js
A Node.js API is used (setImmediate at line: 51) which is not supported in the Edge Runtime.
Learn more: https://nextjs.org/docs/api-reference/edge-runtime
Import trace for requested module:
./node_modules/scheduler/cjs/scheduler.production.min.js
./node_modules/scheduler/index.js
./node_modules/react-dom/cjs/react-dom.production.min.js
./node_modules/react-dom/index.js
./node_modules/@clerk/clerk-react/dist/esm/utils/useCustomElementPortal.js
./node_modules/@clerk/clerk-react/dist/esm/utils/index.js
./node_modules/@clerk/clerk-react/dist/esm/contexts/ClerkProvider.js
./node_modules/@clerk/clerk-react/dist/esm/contexts/index.js
./node_modules/@clerk/clerk-react/dist/esm/index.js
./node_modules/@clerk/nextjs/dist/esm/client-boundary/controlComponents.js
./node_modules/@clerk/nextjs/dist/esm/index.js
./node_modules/scheduler/cjs/scheduler.production.min.js
A Node.js API is used (MessageChannel at line: 120) which is not supported in the Edge Runtime.
Learn more: https://nextjs.org/docs/api-reference/edge-runtime
Import trace for requested module:
./node_modules/scheduler/cjs/scheduler.production.min.js
./node_modules/scheduler/index.js
./node_modules/react-dom/cjs/react-dom.production.min.js
./node_modules/react-dom/index.js
./node_modules/@clerk/clerk-react/dist/esm/utils/useCustomElementPortal.js
./node_modules/@clerk/clerk-react/dist/esm/utils/index.js
./node_modules/@clerk/clerk-react/dist/esm/contexts/ClerkProvider.js
./node_modules/@clerk/clerk-react/dist/esm/contexts/index.js
./node_modules/@clerk/clerk-react/dist/esm/index.js
./node_modules/@clerk/nextjs/dist/esm/client-boundary/controlComponents.js
./node_modules/@clerk/nextjs/dist/esm/index.js
./node_modules/scheduler/cjs/scheduler.production.min.js
A Node.js API is used (MessageChannel at line: 121) which is not supported in the Edge Runtime.
Learn more: https://nextjs.org/docs/api-reference/edge-runtime
Import trace for requested module:
./node_modules/scheduler/cjs/scheduler.production.min.js
./node_modules/scheduler/index.js
./node_modules/react-dom/cjs/react-dom.production.min.js
./node_modules/react-dom/index.js
./node_modules/@clerk/clerk-react/dist/esm/utils/useCustomElementPortal.js
./node_modules/@clerk/clerk-react/dist/esm/utils/index.js
./node_modules/@clerk/clerk-react/dist/esm/contexts/ClerkProvider.js
./node_modules/@clerk/clerk-react/dist/esm/contexts/index.js
./node_modules/@clerk/clerk-react/dist/esm/index.js
./node_modules/@clerk/nextjs/dist/esm/client-boundary/controlComponents.js
./node_modules/@clerk/nextjs/dist/esm/index.js
./node_modules/@clerk/shared/dist/chunk-RSOCGYTF.mjs
A Node.js API is used (MessageEvent at line: 27) which is not supported in the Edge Runtime.
Learn more: https://nextjs.org/docs/api-reference/edge-runtime
Import trace for requested module:
./node_modules/@clerk/shared/dist/chunk-RSOCGYTF.mjs
./node_modules/@clerk/shared/dist/index.mjs
./node_modules/@clerk/clerk-react/dist/esm/components/uiComponents.js
./node_modules/@clerk/clerk-react/dist/esm/components/index.js
./node_modules/@clerk/clerk-react/dist/esm/index.js
./node_modules/@clerk/nextjs/dist/esm/client-boundary/controlComponents.js
./node_modules/@clerk/nextjs/dist/esm/index.js
- info Linting and checking validity of types .Failed to compile.
./components/ui/dialog.tsx:14:3
Type error: Property 'className' does not exist on type 'DialogPortalProps'.
12 |
13 | const DialogPortal = ({
> 14 | className,
| ^
15 | ...props
16 | }: DialogPrimitive.DialogPortalProps) => (
17 | <DialogPrimitive.Portal className={cn(className)} {...props} />
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.
|
b516fd44727935ea7f2542decd2a496f
|
{
"intermediate": 0.37342527508735657,
"beginner": 0.32090291380882263,
"expert": 0.3056718707084656
}
|
44,762
|
Какая команда выведет мне такой результат:
SDA 5.5 Тб
SDA1 953 мб /root
SDA2 465 гб /
SDA3 4 ТБ /media/obraz
А так же:
SDB1 500 гб /media/user1
SDB2 8ТБ /media/public
SDB3 4ТБ /media/backup
SDB4 465 гб
SDB5 1.5 ТБ /media/vmail
SDB6 500 гб /media/klaster
|
40f9326c1afb89dfbc39e1b01efe25cf
|
{
"intermediate": 0.43709075450897217,
"beginner": 0.2665206789970398,
"expert": 0.29638850688934326
}
|
44,763
|
class Sobel_GradientLoss(nn.Module): def init(self): super(Sobel_GradientLoss, self).init() sobel_x = np.array([[-1, 0, 1], [-2, 0, 2], [-1, 0, 1]], dtype=np.float32) sobel_y = np.array([[1, 2, 1], [0, 0, 0], [-1, -2, -1]], dtype=np.float32) sobel_x = sobel_x.reshape((1, 1, 3, 3)) sobel_y = sobel_y.reshape((1, 1, 3, 3)) conv_x = nn.Conv2d(1,1,3, bias=False) conv_y = nn.Conv2d(1,1,3, bias=False) conv_x.weight.data = torch.from_numpy(sobel_x).cuda() conv_y.weight.data = torch.from_numpy(sobel_y).cuda() self.conv_x = conv_x self.conv_y = conv_y def forward(self, predict, target): pred_x = self.conv_x(predict) pred_y = self.conv_y(predict) G_pred = torch.abs(pred_x) + torch.abs(pred_y) target_x = self.conv_x(target) self.conv_x.train(False) target_y = self.conv_y(target) self.conv_y.train(False) G_target = torch.abs(target_x) + torch.abs(target_y) loss = F.mse_loss(G_pred, G_target, reduction='mean') return loss class CombinedLoss2(nn.Module): def init(self, ssim_weight=0.25, dice_weight=0.25, sobel_weight=0.25, l2_weight=0.25): super(CombinedLoss2, self).init() self.ssim_weight = ssim_weight self.dice_weight = dice_weight self.l2_weight = l2_weight self.sobel_weight = sobel_weight self.dice_loss = DiceLoss() self.sobel_loss = Sobel_GradientLoss() self.l2_loss = nn.MSELoss() self.ssim_loss = SSIM_func.SSIM() def forward(self, predicitions, targets): ssim_loss = 1 - self.ssim_loss(predicitions, targets) sobel_loss = self.sobel_loss(predicitions, targets) l2_loss = self.l2_loss(predicitions, targets) dice_loss = self.dice_loss.dice_loss(predicitions, targets) combine_loss = (self.ssim_weight * ssim_loss + self.sobel_weightsobel_loss + self.l2_weightl2_loss + self.dice_weight * dice_loss) return combine_loss class DiceLoss(nn.Module): def init(self): super(DiceLoss, self).init() def dice_loss(self, y_pred, y_true): smooth = 1.0 product = torch.mul(y_pred, y_true) intersection = torch.sum(product) coefficient = (2.*intersection + smooth) / (torch.sum(y_pred) + torch.sum(y_true) + smooth) loss = 1. - coefficient return loss 在实现 Combinedloss2类进行网络训练时, 发现loss不收敛,是否和Sobel_Gradientloss, diceloss类的构造有关
|
a5c4d50dbfbe685fade0e57d7634714d
|
{
"intermediate": 0.31063026189804077,
"beginner": 0.4966375231742859,
"expert": 0.19273222982883453
}
|
44,764
|
In servicenow, I am displaying a dot walked field (type :duration ) on the form and the data is being shown empty , although I can see data on the Source.
|
04a85569914a137c792f40e1e10b19f3
|
{
"intermediate": 0.3487634062767029,
"beginner": 0.30674806237220764,
"expert": 0.3444885313510895
}
|
44,765
|
how can change django sync to async?
|
97737401161335711f5ad6544fbb646c
|
{
"intermediate": 0.737214207649231,
"beginner": 0.11457502841949463,
"expert": 0.14821083843708038
}
|
44,766
|
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
contract SafuTransfer {
mapping(address => uint256) _balances;
function _transfer(
address _from,
address _to,
address _amount
) external virtual {
uint256 _fromBalance = _balances[_from];
uint256 _toBalance = _balances[_to];
unchecked {
_balances[_from] = _fromBalance - _amount;
_balances[_to] = _toBalance + _amount;
}
}
}
Take a look at this seemingly harmless transfer functions.Can you identify any potential issues that may be lurking in the code?
|
fae8bf65ac00004d7761de525d4cab46
|
{
"intermediate": 0.5271129012107849,
"beginner": 0.2137995809316635,
"expert": 0.259087473154068
}
|
44,767
|
def hello():
return 'Goodbye, Mars!'
Modify the provided code in python so that it produces the string "Hello, World!".
|
734ed0ebbcd8c44c20c0d147e5d6c1f3
|
{
"intermediate": 0.3680327236652374,
"beginner": 0.34030255675315857,
"expert": 0.2916647493839264
}
|
44,768
|
how to resolve the error cc1plus: error: command line option ‘-Wno-implicit-function-declaration’ is valid for C/ObjC but not for C++ [-Werror]
|
bd81952d7cb442f66a58add34dda0fd2
|
{
"intermediate": 0.4591962695121765,
"beginner": 0.3550781309604645,
"expert": 0.1857256144285202
}
|
44,769
|
Create a chatbot such that,it will take user input and matches the similarity of question with a predefined question and answers txt file and give the most imilar match ,also if the quesstion ansked by user is not present in Question answer txt file then it should generate a sql quesry based on schema that i will provide and that query should be executed on my sales_database.db file and generate ouptut.
|
040a43b6c8621bf2a66e87578065bad9
|
{
"intermediate": 0.4202790856361389,
"beginner": 0.30510804057121277,
"expert": 0.2746128737926483
}
|
44,770
|
How can i set a variable in cmakelist and use in code file as macro
|
a6778c388c66c1cc978097d4f12e38fb
|
{
"intermediate": 0.41996973752975464,
"beginner": 0.4374711811542511,
"expert": 0.14255906641483307
}
|
44,771
|
How can i set a variable in cmakelist and use in code file as macro
|
8fcf0327c63d30b1fa3f7ecf406b6708
|
{
"intermediate": 0.41996973752975464,
"beginner": 0.4374711811542511,
"expert": 0.14255906641483307
}
|
44,772
|
def is_armstrong_number(number):
digits = len(str(number))
number_as_string = str(number)
sum = 0
for digit in number_as_string:
sum += int(digit) ** digits
return sum == number
|
131e7939d6f219235f7dfd0d9f6b4787
|
{
"intermediate": 0.36393317580223083,
"beginner": 0.4380419850349426,
"expert": 0.19802482426166534
}
|
44,773
|
def is_armstrong_number(number): digits = len(str(number)) number_as_string = str(number) sum = 0 for digit in number_as_string: sum += int(digit) ** digits return sum == number Can you just explain this code step by step as if I am a beginner
|
047f53784cb6884049195b5f40be950e
|
{
"intermediate": 0.40265950560569763,
"beginner": 0.4149053692817688,
"expert": 0.18243511021137238
}
|
44,774
|
def is_armstrong_number(number): digits = len(str(number)) number_as_string = str(number) sum = 0 for digit in number_as_string: sum += int(digit) ** digits return sum == number Can you just explain this code step by step as if I am a beginner
|
e78367a956bd17717fa886a617b97b1f
|
{
"intermediate": 0.40265950560569763,
"beginner": 0.4149053692817688,
"expert": 0.18243511021137238
}
|
44,775
|
explain django delplay with uvicorn and nginx
|
7ec5429f9ee2c150718128f2871c7118
|
{
"intermediate": 0.8275997042655945,
"beginner": 0.10200521349906921,
"expert": 0.07039506733417511
}
|
44,776
|
how to set a variable in cmakelists and use on code file
|
08f83ea81fae984c21c3a601e3678a76
|
{
"intermediate": 0.39344102144241333,
"beginner": 0.46674367785453796,
"expert": 0.1398153156042099
}
|
44,777
|
My undirected bipartite miltigraph is having two set of nodes which is formed in two sides of the graph, one side of the nodes are components (11 components) and another side of the nodes are nets (9 nets), totally we have 20 nodes, and the components and the nets of the opposite sides are connected by the edges, we have totally 40 edges between components and nets. among this total edges few of the edges connected from the transistor components are in parallel edge(edge connected between same component and nets).
Structure of my state inputs from graph data for RL GNN architecture model:
State reperesentation:
My implementation for getting the State reperesentation is shown below for your understanding.
node_features_tensor:
device_type = [0] if data.get('device_type') in ['transistor', 'passive', 'current_source', 'voltage_source'] else [1]
device_map = {'NMOS': [1, 0, 0, 0, 0, 0], 'PMOS': [0, 1, 0, 0, 0, 0], 'C': [0, 0, 1, 0, 0, 0],
'I': [0, 0, 0, 1, 0, 0], 'V': [0, 0, 0, 0, 1, 0], 'net': [0, 0, 0, 0, 0, 1]
}
component_index_map = {'M0': [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], 'M1': [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0],
'M2': [0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], 'M3': [0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0],
'M4': [0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0], 'M5': [0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0],
'M6': [0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0], 'M7': [0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0],
'C0': [0]*8 + [1, 0, 0],
'I0': [0]*9 + [1, 0], 'V1': [0]*10 + [1], 'net': [0]*11}
component_onehot = component_index_map.get(node, [0]*11) # Defaults to all zeros for unmatched nodes
device_onehot = device_map.get(data.get('vertex_type', 'net'), [0, 0, 0, 0, 0, 1]) # Defaults to 'net'
# Construct the feature vector
feature_vector = device_type + device_onehot + component_onehot + values
# values are the scalar values of circuit design parameters 'w_value', 'l_value', 'C_value', 'I_value', 'V_value'
node_features.append(feature_vector)
# Convert to Tensor
node_features_tensor = torch.FloatTensor(node_features)
sample node_features_tensor of one of my total 20 nodes,
node_features_tensor tensor([[0.0000, 1.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000,
0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 1.0000, 0.0000, 0.0000, 0.0000,
0.2150, 0.3015, 0.0000, 0.0000, 0.0000]
Among these total 20 nodes, we have 11 component nodes and 9 net nodes, it can be read from the 'device_type' in feature vector, if it is '0.0000', then it is component node and if it is '1.0000', then it is net node. The 11 component nodes are 'M0', 'M1', 'M2', 'M3', 'M4', 'M5', 'M6', 'M7', 'C0', 'I0', 'V1', which can be recognize with the corresponding one hot representation in the 'component_onehot' in feature vector. Here the ultimate optimization process is to optimaly tune the vlaues of 'w_value', 'l_value', 'C_value', 'I_value', 'V_value' corresponding to the each 'component_onehot'(11 component nodes). normalized scalar 'values' of 'w_value', 'l_value' are belongs to the components 'M0', 'M1', 'M2', 'M3', 'M4', 'M5', 'M6', 'M7'and normalized scalar 'values' of 'C_value', 'I_value', and 'V_value' are belongs to the components 'C0', 'I0', 'V1' respectively.
Additional constraint requirements to be must follow by the GNN nodes(11 component nodes),
the values of 'w_value', 'l_value' of component 'M0' and 'M1' must tune with same values as 'w1_value', 'l1_value',
the values of 'w_value', 'l_value' of component 'M2' and 'M3' must tune with same values as 'w3_value', 'l3_value',
the values of 'w_value', 'l_value' of component 'M4' and 'M7' must tune with same values as 'w5_value', 'l5_value',
the values of 'w_value', 'l_value' of component 'M5', must tune with values as 'w6_value', 'l6_value',
the values of 'w_value', 'l_value' of component 'M5', must tune with values as 'w7_value', 'l7_value',
the values of 'C_value' of component 'C0', must tune with values as 'Cc_value',
the values of 'I_value' of component 'I0', must tune with values as 'Ib_value',
the values of 'V_value' of component 'V1', must tune with values as 'Vc_value',
after tuned the above said values by the GNN model at the output we can get the 13 action space values corresponding to the parameters ['w1_value', 'l1_value', 'w3_value', 'l3_value', 'w5_value', 'l5_value', 'w6_value', 'l6_value', 'w7_value', 'l7_value', 'Cc_value', 'Ib_value', 'Vc_value']
after getting output from the GNN model we need to rearrange the action space of 13 values by ['l1_value', 'l3_value', 'l5_value', 'w6_value', 'l6_value', 'w7_value', 'l7_value', 'w1_value', 'w3_value', 'w5_value', 'Ib_value', 'Cc_value', 'Vc_value']
another State reperesentation:
In my graph structure, where i have parallel edges between two same nodes, for the Mosfet transistor (considered as one component node) having four terminals D, G, S, B, among the four terminal, the terminals D and S are connected to the same nets, which makes the two edges parallel between the same component node and nets (these parallel edge may wrongly considered as self loop by the model)
Edge feature tensor(edge_embeddings):
edge features are having high dimentional values so i used embedding technique to reduce each feature dimensions,
# Mapping dictionaries for categorical variables
device_type_mapping = {'NMOS': 0, 'PMOS': 1, 'R': 2, 'L': 3, 'C': 4, 'I': 5, 'V': 6}
device_mapping = {'M0': 0, 'M1': 1, 'M2': 2, 'M3': 3, 'M4': 4, 'M5': 5, 'M6': 6, 'M7': 7,
'C0': 8, 'I0': 9, 'V1': 10}
terminal_mapping = {'D0': 0, 'G0': 1, 'S0': 2, 'B0': 3, 'D1': 4, 'G1': 5, 'S1': 6, 'B1': 7,
'D2': 8, 'G2': 9, 'S2': 10, 'B2': 11, 'D3': 12, 'G3': 13, 'S3': 14, 'B3': 15,
'D4': 16, 'G4': 17, 'S4': 18, 'B4': 19, 'D5': 20, 'G5': 21, 'S5': 22, 'B5': 23,
'D6': 24, 'G6': 25, 'S6': 26, 'B6': 27, 'D7': 28, 'G7': 29, 'S7': 30, 'B7': 31,
'C0': 32, 'I0': 33, 'V1': 34}
edge_colors_mapping = {'blue': 0, 'red': 1, 'green': 2, 'grey': 3, 'yellow': 4, 'black': 5}
parallel_edges_mapping = {'T': 0, 'F': 1}
net_mapping = {'net1': 0, 'net2': 1, 'net3': 2, 'IN1': 3, 'IN2': 4, 'VOUT': 5, 'Vbias': 6, '0': 7, 'vdd!': 8}
# Define the embedding dimensions for each edge feature
device_type_embedding_dim = 2
device_embedding_dim = 2
net_embedding_dim = 2
terminal_name_embedding_dim = 3
edge_pairs_embedding_dim = 3
edge_colors_embedding_dim = 2
parallel_edges_embedding_dim = 2
# Create embedding layers for each edge feature
device_type_embedding = nn.Embedding(num_embeddings=7, embedding_dim=device_type_embedding_dim)
device_embedding = nn.Embedding(num_embeddings=15, embedding_dim=device_embedding_dim)
net_embedding = nn.Embedding(num_embeddings=9, embedding_dim=net_embedding_dim)
terminal_name_embedding = nn.Embedding(num_embeddings=39, embedding_dim=terminal_name_embedding_dim)
edge_pairs_embedding = nn.Embedding(num_embeddings=40, embedding_dim=edge_pairs_embedding_dim)
edge_colors_embedding = nn.Embedding(num_embeddings=6, embedding_dim=edge_colors_embedding_dim)
parallel_edges_embedding = nn.Embedding(num_embeddings=2, embedding_dim=parallel_edges_embedding_dim)
# Function to map categorical values to numerical indices
def map_categorical_to_index(feature_value, mapping_dict):
if feature_value in mapping_dict:
return mapping_dict[feature_value]
else:
return -1 # Handle unknown values
# Function to create embeddings for edge features
def get_edge_embeddings(edge_features):
embeddings = []
for edge in edge_features:
device_type_index = map_categorical_to_index(edge['device_type'], device_type_mapping)
device_index = map_categorical_to_index(edge['device'], device_mapping)
terminal_index = map_categorical_to_index(edge['terminal_name'], terminal_mapping)
net_index = map_categorical_to_index(edge['nets'], net_mapping)
net_embed = net_embedding(torch.tensor(net_index))
edge_colors_index = map_categorical_to_index(edge['edge_colors'], edge_colors_mapping)
parallel_edges_index = map_categorical_to_index(edge['Parallel edges present'], parallel_edges_mapping)
device_type_embed = device_type_embedding(torch.tensor(device_type_index))
device_embed = device_embedding(torch.tensor(device_index))
terminal_name_embed = terminal_name_embedding(torch.tensor(terminal_index))
edge_colors_embed = edge_colors_embedding(torch.tensor(edge_colors_index))
parallel_edges_embed = parallel_edges_embedding(torch.tensor(parallel_edges_index))
edge_pair_embed = torch.cat([device_embed, net_embed], dim=0)
edge_embed = torch.cat([device_type_embed, device_embed, terminal_name_embed, edge_colors_embed, parallel_edges_embed, edge_pair_embed], dim=0)
embeddings.append(edge_embed)
return embeddings
sample edge_embeddings of one of my total 38 edges
edge_embeddings [tensor([ 0.7124, -0.1579, 2.0348, 0.4799, 2.0526, -0.9357, 0.2265, 2.0741,
0.5741, 1.6283, -1.4729, 2.0348, 0.4799, -0.9982, -0.4223]
Here the 'device_embed' in 'edge_embed'(edge features) are belongs to the corresponding 11 components 'M0', 'M1', 'M2', 'M3', 'M4', 'M5', 'M6', 'M7', 'C0', 'I0', 'V1', and the 'edge_pair_embed' are the edge pairs corresponding to the respective edge among total 40 edges connected between the 11 components and 9 nets.
|
7d36afeb31d013228b78a21d05733456
|
{
"intermediate": 0.31609833240509033,
"beginner": 0.37198546528816223,
"expert": 0.3119162321090698
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.