Problem with publishing Jupyter Notebook online

I am currently working on an interactive UI in Jupyter Notebook based mainly on IPy Widgets to feature 3D interactive models created and exported previously using Blender. I used an HTML 3D model viewer to show the 3D model (see code below), which works perfectly fine but when I try to publish the Jupyter Notebook e.g. using Voíla it will show everything except for the 3D model (see images attached). Has anyone else encountered this issue or has an idea of how to solve it?

Any hint would be much appreciated, cheers!

JupyterNotebook before publishing with 3D model shown correctly

JupyterNotebook after publishing with Voila

The HTML model viewer code:

from IPython.display import HTML, Javascript, display

# Load the model-viewer script once
display(Javascript("""
if (!window.modelViewerLoaded) {
    const script = document.createElement('script');
    script.type = 'module';
    script.src = 'https://unpkg.com/@google/model-viewer/dist/model-viewer.min.js';
    document.head.appendChild(script);
    window.modelViewerLoaded = true;
}
"""))

# Define the model viewer display function
def display_model_waterdepth(glb_path):
    return HTML(f"""
    <div class="mv-wrap" style="position: relative; width: 100%; height: 375px;">
      <model-viewer src="{glb_path}" alt="Waterdepth model"
        interaction-prompt="auto" interaction-prompt-threshold="8000"
        disable-default-lighting shadow-intensity="0" shadow-softness="0"
        exposure="0.003" environment-image="neutral" camera-controls 
        background-color="#FDF0F5" camera-orbit="0deg 0deg 7000m" 
        min-camera-orbit="auto auto 1m" max-camera-orbit="auto auto 10000m"
        field-of-view="45deg"
        style="width: 100%; height: 100%; filter: brightness(1.0) contrast(1.3);">
      </model-viewer>

      <div style="position: absolute; bottom: 10px; right: 10px; 
                  display: flex; flex-direction: column; align-items: flex-end; gap: 5px; z-index: 10;">
        <button data-zoomplus style="background-color: #f8f8f8; width: 25px; height: 25px;">+</button>
        <button data-zoomminus style="background-color: #f8f8f8; width: 25px; height: 25px;">-</button>
        <button data-reset style="background-color: #f8f8f8; width: 25px; height: 25px;">⟳</button>
        <button data-focus="1" style="background-color: #f8f8f8; width: 100px; height: 25px;">Neubacher Au</button>
        <button data-focus="2" style="background-color: #f8f8f8; width: 100px; height: 25px;">Ofenloch</button>
      </div>
    </div>

    <script>
    (function() {{
      const root = document.currentScript.previousElementSibling;
      const viewer = root.querySelector('model-viewer');

      root.querySelector('[data-zoomplus]').addEventListener('click', () => {{
        const o = viewer.getCameraOrbit();
        viewer.cameraOrbit = `${{o.theta}}rad ${{o.phi}}rad ${{o.radius * 0.9}}m`;
      }});
      root.querySelector('[data-zoomminus]').addEventListener('click', () => {{
        const o = viewer.getCameraOrbit();
        viewer.cameraOrbit = `${{o.theta}}rad ${{o.phi}}rad ${{o.radius * 1.1}}m`;
      }});
      root.querySelector('[data-reset]').addEventListener('click', () => {{
        viewer.cameraOrbit = "0deg 0deg 7000m";
        viewer.cameraTarget = "auto auto auto";
        viewer.fieldOfView = "45deg";
        viewer.jumpCameraToGoal();
      }});
      root.querySelectorAll('[data-focus]').forEach(btn => {{
        btn.addEventListener('click', () => {{
          const area = btn.getAttribute('data-focus');
          if (area === "1") {{
            viewer.cameraOrbit = "0deg 0deg 2300m";
            viewer.cameraTarget = "-850m 0m -450m";
          }} else {{
            viewer.cameraOrbit = "55deg 0deg 1800m";
            viewer.cameraTarget = "1000m 230m -250m";
          }}
          viewer.jumpCameraToGoal();
        }});
      }});
    }})();
    </script>
    """)

Objects as keys in maps: Memory duplication?

I would like to map from objects that already exist elsewhere in the code, to, say, numbers.

var map = new Map();
var keyObj = {a: "b"};

map.set(keyObj, 3);

Does keyObj now exist twice in memory? Or is only a address to the original keyObj stored in the map?

choosing between thing to create like an app [closed]

This are the topic I want to create like an app :

  1. AI-Powered Mental Health Companion
  2. Sustainable Shopping Scanner
  3. Remote Work Productivity Booster
  4. Personalized Nutrition Coach
  5. AR Home Workout Trainer
  6. Local Community Swap Network
  7. AI Language Learning Buddy
  8. Pet Care Reminder & Vet Finder

I want to create something valuable to people and provide value and I am between the line.

SO I am trying to create something, that can help people and I am still in process

AG Grid React: nested (child) grid blinks on every 5s update even with immutableData + deltaRowDataMode. How do I stop the flash?

I have a parent AG Grid that renders a nested child grid inside a custom “detail” row. I poll an API every 5 seconds and update both the parent rows and the child rows. The child grid visibly blinks (flashes) on each poll, which looks like it is being torn down and recreated.

I’m already using:

Stable row IDs (getRowId) for both grids based on Tick + Time

immutableData and deltaRowDataMode on both grids

React.memo on the child grid with a custom prop comparer

An update helper that diffs incoming rows and only moves/updates what changed

Still getting a flash on the second grid whenever new data arrives.

Only changed rows should update. The nested grid should not tear down or blink when polling updates arrive.

What happens

On every poll, the child grid area flashes for a frame. It looks like React is re-rendering the child grid container or AG Grid is remounting the rows despite stable IDs.

How the UI is structured

I do not use AG Grid’s built-in Master/Detail.

I emulate a detail row by injecting an extra row with __kind: “detail” below the clicked parent row.

That detail row cellRenderer returns a component (another ).

React-pdf-highloghter first time load issue

import { useCallback, useEffect, useRef, useState } from "react"
import { XIcon } from "lucide-react"

import { Button } from "../ui/button"
import {
  RightDrawer,
  RightDrawerTitle,
  RightDrawerHeader,
  RightDrawerContent,
  RightDrawerClose,
  RightDrawerDescription,
} from "@/components/right-drawer"

import {
  PdfLoader,
  PdfHighlighter,
  Highlight,
  Popup,
  AreaHighlight,
  type IHighlight,
  Tip,
  ScaledPosition,
  NewHighlight,
  Content,
} from "react-pdf-highlighter"

import { Spinner } from "../ui/spinner"

export interface SourceWithCitations {
  title: string
  document_url: string
  citations: any[]
}

interface DocumentWithCitationsSidebarProps {
  isOpen: boolean
  onClose: () => void
  sources: SourceWithCitations | null
}

const HighlightPopup = ({ comment }: { comment?: { text?: string; emoji?: string } }) =>
  comment && comment.text ? (
    <div className="Highlight__popup">
      {comment.emoji} {comment.text}
    </div>
  ) : null

const resetHash = () => {
  document.location.hash = ""
}

const getNextId = () => String(Math.random()).slice(2)

const parseIdFromHash = () =>
  document.location.hash.slice("#highlight-".length)

export function DocumentWithCitationsSidebar({
  isOpen,
  onClose,
  sources,
}: DocumentWithCitationsSidebarProps) {

  const [highlights, setHighlights] = useState<Array<IHighlight>>(sources?.citations ?? [])

  // store scrollTo ref from PdfHighlighter
  const scrollViewerTo = useRef<(highlight: IHighlight) => void>(() => {})

  // Reset highlights whenever sources change
  useEffect(() => {
    if (sources?.citations) {
      const mapped = sources.citations.map((c, i) => ({
        id: c.id ?? String(i + 1),
        content: c.content ?? { text: "" },
        comment: c.comment ?? {},
        position: c.position,
      }))
      setHighlights(mapped)
    } else {
      setHighlights([])
    }
  }, [sources])

  // After highlights are set, force re-render/scroll
  useEffect(() => {
    if (highlights.length > 0 && scrollViewerTo.current) {
      // wait for PdfHighlighter to fully render pages
      setTimeout(() => {
        scrollViewerTo.current(highlights[0])
        // trigger a resize to ensure highlights paint correctly
        window.dispatchEvent(new Event("resize"))
      }, 50)
    }
  }, [highlights])

  const handleOpenChange = (open: boolean) => {
    if (!open) {
      onClose()
    }
  }

  const getHighlightById = useCallback(
    (id: string) => highlights.find((h) => h.id === id),
    [highlights],
  )

  const scrollToHighlightFromHash = useCallback(() => {
    const highlight = getHighlightById(parseIdFromHash())
    if (highlight) {
      scrollViewerTo.current(highlight)
    }
  }, [getHighlightById])

  useEffect(() => {
    window.addEventListener("hashchange", scrollToHighlightFromHash, false)
    return () => {
      window.removeEventListener("hashchange", scrollToHighlightFromHash, false)
    }
  }, [scrollToHighlightFromHash])

  const addHighlight = (highlight: NewHighlight) => {
    console.log("Saving highlight", highlight)
    setHighlights((prev) => [
      { ...highlight, id: getNextId() } as IHighlight,
      ...prev,
    ])
  }

  const updateHighlight = (
    highlightId: string,
    position: Partial<ScaledPosition>,
    content: Partial<Content>,
  ) => {
    console.log("Updating highlight", highlightId, position, content)
    setHighlights((prev) =>
      prev.map((h) =>
        h.id === highlightId
          ? {
              ...h,
              position: { ...h.position, ...position },
              content: { ...h.content, ...content },
            }
          : h,
      ),
    )
  }

  return (
    <RightDrawer open={isOpen} onOpenChange={handleOpenChange}>
      <RightDrawerContent className="w-[700px] max-w-[90vw]">
        <RightDrawerHeader className="flex items-center justify-between p-6 pb-4 border-b border-slate-100">
          <div>
            <RightDrawerTitle className="text-lg font-semibold text-slate-900">
              {sources?.title}
            </RightDrawerTitle>
            <RightDrawerDescription className="text-sm text-slate-500">
              {sources?.document_url}
            </RightDrawerDescription>
          </div>
          <RightDrawerClose asChild>
            <Button
              variant="ghost"
              size="sm"
              className="text-slate-400 hover:text-slate-600 hover:bg-slate-50"
            >
              <XIcon className="w-4 h-4" />
            </Button>
          </RightDrawerClose>
        </RightDrawerHeader>

        {sources?.document_url && (
          <PdfLoader url={sources.document_url} beforeLoad={<Spinner />}>
            {(pdfDocument) => (
              <PdfHighlighter
                pdfDocument={pdfDocument}
                enableAreaSelection={(event) => event.altKey}
                onScrollChange={resetHash}
                scrollRef={(scrollTo) => {
                  scrollViewerTo.current = scrollTo
                }}
                onSelectionFinished={(
                  position,
                  content,
                  hideTipAndSelection,
                  transformSelection,
                ) => (
                  <Tip
                    onOpen={transformSelection}
                    onConfirm={(comment) => {
                      addHighlight({ content, position, comment })
                      hideTipAndSelection()
                    }}
                  />
                )}
                highlightTransform={(
                  highlight,
                  index,
                  setTip,
                  hideTip,
                  viewportToScaled,
                  screenshot,
                  isScrolledTo,
                ) => {
                  const isTextHighlight = !highlight.content?.image

                  const component = isTextHighlight ? (
                    <Highlight
                      isScrolledTo={isScrolledTo}
                      position={highlight.position}
                      comment={highlight.comment}
                    />
                  ) : (
                    <AreaHighlight
                      isScrolledTo={isScrolledTo}
                      highlight={highlight}
                      onChange={(boundingRect) => {
                        updateHighlight(
                          highlight.id,
                          { boundingRect: viewportToScaled(boundingRect) },
                          { image: screenshot(boundingRect) },
                        )
                      }}
                    />
                  )

                  return (
                    <Popup
                      key={index}
                      popupContent={
                        <HighlightPopup comment={highlight.comment} />
                      }
                      onMouseOver={(popupContent) =>
                        setTip(highlight, () => popupContent)
                      }
                      onMouseOut={hideTip}
                    >
                      {component}
                    </Popup>
                  )
                }}
                highlights={highlights}
              />
            )}
          </PdfLoader>
        )}
      </RightDrawerContent>
    </RightDrawer>
  )
}

This code works correctly to load the documents but the highlights are not coming in the start. When i click on the document anywhere only then I am able to see them why?

I guess somehow the highlights are not able to be present in the start but somehow they comes in one-click. That is what I am not able to understand actually.

Slider inside of Horizontal FlatList: dragging slider also scrolls FlatList

I have a React Native screen that renders a horizontal FlatList.
Each item in the list contains a Slider (from @react-native-community/slider).

  • On iOS, when I try to drag the slider thumb horizontally, the FlatList scroll gesture also gets triggered.
  • On Android, it works fine: the slider moves without scrolling the list.
  <FlatList
          data={pages}
          ref={flatListRef}
          horizontal
          pagingEnabled
          bounces={false}
          showsHorizontalScrollIndicator={false}
          keyExtractor={(_, index) => index.toString()}
          onMomentumScrollEnd={handleScroll}
          renderItem={({ item }) => (
            <View style={[styles.pageContainer, { width: containerWidth }]}>
              {item.map((device: any) => (
                 <TouchableOpacity style={[styles.groupHeader, { width: containerWidth }]} key={device.id}>
              <Textc size={mvs(24)} medium>{groupName}</Textc>
              <Image source={bulbOn} style={[styles.iconImage, { width: s(100) }]} />
              <View style={{ height: mvs(42), justifyContent: 'center', width: '60%' }}>
                <Slider
                  animateTransitions
                  maximumTrackTintColor={Colors.gray400}
                  minimumTrackTintColor={Colors.primary}
                  thumbTintColor={Colors.primary}
                  // value={value}
                  minimumValue={0}
                  maximumValue={100}
                  step={1}
                  onSlidingComplete={([num]) => {
                     setValue(num)
                    onAction("LED_BRIGHTNESS", num)
                  }}
                />
              </View>
            </TouchableOpacity>
              ))}
            </View>
          )}
        />

I’ve tried:

  • Wrapping Slider in TouchableOpacity or PanGestureHandler → didn’t help.

  • onStartShouldSetResponderCapture={() => true} on parent View on Slider → but it stops the slider and flatlist still scrolls

  • Temporary fix: disable FlatList scroll while dragging the slider using onSlidingStart and onSlidingComplete

Is there a proper way to let the slider thumb consume horizontal gestures, without disabling FlatList scrolling manually?

How to correctly close a listening port in oak?

I’m trying to close the port manually (in somewhere else) but not sure the way to do it.

A smallest example:

import { Application, Router } from 'jsr:@oak/oak'
const app = new Application()
const router = new Router()

app.use(router.routes())
app.use(router.allowedMethods())

router.get('/', (ctx) => {
  ctx.response.body = JSON.stringify({ message: 'Hello, Oak!' })
})

const ac = new AbortController()
const promise = app.listen({ port: 8000, signal: ac.signal })

async function close() {
  ac.abort()
  await promise
  // never reached
  console.log('Server closed')
}

await close()

Vue V-for to loop through Objects in Array to display with intput type text box and select option in html page

The below code is a working code. The “additional” columns displays correctly, just like a simple input box. But I would like to edit this code to “select” option for “sex” and “city”. Would be great if someone gives suggestion. Thank you.

    function student(){
       this['name']='',
       this['age']='',
       this['course']='',
       this['additional']=[]
    }

    function additional(){
      this['sex']='',
      this['phone']='',
      this['city']=''
    }

    var student = new student();

    var data=new Vue({
    el="#app",
    data(){
       return{
         student:student,
         sexOptions:['Male','Female'],
         cityOptions:['city1','city2','city3']
       }
    },
    mounted(){
    },
    methods: {
    createadditional: function(){
    var val = this.student['course'];
    var len = this.student['additional'].length;
    var diff = val - len;
    
    if(diff < 0){
      this.student['additional'].splice(diff);
      }else if (diff > 0){
      while (len < val){
      var newadditional = new additional();
      this.student['additional'].push(newadditional);
      len++;
      }
     }  
    },      
   },
   watch:{
   },
   computed: {
    additional_display: {
    get: function(){
    return this.student['additional'].slice(0,this.student['course']);
    },
    },
    }
 });


 <form action="saveSchoolData"  id = "schoolForm" method="post"> 
<table>
<tr> <th> Name: </th> <td> <input type="text" v-model = "school['name']"> </td> </tr>
<tr> <th> Age: </th> <td> <input type="text" v-model = "school['Age']"> </td> </tr>
<tr> <th> Course: </th> <td> <input type="text" v-model = "school['Course']"> </td>       
</tr>
</table>

<table  v-if = "school.course> 0" >
<tr>
<td>Nbr</td>
<td>Sex</td>
<td>Phone</td>
<td>City</td>
</tr>

<tr v-for='additional in additional_display' >
<td>{{additional_display.indexOf(school)+1}}</td>
<td v-for="key in Object.keys(additional)">
{{key}}
<input v-model="additional[key]"> 
</td>
</tr>

</table>

 <input type="button" value="Save" id="saveButton" onclick="saveSchool()" />

 </form>

I would like to have the code like this below, but not getting correct – the values are not getting passed through action when i click “Save”.

<tr v-for='additional in additional_display' >
<td>{{additional_display.indexOf(school)+1}}</td>
<td><select v-model="additional['sex']">
    <option v-for="option in sexOptions" v-bind:value="option">
    {{ option }}
    </option>
    </select>
</td>
<td><input type="text" v-model="additional['phone']>
<td><select v-model="additional['city']">
    <option v-for="option in cityOptions" v-bind:value="option">
    {{ option }}
    </option>
    </select>
</td>
</tr>

Is it allowed to create inheritors from Aggregates in DDD?

There is a PHP project with DDD approach, i.e. class entities have AggregateRoot.

The main classes of entities inherit from AggregateRoot and are implemented in the logic of the object.

Is it allowed within the DDD agreement to create inheritors from classes that implement the logic of the object, if these inheritors will have slightly different logic in the class?

For example

abstract class User extends AggregateRoot
class Customer extends User
class Employee extends User

or

class Order extends AggregateRoot
class RegularOrder extends Order
class SubscriptionOrder extends Order

Are inheritors allowed? In which cases?

.htaccess not working on LiteSpeed server worked fine on apache [closed]

I am retry to rewrite index.php to home and details.php?id=$ to product/$

Options -MultiViews
RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^.]+)$ $1.php [NC,L]




RewriteRule ^product/([0-9a-zA-Z-_]+) details?id=$1 


RewriteRule ^special/([0-9a-zA-Z-_]+) details2?id=$1 




Can someone please assists am not sure what i did wrong thanks

MYSQL stored procedure called in PHP loop – only first iteration works [duplicate]

PHP version: 7.4.3
MySQL version: 8.0.42

I have a simple stored procedure which selects a single column from a table, which is called inside a loop from my PHP. The first iteration works fine. The second iteration fails. I have logged the SQL statements which my PHP builds, and when I run the statement for the second iteration in MySQL Workbench, it works as expected.

This is the stored procedure in question:

DELIMITER $$
USE `Valor`$$
CREATE DEFINER=`sean`@`%` PROCEDURE `Critter_GetType`(IN crtr VARCHAR(35))
BEGIN
    SELECT  `type` FROM Valor.CreatureStats WHERE creature = crtr LIMIT 1 ;
END$$

DELIMITER ;
;

This is my PHP code calling it:

$sql = "CALL Valor.Critter_GetType('$cc');"; 
error_log("sql = $sql");
$typeresult = NULL;
$typeresult = $conn->query($sql);
error_log("num rows = $typeresult->num_rows");
while($typerow = $typeresult->fetch_assoc()){
    $type = $typerow['type'];    
}

I set $typeresult = NULL because that was a suggestion I found for a similar problem, but it doesn’t help. The logged SQL works as expected when I call it from outside of the PHP script. The error stops the script, so when I say that the second iteration fails, I’m not implying that there is a third iteration which runs OK.

The first sign that something is wrong is the message

Trying to get property ‘num_rows’ of non-object” in the line “error_log(“num rows = $typeresult->num_rows”)”.

This message occurs, whether or not I have the $typeresult = NULL; line. Then, of course, the “while” loop is where the script-killing error occurs.

This is the first time I’ve used a stored procedure with PHP. I don’t know if that’s relevant, but I have dozens of other SQL calls from inside loops in my PHP which do not have this problem.

How do I add another array entry to an array? [duplicate]

Here’s the code that works.

$options = [
        'title' => $this->name,
        'options' => [
          [
            'id' => 'home_delivery',
            'icon' => $this->settings['icon'],
            'name' => 'Delivery Fee',
            'description' => 'weight:'.$weight,
            'fields' => $note,
            'cost' => $price1,
            'tax_class_id' => $this->settings['tax_class_id'],
          ],
          [
            'id' => 'option_2',
            'icon' => $this->settings['icon'],
            'name' => $cparray[0],
            'description' => 'This is the description for option 2',
            'fields' => '',
            'cost' => $price2,
            'tax_class_id' => $this->settings['tax_class_id'],
          ],
        ],
      ];

The number of different options (different id’s) varies, so I just want to add another id with its variables afterwards, like maybe add this if there’s a 3rd option:


          [
            'id' => 'option_3',
            'icon' => $this->settings['icon'],
            'name' => $cparray[1],
            'description' => 'This is the description for option 3',
            'fields' => '',
            'cost' => $price3,
            'tax_class_id' => $this->settings['tax_class_id'],
          ],

I’m thinking something like this afterwards, but it’s not quite right:

      $options['options'] += ['id' => 'option_3','icon' => $this->settings['icon'],'name' => $cparray[4],'description' => 'This is the description for option 3','fields' => '','cost' => $price2,'tax_class_id' => $this->settings['tax_class_id'],];

I’m finding several options of adding to an array. I’m obviously not doing something right because I don’t fully understand the array construction being made originally. I think it’s creating an array 2 levels deep and I need to add an element to the inner one.

How to speed up Mailchimp campaign/recipient/activity import in PHP (currently ~4 hours) [closed]

I’m writing a PHP script that fetches all campaigns, recipients, and their activities from the Mailchimp API into my application.

Mailchimp’s API limits me to 1,000 records per request, so my script paginates and inserts everything into MySQL in chunks. Even with chunking and INSERT IGNORE bulk inserts, the full run still takes about 4 hours for large lists.

Example snippet of what I’m doing:

$offset = 0;
$count = 1000;
do {
    $email_activities = $MailChimp->get("reports/$campaign_id/email-activity", [
        'offset' => $offset,
        'count'  => $count,
    ]);

    // bulk insert recipients + activities
    // ...
    
    $offset += $count;
} while (count($email_activities['emails']) === $count);

This works but is extremely slow for campaigns with hundreds of thousands of recipients/activities.

Question:
What are effective ways to improve the performance of importing this data?

  • Are there Mailchimp features (like webhooks) I should use instead of repeatedly polling the API?

  • Are there PHP/MySQL optimizations (e.g., LOAD DATA INFILE, parallel jobs, queue/worker model) that can handle millions of rows faster?

Any best practices or architectural suggestions for large Mailchimp data imports would be appreciated.

Local script does not load when chrome DevTools is open

Working locally, and when Chrome DevTools is open, I get the following errors:

GET http://localhost:3000/main-bundle.js net::ERR_ABORTED 404 (Not Found)

Refused to execute script from ‘http://localhost:3000/main-bundle.js’ because its MIME type (‘text/html’) is not executable, and strict MIME type checking is enabled.

Using Webpack for this project.
When I close the DevTools and refresh, it does not occur.
Does not happen with FireFox DevTools.