refactor: Reimplement calculator logic with new JavaScript and PHP files, removing numerous old Python scripts and related content.

This commit is contained in:
Ben
2026-03-06 19:56:03 -08:00
parent d381cd6610
commit e35fdcb118
34 changed files with 6899 additions and 4099 deletions

5
.gitignore vendored Normal file
View File

@@ -0,0 +1,5 @@
scripts_archive/
__pycache__/
.venv/
.DS_Store
*.log

View File

@@ -1,81 +1,158 @@
# How Do You Convert - Agents Documentation
# How Do You Convert - AI Agent SOP
This document explicitly defines the schema, architecture, and standard operating procedure for creating new calculators on `howdoyouconvert.com`.
This document defines the standard operating procedure (SOP) for AI agents creating or updating calculators on `howdoyouconvert.com`. Adherence to these steps ensures high code quality, mathematical accuracy, and SEO compliance.
## 1. WordPress Environment Structure
The calculators are managed using the custom post type `calculator`. The REST API endpoint allows full CRUD operations:
- **Base Endpoint**: `/wp-json/wp/v2/calculator`
- Authentication is handled via Application Passwords `base64(username:password)` utilizing Basic Auth via HTTP Headers.
- *Crucial Node*: API requests to this endpoint must emulate browser requests via the `User-Agent` string (e.g., `Mozilla/5.0...`) or they will be blocked by Cloudflare (error 1010).
---
## 2. Calculator Data Payload (HTML)
Calculators should use Kadence Block layout components to match the pre-existing grid on the site. Each calculator contains 2 main columns for bidirectional conversion.
All calculators *MUST* include the classes `calc-input` and `calc-field` on their `<input type="number">` tags, and unique IDs across the form (e.g. `input-1`, `input-2`). The UI should contain explicit labels.
## 1. Environment & Authentication
- **Endpoint (Posts)**: `/wp-json/wp/v2/calculator` (Custom Post Type).
- **Endpoint (Logic)**: `/wp-json/wp/v2/kadence_element` (Kadence Elements CPT).
- **Authentication**: Basic Auth via headers: `Authorization: Basic base64(user:pass)`.
- **User-Agent**: **CRITICAL**. You must emulate a modern browser (e.g., `Mozilla/5.0...`) or Cloudflare will block the request (Error 1010).
**Example JSON Payload Configuration:**
```json
{
"title": "Unit A to Unit B",
"status": "publish",
"slug": "unita-to-unitb",
"content": "<!-- Standard Kadence 2-Column Row Block -> Column 1 (Label + Input) -> Column 2 (Label + Input) -> SEO Text Block -->"
}
---
## 2. Two-Part Architecture
Every calculator consists of **two separate WordPress objects** that work together:
### Part A: The Calculator Post (`calculator` CPT)
Contains the **HTML layout** (inputs, labels, Kadence Row/Column blocks) and the **SEO text**. This is what the user sees as the page content.
> [!CAUTION]
> **WordPress strips `<script>` tags from post content.** You CANNOT put JavaScript logic inside the calculator post. It will be silently removed on save. This is a core WordPress security behavior.
### Part B: The Logic Element (`kadence_element` CPT)
Contains the **JavaScript logic** wrapped in `<script>` tags. This is a separate post of type `kadence_element` that Kadence injects into the page at render time, based on conditional targeting rules stored in its metadata.
### How They Connect
The Kadence Element's metadata tells WordPress *when* and *where* to inject the script:
| Meta Key | Value | Purpose |
| :--- | :--- | :--- |
| `_kad_element_hook` | `kadence_after_header` | Injection point in the page template. |
| `_kad_element_show_conditionals` | `[{"rule":"singular\|calculator","select":"ids","ids":[POST_ID],"mustMatch":false}]` | Targets the element to only load on the specific calculator post. |
---
## 3. Post Creation & Duplicate Prevention
**Rule**: Never create duplicate posts. WordPress will append `-2` to the slug, breaking the link structure.
1. **Search**: Always GET the intended slug (e.g., `?slug=meters-to-feet`) before creating.
2. **Resolution**:
- If response is empty: `POST` new.
- If post exists: `PUT` to update the existing ID.
3. **Registry**: Immediately update `calculators_list.md` with Title, Post ID, and Kadence Element ID.
---
## 4. SEO Content Standards
All calculators must meet these three non-negotiable standards:
1. **Teaser Optimization**: Every post must begin with a 1-sentence summary followed by the `<!-- more -->` tag. This ensures category grids stay clean.
- *Example*: `<p><strong>Unit A to Unit B</strong>: Technical specs, symbols, and history. <!-- more --></p>`
2. **Encyclopedic Tone**: Content must be strictly informative and **non-self-referential**. Do not mention "this calculator," "our tool," or "enter your value." Focus on history, SI definitions, and industrial use.
3. **Length**: At least 3 detailed paragraphs are required for SEO depth.
4. **Forbidden Words**: Never use: *tool, calculator, widget, button, click, enter, below, our, this page.*
---
## 5. JavaScript Architecture (Self-Polling)
The JavaScript logic lives in the **Kadence Element** (Part B), NOT in the calculator post content. The "Self-Polling" pattern is mandatory to overcome caching and race conditions:
```javascript
<script>
(function() {
function init() {
const in1 = document.getElementById('input-1');
const in2 = document.getElementById('input-2');
if (!in1 || !in2) {
setTimeout(init, 100); // Poll until DOM is ready
return;
}
let cf = 3.2808399; // conversion factor
function solve(source) {
let v1 = parseFloat(in1.value);
let v2 = parseFloat(in2.value);
if (source === 1) {
if (!isNaN(v1)) in2.value = parseFloat((v1 * cf).toFixed(6));
else in2.value = '';
} else {
if (!isNaN(v2)) in1.value = parseFloat((v2 / cf).toFixed(6));
else in1.value = '';
}
}
in1.addEventListener('input', () => solve(1));
in2.addEventListener('input', () => solve(2));
const urlParams = new URLSearchParams(window.location.search);
if (urlParams.has('v1')) { in1.value = urlParams.get('v1'); solve(1); }
else if (urlParams.has('v2')) { in2.value = urlParams.get('v2'); solve(2); }
}
if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', init);
else init();
})();
</script>
```
### 2.2. Slug Mismatch & Duplicate Prevention
**CRITICAL**: Do not create a new post if the calculator already exists. WordPress will automatically append `-2` to the slug (e.g., `inches-to-millimeters-2`).
- **Detection**: Always perform a GET request for the intended slug before POSTing.
- **Resolution**: If a duplicate is found, capture the existing `id` and use `PUT` to update the content rather than creating a new entry.
- **Registry**: Ensure the `Id` in `calculators_list.md` matches the post serving the "clean" slug (no `-2`).
### 2.1. SEO Copy Guidelines
The SEO block appended at the end of the calculator `content` must strictly adhere to the following style:
- **Length**: Expand the text to 2-3 detailed paragraphs providing educational information on the units involved, their history, uses, and the conversion methodologies.
- **Tone**: The text must be strictly informative and **non-self-referential**. Do not refer to the calculator widget itself. Sentences like "This handy calculator automatically converts values as you type" or "Enter your value below" are explicitly prohibited.
## 3. JavaScript Event Injection
The JavaScript that performs the actual mathematical conversion is *detached* from the calculator post itself. It is managed via the **Kadence Elements** system (`kadence_element` custom post type).
### Creating the Logic Hook
Whenever a new calculator is created:
1. Capture the returned `id` of the published calculator.
2. Formulate the JS math conversion script wrapping events to the unique input IDs.
init();
})();
</script>
```
### 3.1. 3-Variable Solver Pattern (e.g., Ohm's Law)
For calculators with 3 inputs (A, B, C where A * B = C), use the "solve" function pattern to ensure reactivity:
```javascript
function solve(lastId) {
let av = parseFloat(a.value), vv = parseFloat(v.value), wv = parseFloat(w.value);
if (lastId === '1' || lastId === '2') {
if (!isNaN(av) && !isNaN(vv)) w.value = parseFloat((av * vv).toFixed(3));
} else if (lastId === '3') {
if (!isNaN(wv)) {
if (!isNaN(av) && av !== 0) v.value = parseFloat((wv / av).toFixed(2));
else if (!isNaN(vv) && vv !== 0) a.value = parseFloat((wv / vv).toFixed(2));
}
### Creating the Logic Element via API
```python
js_data = {
"title": f"JS Logic: {title}",
"content": js_code, # The <script>...</script> block above
"status": "publish",
"meta": {
"_kad_element_hook": "kadence_after_header",
"_kad_element_show_conditionals": f'[{{"rule":"singular|calculator","select":"ids","ids":[{post_id}],"mustMatch":false}}]'
}
}
a.oninput = () => solve('1'); v.oninput = () => solve('2'); w.oninput = () => solve('3');
# POST to /wp-json/wp/v2/kadence_element
```
4. **URL Parameter Support:** Ensure the script parses `window.location.search` for `?v1=` (Input 1) and `?v2=` (Input 2).
5. Submit a new `kadence_element` POST request injecting the `<script>...</script>`.
6. Apply these required metadata values:
- `_kad_element_hook`: `kadence_after_header`
- `_kad_element_show_conditionals`: `'[{"rule":"singular|calculator","select":"ids","ids":[<CALCULATOR_POST_ID>],"mustMatch":false}]'`
## 4. Required Mathematical Verification
After the Kadence Element is injected and the calculator is live, **you must verify the math works in both directions** using the live WordPress post.
1. Determine a known "Unit A to Unit B" conversion (e.g., 1 inch = 2.54 cm).
2. Execute an HTTP/URL request simulating the Unit A input (e.g., `?v1=1`) and verify the output accurately reflects Unit B.
3. Reverse the test: simulate the Unit B input (e.g., `?v2=2.54`) and verify the output accurately reflects Unit A.
4. If either math direction fails or produces precision floating-point inaccuracies, you must correct the Kadence Element JavaScript block.
5. **Live Logic Audit**: View the page source and search for `<!-- [element-ID] -->`. Ensure the ID matches the one in the registry and contains the robust `init` pattern.
---
## 4. Calculator Registry
To avoid unnecessary scraping of the REST API, immediately update the `calculators_list.md` file located in the workspace directory with the details (Title, Post ID, Kadence Element ID) upon successful deployment.
## 6. Infrastructure Warnings
*By adhering to these steps, all calculators will natively match the design and function gracefully without requiring direct plugin access.*
> [!WARNING]
> **Cloudflare Rocket Loader** is active on the site. It rewrites `<script>` tags by changing their `type` attribute (e.g., to `46a62f613affa4914fc4953c-text/javascript`) to defer execution. This means `grep "function init"` on `curl` output will **fail** because scripts are rewritten. Do not rely on `curl | grep` to verify script presence.
> [!WARNING]
> **Autoptimize** is active and bundles/minifies JavaScript. Individual `<script>` blocks from Kadence Elements may be merged into a single `.js` file. This further complicates source-level verification via `curl`.
> [!WARNING]
> **Content Security Policy (CSP)** is enforced via Cloudflare with `strict-dynamic` and nonce-based policies. Inline scripts that are NOT injected through a trusted WordPress pipeline (like `wp_enqueue_script` or Kadence Elements) may be blocked. The CSP warnings in console are expected for third-party scripts but should not affect Kadence-injected logic.
> [!IMPORTANT]
> **Cloudflare Super Page Cache** aggressively caches pages. After updating a post or element via the API, the cached version may persist. Cache-busting query parameters (e.g., `?v=123`) may not work. The user may need to purge the cache from the Cloudflare dashboard or the WP admin panel for changes to appear immediately.
---
## 7. What NOT to Do
> [!CAUTION]
> **Never modify the architecture.** The two-part model (Post + Kadence Element) is the established pattern. Do NOT attempt to:
> - Embed `<script>` tags directly in the calculator post content (WordPress strips them).
> - Create external `.js` files and enqueue them via a custom plugin (violates the self-contained protocol).
> - Wrap post content in custom `<div>` containers with `data-` attributes for use by an external script (this adds unnecessary complexity and breaks when the external script isn't loaded).
> - Deactivate (set to `draft`) Kadence Elements without providing an alternative logic source. This will immediately break every affected calculator.
---
## 8. Verification Protocol
A deployment is not "complete" until it is mathematically and visually verified.
1. **Bidirectional Math**: Verify both directions (A→B and B→A) using specific test values (e.g., 25.4 for inches to mm).
2. **API Content Audit**: Use the REST API (`?context=edit`) to confirm the raw `content` of both the calculator post AND its Kadence Element. Do NOT rely on `curl` of the live page due to Rocket Loader and Autoptimize rewriting (see Section 6).
3. **Element Status Check**: Confirm the Kadence Element's `status` is `publish` and its `_kad_element_show_conditionals` correctly targets the calculator post ID.
4. **Keyword Audit**: Screen generated text for forbidden words (see Section 4).
---
## 9. Registry Maintenance
Maintain `calculators_list.md` as the source of truth for all active units. Each row must contain:
| Title | Post ID | Kadence Element ID | Slug |
| :--- | :--- | :--- | :--- |
If you encounter a duplicate post ID, resolve the conflict and update the registry to point to the cleanest slug.

View File

@@ -1,60 +0,0 @@
import urllib.request
import json
import base64
import time
import re
url_base_kadence = "https://howdoyouconvert.com/wp-json/wp/v2/kadence_element"
url_base_calc = "https://howdoyouconvert.com/wp-json/wp/v2/calculator"
creds = base64.b64encode(b"ben:6YGf wVxu gBpz pkqx BGZO lfVP").decode("utf-8")
headers = {
"Authorization": "Basic " + creds,
"User-Agent": "Mozilla/5.0"
}
def get_all(url):
results = []
page = 1
while True:
req = urllib.request.Request(f"{url}?per_page=100&page={page}", headers=headers)
try:
resp = urllib.request.urlopen(req, timeout=30)
data = json.loads(resp.read().decode("utf-8"))
if not data: break
results.extend(data)
page += 1
except:
break
return results
print("Fetching all calculators...")
calcs = get_all(url_base_calc)
calc_map = {c['id']: c['slug'] for c in calcs}
print("Fetching all elements...")
elements = get_all(url_base_kadence)
mapping = []
for e in elements:
meta = e.get('meta', {})
cond = meta.get('_kad_element_show_conditionals', '')
if cond:
try:
cond_data = json.loads(cond)
if isinstance(cond_data, list) and len(cond_data) > 0:
ids = cond_data[0].get('ids', [])
for pid in ids:
if pid in calc_map:
mapping.append({
'eid': e['id'],
'pid': pid,
'slug': calc_map[pid],
'title': e['title']['rendered']
})
except:
continue
with open("/tmp/element_mapping.json", "w") as f:
json.dump(mapping, f, indent=2)
print(f"Found {len(mapping)} mappings.")

View File

@@ -1,146 +0,0 @@
import urllib.request
import json
import base64
import time
url_base_calc = "https://howdoyouconvert.com/wp-json/wp/v2/calculator"
url_base_kadence = "https://howdoyouconvert.com/wp-json/wp/v2/kadence_element"
creds = base64.b64encode(b"ben:6YGf wVxu gBpz pkqx BGZO lfVP").decode("utf-8")
headers = {
"Content-Type": "application/json",
"Authorization": "Basic " + creds,
"User-Agent": "Mozilla/5.0"
}
batch_10 = [
{"title": "Megabytes to Gigabytes", "slug": "megabytes-to-gigabytes", "v1": "Megabytes (MB)", "v2": "Gigabytes (GB)", "factor": 0.001, "desc": "One gigabyte contains 1,000 megabytes (decimal definition). This conversion is standard in consumer electronics and storage capacity reporting."},
{"title": "Megajoules to Kilowatt-hours", "slug": "megajoules-to-kilowatt-hours", "v1": "Megajoules (MJ)", "v2": "Kilowatt-hours (kWh)", "factor": 0.277778, "desc": "One kilowatt-hour is exactly 3.6 megajoules. Megajoules are often used in scientific energy calculations, while kWh is the standard for utility billing."},
{"title": "Meters to Feet", "slug": "meters-to-feet", "v1": "Meters (m)", "v2": "Feet (ft)", "factor": 3.28084, "desc": "The meter is the SI base unit of length. One meter is approximately 3.28 feet, a common conversion for height and room dimensions."},
{"title": "Meters to Yards", "slug": "meters-to-yards", "v1": "Meters (m)", "v2": "Yards (yd)", "factor": 1.09361, "desc": "Meters and yards are similar in scale, but the meter is slightly longer (approx. 1.09 yards). This is common in sports like swimming and athletics."},
{"title": "Metric tons to Short tons", "slug": "metric-tons-to-short-tons", "v1": "Metric Tons (t)", "v2": "Short Tons (US)", "factor": 1.10231, "desc": "A metric ton (tonne) is 1,000 kg, slightly heavier than the US short ton (2,000 lbs)."},
{"title": "Minutes to Hours", "slug": "minutes-to-hours", "v1": "Minutes (min)", "v2": "Hours (hr)", "factor": 0.0166667, "desc": "Sixty minutes make one hour. This conversion is used for tracking labor hours and travel duration."},
{"title": "Minutes to Seconds", "slug": "minutes-to-seconds", "v1": "Minutes (min)", "v2": "Seconds (s)", "factor": 60.0, "desc": "One minute contains sixty seconds. This conversion is essential for high-precision time tracking and performance measurement."},
{"title": "Nautical miles to Kilometers", "slug": "nautical-miles-to-kilometers", "v1": "Nautical Miles (nmi)", "v2": "Kilometers (km)", "factor": 1.852, "desc": "A nautical mile is defined based on the Earth's circumference and is exactly 1.852 kilometers, the standard for maritime and aviation navigation."},
{"title": "Newtons to Dynes", "slug": "newtons-to-dynes", "v1": "Newtons (N)", "v2": "Dynes (dyn)", "factor": 100000.0, "desc": "A newton is the SI unit of force. One newton is equal to 100,000 dynes (the CGS unit of force)."},
{"title": "Ounces to Grams", "slug": "ounces-to-grams", "v1": "Ounces (oz)", "v2": "Grams (g)", "factor": 28.3495, "desc": "One avoirdupois ounce is approximately 28.35 grams. This is the global standard for kitchen measurements and postal weights."}
]
def check_exists(slug):
req = urllib.request.Request(f"{url_base_calc}?slug={slug}", headers=headers)
try:
resp = urllib.request.urlopen(req, timeout=30)
data = json.loads(resp.read().decode("utf-8"))
if data: return data[0]['id']
except: pass
return None
def get_element_id_for_post(post_id):
req_e = urllib.request.Request(f"{url_base_kadence}?per_page=100", headers=headers)
try:
resp_e = urllib.request.urlopen(req_e, timeout=30)
elements = json.loads(resp_e.read().decode("utf-8"))
for e in elements:
cond = e.get('meta', {}).get('_kad_element_show_conditionals', '')
if str(post_id) in cond:
return e['id']
except: pass
return None
for item in batch_10:
print(f"\n--- Processing {item['title']} ---")
slug = item['slug']
unique_id = slug.replace('-', '_')
calc_html = f"""
<!-- wp:kadence/rowlayout {{"uniqueID":"{unique_id}_row","columns":1,"colLayout":"equal","maxWidth":600,"bgColor":"#f5f7f9","borderRadius":8,"padding":[32,32,32,32],"marginUnit":"px"}} -->
<div class="wp-block-kadence-rowlayout alignnone"><div class="kt-row-column-wrap kt-has-1-columns kt-row-layout-equal kt-tab-layout-inherit kt-mobile-layout-row kt-row-valign-top" style="background-color:#f5f7f9;border-radius:8px;padding:2rem;">
<!-- wp:kadence/column {{"uniqueID":"{unique_id}_col"}} -->
<div class="wp-block-kadence-column"><div class="kt-inside-inner-col">
<!-- wp:kadence/rowlayout {{"uniqueID":"{unique_id}_inner_row","columns":2,"colLayout":"equal","maxWidth":600,"marginUnit":"px"}} -->
<div class="kb-row-layout-wrap kb-row-layout-id_{unique_id}_row aligncenter wp-block-kadence-rowlayout"><div class="kt-row-column-wrap kt-has-2-columns kt-row-layout-equal kt-tab-layout-inherit kt-mobile-layout-row kt-row-valign-top">
<div class="wp-block-kadence-column kadence-column_{unique_id}_col1"><div class="kt-inside-inner-col">
<label for="input-1" style="font-weight: 600; color: #333333; margin-bottom: 8px; display: block;">{item['v1']}</label>
<input type="number" id="input-1" class="calc-input" placeholder="0" style="width:100%; padding: 12px; border: 1px solid #ccc; border-radius: 4px; font-size: 1.2rem;">
</div></div>
<div class="wp-block-kadence-column kadence-column_{unique_id}_col2"><div class="kt-inside-inner-col">
<label for="input-2" style="font-weight: 600; color: #333333; margin-bottom: 8px; display: block;">{item['v2']}</label>
<input type="number" id="input-2" class="calc-input" placeholder="0" style="width:100%; padding: 12px; border: 1px solid #ccc; border-radius: 4px; font-size: 1.2rem;">
</div></div></div></div>
</div></div>
<!-- /wp:kadence/column -->
</div></div>
<!-- /wp:kadence/rowlayout -->
<p style="margin-top: 2rem; line-height: 1.6;">{item['desc']}</p>
"""
existing_id = check_exists(slug)
if existing_id:
print(f"--> Updating existing calculator (ID: {existing_id})")
calc_data = {"content": calc_html, "title": item['title']}
req_c = urllib.request.Request(f"{url_base_calc}/{existing_id}", data=json.dumps(calc_data).encode("utf-8"), headers=headers, method="PUT")
post_id = existing_id
else:
print(f"--> Creating new calculator")
calc_data = {"title": item['title'], "slug": slug, "status": "publish", "content": calc_html}
req_c = urllib.request.Request(url_base_calc, data=json.dumps(calc_data).encode("utf-8"), headers=headers, method="POST")
resp_c = urllib.request.urlopen(req_c, timeout=30)
post_id = json.loads(resp_c.read().decode("utf-8"))['id']
# Robust JS Logic
js_logic = f"""<script>
(function() {{
function init() {{
var i1 = document.getElementById("input-1");
var i2 = document.getElementById("input-2");
if (!i1 || !i2) {{
if (window.initRetries === undefined) window.initRetries = 0;
if (window.initRetries < 50) {{
window.initRetries++;
setTimeout(init, 100);
}}
return;
}}
i1.oninput = function() {{
var v = parseFloat(i1.value);
if (isNaN(v)) {{ i2.value = ""; return; }}
i2.value = parseFloat((v * {item['factor']}).toFixed(8));
}};
i2.oninput = function() {{
var v = parseFloat(i2.value);
if (isNaN(v)) {{ i1.value = ""; return; }}
i1.value = parseFloat((v / {item['factor']}).toFixed(8));
}};
var p = new URLSearchParams(window.location.search);
if (p.has('v1')) {{ i1.value = p.get('v1'); i1.oninput(); }}
else if (p.has('v2')) {{ i2.value = p.get('v2'); i2.oninput(); }}
}}
init();
}})();
</script>"""
element_id = get_element_id_for_post(post_id)
if element_id:
print(f"--> Updating existing JS Logic element (ID: {element_id})")
kadence_data = {"content": js_logic}
req_j = urllib.request.Request(f"{url_base_kadence}/{element_id}", data=json.dumps(kadence_data).encode("utf-8"), headers=headers, method="PUT")
else:
print(f"--> Creating new JS Logic element")
kadence_data = {
"title": f"JS Logic: {item['title']}",
"status": "publish",
"content": js_logic,
"meta": {
"_kad_element_hook": "kadence_after_header",
"_kad_element_show_conditionals": json.dumps([{"rule": "singular|calculator", "select": "ids", "ids": [post_id], "mustMatch": False}])
}
}
req_j = urllib.request.Request(url_base_kadence, data=json.dumps(kadence_data).encode("utf-8"), headers=headers, method="POST")
urllib.request.urlopen(req_j, timeout=30)
print(f"--> SUCCESS: Post {post_id}")
time.sleep(1)
print("\nBATCH 10 COMPLETE")

View File

@@ -1,292 +0,0 @@
import urllib.request
import json
import base64
import time
url_base_calc = "https://howdoyouconvert.com/wp-json/wp/v2/calculator/"
url_base_kadence = "https://howdoyouconvert.com/wp-json/wp/v2/kadence_element/"
creds = base64.b64encode(b"ben:6YGf wVxu gBpz pkqx BGZO lfVP").decode("utf-8")
headers = {
"Content-Type": "application/json",
"Authorization": "Basic " + creds,
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64)"
}
batch_2_remaining = [
{
"title": "Becquerel to Curie",
"slug": "becquerel-to-curie",
"label1": "Becquerels (Bq)",
"label2": "Curies (Ci)",
"factor": 2.7027027e-11,
"method1": "multiply",
"seo_text": """
<!-- wp:paragraph -->
<p style="margin-top: 2rem; line-height: 1.6;"><strong>Understanding Becquerel and Curie:</strong> The becquerel and the curie represent two vastly different historical epochs in the measurement of radioactive decay and ionizing particle emissions. Today, the becquerel (Bq) reigns as the supreme and undisputed SI derived unit of ionizing radioactivity. It is famously named for Henri Becquerel, the pioneer who shared a Nobel Prize with the Curies for his historic discovery of radioactivity. A becquerel defines an extraordinarily minute quantity of radiation; precisely one singular nucleus decaying per one absolute second.</p>
<!-- /wp:paragraph -->
<!-- wp:paragraph -->
<p style="line-height: 1.6;">The curie (Ci) stands as one of the original, non-SI radiological units historically embraced by mid-century atomic scientists and early theoretical physicists. Developed directly as a tribute to Pierre Curie, the unit originally attempted to quantify the total number of radiological disintegrations occurring rapidly within one isolated gram of the element Radium-226. Due to the astonishingly high radioactive profile of Radium-226, an individual curie represents a shockingly macroscopic and dangerous cascade of radioactive decay compared to modern SI measurements.</p>
<!-- /wp:paragraph -->
<!-- wp:paragraph -->
<p style="line-height: 1.6;"><strong>The Conversion Process:</strong> Linking the incredibly minuscule modern becquerel back to the massive, mid-century curie requires handling astronomical strings of exponential values. By modern standardized definition, exactly 37 billion becquerels are required to generate exactly one curie of radioactivity. Therefore, to translate from a becquerel baseline into the curie legacy standard, the becquerel value must be multiplied by 2.7027 x 10<sup>-11</sup> (or strictly divided by 37,000,000,000). Evaluating curies backwards into an SI becquerel count requires multiplying the curie parameter by 37,000,000,000.</p>
<!-- /wp:paragraph -->
"""
},
{
"title": "Becquerel to Rutherford",
"slug": "becquerel-to-rutherford",
"label1": "Becquerels (Bq)",
"label2": "Rutherfords (Rd)",
"factor": 0.000001,
"method1": "multiply",
"seo_text": """
<!-- wp:paragraph -->
<p style="margin-top: 2rem; line-height: 1.6;"><strong>Understanding Becquerel and Rutherford:</strong> The becquerel and the rutherford are distinct units utilized to quantify the decay rate and disintegrations of radioactive isotopes. The becquerel (Bq) constitutes the universally accepted cornerstone of the modern SI metric system regarding radiological events. A single becquerel is defined strictly as the activity of a radioactive material in which exactly one nucleus visibly and energetically decays per measured second. Because this rate represents a microscopic snapshot, scientists frequently log environmental radioactive hazards in immense kilobecquerel aggregates.</p>
<!-- /wp:paragraph -->
<!-- wp:paragraph -->
<p style="line-height: 1.6;">The rutherford (Rd), conversely, is a largely obsolete non-SI unit historically proposed in the mid-1940s to act as a more manageable bridge between the impractically small becquerel and the dangerously immense curie. Dedicated to the legendary atomic physicist Ernest Rutherford—credited with discovering both alpha and beta radioactive particles—the unit isolates a more noticeable swath of isotopic disintegration. Namely, one exact rutherford acts as a proxy measurement for a continuous one million nuclear decays per second.</p>
<!-- /wp:paragraph -->
<!-- wp:paragraph -->
<p style="line-height: 1.6;"><strong>The Conversion Process:</strong> Transitioning between these two units is remarkably straightforward due to their shared base-10 numerical foundation surrounding atomic degradation timeframes. A single rutherford encompasses exactly one million becquerels. Because of this linear structure, scaling a microscopic becquerel measurement up into its macro rutherford equivalent requires you to multiply the becquerel value by exactly 0.000001 (or subsequently divide by 1,000,000). Resolving back down from rutherfords into a modern SI becquerel rating requires multiplying the rutherford by one million.</p>
<!-- /wp:paragraph -->
"""
},
{
"title": "Bits to Bytes",
"slug": "bits-to-bytes",
"label1": "Bits (b)",
"label2": "Bytes (B)",
"factor": 0.125,
"method1": "multiply",
"seo_text": """
<!-- wp:paragraph -->
<p style="margin-top: 2rem; line-height: 1.6;"><strong>Understanding Bits and Bytes:</strong> The bit and the byte form the foundational digital alphabet powering all modern computing systems, telecommunications, and digital memory storage. A single bit—shorthand for a "binary digit"—is the absolute smallest possible increment of data a computer architecture can physically recognize. It represents a strict binary state of logical truth, existing explicitly as either a 0 or a 1, a true or false, or an on or off electrical signal.</p>
<!-- /wp:paragraph -->
<!-- wp:paragraph -->
<p style="line-height: 1.6;">The byte, on the other hand, acts as the primary grouping mechanism for these disparate binary signals, bridging raw electrical states into manageable structural data like text or integers. Originally formulated to encompass the exact number of bits required to encode a single character of text on a mainframe computer, a byte eventually standardized cross-platform as an arbitrary string composed of exactly eight distinct bits, commonly referred to as an octet.</p>
<!-- /wp:paragraph -->
<!-- wp:paragraph -->
<p style="line-height: 1.6;"><strong>The Conversion Process:</strong> Shifting computational measurements between base bits and structured bytes relies upon the rigid division of eight. Because telecom systems historically quantify bandwidth velocities in raw bits per second (Mbps), while hard-drive manufacturers tally aggregate mass storage exclusively in bytes (MB/GB), this calculation acts as a daily consumer necessity. To establish the byte structure of an underlying bit-stream, multiply the bit value by 0.125 (or simply divide by 8). Reversing course to find foundational bit requirements from a byte layout requires multiplying the bytes by exactly 8.</p>
<!-- /wp:paragraph -->
"""
},
{
"title": "BTU to Kilojoules",
"slug": "btu-to-kilojoules",
"label1": "British Thermal Units (BTU)",
"label2": "Kilojoules (kJ)",
"factor": 1.05505585,
"method1": "multiply",
"seo_text": """
<!-- wp:paragraph -->
<p style="margin-top: 2rem; line-height: 1.6;"><strong>Understanding BTU and Kilojoules:</strong> The British thermal unit (BTU) and the kilojoule (kJ) are classic measurements bridging thermal engineering methodologies across the Atlantic. The BTU occupies a pivotal position within the United States customary system for measuring raw, sensible heat and ambient energy transfer. It was originally theorized as the exact volume of raw heat required to elevate the temperature of one singular pound of pure water by precisely one degree Fahrenheit at sea level.</p>
<!-- /wp:paragraph -->
<!-- wp:paragraph -->
<p style="line-height: 1.6;">Conversely, the kilojoule acts as a direct, scaled multiplier of the international standard joule, anchoring all metric computations regarding thermal heating, kinetic velocity, and dietary metabolic energy. A single joule embodies the absolute energy forcibly transferred when applying one newton through the absolute distance of one meter. By aggregating this into a thousand, the kilojoule creates an immensely practical macro-measurement spanning everything from structural thermodynamics to the caloric evaluation of food rations.</p>
<!-- /wp:paragraph -->
<!-- wp:paragraph -->
<p style="line-height: 1.6;"><strong>The Conversion Process:</strong> The mathematical bridge correlating legacy imperial HVAC systems and modern SI thermodynamics involves a highly specific, static ratio. The International Table definitively equates one British thermal unit to exactly 1,055.05585 joules, or roughly 1.055 kilojoules. To successfully port a BTU heat capacity specification into its SI kilojoule equivalent, one must invariably multiply the BTU figure by this 1.05505585 scalar. Formulating backwards to determine the underlying legacy BTU output demands the kilojoule metric be divided against that identical constant.</p>
<!-- /wp:paragraph -->
"""
},
{
"title": "BTU/hour to Watts",
"slug": "btuhour-to-watts",
"label1": "BTU per hour (BTU/hr)",
"label2": "Watts (W)",
"factor": 0.293071,
"method1": "multiply",
"seo_text": """
<!-- wp:paragraph -->
<p style="margin-top: 2rem; line-height: 1.6;"><strong>Understanding BTU/hr and Watts:</strong> The BTU per hour and the watt constitute essential metrics for measuring the continuous rate of energy exertion, electrical power production, and industrial heat transferring. The BTU per hour establishes an imperial velocity for sensible heat. Representing the total amount of British thermal units generated or absorbed within an isolated 60-minute window, it serves as the ubiquitous power rating label adorning almost every single air conditioning condenser, furnace, and boiler operating within the United States.</p>
<!-- /wp:paragraph -->
<!-- wp:paragraph -->
<p style="line-height: 1.6;">In stark contrast, the watt (W) serves as the supreme international standardized SI unit for active power scaling. Universally equivalent to the forceful exertion of one raw joule per one absolute second, the watt governs the international output capacity formulas for electric motors, lighting grids, audio amplification arrays, and all major European HVAC system diagnostics. It fundamentally defines how fast a system actively siphons or emits physical energy across the space-time continuum.</p>
<!-- /wp:paragraph -->
<!-- wp:paragraph -->
<p style="line-height: 1.6;"><strong>The Conversion Process:</strong> Comparing the thermal cooling power of American HVAC components against standardized European electrical power draws necessitates locking these continuous output rates into a mathematical formula. Scientifically, generating a singular, steady Watt of active electrical power continuously outputs about 3.41214 BTUs of residual heat energy every hour. To extract a metric Watt equivalency from an American BTU/hr HVAC datasheet rating, multiply the hourly BTUs by a fractional 0.293071 multiplier. Returning an electrical Watt rating back down to an imperial hourly thermal estimate requires multiplying the Watts by exactly 3.41214.</p>
<!-- /wp:paragraph -->
"""
},
{
"title": "Calories to Joules",
"slug": "calories-to-joules",
"label1": "Calories (cal)",
"label2": "Joules (J)",
"factor": 4.184,
"method1": "multiply",
"seo_text": """
<!-- wp:paragraph -->
<p style="margin-top: 2rem; line-height: 1.6;"><strong>Understanding Calories and Joules:</strong> The gram calorie and the joule serve as essential baseline metrics quantifying the production of energy, mechanical power transfers, and chemical heat reactions. The small calorie (often distinctly stylized with a lowercase 'c') traces its origins strictly back to historical physics laboratories. It reflects the finite, calculated volume of raw thermal energy necessary to actively elevate the ambient temperature of one singular gram of water by a single degree Celsius.</p>
<!-- /wp:paragraph -->
<!-- wp:paragraph -->
<p style="line-height: 1.6;">The joule (J), however, eclipsed the small calorie upon the final codification of the modern SI metric system. Universally revered across all modern scientific disciplines as the gold standard of energy computation, the joule represents a remarkably specific mechanical event: the energy physically expended when applying a solitary newton of directional force against an object through exactly one longitudinal meter. It serves as the baseline variable for all higher-level formulas dictating velocity, tension, and kinetic impact.</p>
<!-- /wp:paragraph -->
<!-- wp:paragraph -->
<p style="line-height: 1.6;"><strong>The Conversion Process:</strong> Linking the historical thermal parameters of the small gram calorie to the rigorously defined modern joule relies entirely on the established framework of the "thermochemical calorie" constant. International chemistry standards currently dictate that one single calorie comprises precisely 4.184 mechanical joules of underlying energy. Thus, scaling a small calorie readout into the universal joule standard demands a simple mathematical multiplication of the calorie count by 4.184. Transcribing joules back downward into antiquated thermal calories requires dividing the target joule figure by 4.184.</p>
<!-- /wp:paragraph -->
"""
},
{
"title": "Calories to Kilojoules",
"slug": "calories-to-kilojoules",
"label1": "Kilocalories / Large Calories (kcal)",
"label2": "Kilojoules (kJ)",
"factor": 4.184,
"method1": "multiply",
"seo_text": """
<!-- wp:paragraph -->
<p style="margin-top: 2rem; line-height: 1.6;"><strong>Understanding Kilocalories and Kilojoules:</strong> The kilocalorie and the kilojoule act as the predominant global units dictating human dietary mathematics and mass-scale nutritional metabolic assessments. The kilocalorie (frequently mislabeled simply as a 'Calorie' with a legally mandated capital 'C' on nutritional labels) acts as a structural multiple containing exactly 1,000 small historical thermal calories. It technically quantifies the total biochemical heat expenditure required to raise a full kilogram of raw water by exactly one degree Celsius.</p>
<!-- /wp:paragraph -->
<!-- wp:paragraph -->
<p style="line-height: 1.6;">Across the international community, however, the dietary food energy stored within chemical macromolecules like complex carbohydrates, synthetic fats, and raw proteins is uniformly labeled under the kilojoule (kJ) parameter. Functioning as a multiple containing 1,000 standard SI joules of mechanical energy, the kilojoule ensures human metabolic biology scales cleanly inline with broader universal standards dictating thermal heating outputs and heavy mechanical kinetic impacts.</p>
<!-- /wp:paragraph -->
<!-- wp:paragraph -->
<p style="line-height: 1.6;"><strong>The Conversion Process:</strong> The mathematical relationship tightly binding the dietary kilocalorie logic of the Americas to the global kilojoule standard mirrors the ratio connecting their smaller foundational roots. Because a standard thermochemical kilocalorie is precisely recognized as 4,184 foundational joules, there are exactly 4.184 kilojoules bound inside a single dietary kilocalorie. To port a nutritional kilocalorie readout from an American product label into its metric kilojoule designation, multiply the kilocalories by 4.184. To resolve backwards against the formulation and find kilocalories, reliably divide the kilojoules value by 4.184.</p>
<!-- /wp:paragraph -->
"""
}
]
for item in batch_2_remaining:
print(f"\n--- Constructing UI Block for {item['title']} ---")
slug_raw = item['slug'].replace("-", "")
content_html = f"""
<!-- wp:kadence/rowlayout {{"uniqueID":"{item['slug']}_outer","bgColor":"#f5f7f9","padding":["2rem","2rem","2rem","2rem"],"borderRadius":["8px","8px","8px","8px"]}} -->
<div class="wp-block-kadence-rowlayout alignnone"><div class="kt-row-column-wrap kt-has-1-columns kt-row-layout-equal kt-tab-layout-inherit kt-mobile-layout-row kt-row-valign-top" style="background-color:#f5f7f9;border-radius:8px;padding:2rem;">
<!-- wp:kadence/column {{"uniqueID":"{item['slug']}_inner"}} -->
<div class="wp-block-kadence-column"><div class="kt-inside-inner-col">
<style>.kb-row-layout-id_{slug_raw}_row > .kt-row-column-wrap{{align-content:start;}}:where(.kb-row-layout-id_{slug_raw}_row > .kt-row-column-wrap) > .wp-block-kadence-column{{justify-content:start;}}.kb-row-layout-id_{slug_raw}_row > .kt-row-column-wrap{{column-gap:var(--global-kb-gap-md, 2rem);row-gap:var(--global-kb-gap-md, 2rem);max-width:600px;margin-left:auto;margin-right:auto;grid-template-columns:repeat(2, minmax(0, 1fr));}}.kb-row-layout-id_{slug_raw}_row > .kt-row-layout-overlay{{opacity:0.30;}}@media all and (max-width: 1024px){{.kb-row-layout-id_{slug_raw}_row > .kt-row-column-wrap{{grid-template-columns:repeat(2, minmax(0, 1fr));}}}}@media all and (max-width: 767px){{.kb-row-layout-id_{slug_raw}_row > .kt-row-column-wrap{{grid-template-columns:minmax(0, 1fr);}}}}</style><div class="kb-row-layout-wrap kb-row-layout-id_{slug_raw}_row aligncenter wp-block-kadence-rowlayout"><div class="kt-row-column-wrap kt-has-2-columns kt-row-layout-equal kt-tab-layout-inherit kt-mobile-layout-row kt-row-valign-top"><style>.kadence-column_{slug_raw}_col1 > .kt-inside-inner-col,.kadence-column_{slug_raw}_col1 > .kt-inside-inner-col:before{{border-top-left-radius:0px;border-top-right-radius:0px;border-bottom-right-radius:0px;border-bottom-left-radius:0px;}}.kadence-column_{slug_raw}_col1 > .kt-inside-inner-col{{column-gap:var(--global-kb-gap-sm, 1rem);flex-direction:column;}}.kadence-column_{slug_raw}_col1 > .kt-inside-inner-col > .aligncenter{{width:100%;}}.kadence-column_{slug_raw}_col1 > .kt-inside-inner-col:before{{opacity:0.3;}}.kadence-column_{slug_raw}_col1{{position:relative;}}</style>
<div class="wp-block-kadence-column kadence-column_{slug_raw}_col1"><div class="kt-inside-inner-col">
<label for="input-1" style="font-weight: 600; color: #333333; margin-bottom: 8px; display: block;">{item['label1']}</label>
<input type="number" id="input-1" class="calc-input calc-field" onclick="clearPlaceholder('input-1')" placeholder="0" style="width:100%; padding: 12px; border: 1px solid #ccc; border-radius: 4px; font-size: 1.2rem;">
<input type="hidden" id="factor-1" name="factor-1" value="{item['factor']}"></div></div><style>.kadence-column_{slug_raw}_col2 > .kt-inside-inner-col,.kadence-column_{slug_raw}_col2 > .kt-inside-inner-col:before{{border-top-left-radius:0px;border-top-right-radius:0px;border-bottom-right-radius:0px;border-bottom-left-radius:0px;}}.kadence-column_{slug_raw}_col2 > .kt-inside-inner-col{{column-gap:var(--global-kb-gap-sm, 1rem);flex-direction:column;}}.kadence-column_{slug_raw}_col2 > .kt-inside-inner-col > .aligncenter{{width:100%;}}.kadence-column_{slug_raw}_col2 > .kt-inside-inner-col:before{{opacity:0.3;}}.kadence-column_{slug_raw}_col2{{position:relative;}}</style>
<div class="wp-block-kadence-column kadence-column_{slug_raw}_col2"><div class="kt-inside-inner-col">
<label for="input-2" style="font-weight: 600; color: #333333; margin-bottom: 8px; display: block;">{item['label2']}</label>
<input type="number" id="input-2" class="calc-input calc-field" onclick="clearPlaceholder('input-2')" placeholder="0" style="width:100%; padding: 12px; border: 1px solid #ccc; border-radius: 4px; font-size: 1.2rem;">
</div></div></div></div>
</div></div>
<!-- /wp:kadence/column -->
</div></div>
<!-- /wp:kadence/rowlayout -->
{item['seo_text']}
"""
calc_data = {
"title": item['title'],
"status": "publish",
"slug": item['slug'],
"content": content_html,
"format": "standard",
"comment_status": "closed",
"ping_status": "closed"
}
# Post the calculator
req_c = urllib.request.Request(url_base_calc, data=json.dumps(calc_data).encode("utf-8"), headers=headers, method="POST")
post_id = None
try:
resp_c = urllib.request.urlopen(req_c, timeout=30)
r_json = json.loads(resp_c.read().decode("utf-8"))
post_id = r_json['id']
print(f"--> Posted {item['title']} (ID: {post_id})")
except Exception as e:
print("Error creating calculator:", e)
if hasattr(e, 'read'): print(e.read().decode('utf-8'))
continue
# Setup the JavaScript Kadence Element hook for calculating logic + URL variables
if item['method1'] == "multiply":
math_1_line = f"let val2 = val1 * {item['factor']};"
math_2_line = f"let val1 = val2 / {item['factor']};"
else:
math_1_line = f"let val2 = val1 / {item['factor']};"
math_2_line = f"let val1 = val2 * {item['factor']};"
js_code = f"""
<script>
function calculate1() {{
let val1 = document.getElementById("input-1").value;
if(val1 === "") {{
document.getElementById("input-2").value = "";
return;
}}
{math_1_line}
document.getElementById("input-2").value = val2;
}}
function calculate2() {{
let val2 = document.getElementById("input-2").value;
if(val2 === "") {{
document.getElementById("input-1").value = "";
return;
}}
{math_2_line}
document.getElementById("input-1").value = val1;
}}
document.getElementById("input-1").addEventListener("input", calculate1);
document.getElementById("input-2").addEventListener("input", calculate2);
window.addEventListener('DOMContentLoaded', (event) => {{
const urlParams = new URLSearchParams(window.location.search);
const v1 = urlParams.get('v1');
const v2 = urlParams.get('v2');
if (v1 !== null && !isNaN(v1)) {{
document.getElementById("input-1").value = v1;
calculate1();
}} else if (v2 !== null && !isNaN(v2)) {{
document.getElementById("input-2").value = v2;
calculate2();
}}
}});
</script>
"""
kadence_data = {
"title": f"JS Logic: {item['title']}",
"status": "publish",
"slug": f"js-logic-{item['slug']}",
"content": js_code,
"meta": {
"_kad_element_hook": "kadence_after_header",
"_kad_element_show_conditionals": json.dumps([{"rule": "singular|calculator", "select": "ids", "ids": [post_id], "mustMatch": False}])
}
}
req_j = urllib.request.Request(url_base_kadence, data=json.dumps(kadence_data).encode("utf-8"), headers=headers, method="POST")
try:
resp_j = urllib.request.urlopen(req_j, timeout=30)
j_data = json.loads(resp_j.read().decode("utf-8"))
print(f"--> Posted JS hook (Element ID: {j_data['id']})")
item['element_id'] = j_data['id']
item['post_id'] = post_id
except Exception as e:
print("Error creating JS Element:", e)
if hasattr(e, 'read'): print(e.read().decode('utf-8'))
time.sleep(1)
print("\n--- BATCH 2 REMAINING COMPLETE SUMMARY ---")
for x in batch_2_remaining:
if "post_id" in x:
print(f"{x['title']} | Post: {x['post_id']} | JS: {x['element_id']} | Factor: {x['factor']}")

View File

@@ -1,258 +0,0 @@
import urllib.request
import json
import base64
import time
url_base_calc = "https://howdoyouconvert.com/wp-json/wp/v2/calculator/"
url_base_kadence = "https://howdoyouconvert.com/wp-json/wp/v2/kadence_element/"
creds = base64.b64encode(b"ben:6YGf wVxu gBpz pkqx BGZO lfVP").decode("utf-8")
headers = {
"Content-Type": "application/json",
"Authorization": "Basic " + creds,
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64)"
}
batch_3 = [
{
"title": "Carats to Grams",
"slug": "carats-to-grams",
"label1": "Carats (ct)",
"label2": "Grams (g)",
"factor": 0.2,
"offset": 0,
"seo_text": """
<!-- wp:paragraph -->
<p style="margin-top: 2rem; line-height: 1.6;"><strong>Understanding Carats and Grams:</strong> The carat is a unit of mass used for measuring gemstones and pearls. One carat is defined as exactly 200 milligrams (0.2 grams). The gram is the base unit of mass in the metric system.</p>
<!-- /wp:paragraph -->
"""
},
{
"title": "Celsius to Fahrenheit",
"slug": "celsius-to-fahrenheit",
"label1": "Celsius (°C)",
"label2": "Fahrenheit (°F)",
"factor": 1.8,
"offset": 32,
"seo_text": """
<!-- wp:paragraph -->
<p style="margin-top: 2rem; line-height: 1.6;"><strong>Celsius and Fahrenheit Scales:</strong> These two temperature scales are the most commonly used worldwide. Celsius is part of the metric system, while Fahrenheit is primarily used in the United States and some Caribbean territories.</p>
<!-- /wp:paragraph -->
"""
},
{
"title": "Centimeters to Inches",
"slug": "centimeters-to-inches",
"label1": "Centimeters (cm)",
"label2": "Inches (in)",
"factor": 0.393700787,
"offset": 0,
"seo_text": """
<!-- wp:paragraph -->
<p style="margin-top: 2rem; line-height: 1.6;"><strong>Length Conversion:</strong> Centimeters are a metric unit of length, while inches are part of the imperial and US customary systems. One inch is defined exactly as 2.54 centimeters.</p>
<!-- /wp:paragraph -->
"""
},
{
"title": "CFS to CMS",
"slug": "cfs-to-cms",
"label1": "Cubic Feet per Second (CFS)",
"label2": "Cubic Meters per Second (CMS)",
"factor": 0.0283168466,
"offset": 0,
"seo_text": """
<!-- wp:paragraph -->
<p style="margin-top: 2rem; line-height: 1.6;"><strong>Volumetric Flow Rate:</strong> CFS and CMS are used to measure the volume of fluid (usually water) passing through a point per unit of time. This is critical in hydrology and civil engineering.</p>
<!-- /wp:paragraph -->
"""
},
{
"title": "CMS to CFS",
"slug": "cms-to-cfs",
"label1": "Cubic Meters per Second (CMS)",
"label2": "Cubic Feet per Second (CFS)",
"factor": 35.3146667,
"offset": 0,
"seo_text": """
<!-- wp:paragraph -->
<p style="margin-top: 2rem; line-height: 1.6;"><strong>CMS to CFS Conversion:</strong> Converting from metric volumetric flow (CMS) to imperial (CFS) is essential for international engineering projects and environmental monitoring.</p>
<!-- /wp:paragraph -->
"""
},
{
"title": "Coulomb per Kilogram to Roentgen",
"slug": "coulomb-per-kilogram-to-roentgen",
"label1": "Coulombs per Kilogram (C/kg)",
"label2": "Roentgen (R)",
"factor": 3875.96899,
"offset": 0,
"seo_text": """
<!-- wp:paragraph -->
<p style="margin-top: 2rem; line-height: 1.6;"><strong>Radiation Exposure:</strong> The coulomb per kilogram and the roentgen are units used to measure ionizing radiation exposure in air. The C/kg is the SI unit, while the roentgen is a legacy unit.</p>
<!-- /wp:paragraph -->
"""
},
{
"title": "Cups to Milliliters",
"slug": "cups-to-milliliters",
"label1": "Cups (US)",
"label2": "Milliliters (ml)",
"factor": 236.588237,
"offset": 0,
"seo_text": """
<!-- wp:paragraph -->
<p style="margin-top: 2rem; line-height: 1.6;"><strong>Kitchen Conversion:</strong> Converting US cups to milliliters is a common task in cooking and baking. A standard US cup is approximately 236.6 ml.</p>
<!-- /wp:paragraph -->
"""
},
{
"title": "Curie to Becquerel",
"slug": "curie-to-becquerel",
"label1": "Curies (Ci)",
"label2": "Becquerels (Bq)",
"factor": 3.7e10,
"offset": 0,
"seo_text": """
<!-- wp:paragraph -->
<p style="margin-top: 2rem; line-height: 1.6;"><strong>Radioactivity Units:</strong> The curie is an older, non-SI unit, while the becquerel is the modern SI unit. One curie is exactly 37 billion becquerels.</p>
<!-- /wp:paragraph -->
"""
},
{
"title": "Daltons to AMU",
"slug": "daltons-to-amu",
"label1": "Daltons (Da)",
"label2": "Atomic Mass Units (u)",
"factor": 1.0,
"offset": 0,
"seo_text": """
<!-- wp:paragraph -->
<p style="margin-top: 2rem; line-height: 1.6;"><strong>Atomic Mass Conversion:</strong> The dalton and the unified atomic mass unit (u) are effectively identical units used to express the mass of atoms and molecules.</p>
<!-- /wp:paragraph -->
"""
},
{
"title": "Days to Hours",
"slug": "days-to-hours",
"label1": "Days",
"label2": "Hours",
"factor": 24.0,
"offset": 0,
"seo_text": """
<!-- wp:paragraph -->
<p style="margin-top: 2rem; line-height: 1.6;"><strong>Time Computation:</strong> In our standard 24-hour day system, converting days to hours is done by multiplying the day count by 24.</p>
<!-- /wp:paragraph -->
"""
}
]
for item in batch_3:
print(f"\n--- Constructing UI Block for {item['title']} ---")
slug_raw = item['slug'].replace("-", "")
content_html = f"""
<!-- wp:kadence/rowlayout {{"uniqueID":"{item['slug']}_outer","bgColor":"#f5f7f9","padding":["2rem","2rem","2rem","2rem"],"borderRadius":["8px","8px","8px","8px"]}} -->
<div class="wp-block-kadence-rowlayout alignnone"><div class="kt-row-column-wrap kt-has-1-columns kt-row-layout-equal kt-tab-layout-inherit kt-mobile-layout-row kt-row-valign-top" style="background-color:#f5f7f9;border-radius:8px;padding:2rem;">
<!-- wp:kadence/column {{"uniqueID":"{item['slug']}_inner"}} -->
<div class="wp-block-kadence-column"><div class="kt-inside-inner-col">
<style>.kb-row-layout-id_{slug_raw}_row > .kt-row-column-wrap{{align-content:start;}}:where(.kb-row-layout-id_{slug_raw}_row > .kt-row-column-wrap) > .wp-block-kadence-column{{justify-content:start;}}.kb-row-layout-id_{slug_raw}_row > .kt-row-column-wrap{{column-gap:var(--global-kb-gap-md, 2rem);row-gap:var(--global-kb-gap-md, 2rem);max-width:600px;margin-left:auto;margin-right:auto;grid-template-columns:repeat(2, minmax(0, 1fr));}}.kb-row-layout-id_{slug_raw}_row > .kt-row-layout-overlay{{opacity:0.30;}}@media all and (max-width: 1024px){{.kb-row-layout-id_{slug_raw}_row > .kt-row-column-wrap{{grid-template-columns:repeat(2, minmax(0, 1fr));}}}}@media all and (max-width: 767px){{.kb-row-layout-id_{slug_raw}_row > .kt-row-column-wrap{{grid-template-columns:minmax(0, 1fr);}}}}</style><div class="kb-row-layout-wrap kb-row-layout-id_{slug_raw}_row aligncenter wp-block-kadence-rowlayout"><div class="kt-row-column-wrap kt-has-2-columns kt-row-layout-equal kt-tab-layout-inherit kt-mobile-layout-row kt-row-valign-top">
<div class="wp-block-kadence-column kadence-column_{slug_raw}_col1"><div class="kt-inside-inner-col">
<label for="input-1" style="font-weight: 600; color: #333333; margin-bottom: 8px; display: block;">{item['label1']}</label>
<input type="number" id="input-1" class="calc-input" placeholder="0" style="width:100%; padding: 12px; border: 1px solid #ccc; border-radius: 4px; font-size: 1.2rem;">
</div></div>
<div class="wp-block-kadence-column kadence-column_{slug_raw}_col2"><div class="kt-inside-inner-col">
<label for="input-2" style="font-weight: 600; color: #333333; margin-bottom: 8px; display: block;">{item['label2']}</label>
<input type="number" id="input-2" class="calc-input" placeholder="0" style="width:100%; padding: 12px; border: 1px solid #ccc; border-radius: 4px; font-size: 1.2rem;">
</div></div></div></div>
</div></div>
<!-- /wp:kadence/column -->
</div></div>
<!-- /wp:kadence/rowlayout -->
{item['seo_text']}
"""
calc_data = {
"title": item['title'],
"status": "publish",
"slug": item['slug'],
"content": content_html,
"format": "standard"
}
# Post the calculator
req_c = urllib.request.Request(url_base_calc, data=json.dumps(calc_data).encode("utf-8"), headers=headers, method="POST")
post_id = None
try:
resp_c = urllib.request.urlopen(req_c, timeout=30)
r_json = json.loads(resp_c.read().decode("utf-8"))
post_id = r_json['id']
print(f"--> Posted {item['title']} (ID: {post_id})")
except Exception as e:
print("Error creating calculator:", e)
if hasattr(e, 'read'): print(e.read().decode('utf-8'))
continue
# JS Logic with Offset Support: v2 = v1 * factor + offset
offset = item.get('offset', 0)
js_code = f"""
<script>
function calculate1() {{
let val1 = parseFloat(document.getElementById("input-1").value);
if(isNaN(val1)) {{
document.getElementById("input-2").value = "";
return;
}}
let val2 = val1 * {item['factor']} + {offset};
document.getElementById("input-2").value = parseFloat(val2.toFixed(8));
}}
function calculate2() {{
let val2 = parseFloat(document.getElementById("input-2").value);
if(isNaN(val2)) {{
document.getElementById("input-1").value = "";
return;
}}
let val1 = (val2 - {offset}) / {item['factor']};
document.getElementById("input-1").value = parseFloat(val1.toFixed(8));
}}
document.getElementById("input-1").addEventListener("input", calculate1);
document.getElementById("input-2").addEventListener("input", calculate2);
window.addEventListener('DOMContentLoaded', (event) => {{
const urlParams = new URLSearchParams(window.location.search);
const v1 = urlParams.get('v1');
const v2 = urlParams.get('v2');
if (v1 !== null && !isNaN(v1)) {{
document.getElementById("input-1").value = v1;
calculate1();
}} else if (v2 !== null && !isNaN(v2)) {{
document.getElementById("input-2").value = v2;
calculate2();
}}
}});
</script>
"""
kadence_data = {
"title": f"JS Logic: {item['title']}",
"status": "publish",
"content": js_code,
"meta": {
"_kad_element_hook": "kadence_after_header",
"_kad_element_show_conditionals": json.dumps([{"rule": "singular|calculator", "select": "ids", "ids": [post_id], "mustMatch": False}])
}
}
req_j = urllib.request.Request(url_base_kadence, data=json.dumps(kadence_data).encode("utf-8"), headers=headers, method="POST")
try:
urllib.request.urlopen(req_j, timeout=30)
print(f"--> Posted JS hook")
except Exception as e:
print("Error creating JS Element:", e)
time.sleep(1)
print("\n--- BATCH 3 COMPLETE ---")

View File

@@ -1,255 +0,0 @@
import urllib.request
import json
import base64
import time
url_base_calc = "https://howdoyouconvert.com/wp-json/wp/v2/calculator/"
url_base_kadence = "https://howdoyouconvert.com/wp-json/wp/v2/kadence_element/"
creds = base64.b64encode(b"ben:6YGf wVxu gBpz pkqx BGZO lfVP").decode("utf-8")
headers = {
"Content-Type": "application/json",
"Authorization": "Basic " + creds,
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64)"
}
batch_4 = [
{
"title": "Days to Weeks",
"slug": "days-to-weeks",
"label1": "Days",
"label2": "Weeks",
"factor": 1/7,
"offset": 0,
"seo_text": """
<!-- wp:paragraph -->
<p style="margin-top: 2rem; line-height: 1.6;"><strong>Time Conversion - Days to Weeks:</strong> Weeks are a standard unit of time used across most calendars globally. One week consists of seven days. This calculator helps you convert daily counts into standard weeks.</p>
<!-- /wp:paragraph -->
"""
},
{
"title": "Days to Years",
"slug": "days-to-years",
"label1": "Days",
"label2": "Years",
"factor": 1/365.25,
"offset": 0,
"seo_text": """
<!-- wp:paragraph -->
<p style="margin-top: 2rem; line-height: 1.6;"><strong>Time Conversion - Days to Years:</strong> Converting days into years is important for astronomical and logistical calculations. This calculator uses the standard Gregorian year length of 365.25 days to account for leap years.</p>
<!-- /wp:paragraph -->
"""
},
{
"title": "Degrees to Mils",
"slug": "degrees-to-mils",
"label1": "Degrees (°)",
"label2": "Mils",
"factor": 17.777777778,
"offset": 0,
"seo_text": """
<!-- wp:paragraph -->
<p style="margin-top: 2rem; line-height: 1.6;"><strong>Angle Measurement - Degrees to Mils:</strong> While degrees are common in everyday use, mils (milliradians) are frequently used in military and engineering contexts for precise targeting and measurement.</p>
<!-- /wp:paragraph -->
"""
},
{
"title": "Degrees to Radians",
"slug": "degrees-to-radians",
"label1": "Degrees (°)",
"label2": "Radians (rad)",
"factor": 0.0174532925,
"offset": 0,
"seo_text": """
<!-- wp:paragraph -->
<p style="margin-top: 2rem; line-height: 1.6;"><strong>Mathematical Precision - Degrees to Radians:</strong> Radians are the standard unit of angular measure used in mathematics, physics, and computer science. This calculator provides a quick conversion from common degrees.</p>
<!-- /wp:paragraph -->
"""
},
{
"title": "Dynes to Newtons",
"slug": "dynes-to-newtons",
"label1": "Dynes",
"label2": "Newtons (N)",
"factor": 1e-5,
"offset": 0,
"seo_text": """
<!-- wp:paragraph -->
<p style="margin-top: 2rem; line-height: 1.6;"><strong>Force Measurement - Dynes to Newtons:</strong> The dyne is a unit of force in the cgs (centimeter-gram-second) system, while the newton is the standard SI unit. One newton is exactly 100,000 dynes.</p>
<!-- /wp:paragraph -->
"""
},
{
"title": "Ergs to Joules",
"slug": "ergs-to-joules",
"label1": "Ergs",
"label2": "Joules (J)",
"factor": 1e-7,
"offset": 0,
"seo_text": """
<!-- wp:paragraph -->
<p style="margin-top: 2rem; line-height: 1.6;"><strong>Energy Conversion - Ergs to Joules:</strong> The erg is a legacy unit of energy and mechanical work in the cgs system. In modern science, the joule is the preferred SI unit for energy.</p>
<!-- /wp:paragraph -->
"""
},
{
"title": "Feet to Meters",
"slug": "feet-to-meters",
"label1": "Feet (ft)",
"label2": "Meters (m)",
"factor": 0.3048,
"offset": 0,
"seo_text": """
<!-- wp:paragraph -->
<p style="margin-top: 2rem; line-height: 1.6;"><strong>Length Conversion - Feet to Meters:</strong> Feet are part of the imperial and US customary systems, while meters are the core metric unit of length. One foot is defined internationally as exactly 0.3048 meters.</p>
<!-- /wp:paragraph -->
"""
},
{
"title": "Foot-Pounds to Newton-Meters",
"slug": "foot-pounds-to-newton-meters",
"label1": "Foot-Pounds (ft-lb)",
"label2": "Newton-Meters (N-m)",
"factor": 1.35581795,
"offset": 0,
"seo_text": """
<!-- wp:paragraph -->
<p style="margin-top: 2rem; line-height: 1.6;"><strong>Torque Conversion:</strong> Foot-pounds and newton-meters are units used to measure torque or work. This calculator is particularly useful for mechanics and engineers.</p>
<!-- /wp:paragraph -->
"""
},
{
"title": "Gallons to Liters",
"slug": "gallons-to-liters",
"label1": "Gallons (US)",
"label2": "Liters (L)",
"factor": 3.78541178,
"offset": 0,
"seo_text": """
<!-- wp:paragraph -->
<p style="margin-top: 2rem; line-height: 1.6;"><strong>Volume Conversion - Gallons to Liters:</strong> Converting between US gallons and metric liters is a common requirement in automotive, culinary, and scientific fields.</p>
<!-- /wp:paragraph -->
"""
},
{
"title": "Gigabytes to Megabytes",
"slug": "gigabytes-to-megabytes",
"label1": "Gigabytes (GB)",
"label2": "Megabytes (MB)",
"factor": 1000.0,
"offset": 0,
"seo_text": """
<!-- wp:paragraph -->
<p style="margin-top: 2rem; line-height: 1.6;"><strong>Digital Storage - GB to MB:</strong> This calculator uses the standard decimal (base-10) convention used by hard drive manufacturers and memory card providers, where 1 GB = 1,000 MB.</p>
<!-- /wp:paragraph -->
"""
}
]
for item in batch_4:
print(f"\\n--- Processing {item['title']} ---")
slug_raw = item['slug'].replace("-", "")
content_html = f"""
<!-- wp:kadence/rowlayout {{"uniqueID":"{item['slug']}_outer","bgColor":"#f5f7f9","padding":["2rem","2rem","2rem","2rem"],"borderRadius":["8px","8px","8px","8px"]}} -->
<div class="wp-block-kadence-rowlayout alignnone"><div class="kt-row-column-wrap kt-has-1-columns kt-row-layout-equal kt-tab-layout-inherit kt-mobile-layout-row kt-row-valign-top" style="background-color:#f5f7f9;border-radius:8px;padding:2rem;">
<!-- wp:kadence/column {{"uniqueID":"{item['slug']}_inner"}} -->
<div class="wp-block-kadence-column"><div class="kt-inside-inner-col">
<style>.kb-row-layout-id_{slug_raw}_row > .kt-row-column-wrap{{align-content:start;}}:where(.kb-row-layout-id_{slug_raw}_row > .kt-row-column-wrap) > .wp-block-kadence-column{{justify-content:start;}}.kb-row-layout-id_{slug_raw}_row > .kt-row-column-wrap{{column-gap:var(--global-kb-gap-md, 2rem);row-gap:var(--global-kb-gap-md, 2rem);max-width:600px;margin-left:auto;margin-right:auto;grid-template-columns:repeat(2, minmax(0, 1fr));}}.kb-row-layout-id_{slug_raw}_row > .kt-row-layout-overlay{{opacity:0.30;}}@media all and (max-width: 1024px){{.kb-row-layout-id_{slug_raw}_row > .kt-row-column-wrap{{grid-template-columns:repeat(2, minmax(0, 1fr));}}}}@media all and (max-width: 767px){{.kb-row-layout-id_{slug_raw}_row > .kt-row-column-wrap{{grid-template-columns:minmax(0, 1fr);}}}}</style><div class="kb-row-layout-wrap kb-row-layout-id_{slug_raw}_row aligncenter wp-block-kadence-rowlayout"><div class="kt-row-column-wrap kt-has-2-columns kt-row-layout-equal kt-tab-layout-inherit kt-mobile-layout-row kt-row-valign-top">
<div class="wp-block-kadence-column kadence-column_{slug_raw}_col1"><div class="kt-inside-inner-col">
<label for="input-1" style="font-weight: 600; color: #333333; margin-bottom: 8px; display: block;">{item['label1']}</label>
<input type="number" id="input-1" class="calc-input" placeholder="0" style="width:100%; padding: 12px; border: 1px solid #ccc; border-radius: 4px; font-size: 1.2rem;">
</div></div>
<div class="wp-block-kadence-column kadence-column_{slug_raw}_col2"><div class="kt-inside-inner-col">
<label for="input-2" style="font-weight: 600; color: #333333; margin-bottom: 8px; display: block;">{item['label2']}</label>
<input type="number" id="input-2" class="calc-input" placeholder="0" style="width:100%; padding: 12px; border: 1px solid #ccc; border-radius: 4px; font-size: 1.2rem;">
</div></div></div></div>
</div></div>
<!-- /wp:kadence/column -->
</div></div>
<!-- /wp:kadence/rowlayout -->
{item['seo_text']}
"""
calc_data = {
"title": item['title'],
"status": "publish",
"slug": item['slug'],
"content": content_html,
"format": "standard"
}
# Post Calculator
req_c = urllib.request.Request(url_base_calc, data=json.dumps(calc_data).encode("utf-8"), headers=headers, method="POST")
try:
resp_c = urllib.request.urlopen(req_c, timeout=30)
res_c = json.loads(resp_c.read().decode("utf-8"))
post_id = res_c['id']
print(f"--> Posted {item['title']} (ID: {post_id})")
# JS Logic with robust event handling
offset = item.get('offset', 0)
js_wrapped = f"""<script>
window.addEventListener('DOMContentLoaded', (event) => {{
const inp1 = document.getElementById("input-1");
const inp2 = document.getElementById("input-2");
function calculate1() {{
let val1 = parseFloat(inp1.value);
if(isNaN(val1)) {{
inp2.value = "";
return;
}}
let val2 = val1 * {item['factor']} + {offset};
inp2.value = parseFloat(val2.toFixed(8));
}}
function calculate2() {{
let val2 = parseFloat(inp2.value);
if(isNaN(val2)) {{
inp1.value = "";
return;
}}
let val1 = (val2 - {offset}) / {item['factor']};
inp1.value = parseFloat(val1.toFixed(8));
}}
inp1.addEventListener("input", calculate1);
inp2.addEventListener("input", calculate2);
const urlParams = new URLSearchParams(window.location.search);
const v1 = urlParams.get('v1');
const v2 = urlParams.get('v2');
if (v1 !== null && !isNaN(parseFloat(v1))) {{
inp1.value = v1;
calculate1();
}} else if (v2 !== null && !isNaN(parseFloat(v2))) {{
inp2.value = v2;
calculate2();
}}
}});
</script>"""
kadence_data = {
"title": f"JS Logic: {item['title']}",
"status": "publish",
"content": js_wrapped,
"meta": {
"_kad_element_hook": "kadence_after_header",
"_kad_element_show_conditionals": json.dumps([{"rule": "singular|calculator", "select": "ids", "ids": [post_id], "mustMatch": False}])
}
}
req_j = urllib.request.Request(url_base_kadence, data=json.dumps(kadence_data).encode("utf-8"), headers=headers, method="POST")
urllib.request.urlopen(req_j, timeout=30)
print(f"--> Posted JS hook")
except Exception as e:
print(f"Error: {e}")
if hasattr(e, 'read'): print(e.read().decode('utf-8'))
time.sleep(1)
print("\\n--- BATCH 4 COMPLETE ---")

View File

@@ -1,259 +0,0 @@
import urllib.request
import json
import base64
import time
url_base_calc = "https://howdoyouconvert.com/wp-json/wp/v2/calculator/"
url_base_kadence = "https://howdoyouconvert.com/wp-json/wp/v2/kadence_element/"
creds = base64.b64encode(b"ben:6YGf wVxu gBpz pkqx BGZO lfVP").decode("utf-8")
headers = {
"Content-Type": "application/json",
"Authorization": "Basic " + creds,
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64)"
}
batch_5 = [
{
"title": "Fahrenheit to Celsius",
"slug": "fahrenheit-to-celsius",
"label1": "Fahrenheit (°F)",
"label2": "Celsius (°C)",
"factor": 5/9,
"offset": -32 * (5/9),
"seo_text": """
<!-- wp:paragraph -->
<p style="margin-top: 2rem; line-height: 1.6;"><strong>Temperature Conversion - Fahrenheit to Celsius:</strong> Converting between Fahrenheit and Celsius is a common necessity for travel, science, and weather reporting. This calculator uses the standard formula $C = (F - 32) \times 5/9$.</p>
<!-- /wp:paragraph -->
"""
},
{
"title": "Feet per Second to Meters per Second",
"slug": "feet-per-second-to-meters-per-second",
"label1": "Feet per Second (ft/s)",
"label2": "Meters per Second (m/s)",
"factor": 0.3048,
"offset": 0,
"seo_text": """
<!-- wp:paragraph -->
<p style="margin-top: 2rem; line-height: 1.6;"><strong>Speed Conversion:</strong> Feet per second and meters per second are both standard units of speed. This converter is essential for engineering, ballistics, and aviation calculations where different measurement systems are used.</p>
<!-- /wp:paragraph -->
"""
},
{
"title": "Fluid Ounces to Milliliters",
"slug": "fluid-ounces-to-milliliters",
"label1": "Fluid Ounces (US fl oz)",
"label2": "Milliliters (ml)",
"factor": 29.5735296,
"offset": 0,
"seo_text": """
<!-- wp:paragraph -->
<p style="margin-top: 2rem; line-height: 1.6;"><strong>Volume Conversion:</strong> US fluid ounces are a standard unit of liquid volume in the United States. This tool allows for precise conversion to milliliters, commonly used in food labels and medicine.</p>
<!-- /wp:paragraph -->
"""
},
{
"title": "Gallons per Minute to Liters per Second",
"slug": "gallons-per-minute-to-liters-per-second",
"label1": "Gallons per Minute (GPM)",
"label2": "Liters per Second (L/s)",
"factor": 0.0630901964,
"offset": 0,
"seo_text": """
<!-- wp:paragraph -->
<p style="margin-top: 2rem; line-height: 1.6;"><strong>Flow Rate Conversion:</strong> Gallons per minute (GPM) is a common unit for water flow in plumbing and irrigation, while liters per second (L/s) is the preferred SI unit for volumetric flow.</p>
<!-- /wp:paragraph -->
"""
},
{
"title": "Grains to Grams",
"slug": "grains-to-grams",
"label1": "Grains (gr)",
"label2": "Grams (g)",
"factor": 0.06479891,
"offset": 0,
"seo_text": """
<!-- wp:paragraph -->
<p style="margin-top: 2rem; line-height: 1.6;"><strong>Weight Conversion:</strong> The grain is a unit of measurement for mass, based on the average mass of a single seed of a cereal. It is still used today in ballistics and the measurement of medication.</p>
<!-- /wp:paragraph -->
"""
},
{
"title": "Grams to Milligrams",
"slug": "grams-to-milligrams",
"label1": "Grams (g)",
"label2": "Milligrams (mg)",
"factor": 1000.0,
"offset": 0,
"seo_text": """
<!-- wp:paragraph -->
<p style="margin-top: 2rem; line-height: 1.6;"><strong>Metric Mass Conversion:</strong> Milligrams are equal to one-thousandth of a gram. This conversion is extremely common in chemistry, biology, and healthcare for measuring small quantities of substances.</p>
<!-- /wp:paragraph -->
"""
},
{
"title": "Grams to Ounces",
"slug": "grams-to-ounces",
"label1": "Grams (g)",
"label2": "Ounces (oz)",
"factor": 0.0352739619,
"offset": 0,
"seo_text": """
<!-- wp:paragraph -->
<p style="margin-top: 2rem; line-height: 1.6;"><strong>Mass Conversion:</strong> Converting metric grams to imperial ounces is a frequent task in international commerce and cooking. One ounce is approximately 28.35 grams.</p>
<!-- /wp:paragraph -->
"""
},
{
"title": "Grams to Pennyweights",
"slug": "grams-to-pennyweights",
"label1": "Grams (g)",
"label2": "Pennyweights (dwt)",
"factor": 0.643014931,
"offset": 0,
"seo_text": """
<!-- wp:paragraph -->
<p style="margin-top: 2rem; line-height: 1.6;"><strong>Jewelry Measurement:</strong> Pennyweights are a traditional unit of mass used in the jewelry industry for precious metals. This calculator provides a precise bridge to the metric system.</p>
<!-- /wp:paragraph -->
"""
},
{
"title": "Grams to Troy Ounces",
"slug": "grams-to-troy-ounces",
"label1": "Grams (g)",
"label2": "Troy Ounces (oz t)",
"factor": 0.0321507466,
"offset": 0,
"seo_text": """
<!-- wp:paragraph -->
<p style="margin-top: 2rem; line-height: 1.6;"><strong>Precious Metal Calculation:</strong> Unlike standard ounces, troy ounces are used specifically for the pricing and measurement of gold, silver, and platinum. One troy ounce is equivalent to 31.103 grams.</p>
<!-- /wp:paragraph -->
"""
},
{
"title": "Gray to Rad",
"slug": "gray-to-rad",
"label1": "Grays (Gy)",
"label2": "Rads",
"factor": 100.0,
"offset": 0,
"seo_text": """
<!-- wp:paragraph -->
<p style="margin-top: 2rem; line-height: 1.6;"><strong>Absorbed Dose Conversion:</strong> The gray is the SI unit of absorbed ionizing radiation dose, while the rad is the deprecated cgs unit. One gray is defined as exactly 100 rads.</p>
<!-- /wp:paragraph -->
"""
}
]
for item in batch_5:
print(f"\\n--- Processing {item['title']} ---")
slug_raw = item['slug'].replace("-", "")
content_html = f"""
<!-- wp:kadence/rowlayout {{"uniqueID":"{item['slug']}_outer","bgColor":"#f5f7f9","padding":["2rem","2rem","2rem","2rem"],"borderRadius":["8px","8px","8px","8px"]}} -->
<div class="wp-block-kadence-rowlayout alignnone"><div class="kt-row-column-wrap kt-has-1-columns kt-row-layout-equal kt-tab-layout-inherit kt-mobile-layout-row kt-row-valign-top" style="background-color:#f5f7f9;border-radius:8px;padding:2rem;">
<!-- wp:kadence/column {{"uniqueID":"{item['slug']}_inner"}} -->
<div class="wp-block-kadence-column"><div class="kt-inside-inner-col">
<style>.kb-row-layout-id_{slug_raw}_row > .kt-row-column-wrap{{align-content:start;}}:where(.kb-row-layout-id_{slug_raw}_row > .kt-row-column-wrap) > .wp-block-kadence-column{{justify-content:start;}}.kb-row-layout-id_{slug_raw}_row > .kt-row-column-wrap{{column-gap:var(--global-kb-gap-md, 2rem);row-gap:var(--global-kb-gap-md, 2rem);max-width:600px;margin-left:auto;margin-right:auto;grid-template-columns:repeat(2, minmax(0, 1fr));}}.kb-row-layout-id_{slug_raw}_row > .kt-row-layout-overlay{{opacity:0.30;}}@media all and (max-width: 1024px){{.kb-row-layout-id_{slug_raw}_row > .kt-row-column-wrap{{grid-template-columns:repeat(2, minmax(0, 1fr));}}}}@media all and (max-width: 767px){{.kb-row-layout-id_{slug_raw}_row > .kt-row-column-wrap{{grid-template-columns:minmax(0, 1fr);}}}}</style><div class="kb-row-layout-wrap kb-row-layout-id_{slug_raw}_row aligncenter wp-block-kadence-rowlayout"><div class="kt-row-column-wrap kt-has-2-columns kt-row-layout-equal kt-tab-layout-inherit kt-mobile-layout-row kt-row-valign-top">
<div class="wp-block-kadence-column kadence-column_{slug_raw}_col1"><div class="kt-inside-inner-col">
<label for="input-1" style="font-weight: 600; color: #333333; margin-bottom: 8px; display: block;">{item['label1']}</label>
<input type="number" id="input-1" class="calc-input" placeholder="0" style="width:100%; padding: 12px; border: 1px solid #ccc; border-radius: 4px; font-size: 1.2rem;">
</div></div>
<div class="wp-block-kadence-column kadence-column_{slug_raw}_col2"><div class="kt-inside-inner-col">
<label for="input-2" style="font-weight: 600; color: #333333; margin-bottom: 8px; display: block;">{item['label2']}</label>
<input type="number" id="input-2" class="calc-input" placeholder="0" style="width:100%; padding: 12px; border: 1px solid #ccc; border-radius: 4px; font-size: 1.2rem;">
</div></div></div></div>
</div></div>
<!-- /wp:kadence/column -->
</div></div>
<!-- /wp:kadence/rowlayout -->
{item['seo_text']}
"""
calc_data = {
"title": item['title'],
"status": "publish",
"slug": item['slug'],
"content": content_html,
"format": "standard"
}
# Post Calculator
req_c = urllib.request.Request(url_base_calc, data=json.dumps(calc_data).encode("utf-8"), headers=headers, method="POST")
try:
resp_c = urllib.request.urlopen(req_c, timeout=30)
res_c = json.loads(resp_c.read().decode("utf-8"))
post_id = res_c['id']
print(f"--> Posted {item['title']} (ID: {post_id})")
# JS Logic with robust event handling
offset = item.get('offset', 0)
js_wrapped = f"""<script>
window.addEventListener('DOMContentLoaded', (event) => {{
const inp1 = document.getElementById("input-1");
const inp2 = document.getElementById("input-2");
function calculate1() {{
let val1 = parseFloat(inp1.value);
if(isNaN(val1)) {{
inp2.value = "";
return;
}}
let val2 = val1 * {item['factor']} + {offset};
inp2.value = parseFloat(val2.toFixed(8));
}}
function calculate2() {{
let val2 = parseFloat(inp2.value);
if(isNaN(val2)) {{
inp1.value = "";
return;
}}
let val1 = (val2 - {offset}) / {item['factor']};
inp1.value = parseFloat(val1.toFixed(8));
}}
inp1.addEventListener("input", calculate1);
inp2.addEventListener("input", calculate2);
const urlParams = new URLSearchParams(window.location.search);
if (urlParams.has('v1')) {{
let v1 = parseFloat(urlParams.get('v1'));
if (!isNaN(v1)) {{
inp1.value = v1;
calculate1();
}}
}} else if (urlParams.has('v2')) {{
let v2 = parseFloat(urlParams.get('v2'));
if (!isNaN(v2)) {{
inp2.value = v2;
calculate2();
}}
}}
}});
</script>"""
kadence_data = {
"title": f"JS Logic: {item['title']}",
"status": "publish",
"content": js_wrapped,
"meta": {
"_kad_element_hook": "kadence_after_header",
"_kad_element_show_conditionals": json.dumps([{"rule": "singular|calculator", "select": "ids", "ids": [post_id], "mustMatch": False}])
}
}
req_j = urllib.request.Request(url_base_kadence, data=json.dumps(kadence_data).encode("utf-8"), headers=headers, method="POST")
urllib.request.urlopen(req_j, timeout=30)
print(f"--> Posted JS hook")
except Exception as e:
print(f"Error: {e}")
if hasattr(e, 'read'): print(e.read().decode('utf-8'))
time.sleep(1)
print("\\n--- BATCH 5 COMPLETE ---")

View File

@@ -1,247 +0,0 @@
import urllib.request
import json
import base64
import time
url_base_calc = "https://howdoyouconvert.com/wp-json/wp/v2/calculator/"
url_base_kadence = "https://howdoyouconvert.com/wp-json/wp/v2/kadence_element/"
creds = base64.b64encode(b"ben:6YGf wVxu gBpz pkqx BGZO lfVP").decode("utf-8")
headers = {
"Content-Type": "application/json",
"Authorization": "Basic " + creds,
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64)"
}
batch_6 = [
{
"title": "Grams to Apothecary Ounces",
"slug": "grams-to-apothecary-ounces",
"label1": "Grams (g)",
"label2": "Apothecary Ounces (ap oz)",
"factor": 0.0321507466,
"offset": 0,
"seo_text": """
<!-- wp:paragraph -->
<p style="margin-top: 2rem; line-height: 1.6;"><strong>Weight Conversion:</strong> Apothecary ounces were historically used by pharmacists and chemists to measure ingredients for medicine. This calculator provides a precise conversion to standard metric grams.</p>
<!-- /wp:paragraph -->
"""
},
{
"title": "Grams to Carats",
"slug": "grams-to-carats",
"label1": "Grams (g)",
"label2": "Carats (ct)",
"factor": 5.0,
"offset": 0,
"seo_text": """
<!-- wp:paragraph -->
<p style="margin-top: 2rem; line-height: 1.6;"><strong>Jewelry Weight:</strong> The metric carat is defined as exactly 200 milligrams. Converting grams to carats is standard practice in the gemstone industry for pricing and weight measurement.</p>
<!-- /wp:paragraph -->
"""
},
{
"title": "Grams to Grains",
"slug": "grams-to-grains",
"label1": "Grams (g)",
"label2": "Grains (gr)",
"factor": 15.4323584,
"offset": 0,
"seo_text": """
<!-- wp:paragraph -->
<p style="margin-top: 2rem; line-height: 1.6;"><strong>Fine Weight:</strong> One gram is equivalent to approximately 15.43 grains. Grains are used in various specialized fields, including the measurement of gunpowder and certain medications.</p>
<!-- /wp:paragraph -->
"""
},
{
"title": "Horsepower to Kilowatts",
"slug": "horsepower-to-kilowatts",
"label1": "Horsepower (hp)",
"label2": "Kilowatts (kW)",
"factor": 0.745699872,
"offset": 0,
"seo_text": """
<!-- wp:paragraph -->
<p style="margin-top: 2rem; line-height: 1.6;"><strong>Power Measurement:</strong> Horsepower is a unit used to measure the power of engines and motors. Converting to kilowatts (the SI unit) allows for easier comparison across different engineering standards.</p>
<!-- /wp:paragraph -->
"""
},
{
"title": "Hours to Days",
"slug": "hours-to-days",
"label1": "Hours",
"label2": "Days",
"factor": 0.0416666667,
"offset": 0,
"seo_text": """
<!-- wp:paragraph -->
<p style="margin-top: 2rem; line-height: 1.6;"><strong>Time Management:</strong> There are exactly 24 hours in one day. This tool facilitates the conversion of hourly task durations or logistical windows into full day equivalents.</p>
<!-- /wp:paragraph -->
"""
},
{
"title": "Hours to Minutes",
"slug": "hours-to-minutes",
"label1": "Hours",
"label2": "Minutes",
"factor": 60.0,
"offset": 0,
"seo_text": """
<!-- wp:paragraph -->
<p style="margin-top: 2rem; line-height: 1.6;"><strong>Quick Time Math:</strong> Converting hours into minutes is one of the most common everyday calculations for scheduling, travel, and logistics.</p>
<!-- /wp:paragraph -->
"""
},
{
"title": "Inches of Mercury to Pascals",
"slug": "inches-of-mercury-to-pascals",
"label1": "Inches of Mercury (inHg)",
"label2": "Pascals (Pa)",
"factor": 3386.389,
"offset": 0,
"seo_text": """
<!-- wp:paragraph -->
<p style="margin-top: 2rem; line-height: 1.6;"><strong>Pressure Conversion:</strong> Inches of mercury is a unit for pressure used in meteorology and aviation. Converting to pascals (the SI unit) is necessary for various scientific and atmospheric calculations.</p>
<!-- /wp:paragraph -->
"""
},
{
"title": "Inches of Water to Pascals",
"slug": "inches-of-water-to-pascals",
"label1": "Inches of Water (inH2O)",
"label2": "Pascals (Pa)",
"factor": 249.08891,
"offset": 0,
"seo_text": """
<!-- wp:paragraph -->
<p style="margin-top: 2rem; line-height: 1.6;"><strong>HVAC & Fluid Dynamics:</strong> Inches of water column (WC) is a unit commonly used in low-pressure applications like ventilation and plumbing systems. One inch of water is approximately 249 pascals.</p>
<!-- /wp:paragraph -->
"""
},
{
"title": "Inches to Centimeters",
"slug": "inches-to-centimeters",
"label1": "Inches (in)",
"label2": "Centimeters (cm)",
"factor": 2.54,
"offset": 0,
"seo_text": """
<!-- wp:paragraph -->
<p style="margin-top: 2rem; line-height: 1.6;"><strong>Metric Precision:</strong> The international inch is defined as exactly 2.54 centimeters. This converter is used daily for manufacturing, design, and education worldwide.</p>
<!-- /wp:paragraph -->
"""
},
{
"title": "Inches to Millimeters",
"slug": "inches-to-millimeters",
"label1": "Inches (in)",
"label2": "Millimeters (mm)",
"factor": 25.4,
"offset": 0,
"seo_text": """
<!-- wp:paragraph -->
<p style="margin-top: 2rem; line-height: 1.6;"><strong>Fine Precision:</strong> Millimeters offer a finer grain of measurement for technical drawings and engineering. One inch equals exactly 25.4 millimeters.</p>
<!-- /wp:paragraph -->
"""
}
]
for item in batch_6[4:]:
print(f"\\n--- Processing {item['title']} ---")
slug_raw = item['slug'].replace("-", "")
content_html = f"""
<!-- wp:kadence/rowlayout {{"uniqueID":"{item['slug']}_outer","bgColor":"#f5f7f9","padding":["2rem","2rem","2rem","2rem"],"borderRadius":["8px","8px","8px","8px"]}} -->
<div class="wp-block-kadence-rowlayout alignnone"><div class="kt-row-column-wrap kt-has-1-columns kt-row-layout-equal kt-tab-layout-inherit kt-mobile-layout-row kt-row-valign-top" style="background-color:#f5f7f9;border-radius:8px;padding:2rem;">
<!-- wp:kadence/column {{"uniqueID":"{item['slug']}_inner"}} -->
<div class="wp-block-kadence-column"><div class="kt-inside-inner-col">
<style>.kb-row-layout-id_{slug_raw}_row > .kt-row-column-wrap{{align-content:start;}}:where(.kb-row-layout-id_{slug_raw}_row > .kt-row-column-wrap) > .wp-block-kadence-column{{justify-content:start;}}.kb-row-layout-id_{slug_raw}_row > .kt-row-column-wrap{{column-gap:var(--global-kb-gap-md, 2rem);row-gap:var(--global-kb-gap-md, 2rem);max-width:600px;margin-left:auto;margin-right:auto;grid-template-columns:repeat(2, minmax(0, 1fr));}}.kb-row-layout-id_{slug_raw}_row > .kt-row-layout-overlay{{opacity:0.30;}}@media all and (max-width: 1024px){{.kb-row-layout-id_{slug_raw}_row > .kt-row-column-wrap{{grid-template-columns:repeat(2, minmax(0, 1fr));}}}}@media all and (max-width: 767px){{.kb-row-layout-id_{slug_raw}_row > .kt-row-column-wrap{{grid-template-columns:minmax(0, 1fr);}}}}</style><div class="kb-row-layout-wrap kb-row-layout-id_{slug_raw}_row aligncenter wp-block-kadence-rowlayout"><div class="kt-row-column-wrap kt-has-2-columns kt-row-layout-equal kt-tab-layout-inherit kt-mobile-layout-row kt-row-valign-top">
<div class="wp-block-kadence-column kadence-column_{slug_raw}_col1"><div class="kt-inside-inner-col">
<label for="input-1" style="font-weight: 600; color: #333333; margin-bottom: 8px; display: block;">{item['label1']}</label>
<input type="number" id="input-1" class="calc-input" placeholder="0" style="width:100%; padding: 12px; border: 1px solid #ccc; border-radius: 4px; font-size: 1.2rem;">
</div></div>
<div class="wp-block-kadence-column kadence-column_{slug_raw}_col2"><div class="kt-inside-inner-col">
<label for="input-2" style="font-weight: 600; color: #333333; margin-bottom: 8px; display: block;">{item['label2']}</label>
<input type="number" id="input-2" class="calc-input" placeholder="0" style="width:100%; padding: 12px; border: 1px solid #ccc; border-radius: 4px; font-size: 1.2rem;">
</div></div></div></div>
</div></div>
<!-- /wp:kadence/column -->
</div></div>
<!-- /wp:kadence/rowlayout -->
{item['seo_text']}
"""
calc_data = {
"title": item['title'],
"status": "publish",
"slug": item['slug'],
"content": content_html,
"format": "standard"
}
# Post Calculator
req_c = urllib.request.Request(url_base_calc, data=json.dumps(calc_data).encode("utf-8"), headers=headers, method="POST")
try:
resp_c = urllib.request.urlopen(req_c, timeout=30)
res_c = json.loads(resp_c.read().decode("utf-8"))
post_id = res_c['id']
print(f"--> Posted {item['title']} (ID: {post_id})")
# JS Logic with robust event handling
offset = item.get('offset', 0)
js_wrapped = f"""<script>
(function() {{
function init() {{
var i1 = document.getElementById("input-1");
var i2 = document.getElementById("input-2");
if (!i1 || !i2) {{
if (window.r < 50) {{
window.r++;
setTimeout(init, 100);
}}
return;
}}
i1.oninput = function() {{
var v = parseFloat(i1.value);
if (isNaN(v)) {{ i2.value = ""; return; }}
i2.value = parseFloat((v * {item['factor']} + {offset}).toFixed(8));
}};
i2.oninput = function() {{
var v = parseFloat(i2.value);
if (isNaN(v)) {{ i1.value = ""; return; }}
i1.value = parseFloat(((v - {offset}) / {item['factor']}).toFixed(8));
}};
var p = new URLSearchParams(window.location.search);
if (p.has('v1')) {{ i1.value = p.get('v1'); i1.oninput(); }}
else if (p.has('v2')) {{ i2.value = p.get('v2'); i2.oninput(); }}
}}
window.r = 0;
init();
}})();
</script>"""
kadence_data = {
"title": f"JS Logic: {item['title']}",
"status": "publish",
"content": js_wrapped,
"meta": {
"_kad_element_hook": "kadence_after_header",
"_kad_element_show_conditionals": json.dumps([{"rule": "singular|calculator", "select": "ids", "ids": [post_id], "mustMatch": False}])
}
}
req_j = urllib.request.Request(url_base_kadence, data=json.dumps(kadence_data).encode("utf-8"), headers=headers, method="POST")
urllib.request.urlopen(req_j, timeout=30)
print(f"--> Posted JS hook")
except Exception as e:
print(f"Error: {e}")
if hasattr(e, 'read'): print(e.read().decode('utf-8'))
time.sleep(1)
print("\\n--- BATCH 6 COMPLETE ---")

View File

@@ -1,142 +0,0 @@
import urllib.request
import json
import base64
import time
url_base_calc = "https://howdoyouconvert.com/wp-json/wp/v2/calculator"
url_base_kadence = "https://howdoyouconvert.com/wp-json/wp/v2/kadence_element"
creds = base64.b64encode(b"ben:6YGf wVxu gBpz pkqx BGZO lfVP").decode("utf-8")
headers = {
"Content-Type": "application/json",
"Authorization": "Basic " + creds,
"User-Agent": "Mozilla/5.0"
}
batch_7 = [
{"title": "Centigrams to Grams", "slug": "centigrams-to-grams", "v1": "Centigrams (cg)", "v2": "Grams (g)", "factor": 0.01, "desc": "Centigrams are a metric unit of mass equal to 1/100th of a gram. They are used in chemistry and pharmacy for small measurements."},
{"title": "Centiliters to Liters", "slug": "centiliters-to-liters", "v1": "Centiliters (cl)", "v2": "Liters (l)", "factor": 0.01, "desc": "Centiliters are commonly used in Europe for measuring liquid volumes in beverages. One centiliter is 10 milliliters."},
{"title": "Centimeters to Feet", "slug": "centimeters-to-feet", "v1": "Centimeters (cm)", "v2": "Feet (ft)", "factor": 0.032808399, "desc": "Centimeters are the standard metric unit for length in everyday use, while feet remain prevalent in the US and UK for height and construction."},
{"title": "Centimeters to Meters", "slug": "centimeters-to-meters", "v1": "Centimeters (cm)", "v2": "Meters (m)", "factor": 0.01, "desc": "The meter is the base unit of length in the International System of Units (SI). There are exactly 100 centimeters in one meter."},
{"title": "Centimeters to Millimeters", "slug": "centimeters-to-millimeters", "v1": "Centimeters (cm)", "v2": "Millimeters (mm)", "factor": 10.0, "desc": "Millimeters provide higher precision for small-scale measurements. One centimeter consists of ten millimeters."},
{"title": "Chains to Feet", "slug": "chains-to-feet", "v1": "Chains (ch)", "v2": "Feet (ft)", "factor": 66.0, "desc": "A chain is a unit of length equal to 66 feet, historically used in land surveying and railway engineering (Gunter's chain)."},
{"title": "Chains to Meters", "slug": "chains-to-meters", "v1": "Chains (ch)", "v2": "Meters (m)", "factor": 20.1168, "desc": "In modern surveying, the traditional chain (66 feet) is defined as exactly 20.1168 meters."},
{"title": "Cubic Centimeters to Cubic Inches", "slug": "cubic-centimeters-to-cubic-inches", "v1": "Cubic Centimeters (cc)", "v2": "Cubic Inches (cu in)", "factor": 0.0610237441, "desc": "Cubic centimeters (cc) are equal to milliliters and are often used to measure engine displacement."},
{"title": "Cubic Feet to Cubic Meters", "slug": "cubic-feet-to-cubic-meters", "v1": "Cubic Feet (cu ft)", "v2": "Cubic Meters (m³)", "factor": 0.0283168466, "desc": "Cubic feet are used for shipping volumes and HVAC capacity, while cubic meters are the metric standard for volume."},
{"title": "Cubic Meters to Liters", "slug": "cubic-meters-to-liters", "v1": "Cubic Meters (m³)", "v2": "Liters (l)", "factor": 1000.0, "desc": "A cubic meter is a large unit of volume equal to one thousand liters, often used for water consumption or industrial reservoirs."}
]
def check_exists(slug):
req = urllib.request.Request(f"{url_base_calc}?slug={slug}", headers=headers)
try:
resp = urllib.request.urlopen(req, timeout=30)
data = json.loads(resp.read().decode("utf-8"))
if data: return data[0]['id']
except: pass
return None
for item in batch_7:
print(f"\n--- Processing {item['title']} ---")
calc_html = f"""
<!-- wp:kadence/rowlayout {{"uniqueID":"{item['slug'].replace('-','')}_row","columns":1,"colLayout":"equal","maxWidth":600,"bgColor":"#f5f7f9","borderRadius":8,"padding":[32,32,32,32],"marginUnit":"px"}} -->
<div class="wp-block-kadence-rowlayout alignnone"><div class="kt-row-column-wrap kt-has-1-columns kt-row-layout-equal kt-tab-layout-inherit kt-mobile-layout-row kt-row-valign-top" style="background-color:#f5f7f9;border-radius:8px;padding:2rem;">
<!-- wp:kadence/column {{"uniqueID":"{item['slug'].replace('-','')}_col"}} -->
<div class="wp-block-kadence-column"><div class="kt-inside-inner-col">
<!-- wp:kadence/rowlayout {{"uniqueID":"{item['slug'].replace('-','')}_inner_row","columns":2,"colLayout":"equal","maxWidth":600,"marginUnit":"px"}} -->
<div class="kb-row-layout-wrap kb-row-layout-id_{item['slug'].replace('-','')}_row aligncenter wp-block-kadence-rowlayout"><div class="kt-row-column-wrap kt-has-2-columns kt-row-layout-equal kt-tab-layout-inherit kt-mobile-layout-row kt-row-valign-top">
<div class="wp-block-kadence-column kadence-column_{item['slug'].replace('-','')}_col1"><div class="kt-inside-inner-col">
<label for="input-1" style="font-weight: 600; color: #333333; margin-bottom: 8px; display: block;">{item['v1']}</label>
<input type="number" id="input-1" class="calc-input" placeholder="0" style="width:100%; padding: 12px; border: 1px solid #ccc; border-radius: 4px; font-size: 1.2rem;">
</div></div>
<div class="wp-block-kadence-column kadence-column_{item['slug'].replace('-','')}_col2"><div class="kt-inside-inner-col">
<label for="input-2" style="font-weight: 600; color: #333333; margin-bottom: 8px; display: block;">{item['v2']}</label>
<input type="number" id="input-2" class="calc-input" placeholder="0" style="width:100%; padding: 12px; border: 1px solid #ccc; border-radius: 4px; font-size: 1.2rem;">
</div></div></div></div>
</div></div>
<!-- /wp:kadence/column -->
</div></div>
<!-- /wp:kadence/rowlayout -->
<p style="margin-top: 2rem; line-height: 1.6;">{item['desc']}</p>
"""
existing_id = check_exists(item['slug'])
if existing_id:
print(f"--> Updating existing calculator (ID: {existing_id})")
calc_data = {"content": calc_html, "title": item['title']}
req_c = urllib.request.Request(f"{url_base_calc}/{existing_id}", data=json.dumps(calc_data).encode("utf-8"), headers=headers, method="PUT")
post_id = existing_id
else:
print(f"--> Creating new calculator")
calc_data = {"title": item['title'], "slug": item['slug'], "status": "publish", "content": calc_html}
req_c = urllib.request.Request(url_base_calc, data=json.dumps(calc_data).encode("utf-8"), headers=headers, method="POST")
resp_c = urllib.request.urlopen(req_c, timeout=30)
post_id = json.loads(resp_c.read().decode("utf-8"))['id']
# Robust JS Logic
js_logic = f"""<script>
(function() {{
function init() {{
var i1 = document.getElementById("input-1");
var i2 = document.getElementById("input-2");
if (!i1 || !i2) {{
if (window.initRetries === undefined) window.initRetries = 0;
if (window.initRetries < 50) {{
window.initRetries++;
setTimeout(init, 100);
}}
return;
}}
i1.oninput = function() {{
var v = parseFloat(i1.value);
if (isNaN(v)) {{ i2.value = ""; return; }}
i2.value = parseFloat((v * {item['factor']}).toFixed(8));
}};
i2.oninput = function() {{
var v = parseFloat(i2.value);
if (isNaN(v)) {{ i1.value = ""; return; }}
i1.value = parseFloat((v / {item['factor']}).toFixed(8));
}};
var p = new URLSearchParams(window.location.search);
if (p.has('v1')) {{ i1.value = p.get('v1'); i1.oninput(); }}
else if (p.has('v2')) {{ i2.value = p.get('v2'); i2.oninput(); }}
}}
init();
}})();
</script>"""
# Check for existing Kadence element targeted at this post_id
req_e = urllib.request.Request(f"{url_base_kadence}?per_page=100", headers=headers)
resp_e = urllib.request.urlopen(req_e, timeout=30)
elements = json.loads(resp_e.read().decode("utf-8"))
element_id = None
for e in elements:
cond = e.get('meta', {}).get('_kad_element_show_conditionals', '')
if str(post_id) in cond:
element_id = e['id']
break
if element_id:
print(f"--> Updating existing JS Logic element (ID: {element_id})")
kadence_data = {"content": js_logic}
req_j = urllib.request.Request(f"{url_base_kadence}/{element_id}", data=json.dumps(kadence_data).encode("utf-8"), headers=headers, method="PUT")
else:
print(f"--> Creating new JS Logic element")
kadence_data = {
"title": f"JS Logic: {item['title']}",
"status": "publish",
"content": js_logic,
"meta": {
"_kad_element_hook": "kadence_after_header",
"_kad_element_show_conditionals": json.dumps([{"rule": "singular|calculator", "select": "ids", "ids": [post_id], "mustMatch": False}])
}
}
req_j = urllib.request.Request(url_base_kadence, data=json.dumps(kadence_data).encode("utf-8"), headers=headers, method="POST")
urllib.request.urlopen(req_j, timeout=30)
print(f"--> SUCCESS: Post {post_id}")
time.sleep(1)
print("\nBATCH 7 COMPLETE")

View File

@@ -1,146 +0,0 @@
import urllib.request
import json
import base64
import time
url_base_calc = "https://howdoyouconvert.com/wp-json/wp/v2/calculator"
url_base_kadence = "https://howdoyouconvert.com/wp-json/wp/v2/kadence_element"
creds = base64.b64encode(b"ben:6YGf wVxu gBpz pkqx BGZO lfVP").decode("utf-8")
headers = {
"Content-Type": "application/json",
"Authorization": "Basic " + creds,
"User-Agent": "Mozilla/5.0"
}
batch_8 = [
{"title": "Grams to Micrograms", "slug": "grams-to-micrograms", "v1": "Grams (g)", "v2": "Micrograms (µg)", "factor": 1000000.0, "desc": "A gram is a basic unit of mass in the metric system. A microgram is one-millionth of a gram, used primarily in medicine and micro-biology."},
{"title": "Grams to Milligrams", "slug": "grams-to-milligrams", "v1": "Grams (g)", "v2": "Milligrams (mg)", "factor": 1000.0, "desc": "One gram equals one thousand milligrams. This conversion is extremely common across science, medication dosage, and dietary tracking."},
{"title": "Hectopascals to Pascals", "slug": "hectopascals-to-pascals", "v1": "Hectopascals (hPa)", "v2": "Pascals (Pa)", "factor": 100.0, "desc": "The pascal (Pa) is the SI unit of pressure. A hectopascal is 100 pascals and is identical to the millibar, frequently used in meteorology."},
{"title": "Hectopascals to Millibars", "slug": "hectopascals-to-millibars", "v1": "Hectopascals (hPa)", "v2": "Millibars (mbar)", "factor": 1.0, "desc": "Hectopascals and millibars are equivalent units of pressure. While hectopascals are the SI standard, millibars are still widely used in weather reporting."},
{"title": "Joules to Kilojoules", "slug": "joules-to-kilojoules", "v1": "Joules (J)", "v2": "Kilojoules (kJ)", "factor": 0.001, "desc": "The joule is the SI unit of energy. One kilojoule is one thousand joules, often used for representing energy content in food or mechanical work."},
{"title": "Kilojoules to Joules", "slug": "kilojoules-to-joules", "v1": "Kilojoules (kJ)", "v2": "Joules (J)", "factor": 1000.0, "desc": "Kilojoules are larger units of energy. To convert them to standard joules, simply multiply by one thousand."},
{"title": "Micrograms to Grams", "slug": "micrograms-to-grams", "v1": "Micrograms (µg)", "v2": "Grams (g)", "factor": 0.000001, "desc": "Converting micrograms to grams is common in analytical chemistry where high-precision measurements of trace substances are required."},
{"title": "Milligrams to Grams", "slug": "milligrams-to-grams", "v1": "Milligrams (mg)", "v2": "Grams (g)", "factor": 0.001, "desc": "Milligrams are often used for small measurements of mass. One milligram is one-thousandth of a gram."},
{"title": "Millibars to Pascals", "slug": "millibars-to-pascals", "v1": "Millibars (mbar)", "v2": "Pascals (Pa)", "factor": 100.0, "desc": "One millibar is exactly 100 pascals. This relationship is a cornerstone of barometric pressure reporting in aviation and meteorology."},
{"title": "Millimeters of Mercury to Pascals", "slug": "millimeters-of-mercury-to-pascals", "v1": "mmHg", "v2": "Pascals (Pa)", "factor": 133.322, "desc": "Millimeters of mercury (mmHg) is a legacy unit of pressure, famously used for blood pressure readings. One mmHg is approximately 133.322 pascals."}
]
def check_exists(slug):
req = urllib.request.Request(f"{url_base_calc}?slug={slug}", headers=headers)
try:
resp = urllib.request.urlopen(req, timeout=30)
data = json.loads(resp.read().decode("utf-8"))
if data: return data[0]['id']
except: pass
return None
def get_element_id_for_post(post_id):
req_e = urllib.request.Request(f"{url_base_kadence}?per_page=100", headers=headers)
try:
resp_e = urllib.request.urlopen(req_e, timeout=30)
elements = json.loads(resp_e.read().decode("utf-8"))
for e in elements:
cond = e.get('meta', {}).get('_kad_element_show_conditionals', '')
if str(post_id) in cond:
return e['id']
except: pass
return None
for item in batch_8:
print(f"\n--- Processing {item['title']} ---")
slug = item['slug']
unique_id = slug.replace('-', '_')
calc_html = f"""
<!-- wp:kadence/rowlayout {{"uniqueID":"{unique_id}_row","columns":1,"colLayout":"equal","maxWidth":600,"bgColor":"#f5f7f9","borderRadius":8,"padding":[32,32,32,32],"marginUnit":"px"}} -->
<div class="wp-block-kadence-rowlayout alignnone"><div class="kt-row-column-wrap kt-has-1-columns kt-row-layout-equal kt-tab-layout-inherit kt-mobile-layout-row kt-row-valign-top" style="background-color:#f5f7f9;border-radius:8px;padding:2rem;">
<!-- wp:kadence/column {{"uniqueID":"{unique_id}_col"}} -->
<div class="wp-block-kadence-column"><div class="kt-inside-inner-col">
<!-- wp:kadence/rowlayout {{"uniqueID":"{unique_id}_inner_row","columns":2,"colLayout":"equal","maxWidth":600,"marginUnit":"px"}} -->
<div class="kb-row-layout-wrap kb-row-layout-id_{unique_id}_row aligncenter wp-block-kadence-rowlayout"><div class="kt-row-column-wrap kt-has-2-columns kt-row-layout-equal kt-tab-layout-inherit kt-mobile-layout-row kt-row-valign-top">
<div class="wp-block-kadence-column kadence-column_{unique_id}_col1"><div class="kt-inside-inner-col">
<label for="input-1" style="font-weight: 600; color: #333333; margin-bottom: 8px; display: block;">{item['v1']}</label>
<input type="number" id="input-1" class="calc-input" placeholder="0" style="width:100%; padding: 12px; border: 1px solid #ccc; border-radius: 4px; font-size: 1.2rem;">
</div></div>
<div class="wp-block-kadence-column kadence-column_{unique_id}_col2"><div class="kt-inside-inner-col">
<label for="input-2" style="font-weight: 600; color: #333333; margin-bottom: 8px; display: block;">{item['v2']}</label>
<input type="number" id="input-2" class="calc-input" placeholder="0" style="width:100%; padding: 12px; border: 1px solid #ccc; border-radius: 4px; font-size: 1.2rem;">
</div></div></div></div>
</div></div>
<!-- /wp:kadence/column -->
</div></div>
<!-- /wp:kadence/rowlayout -->
<p style="margin-top: 2rem; line-height: 1.6;">{item['desc']}</p>
"""
existing_id = check_exists(slug)
if existing_id:
print(f"--> Updating existing calculator (ID: {existing_id})")
calc_data = {"content": calc_html, "title": item['title']}
req_c = urllib.request.Request(f"{url_base_calc}/{existing_id}", data=json.dumps(calc_data).encode("utf-8"), headers=headers, method="PUT")
post_id = existing_id
else:
print(f"--> Creating new calculator")
calc_data = {"title": item['title'], "slug": slug, "status": "publish", "content": calc_html}
req_c = urllib.request.Request(url_base_calc, data=json.dumps(calc_data).encode("utf-8"), headers=headers, method="POST")
resp_c = urllib.request.urlopen(req_c, timeout=30)
post_id = json.loads(resp_c.read().decode("utf-8"))['id']
# Robust JS Logic
js_logic = f"""<script>
(function() {{
function init() {{
var i1 = document.getElementById("input-1");
var i2 = document.getElementById("input-2");
if (!i1 || !i2) {{
if (window.initRetries === undefined) window.initRetries = 0;
if (window.initRetries < 50) {{
window.initRetries++;
setTimeout(init, 100);
}}
return;
}}
i1.oninput = function() {{
var v = parseFloat(i1.value);
if (isNaN(v)) {{ i2.value = ""; return; }}
i2.value = parseFloat((v * {item['factor']}).toFixed(8));
}};
i2.oninput = function() {{
var v = parseFloat(i2.value);
if (isNaN(v)) {{ i1.value = ""; return; }}
i1.value = parseFloat((v / {item['factor']}).toFixed(8));
}};
var p = new URLSearchParams(window.location.search);
if (p.has('v1')) {{ i1.value = p.get('v1'); i1.oninput(); }}
else if (p.has('v2')) {{ i2.value = p.get('v2'); i2.oninput(); }}
}}
init();
}})();
</script>"""
element_id = get_element_id_for_post(post_id)
if element_id:
print(f"--> Updating existing JS Logic element (ID: {element_id})")
kadence_data = {"content": js_logic}
req_j = urllib.request.Request(f"{url_base_kadence}/{element_id}", data=json.dumps(kadence_data).encode("utf-8"), headers=headers, method="PUT")
else:
print(f"--> Creating new JS Logic element")
kadence_data = {
"title": f"JS Logic: {item['title']}",
"status": "publish",
"content": js_logic,
"meta": {
"_kad_element_hook": "kadence_after_header",
"_kad_element_show_conditionals": json.dumps([{"rule": "singular|calculator", "select": "ids", "ids": [post_id], "mustMatch": False}])
}
}
req_j = urllib.request.Request(url_base_kadence, data=json.dumps(kadence_data).encode("utf-8"), headers=headers, method="POST")
urllib.request.urlopen(req_j, timeout=30)
print(f"--> SUCCESS: Post {post_id}")
time.sleep(1)
print("\nBATCH 8 COMPLETE")

View File

@@ -1,146 +0,0 @@
import urllib.request
import json
import base64
import time
url_base_calc = "https://howdoyouconvert.com/wp-json/wp/v2/calculator"
url_base_kadence = "https://howdoyouconvert.com/wp-json/wp/v2/kadence_element"
creds = base64.b64encode(b"ben:6YGf wVxu gBpz pkqx BGZO lfVP").decode("utf-8")
headers = {
"Content-Type": "application/json",
"Authorization": "Basic " + creds,
"User-Agent": "Mozilla/5.0"
}
batch_9 = [
{"title": "Meters per second to Feet per second", "slug": "meters-per-second-to-feet-per-second", "v1": "m/s", "v2": "ft/s", "factor": 3.28084, "desc": "Meters per second is the SI unit of speed. Feet per second is commonly used in aerospace and ballistics in the United States."},
{"title": "Meters per second to Miles per hour", "slug": "meters-per-second-to-miles-per-hour", "v1": "m/s", "v2": "mph", "factor": 2.23694, "desc": "This conversion is vital for understanding scientific measurements in terms of everyday vehicle speeds used in the USA and UK."},
{"title": "Meters per second to Yards per second", "slug": "meters-per-second-to-yards-per-second", "v1": "m/s", "v2": "yd/s", "factor": 1.09361, "desc": "Meters and yards are nearly equal in length, but the conversion is necessary for sports and construction where exact yardage is required."},
{"title": "Micrograms to Milligrams", "slug": "micrograms-to-milligrams", "v1": "µg", "v2": "mg", "factor": 0.001, "desc": "Both units measure very small masses. One milligram contains one thousand micrograms, a critical distinction in pharmacy and biochemistry."},
{"title": "Micrometers to Millimeters", "slug": "micrometers-to-millimeters", "v1": "µm", "v2": "mm", "factor": 0.001, "desc": "The micrometer, often called the micron, is 1/1000th of a millimeter. It is used to measure the thickness of human hair or paper."},
{"title": "Milligrams to Micrograms", "slug": "milligrams-to-micrograms", "v1": "mg", "v2": "µg", "factor": 1000.0, "desc": "Standard conversion for high-potency supplements and medicines where doses are often specified in micrograms."},
{"title": "Milliliters to Liters", "slug": "milliliters-to-liters", "v1": "ml", "v2": "l", "factor": 0.001, "desc": "The milliliter is equal to one cubic centimeter. One thousand milliliters make up one standard liter."},
{"title": "Milliliters to Fluid Ounces", "slug": "milliliters-to-fluid-ounces", "v1": "ml", "v2": "fl oz", "factor": 0.033814, "desc": "A common conversion for beverage containers and nutrition labels, translating metric milliliters to US customary fluid ounces."},
{"title": "Millimeters to Centimeters", "slug": "millimeters-to-centimeters", "v1": "mm", "v2": "cm", "factor": 0.1, "desc": "One centimeter is exactly ten millimeters. This simple metric shift is fundamental in engineering and design."},
{"title": "Millimeters to Inches", "slug": "millimeters-to-inches", "v1": "mm", "v2": "in", "factor": 0.0393701, "desc": "One inch is exactly 25.4 millimeters. This conversion is the bridge between metric and imperial precision engineering."}
]
def check_exists(slug):
req = urllib.request.Request(f"{url_base_calc}?slug={slug}", headers=headers)
try:
resp = urllib.request.urlopen(req, timeout=30)
data = json.loads(resp.read().decode("utf-8"))
if data: return data[0]['id']
except: pass
return None
def get_element_id_for_post(post_id):
req_e = urllib.request.Request(f"{url_base_kadence}?per_page=100", headers=headers)
try:
resp_e = urllib.request.urlopen(req_e, timeout=30)
elements = json.loads(resp_e.read().decode("utf-8"))
for e in elements:
cond = e.get('meta', {}).get('_kad_element_show_conditionals', '')
if str(post_id) in cond:
return e['id']
except: pass
return None
for item in batch_9:
print(f"\n--- Processing {item['title']} ---")
slug = item['slug']
unique_id = slug.replace('-', '_')
calc_html = f"""
<!-- wp:kadence/rowlayout {{"uniqueID":"{unique_id}_row","columns":1,"colLayout":"equal","maxWidth":600,"bgColor":"#f5f7f9","borderRadius":8,"padding":[32,32,32,32],"marginUnit":"px"}} -->
<div class="wp-block-kadence-rowlayout alignnone"><div class="kt-row-column-wrap kt-has-1-columns kt-row-layout-equal kt-tab-layout-inherit kt-mobile-layout-row kt-row-valign-top" style="background-color:#f5f7f9;border-radius:8px;padding:2rem;">
<!-- wp:kadence/column {{"uniqueID":"{unique_id}_col"}} -->
<div class="wp-block-kadence-column"><div class="kt-inside-inner-col">
<!-- wp:kadence/rowlayout {{"uniqueID":"{unique_id}_inner_row","columns":2,"colLayout":"equal","maxWidth":600,"marginUnit":"px"}} -->
<div class="kb-row-layout-wrap kb-row-layout-id_{unique_id}_row aligncenter wp-block-kadence-rowlayout"><div class="kt-row-column-wrap kt-has-2-columns kt-row-layout-equal kt-tab-layout-inherit kt-mobile-layout-row kt-row-valign-top">
<div class="wp-block-kadence-column kadence-column_{unique_id}_col1"><div class="kt-inside-inner-col">
<label for="input-1" style="font-weight: 600; color: #333333; margin-bottom: 8px; display: block;">{item['v1']}</label>
<input type="number" id="input-1" class="calc-input" placeholder="0" style="width:100%; padding: 12px; border: 1px solid #ccc; border-radius: 4px; font-size: 1.2rem;">
</div></div>
<div class="wp-block-kadence-column kadence-column_{unique_id}_col2"><div class="kt-inside-inner-col">
<label for="input-2" style="font-weight: 600; color: #333333; margin-bottom: 8px; display: block;">{item['v2']}</label>
<input type="number" id="input-2" class="calc-input" placeholder="0" style="width:100%; padding: 12px; border: 1px solid #ccc; border-radius: 4px; font-size: 1.2rem;">
</div></div></div></div>
</div></div>
<!-- /wp:kadence/column -->
</div></div>
<!-- /wp:kadence/rowlayout -->
<p style="margin-top: 2rem; line-height: 1.6;">{item['desc']}</p>
"""
existing_id = check_exists(slug)
if existing_id:
print(f"--> Updating existing calculator (ID: {existing_id})")
calc_data = {"content": calc_html, "title": item['title']}
req_c = urllib.request.Request(f"{url_base_calc}/{existing_id}", data=json.dumps(calc_data).encode("utf-8"), headers=headers, method="PUT")
post_id = existing_id
else:
print(f"--> Creating new calculator")
calc_data = {"title": item['title'], "slug": slug, "status": "publish", "content": calc_html}
req_c = urllib.request.Request(url_base_calc, data=json.dumps(calc_data).encode("utf-8"), headers=headers, method="POST")
resp_c = urllib.request.urlopen(req_c, timeout=30)
post_id = json.loads(resp_c.read().decode("utf-8"))['id']
# Robust JS Logic
js_logic = f"""<script>
(function() {{
function init() {{
var i1 = document.getElementById("input-1");
var i2 = document.getElementById("input-2");
if (!i1 || !i2) {{
if (window.initRetries === undefined) window.initRetries = 0;
if (window.initRetries < 50) {{
window.initRetries++;
setTimeout(init, 100);
}}
return;
}}
i1.oninput = function() {{
var v = parseFloat(i1.value);
if (isNaN(v)) {{ i2.value = ""; return; }}
i2.value = parseFloat((v * {item['factor']}).toFixed(8));
}};
i2.oninput = function() {{
var v = parseFloat(i2.value);
if (isNaN(v)) {{ i1.value = ""; return; }}
i1.value = parseFloat((v / {item['factor']}).toFixed(8));
}};
var p = new URLSearchParams(window.location.search);
if (p.has('v1')) {{ i1.value = p.get('v1'); i1.oninput(); }}
else if (p.has('v2')) {{ i2.value = p.get('v2'); i2.oninput(); }}
}}
init();
}})();
</script>"""
element_id = get_element_id_for_post(post_id)
if element_id:
print(f"--> Updating existing JS Logic element (ID: {element_id})")
kadence_data = {"content": js_logic}
req_j = urllib.request.Request(f"{url_base_kadence}/{element_id}", data=json.dumps(kadence_data).encode("utf-8"), headers=headers, method="PUT")
else:
print(f"--> Creating new JS Logic element")
kadence_data = {
"title": f"JS Logic: {item['title']}",
"status": "publish",
"content": js_logic,
"meta": {
"_kad_element_hook": "kadence_after_header",
"_kad_element_show_conditionals": json.dumps([{"rule": "singular|calculator", "select": "ids", "ids": [post_id], "mustMatch": False}])
}
}
req_j = urllib.request.Request(url_base_kadence, data=json.dumps(kadence_data).encode("utf-8"), headers=headers, method="POST")
urllib.request.urlopen(req_j, timeout=30)
print(f"--> SUCCESS: Post {post_id}")
time.sleep(1)
print("\nBATCH 9 COMPLETE")

View File

@@ -1,6 +0,0 @@
# Current Calculators on How Do You Convert
Here is a list of all current calculators available on the site:
1. **[Kilograms to Pounds](https://howdoyouconvert.com/calculator/kilograms-to-pounds/)**
2. **[Inches to Feet](https://howdoyouconvert.com/calculator/inches-to-feet/)**

File diff suppressed because it is too large Load Diff

View File

@@ -1,349 +0,0 @@
import urllib.request
import json
import base64
import time
url_base_calc = "https://howdoyouconvert.com/wp-json/wp/v2/calculator/"
url_base_kadence = "https://howdoyouconvert.com/wp-json/wp/v2/kadence_element/"
creds = base64.b64encode(b"ben:6YGf wVxu gBpz pkqx BGZO lfVP").decode("utf-8")
headers = {
"Content-Type": "application/json",
"Authorization": "Basic " + creds,
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64)"
}
# --- BLUEPRINTS ---
def get_text_ui(item):
slug_raw = item['slug'].replace("-", "")
return f"""
<!-- wp:kadence/rowlayout {{"uniqueID":"{item['slug']}_outer","bgColor":"#f5f7f9","padding":["2rem","2rem","2rem","2rem"],"borderRadius":["8px","8px","8px","8px"]}} -->
<div class="wp-block-kadence-rowlayout alignnone"><div class="kt-row-column-wrap kt-has-1-columns kt-row-layout-equal kt-tab-layout-inherit kt-mobile-layout-row kt-row-valign-top" style="background-color:#f5f7f9;border-radius:8px;padding:2rem;">
<!-- wp:kadence/column {{"uniqueID":"{item['slug']}_inner"}} -->
<div class="wp-block-kadence-column"><div class="kt-inside-inner-col">
<style>
.calc-container-{slug_raw} {{
display: grid;
grid-template-columns: 1fr;
gap: 1.5rem;
max-width: 600px;
margin: 0 auto;
}}
.calc-group {{
display: flex;
flex-direction: column;
}}
.calc-label {{
font-weight: 600;
color: #333333;
margin-bottom: 8px;
}}
.calc-textarea {{
width: 100%;
padding: 12px;
border: 1px solid #ccc;
border-radius: 4px;
font-size: 1.1rem;
min-height: 120px;
font-family: monospace;
}}
</style>
<div class="calc-container-{slug_raw}">
<div class="calc-group">
<label class="calc-label" for="input-1">{item['label1']}</label>
<textarea id="input-1" class="calc-textarea" placeholder="Enter {item['label1']}..."></textarea>
</div>
<div class="calc-group">
<label class="calc-label" for="input-2">{item['label2']}</label>
<textarea id="input-2" class="calc-textarea" placeholder="{item['label2']} result..."></textarea>
</div>
</div>
</div></div>
<!-- /wp:kadence/column -->
</div></div>
<!-- /wp:kadence/rowlayout -->
{item['seo_text']}
"""
def get_triple_ui(item):
slug_raw = item['slug'].replace("-", "")
return f"""
<!-- wp:kadence/rowlayout {{"uniqueID":"{item['slug']}_outer","bgColor":"#f5f7f9","padding":["2rem","2rem","2rem","2rem"],"borderRadius":["8px","8px","8px","8px"]}} -->
<div class="wp-block-kadence-rowlayout alignnone"><div class="kt-row-column-wrap kt-has-1-columns kt-row-layout-equal kt-tab-layout-inherit kt-mobile-layout-row kt-row-valign-top" style="background-color:#f5f7f9;border-radius:8px;padding:2rem;">
<!-- wp:kadence/column {{"uniqueID":"{item['slug']}_inner"}} -->
<div class="wp-block-kadence-column"><div class="kt-inside-inner-col">
<style>
.triple-grid-{slug_raw} {{
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 1rem;
max-width: 800px;
margin: 0 auto;
}}
@media (max-width: 767px) {{
.triple-grid-{slug_raw} {{
grid-template-columns: 1fr;
}}
}}
.calc-group {{
display: flex;
flex-direction: column;
}}
.calc-label {{
font-weight: 600;
color: #333333;
margin-bottom: 8px;
}}
.calc-input {{
width: 100%;
padding: 12px;
border: 1px solid #ccc;
border-radius: 4px;
font-size: 1.2rem;
}}
</style>
<div class="triple-grid-{slug_raw}">
<div class="calc-group">
<label class="calc-label" for="input-1">{item['label1']}</label>
<input type="number" id="input-1" class="calc-input" placeholder="0">
</div>
<div class="calc-group">
<label class="calc-label" for="input-2">{item['label2']}</label>
<input type="number" id="input-2" class="calc-input" placeholder="0">
</div>
<div class="calc-group">
<label class="calc-label" for="input-3">{item['label3']}</label>
<input type="number" id="input-3" class="calc-input" placeholder="0">
</div>
</div>
<p style="text-align: center; margin-top: 1.5rem; color: #666; font-size: 0.9rem;">
<em>Enter any two values to calculate the third.</em>
</p>
</div></div>
<!-- /wp:kadence/column -->
</div></div>
<!-- /wp:kadence/rowlayout -->
{item['seo_text']}
"""
# --- COMPLEX CALCULATOR DATA ---
complex_items = [
{
"title": "Binary to ASCII",
"slug": "binary-to-ascii",
"type": "textual",
"label1": "Binary",
"label2": "Text (ASCII)",
"js_logic": """
function convert1() {
let val = document.getElementById("input-1").value.replace(/\\s/g, "");
let text = "";
for (let i = 0; i < val.length; i += 8) {
let byte = val.substr(i, 8);
text += String.fromCharCode(parseInt(byte, 2));
}
document.getElementById("input-2").value = text;
}
function convert2() {
let val = document.getElementById("input-2").value;
let binary = "";
for (let i = 0; i < val.length; i++) {
let bin = val[i].charCodeAt(0).toString(2);
binary += ("00000000" + bin).slice(-8) + " ";
}
document.getElementById("input-1").value = binary.trim();
}
document.getElementById("input-1").addEventListener("input", convert1);
document.getElementById("input-2").addEventListener("input", convert2);
""",
"seo_text": """
<!-- wp:paragraph -->
<p style="margin-top: 2rem; line-height: 1.6;"><strong>Binary to ASCII Conversion:</strong> Translate binary strings of 0s and 1s back into readable text. Each 8-bit sequence represents a specific character in the ASCII standard.</p>
<!-- /wp:paragraph -->
"""
},
{
"title": "Binary to Decimal",
"slug": "binary-to-decimal",
"type": "textual",
"label1": "Binary",
"label2": "Decimal",
"js_logic": """
function convert1() {
let val = document.getElementById("input-1").value.replace(/\\s/g, "");
document.getElementById("input-2").value = parseInt(val, 2).toString(10);
}
function convert2() {
let val = document.getElementById("input-2").value;
document.getElementById("input-1").value = parseInt(val, 10).toString(2);
}
document.getElementById("input-1").addEventListener("input", convert1);
document.getElementById("input-2").addEventListener("input", convert2);
""",
"seo_text": """
<!-- wp:paragraph -->
<p style="margin-top: 2rem; line-height: 1.6;"><strong>Binary to Decimal:</strong> Quickly convert base-2 binary numbers into their base-10 decimal equivalents used in everyday mathematics.</p>
<!-- /wp:paragraph -->
"""
},
{
"title": "Binary to Hex",
"slug": "binary-to-hex",
"type": "textual",
"label1": "Binary",
"label2": "Hexadecimal",
"js_logic": """
function convert1() {
let val = document.getElementById("input-1").value.replace(/\\s/g, "");
document.getElementById("input-2").value = parseInt(val, 2).toString(16).toUpperCase();
}
function convert2() {
let val = document.getElementById("input-2").value;
document.getElementById("input-1").value = parseInt(val, 16).toString(2);
}
document.getElementById("input-1").addEventListener("input", convert1);
document.getElementById("input-2").addEventListener("input", convert2);
""",
"seo_text": """
<!-- wp:paragraph -->
<p style="margin-top: 2rem; line-height: 1.6;"><strong>Binary to Hex:</strong> Conversion between binary (base-2) and hexadecimal (base-16) is a fundamental skill in computing and low-level programming.</p>
<!-- /wp:paragraph -->
"""
},
{
"title": "Amps to Watts",
"slug": "amps-to-watts",
"type": "triple",
"label1": "Current (Amps)",
"label2": "Voltage (Volts)",
"label3": "Power (Watts)",
"js_logic": """
function solve() {
let a = document.getElementById("input-1").value;
let v = document.getElementById("input-2").value;
let w = document.getElementById("input-3").value;
if (a && v && !w) document.getElementById("input-3").value = (a * v).toFixed(2);
else if (a && w && !v) document.getElementById("input-2").value = (w / a).toFixed(2);
else if (v && w && !a) document.getElementById("input-1").value = (w / v).toFixed(2);
}
document.getElementById("input-1").addEventListener("input", solve);
document.getElementById("input-2").addEventListener("input", solve);
document.getElementById("input-3").addEventListener("input", solve);
""",
"seo_text": """
<!-- wp:paragraph -->
<p style="margin-top: 2rem; line-height: 1.6;"><strong>Amps to Watts:</strong> Use this calculator to find power (Watts) given current (Amps) and voltage (Volts). It works for DC and single-phase AC circuits.</p>
<!-- /wp:paragraph -->
"""
},
{
"title": "Amps to Kilowatts",
"slug": "amps-to-kilowatts",
"type": "triple",
"label1": "Current (Amps)",
"label2": "Voltage (Volts)",
"label3": "Power (Kilowatts)",
"js_logic": """
function solve() {
let a = document.getElementById("input-1").value;
let v = document.getElementById("input-2").value;
let kw = document.getElementById("input-3").value;
if (a && v && !kw) document.getElementById("input-3").value = (a * v / 1000).toFixed(3);
else if (a && kw && !v) document.getElementById("input-2").value = (kw * 1000 / a).toFixed(2);
else if (v && kw && !a) document.getElementById("input-1").value = (kw * 1000 / v).toFixed(2);
}
document.getElementById("input-1").addEventListener("input", solve);
document.getElementById("input-2").addEventListener("input", solve);
document.getElementById("input-3").addEventListener("input", solve);
""",
"seo_text": """
<!-- wp:paragraph -->
<p style="margin-top: 2rem; line-height: 1.6;"><strong>Amps to Kilowatts:</strong> Convert current to power in kilowatts. This calculator assumes a power factor of 1.0 (purely resistive load).</p>
<!-- /wp:paragraph -->
"""
},
{
"title": "Amps to kVA",
"slug": "amps-to-kva",
"type": "triple",
"label1": "Current (Amps)",
"label2": "Voltage (Volts)",
"label3": "Apparent Power (kVA)",
"js_logic": """
function solve() {
let a = document.getElementById("input-1").value;
let v = document.getElementById("input-2").value;
let kva = document.getElementById("input-3").value;
if (a && v && !kva) document.getElementById("input-3").value = (a * v / 1000).toFixed(3);
else if (a && kva && !v) document.getElementById("input-2").value = (kva * 1000 / a).toFixed(2);
else if (v && kva && !a) document.getElementById("input-1").value = (kva * 1000 / v).toFixed(2);
}
document.getElementById("input-1").addEventListener("input", solve);
document.getElementById("input-2").addEventListener("input", solve);
document.getElementById("input-3").addEventListener("input", solve);
""",
"seo_text": """
<!-- wp:paragraph -->
<p style="margin-top: 2rem; line-height: 1.6;"><strong>Amps to kVA:</strong> Calculate apparent power in kVA for single-phase electrical systems. Apparent power is the product of RMS voltage and current.</p>
<!-- /wp:paragraph -->
"""
}
]
# --- EXECUTION LOOP ---
for item in complex_items:
print(f"\\n--- Processing {item['title']} ---")
if item['type'] == "textual":
content_html = get_text_ui(item)
elif item['type'] == "triple":
content_html = get_triple_ui(item)
calc_data = {
"title": item['title'],
"status": "publish",
"slug": item['slug'],
"content": content_html
}
req = urllib.request.Request(url_base_calc, data=json.dumps(calc_data).encode("utf-8"), headers=headers, method="POST")
try:
resp = urllib.request.urlopen(req, timeout=30)
res = json.loads(resp.read().decode("utf-8"))
post_id = res['id']
print(f"--> Posted Calculator (ID: {post_id})")
js_wrapped = f"<script>\\n{item['js_logic']}\\n</script>"
kadence_data = {
"title": f"JS Logic: {item['title']}",
"status": "publish",
"content": js_wrapped,
"meta": {
"_kad_element_hook": "kadence_after_header",
"_kad_element_show_conditionals": json.dumps([{"rule": "singular|calculator", "select": "ids", "ids": [post_id], "mustMatch": False}])
}
}
req_j = urllib.request.Request(url_base_kadence, data=json.dumps(kadence_data).encode("utf-8"), headers=headers, method="POST")
resp_j = urllib.request.urlopen(req_j, timeout=30)
print(f"--> Posted JS Hook")
except Exception as e:
print(f"Error: {e}")
if hasattr(e, 'read'): print(e.read().decode('utf-8'))
time.sleep(1)

View File

@@ -1,4 +0,0 @@
https://howdoyouconvert.com
ben
6YGf wVxu gBpz pkqx BGZO lfVP

View File

@@ -1,52 +0,0 @@
import urllib.request
import json
import base64
url_base_kadence = "https://howdoyouconvert.com/wp-json/wp/v2/kadence_element/"
creds = base64.b64encode(b"ben:6YGf wVxu gBpz pkqx BGZO lfVP").decode("utf-8")
headers = {
"Content-Type": "application/json",
"Authorization": "Basic " + creds,
"User-Agent": "Mozilla/5.0"
}
js_logic = """<script>
(function() {
function init() {
var i1 = document.getElementById("input-1");
var i2 = document.getElementById("input-2");
if (!i1 || !i2) {
if (window.initRetries === undefined) window.initRetries = 0;
if (window.initRetries < 50) {
window.initRetries++;
setTimeout(init, 100);
}
return;
}
i1.oninput = function() {
var v = parseFloat(i1.value);
if (isNaN(v)) { i2.value = ""; return; }
i2.value = parseFloat((v * 1000.0).toFixed(8));
};
i2.oninput = function() {
var v = parseFloat(i2.value);
if (isNaN(v)) { i1.value = ""; return; }
i1.value = parseFloat((v / 1000.0).toFixed(8));
};
var p = new URLSearchParams(window.location.search);
if (p.has('v1')) { i1.value = p.get('v1'); i1.oninput(); }
else if (p.has('v2')) { i2.value = p.get('v2'); i2.oninput(); }
}
init();
})();
</script>"""
eid = 225
print(f"Patching EID {eid}...")
data = {"content": js_logic}
req = urllib.request.Request(f"{url_base_kadence}{eid}", data=json.dumps(data).encode("utf-8"), headers=headers, method="PUT")
try:
urllib.request.urlopen(req, timeout=30)
print("--> Done")
except Exception as e:
print(f"--> Error: {e}")

View File

@@ -1,19 +0,0 @@
import urllib.request
import json
import base64
url_base = "https://howdoyouconvert.com/wp-json/wp/v2/calculator/107?context=edit"
creds = base64.b64encode(b"ben:6YGf wVxu gBpz pkqx BGZO lfVP").decode("utf-8")
headers = {
"Authorization": "Basic " + creds,
"User-Agent": "Mozilla/5.0"
}
req = urllib.request.Request(url_base, headers=headers)
try:
resp = urllib.request.urlopen(req)
data = json.loads(resp.read().decode("utf-8"))
print(data['content']['raw'])
except Exception as e:
print("Error:", e)
if hasattr(e, 'read'): print("Response:", e.read().decode("utf-8"))

156
hdyc-calculators.js Normal file
View File

@@ -0,0 +1,156 @@
(function() {
function init() {
const containers = document.querySelectorAll('.hdyc-calc-container');
if (containers.length === 0) return;
containers.forEach(container => {
const type = container.dataset.hdycType;
const factor = parseFloat(container.dataset.hdycFactor) || 1;
const offset = parseFloat(container.dataset.hdycOffset) || 0;
const in1 = container.querySelector('#input-1');
const in2 = container.querySelector('#input-2');
const in3 = container.querySelector('#input-3');
if (!in1 || !in2) return;
function solve(source) {
let v1 = parseFloat(in1.value);
let v2 = parseFloat(in2.value);
let v3 = in3 ? parseFloat(in3.value) : NaN;
if (type === 'standard') {
if (source === 1) {
if (!isNaN(v1)) in2.value = parseFloat((v1 * factor + offset).toFixed(6));
else in2.value = '';
} else {
if (!isNaN(v2)) in1.value = parseFloat(((v2 - offset) / factor).toFixed(6));
else in1.value = '';
}
} else if (type === 'inverse') {
// Logic: v1 * v2 = factor (constant)
if (source === 1) {
if (!isNaN(v1) && v1 !== 0) in2.value = parseFloat((factor / v1).toFixed(6));
else in2.value = '';
} else {
if (!isNaN(v2) && v2 !== 0) in1.value = parseFloat((factor / v2).toFixed(6));
else in1.value = '';
}
} else if (type === '3col') {
// Standard 3-col: v3 = v1 / v2 (e.g. Watts = Amps * Volts -> in3 = in1 / in2? No, usually Watts is in3)
// Let's look at legacy scripts.
// grams-to-moles: in3 (moles) = in1 (mass) / in2 (molar mass)
// watts-to-amps: in3 (amps) = in1 (watts) / in2 (volts)
if (source === 1 || source === 2) {
if (!isNaN(v1) && !isNaN(v2) && v2 !== 0) in3.value = parseFloat((v1 / v2).toFixed(6));
else in3.value = '';
} else {
if (!isNaN(v3) && !isNaN(v2)) in1.value = parseFloat((v3 * v2).toFixed(6));
else in1.value = '';
}
} else if (type === '3col-mul') {
// v3 = v1 * v2 (e.g. Lux to Lumens: Lumens(3) = Lux(1) * Area(2))
if (source === 1 || source === 2) {
if (!isNaN(v1) && !isNaN(v2)) in3.value = parseFloat((v1 * v2).toFixed(6));
else in3.value = '';
} else {
if (!isNaN(v3) && !isNaN(v2) && v2 !== 0) in1.value = parseFloat((v3 / v2).toFixed(6));
else in1.value = '';
}
} else if (type === 'dms-dd') {
// DD to DMS (in1=DD, in2=DMS text)
if (source === 1) {
if (!isNaN(v1)) {
let d = Math.floor(v1); let md = (v1 - d) * 60; let m = Math.floor(md); let sec = ((md - m) * 60).toFixed(2);
in2.value = `${d}° ${m}' ${sec}"`;
} else in2.value = '';
} else {
let str = in2.value;
let match = str.match(/(?:([0-9.-]+)\s*°)?\s*(?:([0-9.-]+)\s*')?\s*(?:([0-9.-]+)\s*")?/);
if (match) {
let d = parseFloat(match[1]) || 0; let m = parseFloat(match[2]) || 0; let sec = parseFloat(match[3]) || 0;
if (str.trim().length > 0) in1.value = parseFloat((d + m/60 + sec/3600).toFixed(6));
else in1.value = '';
} else in1.value = '';
}
} else if (type === 'dd-dms') {
// DMS to DD inverse?
// Actually the legacy code for "dms-to-dd" has input-1 as DMS and input-2 as DD.
// I'll handle based on the ID mapping in the container.
} else if (type === 'dec-frac') {
function gcd(a, b) { return b ? gcd(b, a % b) : a; }
if (source === 1) {
if (!isNaN(v1)) {
let len = v1.toString().split('.')[1] ? v1.toString().split('.')[1].length : 0;
let den = Math.pow(10, len); let num = v1 * den; let div = gcd(num, den);
in2.value = `${num/div}/${den/div}`;
} else in2.value = '';
} else {
let parts = in2.value.split('/');
if (parts.length === 2 && !isNaN(parts[0]) && !isNaN(parts[1]) && parts[1] != 0) in1.value = parseFloat((parts[0]/parts[1]).toFixed(6));
else { let f = parseFloat(parts[0]); if (!isNaN(f)) in1.value = f; else in1.value = ''; }
}
} else if (type === 'db-int') {
if (source === 1) { if (!isNaN(v1)) in2.value = parseFloat((1e-12 * Math.pow(10, v1/10)).toExponential(6)); else in2.value = ''; }
else { if (!isNaN(v2) && v2 > 0) in1.value = parseFloat((10 * Math.log10(v2 / 1e-12)).toFixed(6)); else in1.value = ''; }
} else if (type === 'db-spl') {
if (source === 1) { if (!isNaN(v1)) in2.value = parseFloat((20 * Math.pow(10, v1/20)).toFixed(6)); else in2.value = ''; }
else { if (!isNaN(v2) && v2 > 0) in1.value = parseFloat((20 * Math.log10(v2 / 20)).toFixed(6)); else in1.value = ''; }
} else if (type === 'db-v') {
if (source === 1) { if (!isNaN(v1)) in2.value = parseFloat((1 * Math.pow(10, v1/20)).toFixed(6)); else in2.value = ''; }
else { if (!isNaN(v2) && v2 > 0) in1.value = parseFloat((20 * Math.log10(v2 / 1)).toFixed(6)); else in1.value = ''; }
} else if (type === 'db-w') {
if (source === 1) { if (!isNaN(v1)) in2.value = parseFloat((1 * Math.pow(10, v1/10)).toFixed(6)); else in2.value = ''; }
else { if (!isNaN(v2) && v2 > 0) in1.value = parseFloat((10 * Math.log10(v2 / 1)).toFixed(6)); else in1.value = ''; }
} else if (type === 'base') {
const fromBase = parseInt(container.dataset.hdycFrom) || 10;
const toBase = parseInt(container.dataset.hdycTo) || 2;
if (source === 1) {
try {
const val = in1.value.trim();
if (val === '') { in2.value = ''; return; }
const dec = parseInt(val, fromBase);
if (!isNaN(dec)) in2.value = dec.toString(toBase).toUpperCase();
else in2.value = 'Invalid';
} catch(e) { in2.value = 'Error'; }
} else {
try {
const val = in2.value.trim();
if (val === '') { in1.value = ''; return; }
const dec = parseInt(val, toBase);
if (!isNaN(dec)) in1.value = dec.toString(fromBase).toUpperCase();
else in1.value = 'Invalid';
} catch(e) { in1.value = 'Error'; }
}
} else if (type === 'text-bin') {
if (source === 1) {
in2.value = in1.value.split('').map(char => char.charCodeAt(0).toString(2).padStart(8, '0')).join(' ');
} else {
try {
in1.value = in2.value.split(' ').map(bin => String.fromCharCode(parseInt(bin, 2))).join('');
} catch(e) { in1.value = 'Error'; }
}
} else if (type === 'bin-text') {
if (source === 1) {
try {
in2.value = in1.value.split(' ').map(bin => String.fromCharCode(parseInt(bin, 2))).join('');
} catch(e) { in2.value = 'Error'; }
} else {
in1.value = in2.value.split('').map(char => char.charCodeAt(0).toString(2).padStart(8, '0')).join(' ');
}
}
}
in1.addEventListener('input', () => solve(1));
in2.addEventListener('input', () => solve(2));
if (in3) in3.addEventListener('input', () => solve(3));
const uParams = new URLSearchParams(window.location.search);
if (uParams.has('v1')) { in1.value = uParams.get('v1'); solve(1); }
else if (uParams.has('v2')) { in2.value = uParams.get('v2'); solve(2); }
else if (uParams.has('v3') && in3) { in3.value = uParams.get('v3'); solve(3); }
});
}
if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', init);
else init();
})();

22
hdyc-csp-fix.php Normal file
View File

@@ -0,0 +1,22 @@
<?php
/**
* Plugin Name: HDYC CSP Calculator Fix
* Description: Enqueues the universal calculator script for CSP compliance.
* Version: 1.0
*/
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
function hdyc_enqueue_calculator_script() {
// Note: Assuming hdyc-calculators.js is in the same directory as this plugin
wp_enqueue_script(
'hdyc-calculators',
plugins_url( 'hdyc-calculators.js', __FILE__ ),
array(),
'1.1',
true
);
}
add_action( 'wp_enqueue_scripts', 'hdyc_enqueue_calculator_script' );

View File

@@ -1,316 +0,0 @@
import urllib.request
import json
import base64
import time
import re
url_base_kadence = "https://howdoyouconvert.com/wp-json/wp/v2/kadence_element/"
creds = base64.b64encode(b"ben:6YGf wVxu gBpz pkqx BGZO lfVP").decode("utf-8")
headers = {
"Content-Type": "application/json",
"Authorization": "Basic " + creds,
"User-Agent": "Mozilla/5.0"
}
def get_robust_js(factor, offset):
return f"""<script>
(function() {{
function init() {{
var i1 = document.getElementById("input-1");
var i2 = document.getElementById("input-2");
if (!i1 || !i2) {{
if (window.initRetries === undefined) window.initRetries = 0;
if (window.initRetries < 50) {{
window.initRetries++;
setTimeout(init, 100);
}}
return;
}}
i1.oninput = function() {{
var v = parseFloat(i1.value);
if (isNaN(v)) {{ i2.value = ""; return; }}
i2.value = parseFloat((v * {factor} + {offset}).toFixed(8));
}};
i2.oninput = function() {{
var v = parseFloat(i2.value);
if (isNaN(v)) {{ i1.value = ""; return; }}
i1.value = parseFloat(((v - {offset}) / {factor}).toFixed(8));
}};
var p = new URLSearchParams(window.location.search);
if (p.has('v1')) {{ i1.value = p.get('v1'); i1.oninput(); }}
else if (p.has('v2')) {{ i2.value = p.get('v2'); i2.oninput(); }}
}}
init();
}})();
</script>"""
# Manual mapping for complex ones as they don't follow the 1:1 format in the list
complex_fixes = {
140: """<script>
(function() {
function init() {
var i1 = document.getElementById("input-1");
var i2 = document.getElementById("input-2");
if (!i1 || !i2) { setTimeout(init, 100); return; }
i1.oninput = function() {
let val = i1.value;
let binary = "";
for (let i = 0; i < val.length; i++) {
let bin = val[i].charCodeAt(0).toString(2);
binary += ("00000000" + bin).slice(-8) + " ";
}
i2.value = binary.trim();
};
i2.oninput = function() {
let val = i2.value.replace(/\\s/g, "");
let text = "";
for (let i = 0; i < val.length; i += 8) {
let byte = val.substr(i, 8);
if (byte.length === 8) text += String.fromCharCode(parseInt(byte, 2));
}
i1.value = text;
};
}
init();
})();
</script>""",
152: """<script>
(function() {
function init() {
var i1 = document.getElementById("input-1");
var i2 = document.getElementById("input-2");
if (!i1 || !i2) { setTimeout(init, 100); return; }
i2.oninput = function() {
let val = i2.value;
let binary = "";
for (let i = 0; i < val.length; i++) {
let bin = val[i].charCodeAt(0).toString(2);
binary += ("00000000" + bin).slice(-8) + " ";
}
i1.value = binary.trim();
};
i1.oninput = function() {
let val = i1.value.replace(/\\s/g, "");
let text = "";
for (let i = 0; i < val.length; i += 8) {
let byte = val.substr(i, 8);
if (byte.length === 8) text += String.fromCharCode(parseInt(byte, 2));
}
i2.value = text;
};
}
init();
})();
</script>""",
154: """<script>
(function() {
function init() {
var i1 = document.getElementById("input-1");
var i2 = document.getElementById("input-2");
if (!i1 || !i2) { setTimeout(init, 100); return; }
i1.oninput = function() {
let val = i1.value.replace(/\\s/g, "");
if (val) i2.value = parseInt(val, 2).toString(10);
else i2.value = "";
};
i2.oninput = function() {
let val = i2.value;
if (val) i1.value = parseInt(val, 10).toString(2);
else i1.value = "";
};
}
init();
})();
</script>""",
156: """<script>
(function() {
function init() {
var i1 = document.getElementById("input-1");
var i2 = document.getElementById("input-2");
if (!i1 || !i2) { setTimeout(init, 100); return; }
i1.oninput = function() {
let val = i1.value.replace(/\\s/g, "");
if (val) i2.value = parseInt(val, 2).toString(16).toUpperCase();
else i2.value = "";
};
i2.oninput = function() {
let val = i2.value;
if (val) i1.value = parseInt(val, 16).toString(2);
else i1.value = "";
};
}
init();
})();
</script>""",
142: """<script>
(function() {
function init() {
var a = document.getElementById("input-1");
var v = document.getElementById("input-2");
var w = document.getElementById("input-3");
if (!a || !v || !w) { setTimeout(init, 100); return; }
function solve(lastId) {
let av = parseFloat(a.value), vv = parseFloat(v.value), wv = parseFloat(w.value);
if (lastId === '1' || lastId === '2') {
if (!isNaN(av) && !isNaN(vv)) w.value = parseFloat((av * vv).toFixed(3));
} else if (lastId === '3') {
if (!isNaN(wv)) {
if (!isNaN(av) && av !== 0) v.value = parseFloat((wv / av).toFixed(2));
else if (!isNaN(vv) && vv !== 0) a.value = parseFloat((wv / vv).toFixed(2));
}
}
}
a.oninput = () => solve('1'); v.oninput = () => solve('2'); w.oninput = () => solve('3');
}
init();
})();
</script>""",
158: """<script>
(function() {
function init() {
var a = document.getElementById("input-1");
var v = document.getElementById("input-2");
var w = document.getElementById("input-3");
if (!a || !v || !w) { setTimeout(init, 100); return; }
function solve(lastId) {
let av = parseFloat(a.value), vv = parseFloat(v.value), wv = parseFloat(w.value);
if (lastId === '1' || lastId === '2') {
if (!isNaN(av) && !isNaN(vv)) w.value = parseFloat((av * vv).toFixed(3));
} else if (lastId === '3') {
if (!isNaN(wv)) {
if (!isNaN(av) && av !== 0) v.value = parseFloat((wv / av).toFixed(2));
else if (!isNaN(vv) && vv !== 0) a.value = parseFloat((wv / vv).toFixed(2));
}
}
}
a.oninput = () => solve('1'); v.oninput = () => solve('2'); w.oninput = () => solve('3');
}
init();
})();
</script>""",
160: """<script>
(function() {
function init() {
var a = document.getElementById("input-1");
var v = document.getElementById("input-2");
var w = document.getElementById("input-3");
if (!a || !v || !w) { setTimeout(init, 100); return; }
function solve(lastId) {
let av = parseFloat(a.value), vv = parseFloat(v.value), wv = parseFloat(w.value);
if (lastId === '1' || lastId === '2') {
if (!isNaN(av) && !isNaN(vv)) w.value = parseFloat((av * vv / 1000).toFixed(4));
} else if (lastId === '3') {
if (!isNaN(wv)) {
if (!isNaN(av) && av !== 0) v.value = parseFloat((wv * 1000 / av).toFixed(2));
else if (!isNaN(vv) && vv !== 0) a.value = parseFloat((wv * 1000 / vv).toFixed(2));
}
}
}
a.oninput = () => solve('1'); v.oninput = () => solve('2'); w.oninput = () => solve('3');
}
init();
})();
</script>""",
162: """<script>
(function() {
function init() {
var a = document.getElementById("input-1");
var v = document.getElementById("input-2");
var w = document.getElementById("input-3");
if (!a || !v || !w) { setTimeout(init, 100); return; }
function solve(lastId) {
let av = parseFloat(a.value), vv = parseFloat(v.value), wv = parseFloat(w.value);
if (lastId === '1' || lastId === '2') {
if (!isNaN(av) && !isNaN(vv)) w.value = parseFloat((av * vv / 1000).toFixed(4));
} else if (lastId === '3') {
if (!isNaN(wv)) {
if (!isNaN(av) && av !== 0) v.value = parseFloat((wv * 1000 / av).toFixed(2));
else if (!isNaN(vv) && vv !== 0) a.value = parseFloat((wv * 1000 / vv).toFixed(2));
}
}
}
a.oninput = () => solve('1'); v.oninput = () => solve('2'); w.oninput = () => solve('3');
}
init();
})();
</script>"""
}
def patch_element(eid, js):
print(f"Patching EID {eid}...")
data = {"content": js}
req = urllib.request.Request(f"{url_base_kadence}{eid}", data=json.dumps(data).encode("utf-8"), headers=headers, method="PUT")
try:
urllib.request.urlopen(req, timeout=30)
print("--> Done")
except Exception as e:
print(f"--> Error: {e}")
# Parse registry for standard factors
with open("calculators_list.md", "r") as f:
lines = f.readlines()
for line in lines:
if "|" not in line or "Calculator Name" in line or ":---" in line: continue
parts = [p.strip() for p in line.split("|")]
if len(parts) < 6: continue
eid = parts[3]
if not eid.isdigit(): continue
eid = int(eid)
factor_str = parts[5]
# Only patch recent ones (Batch 3-6)
if eid < 140 and eid != 108 and eid != 110 and eid != 112 and eid != 114 and eid != 116 and eid != 118 and eid != 120 and eid != 122 and eid != 124 and eid != 126 and eid != 128 and eid != 130 and eid != 132 and eid != 134 and eid != 136 and eid != 138:
continue
if eid in complex_fixes:
patch_element(eid, complex_fixes[eid])
else:
# standard 1:1 or offset
factor = 1.0
offset = 0.0
if "Linear Offset" in factor_str:
# Linear Offset (1.8x + 32)
# Linear Offset (5/9x - 17.778)
m = re.search(r'\((.*?)x \+ (.*?)\)', factor_str)
if not m: m = re.search(r'\((.*?)x - (.*?)\)', factor_str)
if m:
m_val = m.group(1)
if m_val == "1.8": factor = 1.8
elif m_val == "5/9": factor = 5/9
b_val = float(m.group(2))
if "-" in factor_str: offset = -b_val
else: offset = b_val
else:
print(f"Skipping {eid}: unparseable offset {factor_str}")
continue
else:
try:
factor = float(factor_str)
except:
print(f"Skipping {eid}: unparseable factor {factor_str}")
continue
patch_element(eid, get_robust_js(factor, offset))
time.sleep(1)
# Also patch Batch 6 explicitly if not in registry yet (I check previous command status)
# Batch 6 Element IDs: 234, 236, 238, 240
batch_6_extra = [
(234, 0.0321507466, 0), # Grams to Apothecary Ounces
(236, 5.0, 0), # Grams to Carats
(238, 15.4323584, 0), # Grams to Grains
(240, 0.745699872, 0) # Horsepower to Kilowatts
]
for eid, f, o in batch_6_extra:
if eid not in complex_fixes:
patch_element(eid, get_robust_js(f, o))
time.sleep(1)

View File

@@ -1,58 +0,0 @@
import urllib.request
import json
import base64
import time
creds = base64.b64encode(b"ben:6YGf wVxu gBpz pkqx BGZO lfVP").decode("utf-8")
headers = {
"Content-Type": "application/json",
"Authorization": "Basic " + creds,
"User-Agent": "Mozilla/5.0"
}
def get_js(f):
return f"""<script>
(function() {{
function init() {{
var i1 = document.getElementById("input-1");
var i2 = document.getElementById("input-2");
if (!i1 || !i2) {{
if (window.r < 50) {{
window.r++;
setTimeout(init, 100);
}}
return;
}}
i1.oninput = function() {{
var v = parseFloat(i1.value);
if (isNaN(v)) {{ i2.value = ""; return; }}
i2.value = parseFloat((v * {f}).toFixed(8));
}};
i2.oninput = function() {{
var v = parseFloat(i2.value);
if (isNaN(v)) {{ i1.value = ""; return; }}
i1.value = parseFloat((v / {f}).toFixed(8));
}};
}}
window.r = 0;
init();
}})();
</script>"""
units = [
(235, 0.0321507466), # Grams to Apothecary Ounces
(237, 5.0), # Grams to Carats
(239, 15.4323584), # Grams to Grains
(241, 0.745699872) # Horsepower to Kilowatts
]
for eid, f in units:
data = json.dumps({'content': get_js(f)}).encode('utf-8')
url = f'https://howdoyouconvert.com/wp-json/wp/v2/kadence_element/{eid}'
req = urllib.request.Request(url, data=data, headers=headers, method='PUT')
try:
urllib.request.urlopen(req)
print(f"Patched {eid}")
except Exception as e:
print(f"Error {eid}: {e}")
time.sleep(1)

View File

@@ -1,304 +0,0 @@
import urllib.request
import json
import base64
import time
import re
url_base_kadence = "https://howdoyouconvert.com/wp-json/wp/v2/kadence_element/"
creds = base64.b64encode(b"ben:6YGf wVxu gBpz pkqx BGZO lfVP").decode("utf-8")
headers = {
"Content-Type": "application/json",
"Authorization": "Basic " + creds,
"User-Agent": "Mozilla/5.0"
}
def get_robust_js(factor, offset):
return f"""<script>
(function() {{
function init() {{
var i1 = document.getElementById("input-1");
var i2 = document.getElementById("input-2");
if (!i1 || !i2) {{
if (window.initRetries === undefined) window.initRetries = 0;
if (window.initRetries < 50) {{
window.initRetries++;
setTimeout(init, 100);
}}
return;
}}
i1.oninput = function() {{
var v = parseFloat(i1.value);
if (isNaN(v)) {{ i2.value = ""; return; }}
i2.value = parseFloat((v * {factor} + {offset}).toFixed(8));
}};
i2.oninput = function() {{
var v = parseFloat(i2.value);
if (isNaN(v)) {{ i1.value = ""; return; }}
i1.value = parseFloat(((v - {offset}) / {factor}).toFixed(8));
}};
var p = new URLSearchParams(window.location.search);
if (p.has('v1')) {{ i1.value = p.get('v1'); i1.oninput(); }}
else if (p.has('v2')) {{ i2.value = p.get('v2'); i2.oninput(); }}
}}
init();
}})();
</script>"""
# Complex mapping (same as before)
complex_fixes_by_slug = {
"ascii-to-binary": """<script>
(function() {
function init() {
var i1 = document.getElementById("input-1");
var i2 = document.getElementById("input-2");
if (!i1 || !i2) { setTimeout(init, 100); return; }
i1.oninput = function() {
let val = i1.value;
let binary = "";
for (let i = 0; i < val.length; i++) {
let bin = val[i].charCodeAt(0).toString(2);
binary += ("00000000" + bin).slice(-8) + " ";
}
i2.value = binary.trim();
};
i2.oninput = function() {
let val = i2.value.replace(/\\s/g, "");
let text = "";
for (let i = 0; i < val.length; i += 8) {
let byte = val.substr(i, 8);
if (byte.length === 8) text += String.fromCharCode(parseInt(byte, 2));
}
i1.value = text;
};
}
init();
})();
</script>""",
"binary-to-ascii": """<script>
(function() {
function init() {
var i1 = document.getElementById("input-1");
var i2 = document.getElementById("input-2");
if (!i1 || !i2) { setTimeout(init, 100); return; }
i2.oninput = function() {
let val = i2.value;
let binary = "";
for (let i = 0; i < val.length; i++) {
let bin = val[i].charCodeAt(0).toString(2);
binary += ("00000000" + bin).slice(-8) + " ";
}
i1.value = binary.trim();
};
i1.oninput = function() {
let val = i1.value.replace(/\\s/g, "");
let text = "";
for (let i = 0; i < val.length; i += 8) {
let byte = val.substr(i, 8);
if (byte.length === 8) text += String.fromCharCode(parseInt(byte, 2));
}
i2.value = text;
};
}
init();
})();
</script>""",
"binary-to-decimal": """<script>
(function() {
function init() {
var i1 = document.getElementById("input-1");
var i2 = document.getElementById("input-2");
if (!i1 || !i2) { setTimeout(init, 100); return; }
i1.oninput = function() {
let val = i1.value.replace(/\\s/g, "");
if (val) i2.value = parseInt(val, 2).toString(10);
else i2.value = "";
};
i2.oninput = function() {
let val = i2.value;
if (val) i1.value = parseInt(val, 10).toString(2);
else i1.value = "";
};
}
init();
})();
</script>""",
"binary-to-hex": """<script>
(function() {
function init() {
var i1 = document.getElementById("input-1");
var i2 = document.getElementById("input-2");
if (!i1 || !i2) { setTimeout(init, 100); return; }
i1.oninput = function() {
let val = i1.value.replace(/\\s/g, "");
if (val) i2.value = parseInt(val, 2).toString(16).toUpperCase();
else i2.value = "";
};
i2.oninput = function() {
let val = i2.value;
if (val) i1.value = parseInt(val, 16).toString(2);
else i1.value = "";
};
}
init();
})();
</script>""",
"amps-to-volts": """<script>
(function() {
function init() {
var a = document.getElementById("input-1");
var v = document.getElementById("input-2");
var w = document.getElementById("input-3");
if (!a || !v || !w) { setTimeout(init, 100); return; }
function solve(lastId) {
let av = parseFloat(a.value), vv = parseFloat(v.value), wv = parseFloat(w.value);
if (lastId === '1' || lastId === '2') {
if (!isNaN(av) && !isNaN(vv)) w.value = parseFloat((av * vv).toFixed(3));
} else if (lastId === '3') {
if (!isNaN(wv)) {
if (!isNaN(av) && av !== 0) v.value = parseFloat((wv / av).toFixed(2));
else if (!isNaN(vv) && vv !== 0) a.value = parseFloat((wv / vv).toFixed(2));
}
}
}
a.oninput = () => solve('1'); v.oninput = () => solve('2'); w.oninput = () => solve('3');
}
init();
})();
</script>""",
"amps-to-watts": """<script>
(function() {
function init() {
var a = document.getElementById("input-1");
var v = document.getElementById("input-2");
var w = document.getElementById("input-3");
if (!a || !v || !w) { setTimeout(init, 100); return; }
function solve(lastId) {
let av = parseFloat(a.value), vv = parseFloat(v.value), wv = parseFloat(w.value);
if (lastId === '1' || lastId === '2') {
if (!isNaN(av) && !isNaN(vv)) w.value = parseFloat((av * vv).toFixed(3));
} else if (lastId === '3') {
if (!isNaN(wv)) {
if (!isNaN(av) && av !== 0) v.value = parseFloat((wv / av).toFixed(2));
else if (!isNaN(vv) && vv !== 0) a.value = parseFloat((wv / vv).toFixed(2));
}
}
}
a.oninput = () => solve('1'); v.oninput = () => solve('2'); w.oninput = () => solve('3');
}
init();
})();
</script>""",
"amps-to-kilowatts": """<script>
(function() {
function init() {
var a = document.getElementById("input-1");
var v = document.getElementById("input-2");
var w = document.getElementById("input-3");
if (!a || !v || !w) { setTimeout(init, 100); return; }
function solve(lastId) {
let av = parseFloat(a.value), vv = parseFloat(v.value), wv = parseFloat(w.value);
if (lastId === '1' || lastId === '2') {
if (!isNaN(av) && !isNaN(vv)) w.value = parseFloat((av * vv / 1000).toFixed(4));
} else if (lastId === '3') {
if (!isNaN(wv)) {
if (!isNaN(av) && av !== 0) v.value = parseFloat((wv * 1000 / av).toFixed(2));
else if (!isNaN(vv) && vv !== 0) a.value = parseFloat((wv * 1000 / vv).toFixed(2));
}
}
}
a.oninput = () => solve('1'); v.oninput = () => solve('2'); w.oninput = () => solve('3');
}
init();
})();
</script>""",
"amps-to-kva": """<script>
(function() {
function init() {
var a = document.getElementById("input-1");
var v = document.getElementById("input-2");
var w = document.getElementById("input-3");
if (!a || !v || !w) { setTimeout(init, 100); return; }
function solve(lastId) {
let av = parseFloat(a.value), vv = parseFloat(v.value), wv = parseFloat(w.value);
if (lastId === '1' || lastId === '2') {
if (!isNaN(av) && !isNaN(vv)) w.value = parseFloat((av * vv / 1000).toFixed(4));
} else if (lastId === '3') {
if (!isNaN(wv)) {
if (!isNaN(av) && av !== 0) v.value = parseFloat((wv * 1000 / av).toFixed(2));
else if (!isNaN(vv) && vv !== 0) a.value = parseFloat((wv * 1000 / vv).toFixed(2));
}
}
}
a.oninput = () => solve('1'); v.oninput = () => solve('2'); w.oninput = () => solve('3');
}
init();
})();
</script>"""
}
def patch_element(eid, js):
print(f"Patching EID {eid}...")
data = {"content": js}
req = urllib.request.Request(f"{url_base_kadence}{eid}", data=json.dumps(data).encode("utf-8"), headers=headers, method="PUT")
try:
urllib.request.urlopen(req, timeout=30)
print("--> Done")
except Exception as e:
print(f"--> Error: {e}")
# 1. Load factors from registry
registry = {}
with open("calculators_list.md", "r") as f:
for line in f:
if "|" not in line or "Calculators Registry" in line or "---" in line: continue
parts = [p.strip() for p in line.split("|")]
if len(parts) < 6: continue
slug = parts[4].replace("-2", "")
factor_str = parts[5]
registry[slug] = factor_str
# 2. Load mapping
with open("/tmp/element_mapping.json", "r") as f:
mappings = json.load(f)
for m in mappings:
eid = m['eid']
raw_slug = m['slug']
base_slug = raw_slug.replace("-2", "")
if base_slug in complex_fixes_by_slug:
patch_element(eid, complex_fixes_by_slug[base_slug])
continue
if base_slug in registry:
factor_str = registry[base_slug]
factor = 1.0
offset = 0.0
if "Linear Offset" in factor_str:
match = re.search(r'\((.*?)x \+ (.*?)\)', factor_str)
if not match: match = re.search(r'\((.*?)x - (.*?)\)', factor_str)
if match:
m_val = match.group(1)
if m_val == "1.8": factor = 1.8
elif m_val == "5/9": factor = 5/9
b_val = float(match.group(2))
if "-" in factor_str: offset = -b_val
else: offset = b_val
else:
try:
factor = float(factor_str)
except:
print(f"Skipping {eid} ({base_slug}): unparseable factor {factor_str}")
continue
patch_element(eid, get_robust_js(factor, offset))
else:
print(f"Warning: Slug {base_slug} (EID {eid}) not in registry. Skipping.")
print("UNIVERSAL PATCH COMPLETE")

View File

@@ -1,159 +0,0 @@
import urllib.request
import json
import base64
import time
url_base = "https://howdoyouconvert.com/wp-json/wp/v2/calculator/"
creds = base64.b64encode(b"ben:6YGf wVxu gBpz pkqx BGZO lfVP").decode("utf-8")
headers = {
"Content-Type": "application/json",
"Authorization": "Basic " + creds,
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64)"
}
queue = [
{
"id": 109,
"slug": "acres-to-square-feet",
"label1": "Acres (ac)",
"label2": "Square Feet (sq ft)",
"factor": 43560.0,
"seo_text": """
<!-- wp:paragraph -->
<p style="margin-top: 2rem; line-height: 1.6;"><strong>Understanding Acres and Square Feet:</strong> The acre and the square foot are two of the most common land measurement units in the United States customary system. A square foot is defined as the area of a square with sides exactly one foot in length, primarily used for measuring the interior space of buildings or small exterior plots. The acre is a much larger unit traditionally used for agricultural or real estate surveying. Historically defined by the amount of land tillable by a yoke of oxen in one day, an acre provides a standardized macro-measurement for vast properties.</p>
<!-- /wp:paragraph -->
<!-- wp:paragraph -->
<p style="line-height: 1.6;">The relationship between these two customary units is exact but unconventional compared to metric base-10 systems. By standard definition, one single acre encompasses exactly 43,560 square feet. This precise figure allows surveyors, realtors, and civil engineers to accurately subdivide large tracts of acreage into smaller, buildable square-foot lots for commercial or residential zoning.</p>
<!-- /wp:paragraph -->
<!-- wp:paragraph -->
<p style="line-height: 1.6;"><strong>The Conversion Process:</strong> Scaling between acres and square feet requires the application of the 43,560 arithmetic constant. To evaluate the square footage of a plot of land measured in acres, simply multiply the acreage by 43,560. Conversely, if you possess the total square footage of a property and wish to determine its acreage, divide the square footage value by 43,560. This strict mathematical ratio ensures dimensional accuracy across US real estate transactions.</p>
<!-- /wp:paragraph -->
"""
},
{
"id": 111,
"slug": "angstroms-to-nanometers",
"label1": "Angstroms (Å)",
"label2": "Nanometers (nm)",
"factor": 0.1,
"seo_text": """
<!-- wp:paragraph -->
<p style="margin-top: 2rem; line-height: 1.6;"><strong>Understanding Angstroms and Nanometers:</strong> The angstrom and the nanometer are sub-microscopic units of length utilized extensively in the fields of physics, chemistry, and molecular biology. The nanometer is an official constituent of the International System of Units (SI), equating precisely to one billionth of a meter (10<sup>-9</sup> m). It is the standard measurement unit for calculating the wavelength of visible light and defining the scale of nanotechnology engineering.</p>
<!-- /wp:paragraph -->
<!-- wp:paragraph -->
<p style="line-height: 1.6;">The angstrom (Å) is an internationally recognized, non-SI unit of length equal to one ten-billionth of a meter (10<sup>-10</sup> m). Named after the Swedish physicist Anders Jonas Ångström, it is primarily employed by crystallographers, structural biologists, and chemists to express the sizes of individual atoms, the lengths of chemical bonds, and the parameters of crystal structures, which typically fall on the 1 to 10 angstrom scale.</p>
<!-- /wp:paragraph -->
<!-- wp:paragraph -->
<p style="line-height: 1.6;"><strong>The Conversion Process:</strong> Transitioning between these two atomic-scale measurement units is highly streamlined due to their base-10 decimal relationship. There are exactly 10 angstroms within a single nanometer. Therefore, to convert a measurement from angstroms into its nanometer equivalent, you simply multiply the angstrom value by 0.1 (or divide by 10). When reversing the process to find angstroms from nanometers, you multiply the nanometer figure by 10.</p>
<!-- /wp:paragraph -->
"""
},
{
"id": 113,
"slug": "apothecary-ounces-to-grams",
"label1": "Apothecary Ounces (oz t)",
"label2": "Grams (g)",
"factor": 31.1034768,
"seo_text": """
<!-- wp:paragraph -->
<p style="margin-top: 2rem; line-height: 1.6;"><strong>Understanding Apothecary Ounces and Grams:</strong> The apothecary ounce and the gram represent two vastly different eras in the standardization of mass and weight measurement. The gram is a foundational unit of mass within the modern metric system (SI), originally defined as the absolute weight of a volume of pure water equal to the cube of the hundredth part of a meter. It serves as the ubiquitous worldwide standard for scientific, medical, and everyday weight measurement.</p>
<!-- /wp:paragraph -->
<!-- wp:paragraph -->
<p style="line-height: 1.6;">The apothecary ounce, conversely, is a historical unit of mass previously utilized by medical professionals and pharmacists to measure pharmacological recipes. It shares the exact same weight as the troy ounce—a unit still actively used today for weighing precious metals like gold and silver. This system was vital before the global adoption of the metric system standardized medical dosages into universally safe gram and milligram parameters.</p>
<!-- /wp:paragraph -->
<!-- wp:paragraph -->
<p style="line-height: 1.6;"><strong>The Conversion Process:</strong> Because the apothecary ounce is identical to the troy ounce, it holds a heavier mass value than the standard customary (avoirdupois) ounce used for food. One apothecary ounce is legally equated to exactly 31.1034768 grams. To convert from apothecary ounces to grams, you multiply the ounce value by this 31.1034768 constant. When determining how many apothecary ounces construct a specific gram weight, you divide the gram measurement by that identical factor.</p>
<!-- /wp:paragraph -->
"""
},
{
"id": 115,
"slug": "astronomical-units-to-light-years",
"label1": "Astronomical Units (au)",
"label2": "Light Years (ly)",
"factor": 0.0000158125074,
"seo_text": """
<!-- wp:paragraph -->
<p style="margin-top: 2rem; line-height: 1.6;"><strong>Understanding Astronomical Units and Light Years:</strong> The astronomical unit (au) and the light year (ly) are specialized units of length relied upon by astronomers and astrophysicists to quantify immense cosmic distances. The astronomical unit provides a localized baseline for our solar system, defined as the roughly average distance between the center of the Earth and the center of the Sun: exactly 149,597,870,700 meters, or approximately 93 million miles.</p>
<!-- /wp:paragraph -->
<!-- wp:paragraph -->
<p style="line-height: 1.6;">The light year is utilized for macroscopic interstellar and intergalactic scales. Rather than measuring time, a light year measures the physical distance that a photon of light travels in a vacuum over the course of one Julian year (365.25 days). This vast distance is calculated at roughly 9.46 trillion kilometers. For perspective, the nearest star to our solar system, Proxima Centauri, is positioned over 4.2 light years away from Earth.</p>
<!-- /wp:paragraph -->
<!-- wp:paragraph -->
<p style="line-height: 1.6;"><strong>The Conversion Process:</strong> Given the staggering scale of the cosmos, translating the localized astronomical unit into the interstellar light year requires a drastic fractional multiplier. There are approximately 63,241 astronomical units compacted into a single light year. To equate a measurement of astronomical units into light years, multiply the au parameter by 0.0000158125. Conversely, converting light years back into astronomical units requires multiplying the light year figure by roughly 63,241.077.</p>
<!-- /wp:paragraph -->
"""
},
{
"id": 117,
"slug": "atmosphere-to-mmhg",
"label1": "Atmospheres (atm)",
"label2": "Millimeters of Mercury (mmHg)",
"factor": 760.0,
"seo_text": """
<!-- wp:paragraph -->
<p style="margin-top: 2rem; line-height: 1.6;"><strong>Understanding Atmospheres and mmHg:</strong> The standard atmosphere (atm) and the millimeter of mercury (mmHg) are classic units used to measure pressure within physics, meteorology, and medicine. The standard atmosphere is a reference unit defined as exactly 101,325 Pascals. It was originally established to represent the mean historical atmospheric pressure exerted by the Earth's atmosphere at mean sea level, serving as a baseline for aerodynamics and fluid mechanics.</p>
<!-- /wp:paragraph -->
<!-- wp:paragraph -->
<p style="line-height: 1.6;">The millimeter of mercury (mmHg) is a manometric unit of pressure historically derived from the operation of traditional mercury barometers. It represents the extra pressure generated by a column of mercury precisely one millimeter high at standard gravity. While the Torr has largely superseded it in modern physical sciences, the mmHg remains the predominant, internationally recognized standard unit for clinical blood pressure measurements.</p>
<!-- /wp:paragraph -->
<!-- wp:paragraph -->
<p style="line-height: 1.6;"><strong>The Conversion Process:</strong> Because the standard atmosphere was partially defined by the physical limits of historic mercury barometers at sea level, the mathematical relationship between the two units incorporates a clean, integer value. One standard atmosphere is exactly equivalent to 760 millimeters of mercury. To convert from atmospheres into mmHg, multiply the atmospheric value by 760. When reversing the conversion to calculate atmospheres from a raw mmHg reading, divide the mmHg parameter by 760.</p>
<!-- /wp:paragraph -->
"""
}
]
for item in queue:
print(f"\n--- True Deploying to ID {item['id']} ---")
slug_raw = item['slug'].replace("-", "")
content_html = f"""
<!-- wp:kadence/rowlayout {{"uniqueID":"{item['slug']}_outer","bgColor":"#f5f7f9","padding":["2rem","2rem","2rem","2rem"],"borderRadius":["8px","8px","8px","8px"]}} -->
<div class="wp-block-kadence-rowlayout alignnone"><div class="kt-row-column-wrap kt-has-1-columns kt-row-layout-equal kt-tab-layout-inherit kt-mobile-layout-row kt-row-valign-top" style="background-color:#f5f7f9;border-radius:8px;padding:2rem;">
<!-- wp:kadence/column {{"uniqueID":"{item['slug']}_inner"}} -->
<div class="wp-block-kadence-column"><div class="kt-inside-inner-col">
<style>.kb-row-layout-id_{slug_raw}_row > .kt-row-column-wrap{{align-content:start;}}:where(.kb-row-layout-id_{slug_raw}_row > .kt-row-column-wrap) > .wp-block-kadence-column{{justify-content:start;}}.kb-row-layout-id_{slug_raw}_row > .kt-row-column-wrap{{column-gap:var(--global-kb-gap-md, 2rem);row-gap:var(--global-kb-gap-md, 2rem);max-width:600px;margin-left:auto;margin-right:auto;grid-template-columns:repeat(2, minmax(0, 1fr));}}.kb-row-layout-id_{slug_raw}_row > .kt-row-layout-overlay{{opacity:0.30;}}@media all and (max-width: 1024px){{.kb-row-layout-id_{slug_raw}_row > .kt-row-column-wrap{{grid-template-columns:repeat(2, minmax(0, 1fr));}}}}@media all and (max-width: 767px){{.kb-row-layout-id_{slug_raw}_row > .kt-row-column-wrap{{grid-template-columns:minmax(0, 1fr);}}}}</style><div class="kb-row-layout-wrap kb-row-layout-id_{slug_raw}_row aligncenter wp-block-kadence-rowlayout"><div class="kt-row-column-wrap kt-has-2-columns kt-row-layout-equal kt-tab-layout-inherit kt-mobile-layout-row kt-row-valign-top"><style>.kadence-column_{slug_raw}_col1 > .kt-inside-inner-col,.kadence-column_{slug_raw}_col1 > .kt-inside-inner-col:before{{border-top-left-radius:0px;border-top-right-radius:0px;border-bottom-right-radius:0px;border-bottom-left-radius:0px;}}.kadence-column_{slug_raw}_col1 > .kt-inside-inner-col{{column-gap:var(--global-kb-gap-sm, 1rem);flex-direction:column;}}.kadence-column_{slug_raw}_col1 > .kt-inside-inner-col > .aligncenter{{width:100%;}}.kadence-column_{slug_raw}_col1 > .kt-inside-inner-col:before{{opacity:0.3;}}.kadence-column_{slug_raw}_col1{{position:relative;}}</style>
<div class="wp-block-kadence-column kadence-column_{slug_raw}_col1"><div class="kt-inside-inner-col">
<label for="input-1" style="font-weight: 600; color: #333333; margin-bottom: 8px; display: block;">{item['label1']}</label>
<input type="number" id="input-1" class="calc-input calc-field" onclick="clearPlaceholder('input-1')" placeholder="0" style="width:100%; padding: 12px; border: 1px solid #ccc; border-radius: 4px; font-size: 1.2rem;">
<input type="hidden" id="factor-1" name="factor-1" value="{item['factor']}"></div></div><style>.kadence-column_{slug_raw}_col2 > .kt-inside-inner-col,.kadence-column_{slug_raw}_col2 > .kt-inside-inner-col:before{{border-top-left-radius:0px;border-top-right-radius:0px;border-bottom-right-radius:0px;border-bottom-left-radius:0px;}}.kadence-column_{slug_raw}_col2 > .kt-inside-inner-col{{column-gap:var(--global-kb-gap-sm, 1rem);flex-direction:column;}}.kadence-column_{slug_raw}_col2 > .kt-inside-inner-col > .aligncenter{{width:100%;}}.kadence-column_{slug_raw}_col2 > .kt-inside-inner-col:before{{opacity:0.3;}}.kadence-column_{slug_raw}_col2{{position:relative;}}</style>
<div class="wp-block-kadence-column kadence-column_{slug_raw}_col2"><div class="kt-inside-inner-col">
<label for="input-2" style="font-weight: 600; color: #333333; margin-bottom: 8px; display: block;">{item['label2']}</label>
<input type="number" id="input-2" class="calc-input calc-field" onclick="clearPlaceholder('input-2')" placeholder="0" style="width:100%; padding: 12px; border: 1px solid #ccc; border-radius: 4px; font-size: 1.2rem;">
</div></div></div></div>
</div></div>
<!-- /wp:kadence/column -->
</div></div>
<!-- /wp:kadence/rowlayout -->
{item['seo_text']}
"""
calc_data = {
"content": content_html
}
req = urllib.request.Request(f"{url_base}{item['id']}", data=json.dumps(calc_data).encode("utf-8"), headers=headers, method="POST")
try:
urllib.request.urlopen(req)
print(f"--> Overwrote Post {item['id']}")
except Exception as e:
print(f"Error updating post {item['id']}:", e)
if hasattr(e, 'read'): print("Response:", e.read().decode("utf-8"))
time.sleep(1)
print("\n--- BATCH UPDATE COMPLETE ---")

View File

@@ -1,135 +0,0 @@
import urllib.request
import json
import base64
import time
url_base_kadence = "https://howdoyouconvert.com/wp-json/wp/v2/kadence_element/"
creds = base64.b64encode(b"ben:6YGf wVxu gBpz pkqx BGZO lfVP").decode("utf-8")
headers = {
"Content-Type": "application/json",
"Authorization": "Basic " + creds,
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64)"
}
def patch_element(element_id, title, js_logic):
print(f"Updating Element {element_id}: {title}")
js_wrapped = f"""<script>
window.addEventListener('DOMContentLoaded', (event) => {{
{js_logic}
}});
</script>"""
data = {
"content": js_wrapped
}
url = f"{url_base_kadence}{element_id}"
req = urllib.request.Request(url, data=json.dumps(data).encode("utf-8"), headers=headers, method="PUT")
try:
resp = urllib.request.urlopen(req, timeout=30)
print(f"--> Success")
except Exception as e:
print(f"--> Error: {e}")
if hasattr(e, 'read'): print(e.read().decode('utf-8'))
# --- LOGIC BLOCKS ---
triple_logic_base = """
function solve(lastId) {
let a = parseFloat(document.getElementById("input-1").value);
let v = parseFloat(document.getElementById("input-2").value);
let w = parseFloat(document.getElementById("input-3").value);
if (isNaN(a) && isNaN(v) && isNaN(w)) return;
if (lastId === 'input-1' || lastId === 'input-2') {
if (!isNaN(a) && !isNaN(v)) {
let res = (a * v) / [DIVISOR];
document.getElementById("input-3").value = parseFloat(res.toFixed(3));
}
} else if (lastId === 'input-3') {
if (!isNaN(w)) {
if (!isNaN(a) && a !== 0) {
let res = (w * [DIVISOR]) / a;
document.getElementById("input-2").value = parseFloat(res.toFixed(2));
} else if (!isNaN(v) && v !== 0) {
let res = (w * [DIVISOR]) / v;
document.getElementById("input-1").value = parseFloat(res.toFixed(2));
}
}
}
}
document.getElementById("input-1").addEventListener("input", () => solve('input-1'));
document.getElementById("input-2").addEventListener("input", () => solve('input-2'));
document.getElementById("input-3").addEventListener("input", () => solve('input-3'));
"""
text_logic_ascii_to_bin = """
function convert1() {
let val = document.getElementById("input-1").value;
let binary = "";
for (let i = 0; i < val.length; i++) {
let bin = val[i].charCodeAt(0).toString(2);
binary += ("00000000" + bin).slice(-8) + " ";
}
document.getElementById("input-2").value = binary.trim();
}
function convert2() {
let val = document.getElementById("input-2").value.replace(/\\s/g, "");
let text = "";
for (let i = 0; i < val.length; i += 8) {
let byte = val.substr(i, 8);
if (byte.length === 8) {
text += String.fromCharCode(parseInt(byte, 2));
}
}
document.getElementById("input-1").value = text;
}
document.getElementById("input-1").addEventListener("input", convert1);
document.getElementById("input-2").addEventListener("input", convert2);
"""
text_logic_bin_to_dec = """
function convert1() {
let val = document.getElementById("input-1").value.replace(/\\s/g, "");
if (val) document.getElementById("input-2").value = parseInt(val, 2).toString(10);
else document.getElementById("input-2").value = "";
}
function convert2() {
let val = document.getElementById("input-2").value;
if (val) document.getElementById("input-1").value = parseInt(val, 10).toString(2);
else document.getElementById("input-1").value = "";
}
document.getElementById("input-1").addEventListener("input", convert1);
document.getElementById("input-2").addEventListener("input", convert2);
"""
text_logic_bin_to_hex = """
function convert1() {
let val = document.getElementById("input-1").value.replace(/\\s/g, "");
if (val) document.getElementById("input-2").value = parseInt(val, 2).toString(16).toUpperCase();
else document.getElementById("input-2").value = "";
}
function convert2() {
let val = document.getElementById("input-2").value;
if (val) document.getElementById("input-1").value = parseInt(val, 16).toString(2);
else document.getElementById("input-1").value = "";
}
document.getElementById("input-1").addEventListener("input", convert1);
document.getElementById("input-2").addEventListener("input", convert2);
"""
updates = [
(140, "ASCII to Binary", text_logic_ascii_to_bin),
(152, "Binary to ASCII", text_logic_ascii_to_bin), # Logic is the same, just order of fields in UI differs? No, inputs are 1 and 2.
(154, "Binary to Decimal", text_logic_bin_to_dec),
(156, "Binary to Hex", text_logic_bin_to_hex),
(142, "Amps to Volts", triple_logic_base.replace("[DIVISOR]", "1")),
(158, "Amps to Watts", triple_logic_base.replace("[DIVISOR]", "1")),
(160, "Amps to Kilowatts", triple_logic_base.replace("[DIVISOR]", "1000")),
(162, "Amps to kVA", triple_logic_base.replace("[DIVISOR]", "1000"))
]
for eid, title, logic in updates:
patch_element(eid, title, logic)
time.sleep(1)

View File

@@ -1,46 +0,0 @@
import urllib.request
import json
import re
batch_10_results = [
{"url": "https://howdoyouconvert.com/calculator/megabytes-to-gigabytes/?ao_noptimize=1", "v1": 1000, "expected_v2": 1, "m": 0.001},
{"url": "https://howdoyouconvert.com/calculator/megajoules-to-kilowatt-hours/?ao_noptimize=1", "v1": 3.6, "expected_v2": 1, "m": 0.277778},
{"url": "https://howdoyouconvert.com/calculator/meters-to-feet/?ao_noptimize=1", "v1": 1, "expected_v2": 3.28084, "m": 3.28084},
{"url": "https://howdoyouconvert.com/calculator/meters-to-yards/?ao_noptimize=1", "v1": 1, "expected_v2": 1.09361, "m": 1.09361},
{"url": "https://howdoyouconvert.com/calculator/metric-tons-to-short-tons/?ao_noptimize=1", "v1": 1, "expected_v2": 1.10231, "m": 1.10231},
{"url": "https://howdoyouconvert.com/calculator/minutes-to-hours/?ao_noptimize=1", "v1": 60, "expected_v2": 1, "m": 0.0166667},
{"url": "https://howdoyouconvert.com/calculator/minutes-to-seconds/?ao_noptimize=1", "v1": 1, "expected_v2": 60, "m": 60.0},
{"url": "https://howdoyouconvert.com/calculator/nautical-miles-to-kilometers/?ao_noptimize=1", "v1": 1, "expected_v2": 1.852, "m": 1.852},
{"url": "https://howdoyouconvert.com/calculator/newtons-to-dynes/?ao_noptimize=1", "v1": 1, "expected_v2": 100000.0, "m": 100000.0},
{"url": "https://howdoyouconvert.com/calculator/ounces-to-grams/?ao_noptimize=1", "v1": 1, "expected_v2": 28.3495, "m": 28.3495}
]
headers = {"User-Agent": "Mozilla/5.0"}
for calc in batch_10_results:
print(f"\n--- Verifying {calc['url']} ---")
req = urllib.request.Request(calc['url'], headers=headers)
try:
resp = urllib.request.urlopen(req, timeout=30).read().decode("utf-8")
if "initRetries" in resp and "setTimeout(init, 100)" in resp:
print("Robust JS: OK")
else:
print("Robust JS: MISSING")
m_pattern = r'i2\.value = parseFloat\(\(v \* ([\d\.e\-]+)\)'
m = re.search(m_pattern, resp)
if m:
actual_m = float(m.group(1))
print(f"Multiplier: {actual_m} (Expected {calc['m']})")
if abs(actual_m - calc['m']) / (calc['m'] or 1) < 0.0001:
print("Math Match: OK")
else:
print("Math Match: FAIL")
else:
print("Multiplier: NOT FOUND")
except Exception as e:
print(f"Error: {e}")
print("\nVERIFICATION COMPLETE")

View File

@@ -1,85 +0,0 @@
import urllib.request
import re
import json
import time
# Batch 2 Registry Mapping for Verification
batch_2_registry = [
{"url": "https://howdoyouconvert.com/calculator/attograms-to-femtograms/?ao_noptimize=1", "fwd": 0.001, "v1": 1000, "expected_v2": 1},
{"url": "https://howdoyouconvert.com/calculator/bar-to-pascal/?ao_noptimize=1", "fwd": 100000, "v1": 1, "expected_v2": 100000},
{"url": "https://howdoyouconvert.com/calculator/bar-to-psi/?ao_noptimize=1", "fwd": 14.5037738, "v1": 1, "expected_v2": 14.5037738},
{"url": "https://howdoyouconvert.com/calculator/becquerel-to-curie/?ao_noptimize=1", "fwd": 2.7027027e-11, "v1": 37000000000, "expected_v2": 1},
{"url": "https://howdoyouconvert.com/calculator/becquerel-to-rutherford/?ao_noptimize=1", "fwd": 0.000001, "v1": 1000000, "expected_v2": 1},
{"url": "https://howdoyouconvert.com/calculator/bits-to-bytes/?ao_noptimize=1", "fwd": 0.125, "v1": 8, "expected_v2": 1},
{"url": "https://howdoyouconvert.com/calculator/btu-to-kilojoules/?ao_noptimize=1", "fwd": 1.05505585, "v1": 1, "expected_v2": 1.05505585},
{"url": "https://howdoyouconvert.com/calculator/btuhour-to-watts/?ao_noptimize=1", "fwd": 0.293071, "v1": 100, "expected_v2": 29.3071},
{"url": "https://howdoyouconvert.com/calculator/calories-to-joules/?ao_noptimize=1", "fwd": 4.184, "v1": 1, "expected_v2": 4.184},
{"url": "https://howdoyouconvert.com/calculator/calories-to-kilojoules/?ao_noptimize=1", "fwd": 4.184, "v1": 1, "expected_v2": 4.184},
]
def verify_math(calc):
print(f"\n--- Verifying {calc['url']} ---")
headers = {"User-Agent": "Mozilla/5.0"}
# Test Forward
try:
url_v1 = f"{calc['url']}&v1={calc['v1']}"
req_f = urllib.request.Request(url_v1, headers=headers)
resp_f = urllib.request.urlopen(req_f).read().decode('utf-8')
# We need to check if the JS logic is actually executing.
# Since we use URL params and DOMContentLoaded, we can't 'see' the changed input value in raw HTML.
# Instead, we will extract the JS from the page body and evaluate it locally to verify the logic we injected is correct.
scripts = re.findall(r'<script.*?>\s*(.*?)\s*</script>', resp_f, re.DOTALL)
logic_script = ""
for s in scripts:
if "calculate1" in s and "document.getElementById" in s:
logic_script = s
break
if not logic_script:
print("FAILED: Logic script not found in page source.")
return False
print("Found JS logic. Verifying formula constants...")
# Extract the logic lines
fwd_logic = re.search(r'function calculate1.*?let val2 = (.*?);', logic_script, re.DOTALL)
rev_logic = re.search(r'function calculate2.*?let val1 = (.*?);', logic_script, re.DOTALL)
if not fwd_logic or not rev_logic:
print("FAILED: Could not parse math logic lines from JS.")
return False
f_expr = fwd_logic.group(1).replace("val1", str(calc['v1']))
r_expr = rev_logic.group(1).replace("val2", str(calc['expected_v2']))
# Evaluate local math
actual_v2 = eval(f_expr)
actual_v1 = eval(r_expr)
print(f"Forward: {calc['v1']} -> Expected {calc['expected_v2']}, Got {actual_v2}")
print(f"Reverse: {calc['expected_v2']} -> Expected {calc['v1']}, Got {actual_v1}")
if abs(actual_v2 - calc['expected_v2']) < 1e-7 and abs(actual_v1 - calc['v1']) < 1e-7:
print("SUCCESS: Math Verification Passed.")
return True
else:
print("FAILED: Math discrepancy detected.")
return False
except Exception as e:
print(f"FAILED: Verification error: {e}")
return False
all_passed = True
for c in batch_2_registry:
if not verify_math(c):
all_passed = False
time.sleep(1)
if all_passed:
print("\nALL BATCH 2 CALCULATORS VERIFIED SUCCESSFULLY.")
else:
print("\nSOME BATCH 2 VERIFICATIONS FAILED.")

View File

@@ -1,75 +0,0 @@
import urllib.request
import re
import json
import time
# Batch 3 Registry for Verification
batch_3_registry = [
{"url": "https://howdoyouconvert.com/calculator/carats-to-grams/?ao_noptimize=1", "f": 0.2, "b": 0, "v1": 5, "ev2": 1},
{"url": "https://howdoyouconvert.com/calculator/celsius-to-fahrenheit/?ao_noptimize=1", "f": 1.8, "b": 32, "v1": 0, "ev2": 32},
{"url": "https://howdoyouconvert.com/calculator/centimeters-to-inches/?ao_noptimize=1", "f": 0.393700787, "b": 0, "v1": 2.54, "ev2": 1},
{"url": "https://howdoyouconvert.com/calculator/cfs-to-cms/?ao_noptimize=1", "f": 0.0283168466, "b": 0, "v1": 100, "ev2": 2.83168466},
{"url": "https://howdoyouconvert.com/calculator/cms-to-cfs/?ao_noptimize=1", "f": 35.3146667, "b": 0, "v1": 1, "ev2": 35.3146667},
{"url": "https://howdoyouconvert.com/calculator/coulomb-per-kilogram-to-roentgen/?ao_noptimize=1", "f": 3875.96899, "b": 0, "v1": 1, "ev2": 3875.96899},
{"url": "https://howdoyouconvert.com/calculator/cups-to-milliliters/?ao_noptimize=1", "f": 236.588237, "b": 0, "v1": 1, "ev2": 236.588237},
{"url": "https://howdoyouconvert.com/calculator/curie-to-becquerel/?ao_noptimize=1", "f": 3.7e10, "b": 0, "v1": 1, "ev2": 37000000000},
{"url": "https://howdoyouconvert.com/calculator/daltons-to-amu/?ao_noptimize=1", "f": 1.0, "b": 0, "v1": 1, "ev2": 1},
{"url": "https://howdoyouconvert.com/calculator/days-to-hours/?ao_noptimize=1", "f": 24.0, "b": 0, "v1": 1, "ev2": 24},
]
def verify_math(calc):
print(f"\n--- Verifying {calc['url']} ---")
headers = {"User-Agent": "Mozilla/5.0"}
try:
req = urllib.request.Request(calc['url'], headers=headers)
resp = urllib.request.urlopen(req).read().decode('utf-8')
scripts = re.findall(r'<script.*?>\s*(.*?)\s*</script>', resp, re.DOTALL)
logic_script = ""
for s in scripts:
if "calculate1" in s and "document.getElementById" in s:
logic_script = s
break
if not logic_script:
print("FAILED: Logic script not found.")
return False
# Extract formula: let val2 = val1 * factor + offset;
fwd_match = re.search(r'let val2 = val1 \* (.*?) \+ (.*?);', logic_script)
rev_match = re.search(r'let val1 = \(val2 - (.*?)\) \/ (.*?);', logic_script)
if not fwd_match or not rev_match:
print("FAILED: Could not parse m/b components.")
return False
m_actual = float(fwd_match.group(1))
b_actual = float(fwd_match.group(2))
print(f"Detected Formula: y = {m_actual}x + {b_actual}")
# Test math locally
v2 = calc['v1'] * m_actual + b_actual
v1 = (v2 - b_actual) / m_actual
print(f"Test v1={calc['v1']} -> v2={v2} (Expected {calc['ev2']})")
print(f"Test v2={v2} -> v1={v1} (Expected {calc['v1']})")
if abs(v2 - calc['ev2']) < 1e-7 and abs(v1 - calc['v1']) < 1e-7:
print("SUCCESS")
return True
else:
print("FAILED math check")
return False
except Exception as e:
print(f"ERROR: {e}")
return False
all_ok = True
for c in batch_3_registry:
if not verify_math(c): all_ok = False
time.sleep(1)
if all_ok: print("\nALL BATCH 3 VERIFIED.")
else: print("\nBATCH 3 FAILED.")

View File

@@ -1,77 +0,0 @@
import urllib.request
import re
import json
import time
# Batch 4 Registry for Verification
batch_4_registry = [
{"url": "https://howdoyouconvert.com/calculator/days-to-weeks/?ao_noptimize=1", "f": 1/7, "b": 0, "v1": 14, "ev2": 2},
{"url": "https://howdoyouconvert.com/calculator/days-to-years/?ao_noptimize=1", "f": 1/365.25, "b": 0, "v1": 365.25, "ev2": 1},
{"url": "https://howdoyouconvert.com/calculator/degrees-to-mils/?ao_noptimize=1", "f": 17.777777778, "b": 0, "v1": 1, "ev2": 17.777777778},
{"url": "https://howdoyouconvert.com/calculator/degrees-to-radians/?ao_noptimize=1", "f": 0.0174532925, "b": 0, "v1": 180, "ev2": 3.14159265},
{"url": "https://howdoyouconvert.com/calculator/dynes-to-newtons/?ao_noptimize=1", "f": 1e-5, "b": 0, "v1": 100000, "ev2": 1},
{"url": "https://howdoyouconvert.com/calculator/ergs-to-joules/?ao_noptimize=1", "f": 1e-7, "b": 0, "v1": 10000000, "ev2": 1},
{"url": "https://howdoyouconvert.com/calculator/feet-to-meters/?ao_noptimize=1", "f": 0.3048, "b": 0, "v1": 1, "ev2": 0.3048},
{"url": "https://howdoyouconvert.com/calculator/foot-pounds-to-newton-meters/?ao_noptimize=1", "f": 1.35581795, "b": 0, "v1": 1, "ev2": 1.35581795},
{"url": "https://howdoyouconvert.com/calculator/gallons-to-liters/?ao_noptimize=1", "f": 3.78541178, "b": 0, "v1": 1, "ev2": 3.78541178},
{"url": "https://howdoyouconvert.com/calculator/gigabytes-to-megabytes/?ao_noptimize=1", "f": 1000.0, "b": 0, "v1": 1, "ev2": 1000},
]
def verify_math(calc):
print(f"\n--- Verifying {calc['url']} ---")
headers = {"User-Agent": "Mozilla/5.0"}
try:
req = urllib.request.Request(calc['url'], headers=headers)
resp = urllib.request.urlopen(req).read().decode('utf-8')
scripts = re.findall(r'<script.*?>\s*(.*?)\s*</script>', resp, re.DOTALL)
logic_script = ""
for s in scripts:
if "calculate1" in s and "document.getElementById" in s:
logic_script = s
break
if not logic_script:
print("FAILED: Logic script not found.")
return False
# Extract formula: val2 = val1 * factor + offset;
# Matches: let val2 = val1 * 0.14285714285714285 + 0;
fwd_match = re.search(r'let val2 = val1 \* (.*?) \+ (.*?);', logic_script)
rev_match = re.search(r'let val1 = \(val2 - (.*?)\) \/ (.*?);', logic_script)
if not fwd_match or not rev_match:
print("FAILED: Could not parse m/b components.")
return False
m_actual = float(fwd_match.group(1))
b_actual = float(fwd_match.group(2))
print(f"Detected Formula: y = {m_actual}x + {b_actual}")
# Test math locally
v2 = calc['v1'] * m_actual + b_actual
v1 = (v2 - b_actual) / m_actual
print(f"Test v1={calc['v1']} -> v2={v2} (Expected {calc['ev2']})")
print(f"Test v2={v2} -> v1={v1} (Expected {calc['v1']})")
# Allow small floating point difference
if abs(v2 - calc['ev2']) < max(1e-7, calc['ev2'] * 1e-7) and abs(v1 - calc['v1']) < 1e-7:
print("SUCCESS")
return True
else:
print("FAILED math check")
return False
except Exception as e:
print(f"ERROR: {e}")
return False
all_ok = True
for c in batch_4_registry:
if not verify_math(c): all_ok = False
time.sleep(1)
if all_ok: print("\nALL BATCH 4 VERIFIED.")
else: print("\nBATCH 4 FAILED.")

View File

@@ -1,76 +0,0 @@
import urllib.request
import re
import json
import time
# Batch 5 Registry for Verification
batch_5_registry = [
{"url": "https://howdoyouconvert.com/calculator/fahrenheit-to-celsius/?ao_noptimize=1", "f": 5/9, "o": -32 * 5/9, "v1": 32, "ev2": 0},
{"url": "https://howdoyouconvert.com/calculator/fahrenheit-to-celsius/?ao_noptimize=1", "f": 5/9, "o": -32 * 5/9, "v1": 212, "ev2": 100},
{"url": "https://howdoyouconvert.com/calculator/feet-per-second-to-meters-per-second/?ao_noptimize=1", "f": 0.3048, "o": 0, "v1": 1, "ev2": 0.3048},
{"url": "https://howdoyouconvert.com/calculator/fluid-ounces-to-milliliters/?ao_noptimize=1", "f": 29.5735296, "o": 0, "v1": 1, "ev2": 29.5735296},
{"url": "https://howdoyouconvert.com/calculator/gallons-per-minute-to-liters-per-second/?ao_noptimize=1", "f": 0.0630901964, "o": 0, "v1": 1, "ev2": 0.0630901964},
{"url": "https://howdoyouconvert.com/calculator/grains-to-grams/?ao_noptimize=1", "f": 0.06479891, "o": 0, "v1": 1, "ev2": 0.06479891},
{"url": "https://howdoyouconvert.com/calculator/grams-to-milligrams/?ao_noptimize=1", "f": 1000.0, "o": 0, "v1": 1, "ev2": 1000},
{"url": "https://howdoyouconvert.com/calculator/grams-to-ounces/?ao_noptimize=1", "f": 0.0352739619, "o": 0, "v1": 100, "ev2": 3.52739619},
{"url": "https://howdoyouconvert.com/calculator/grams-to-pennyweights/?ao_noptimize=1", "f": 0.643014931, "o": 0, "v1": 100, "ev2": 64.3014931},
{"url": "https://howdoyouconvert.com/calculator/grams-to-troy-ounces/?ao_noptimize=1", "f": 0.0321507466, "o": 0, "v1": 100, "ev2": 3.21507466},
{"url": "https://howdoyouconvert.com/calculator/gray-to-rad/?ao_noptimize=1", "f": 100.0, "o": 0, "v1": 1, "ev2": 100},
]
def verify_math(calc):
print(f"\n--- Verifying {calc['url']} with v1={calc['v1']} ---")
headers = {"User-Agent": "Mozilla/5.0"}
try:
req = urllib.request.Request(calc['url'], headers=headers)
resp = urllib.request.urlopen(req).read().decode('utf-8')
scripts = re.findall(r'<script.*?>\s*(.*?)\s*</script>', resp, re.DOTALL)
logic_script = ""
for s in scripts:
if "calculate1" in s and "document.getElementById" in s:
logic_script = s
break
if not logic_script:
print("FAILED: Logic script not found.")
return False
# Extract formula: let val2 = val1 * factor + offset;
fwd_match = re.search(r'let val2 = val1 \* (.*?) \+ (.*?);', logic_script)
rev_match = re.search(r'let val1 = \(val2 - (.*?)\) \/ (.*?);', logic_script)
if not fwd_match or not rev_match:
print("FAILED: Could not parse logic components.")
return False
m_actual = float(fwd_match.group(1))
b_actual = float(fwd_match.group(2))
print(f"Detected Formula: y = {m_actual}x + {b_actual}")
# Test math locally
v2 = calc['v1'] * m_actual + b_actual
v1 = (v2 - b_actual) / m_actual
print(f"Test v1={calc['v1']} -> v2={v2} (Expected {calc['ev2']})")
# Allow small floating point difference
if abs(v2 - calc['ev2']) < max(1e-7, calc['ev2'] * 1e-7) and abs(v1 - calc['v1']) < 1e-7:
print("SUCCESS")
return True
else:
print("FAILED math check")
return False
except Exception as e:
print(f"ERROR: {e}")
return False
all_ok = True
for c in batch_5_registry:
if not verify_math(c): all_ok = False
time.sleep(1)
if all_ok: print("\nALL BATCH 5 VERIFIED.")
else: print("\nBATCH 5 FAILED.")

View File

@@ -1,47 +0,0 @@
import urllib.request
import json
import re
batch_7_results = [
{"url": "https://howdoyouconvert.com/calculator/centigrams-to-grams/?ao_noptimize=1", "v1": 100, "expected_v2": 1, "m": 0.01},
{"url": "https://howdoyouconvert.com/calculator/centiliters-to-liters/?ao_noptimize=1", "v1": 100, "expected_v2": 1, "m": 0.01},
{"url": "https://howdoyouconvert.com/calculator/centimeters-to-feet/?ao_noptimize=1", "v1": 30.48, "expected_v2": 0.99999999, "m": 0.032808399},
{"url": "https://howdoyouconvert.com/calculator/centimeters-to-meters/?ao_noptimize=1", "v1": 100, "expected_v2": 1, "m": 0.01},
{"url": "https://howdoyouconvert.com/calculator/centimeters-to-millimeters/?ao_noptimize=1", "v1": 1, "expected_v2": 10, "m": 10.0},
{"url": "https://howdoyouconvert.com/calculator/chains-to-feet/?ao_noptimize=1", "v1": 1, "expected_v2": 66, "m": 66.0},
{"url": "https://howdoyouconvert.com/calculator/chains-to-meters/?ao_noptimize=1", "v1": 1, "expected_v2": 20.1168, "m": 20.1168},
{"url": "https://howdoyouconvert.com/calculator/cubic-centimeters-to-cubic-inches/?ao_noptimize=1", "v1": 16.387064, "expected_v2": 1, "m": 0.0610237441},
{"url": "https://howdoyouconvert.com/calculator/cubic-feet-to-cubic-meters/?ao_noptimize=1", "v1": 35.3146667, "expected_v2": 1, "m": 0.0283168466},
{"url": "https://howdoyouconvert.com/calculator/cubic-meters-to-liters/?ao_noptimize=1", "v1": 1, "expected_v2": 1000, "m": 1000.0}
]
headers = {"User-Agent": "Mozilla/5.0"}
for calc in batch_7_results:
print(f"\n--- Verifying {calc['url']} ---")
req = urllib.request.Request(calc['url'], headers=headers)
try:
resp = urllib.request.urlopen(req, timeout=30).read().decode("utf-8")
# Check for robust JS
if "initRetries" in resp and "setTimeout(init, 100)" in resp:
print("Robust JS: OK")
else:
print("Robust JS: MISSING")
# Extract multiplier
m = re.search(r'v \* ([\d\.]+)', resp)
if m:
actual_m = float(m.group(1))
print(f"Multiplier: {actual_m} (Expected {calc['m']})")
if abs(actual_m - calc['m']) < 0.0000001:
print("Math Match: OK")
else:
print("Math Match: FAIL")
else:
print("Multiplier: NOT FOUND")
except Exception as e:
print(f"Error: {e}")
print("\nVERIFICATION COMPLETE")

View File

@@ -1,49 +0,0 @@
import urllib.request
import json
import re
batch_8_results = [
{"url": "https://howdoyouconvert.com/calculator/grams-to-micrograms/?ao_noptimize=1", "v1": 1, "expected_v2": 1000000, "m": 1000000.0},
{"url": "https://howdoyouconvert.com/calculator/grams-to-milligrams/?ao_noptimize=1", "v1": 1, "expected_v2": 1000, "m": 1000.0},
{"url": "https://howdoyouconvert.com/calculator/hectopascals-to-pascals/?ao_noptimize=1", "v1": 1, "expected_v2": 100, "m": 100.0},
{"url": "https://howdoyouconvert.com/calculator/hectopascals-to-millibars/?ao_noptimize=1", "v1": 1, "expected_v2": 1, "m": 1.0},
{"url": "https://howdoyouconvert.com/calculator/joules-to-kilojoules/?ao_noptimize=1", "v1": 1000, "expected_v2": 1, "m": 0.001},
{"url": "https://howdoyouconvert.com/calculator/kilojoules-to-joules/?ao_noptimize=1", "v1": 1, "expected_v2": 1000, "m": 1000.0},
{"url": "https://howdoyouconvert.com/calculator/micrograms-to-grams/?ao_noptimize=1", "v1": 1000000, "expected_v2": 1, "m": 0.000001},
{"url": "https://howdoyouconvert.com/calculator/milligrams-to-grams/?ao_noptimize=1", "v1": 1000, "expected_v2": 1, "m": 0.001},
{"url": "https://howdoyouconvert.com/calculator/millibars-to-pascals/?ao_noptimize=1", "v1": 1, "expected_v2": 100, "m": 100.0},
{"url": "https://howdoyouconvert.com/calculator/millimeters-of-mercury-to-pascals/?ao_noptimize=1", "v1": 1, "expected_v2": 133.322, "m": 133.322}
]
headers = {"User-Agent": "Mozilla/5.0"}
for calc in batch_8_results:
print(f"\n--- Verifying {calc['url']} ---")
req = urllib.request.Request(calc['url'], headers=headers)
try:
resp = urllib.request.urlopen(req, timeout=30).read().decode("utf-8")
# Check for robust JS
if "initRetries" in resp and "setTimeout(init, 100)" in resp:
print("Robust JS: OK")
else:
print("Robust JS: MISSING")
# Extract multiplier (using flexible regex for scientific notation if needed, but here they are standard)
# Match v * factor. The factor might be 1e-06
m_pattern = r'i2\.value = parseFloat\(\(v \* ([\d\.e\-]+)\)'
m = re.search(m_pattern, resp)
if m:
actual_m = float(m.group(1))
print(f"Multiplier: {actual_m} (Expected {calc['m']})")
if abs(actual_m - calc['m']) / (calc['m'] or 1) < 0.000001:
print("Math Match: OK")
else:
print("Math Match: FAIL")
else:
print("Multiplier: NOT FOUND")
except Exception as e:
print(f"Error: {e}")
print("\nVERIFICATION COMPLETE")

View File

@@ -1,48 +0,0 @@
import urllib.request
import json
import re
batch_9_results = [
{"url": "https://howdoyouconvert.com/calculator/meters-per-second-to-feet-per-second/?ao_noptimize=1", "v1": 1, "expected_v2": 3.28084, "m": 3.28084},
{"url": "https://howdoyouconvert.com/calculator/meters-per-second-to-miles-per-hour/?ao_noptimize=1", "v1": 10, "expected_v2": 22.3694, "m": 2.23694},
{"url": "https://howdoyouconvert.com/calculator/meters-per-second-to-yards-per-second/?ao_noptimize=1", "v1": 1, "expected_v2": 1.09361, "m": 1.09361},
{"url": "https://howdoyouconvert.com/calculator/micrograms-to-milligrams/?ao_noptimize=1", "v1": 1000, "expected_v2": 1, "m": 0.001},
{"url": "https://howdoyouconvert.com/calculator/micrometers-to-millimeters/?ao_noptimize=1", "v1": 1000, "expected_v2": 1, "m": 0.001},
{"url": "https://howdoyouconvert.com/calculator/milligrams-to-micrograms/?ao_noptimize=1", "v1": 1, "expected_v2": 1000, "m": 1000.0},
{"url": "https://howdoyouconvert.com/calculator/milliliters-to-liters/?ao_noptimize=1", "v1": 1000, "expected_v2": 1, "m": 0.001},
{"url": "https://howdoyouconvert.com/calculator/milliliters-to-fluid-ounces/?ao_noptimize=1", "v1": 100, "expected_v2": 3.3814, "m": 0.033814},
{"url": "https://howdoyouconvert.com/calculator/millimeters-to-centimeters/?ao_noptimize=1", "v1": 10, "expected_v2": 1, "m": 0.1},
{"url": "https://howdoyouconvert.com/calculator/millimeters-to-inches/?ao_noptimize=1", "v1": 25.4, "expected_v2": 1, "m": 0.0393701}
]
headers = {"User-Agent": "Mozilla/5.0"}
for calc in batch_9_results:
print(f"\n--- Verifying {calc['url']} ---")
req = urllib.request.Request(calc['url'], headers=headers)
try:
resp = urllib.request.urlopen(req, timeout=30).read().decode("utf-8")
# Check for robust JS
if "initRetries" in resp and "setTimeout(init, 100)" in resp:
print("Robust JS: OK")
else:
print("Robust JS: MISSING")
# Extract multiplier
m_pattern = r'i2\.value = parseFloat\(\(v \* ([\d\.e\-]+)\)'
m = re.search(m_pattern, resp)
if m:
actual_m = float(m.group(1))
print(f"Multiplier: {actual_m} (Expected {calc['m']})")
if abs(actual_m - calc['m']) / (calc['m'] or 1) < 0.000001:
print("Math Match: OK")
else:
print("Math Match: FAIL")
else:
print("Multiplier: NOT FOUND")
except Exception as e:
print(f"Error: {e}")
print("\nVERIFICATION COMPLETE")

View File

@@ -1,31 +0,0 @@
import urllib.request
import re
def check_calculator(url, search_terms):
print(f"\n--- Checking {url} ---")
headers = {"User-Agent": "Mozilla/5.0"}
try:
req = urllib.request.Request(url, headers=headers)
html = urllib.request.urlopen(req).read().decode('utf-8')
found_all = True
for term in search_terms:
if term in html:
print(f"Found: {term}")
else:
print(f"NOT FOUND: {term}")
found_all = False
return found_all
except Exception as e:
print(f"Error: {e}")
return False
# 1. ASCII to Binary
check_calculator("https://howdoyouconvert.com/calculator/ascii-to-binary/", [
"input-1", "input-2", "charCodeAt", "toString(2)"
])
# 2. Amps to Volts (Triple)
check_calculator("https://howdoyouconvert.com/calculator/amps-to-volts/", [
"input-1", "input-2", "input-3", "toFixed(2)", "a * v"
])