Eloquent Sluggable 404 not found

controller :  public function createSlug(Request $request){
        $slug = SlugService::createSlug(Post::class, 'slug', $request->title);
        return response()->json(['slug' => $slug]);
    }

script :  <script>
            const title = document.querySelector('#title')
            const slug = document.querySelector('#slug')

            title.addEventListener('change', () => {
                fetch(`/dashboard/manages/createSlug?title=${title.value}`)
                    .then(response => response.json())
                    .then(data => slug.value = data.slug)
            });
    </script>

input :  <div class="mb-5">
                <label for="title" class="block mb-2 text-sm font-medium text-gray-900 dark:text-white">Title
                    <input type="text" id="title" name="title"
                        class="shadow-sm bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-blue-500 focus:border-blue-500 block w-full p-2.5 dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400 dark:text-white dark:focus:ring-blue-500 dark:focus:border-blue-500 dark:shadow-sm-light"
                        required>
            </div>
            <div class="mb-5">
                <label for="slug" class="block mb-2 text-sm font-medium text-gray-900 dark:text-white">Slug</label>
                <input type="text" id="slug" name="slug"
                    class="shadow-sm bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-blue-500 focus:border-blue-500 block w-full p-2.5 dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400 dark:text-white dark:focus:ring-blue-500 dark:focus:border-blue-500 dark:shadow-sm-light"
                    required>
            </div>

routes : Route::get('/dashboard/manages/createSlug', [DashboardPostController::class, 'createSlug'])->name('dashboard.manages.createSlug');

when i fill title input and press tab or move to the slug input, the slug should automatically be created, but why doesn’t it work? the error message:

GET http://127.0.0.1:8000/dashboard/manages/createSlug?title=first%20post 404 (Not Found)
(anonymous) @create:184
VM6215:1 Uncaught (in promise)

Sortablejs-How not to insert a dom element when the onMove function is called

I try to add draggable function to the tree item. When I try to drag item A to item B, and I don’t let go of the mouse, I notice that the dom element of item A is inserted into itemB.I don’t want the dom element to be inserted into another dom element when dragging, I just want an interface to be called when onEnd is made.

<eltree>
  <div class="custom-node"></div>
</el-tree>
    rowDrop(dom) {
      const _this = this;
      Sortable.create(tbody, {
        group: {
          name: "shared", // set both lists to same group
          pull: 'clone',
        },
        animation: 150,
        forceFallback: true,
        draggable: '.custom-node',
        onMove(evt, originalEvent) {
        },
        onEnd(evt, originalEvent) {
          console.log('111')
          // some function
        }
      }
    }

When I add a return false code block in onMove, the dom is not inserted. But I found the onEnd function is not triggered. I hope it works, I need the final to attribute to in the onEnd Function

so,my needs are:
1、Don’t insert dom item to other item while dragging
2、onEnd function can works, or I can get the final to items

<eltree>
  <div class="custom-node"></div>
</el-tree>
    rowDrop(dom) {
      const _this = this;
      Sortable.create(tbody, {
        group: {
          name: "shared", // set both lists to same group
          pull: 'clone',
        },
        animation: 150,
        forceFallback: true,
        draggable: '.custom-node',
        onMove(evt, originalEvent) {
+          return false
        },
        onEnd(evt, originalEvent) {
          console.log('111')
        }
      }
    }

version:
sortablejs ^1.15.0
vue ^2.7.10

In html and java script using visual studio code the when running the code is not working because the java script code changes. how to fix it?

I’m using visual studio code 1.84.2

I created some long html code and then added this in the bottom

<div class="datetime-info">
        <div class="datetime-info-item">
            <h2>Original Datetime Target</h2>
            <p>5th of December 9 AM ET</p>
        </div>
        <div class="datetime-info-item" id="calculatedDateTime">
            <h2>Calculated Datetime Target on Local</h2>
            <!-- Display the calculated target date and time in the user's local timezone here -->
        </div>
      </div>

and this the html code

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Countdown Timer</title>
    <link rel="stylesheet" href="app.css">
</head>
<body>
    <!-- Your countdown timer HTML structure here -->
    <div class="countdown">
        // some more code here...
      </div>

      <div class="datetime-info">
        <div class="datetime-info-item">
            <h2>Original Datetime Target</h2>
            <p>5th of December 9 AM ET</p>
        </div>
        <div class="datetime-info-item" id="calculatedDateTime">
            <h2>Calculated Datetime Target on Local</h2>
            <!-- Display the calculated target date and time in the user's local timezone here -->
        </div>
      </div>

    <script src="myjava.js"></script>
</body>
</html>

then in the top of the java script

// Step 1: Detect the user's local time zone offset
const userTimeZoneOffset = new Date().getTimezoneOffset() / 60; // Get the offset in hours

// Step 2: Calculate the target date and time in the user's local time zone
const targetDate = new Date('2023-12-05T09:00:00-05:00'); // Specify your target date and time in a fixed format

const targetDateInUserTimeZone = new Date(targetDate);
targetDateInUserTimeZone.setHours(targetDate.getHours() + userTimeZoneOffset);

// Update the calculated target date and time in the "Calculated Datetime Target on Local" section
const calculatedDateTimeTarget = targetDateInUserTimeZone.toLocaleString();

 // Find the HTML element to display the calculated target date and time
const calculatedDateTimeElement = document.querySelector('#calculatedDateTime p');

// Set the content to display the calculated target date and time
calculatedDateTimeElement.textContent = calculatedDateTimeTarget;

I have used breakpoint and found that these two lines if I remove them the whole codes will work fine

// Find the HTML element to display the calculated target date and time
const calculatedDateTimeElement = document.querySelector('#calculatedDateTime p');

// Set the content to display the calculated target date and time
calculatedDateTimeElement.textContent = calculatedDateTimeTarget;

but when using these two lines nothing is not working anymore in the java script.

and I can’t find what the problem on these two lines? maybe something with the code in the html part?

I tried to change in the html to this

<div class="datetime-info-item" id="calculatedDateTime">
            <h2>Calculated Datetime Target on Local</h2>
            <!-- Display the calculated target date and time in the user's local timezone here -->
        </div>

in the original it was

<div class="datetime-info-item">
            <h2>Calculated Datetime Target on Local</h2>
            <!-- Display the calculated target date and time in the user's local timezone here -->
        </div>

but these changes didn’t fix the problem.

How to disable MuiMenuPaper class with Textfield components by using sx props?

I’m currently new to react and mui5. I currently using Textfield components with menuitem to display those container options as you can see below image. But I would like to dynamically control open/close status of menuitem but could not actually find the way, so i would like to control it with css way with ‘display: status’.

So I found it’s class name is MuiPopover-paper but not sure how can use this css class to override this menuitem. Could anybody can help me?

        <Grid item xs={12} sm={12} md={4} lg={4}>
          <TextField
            id="containerDisplay"
            select
            label='Container Code'
            fullWidth
          ...
            InputProps={{
              endAdornment: (
                <InputAdornment position="end">
                  <IconButton
                    edge="end"
                  > 
                  </IconButton>
                </InputAdornment>
              ),
            }}
          >
            {reduxCreatedContainers.map((option) => (
              <MenuItem
                key={option}
                value={option}
                divider={true}
              >
                {option}
              </MenuItem>
            ))}
          </TextField>
        </Grid>

enter image description here

How can I solve Next.js and Antv Graphin “Global CSS cannot be imported from within node_modules” issue?

I’m trying to use Graphin with Next.js but getting this error:

./node_modules/@antv/graphin/es/components/Legend/index.css
Global CSS cannot be imported from within node_modules.
Read more: https://nextjs.org/docs/messages/css-npm
Location: [email protected]

I saw the solution for the same issue and tried to reproduce it. Firstly, I created the component that returns <Graphin /> and use the code from the solution:

// Import the 'dynamic' function from 'next/dynamic'
import dynamic from "next/dynamic";

// Dynamically import your component
const MyGraphineComponent = dynamic(() => import("./myGraphineComponent"), {
  ssr: false,  // disable server-side rendering for this component
});

export default function MyView() {
  return (
    <div style={{ height: "100%" }}>
      <MyGraphineComponent data={[]} />
    </div>
  );
}

Then I used dynamic() to import Graphin itself inside my component:

import dynamic from "next/dynamic";
const Graphin = dynamic(
    () => import("@antv/graphin"),
    {
        ssr: false,
    }
);

However, I’m still getting the error mentioned above. How can I solve this issue?


Versions of the libraries:

  • "react": "^18.2.0"
  • "next": "13.5.6"
  • "@antv/graphin": "^2.7.27"

How can I bypass the protection? [closed]

My friend wrote a program based on working with the browser extension and Google maps. Authorization goes through hwid, I need to bypass this protection. I’m leaving a small config, maybe it can be done with it. I don’t really know much about programming myself.And if you add more. With the help of authorization via hwid, he sets the amount of time that can be used by the program. Will it work around this if you bypass the hwid itself?

I tried to figure out which files are responsible for what at first. As a result, I only realized that there is a mysql database and that it works with an extension in the browser. Authorization goes through hwid and that’s it.

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <configSections>
    <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
    <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
  </configSections>
  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.7.2" />
  </startup>
  <entityFramework>
    <providers>
      <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
      <provider invariantName="System.Data.SQLite.EF6" type="System.Data.SQLite.EF6.SQLiteProviderServices, System.Data.SQLite.EF6" />
    </providers>
  </entityFramework>
  <system.data>
    <DbProviderFactories>
      <remove invariant="System.Data.SQLite.EF6" />
      <add name="SQLite Data Provider (Entity Framework 6)" invariant="System.Data.SQLite.EF6" description=".NET Framework Data Provider for SQLite (Entity Framework 6)" type="System.Data.SQLite.EF6.SQLiteProviderFactory, System.Data.SQLite.EF6" />
      <remove invariant="System.Data.SQLite" />
      <add name="SQLite Data Provider" invariant="System.Data.SQLite" description=".NET Framework Data Provider for SQLite" type="System.Data.SQLite.SQLiteFactory, System.Data.SQLite" />
    </DbProviderFactories>
  </system.data>
  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="System.Net.Http.Extensions" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-2.2.28.0" newVersion="2.2.28.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Net.Http.Primitives" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-4.2.28.0" newVersion="4.2.28.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-13.0.0.0" newVersion="13.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="Google.Apis.Auth" publicKeyToken="4b01fa6e34db77ab" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-1.49.0.0" newVersion="1.49.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="Google.Apis" publicKeyToken="4b01fa6e34db77ab" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-1.49.0.0" newVersion="1.49.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="Google.Apis.Core" publicKeyToken="4b01fa6e34db77ab" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-1.49.0.0" newVersion="1.49.0.0" />
      </dependentAssembly>
    </assemblyBinding>
  </runtime>
</configuration>

Can’t solve Cross-Origin Request Blocked with Flask CORS

Thanks in advance for the advice. I can’t seem to figure this out. I’m trying to access a Flask app I created on my Raspberry Pi through my local network. But I keep getting this error on Firefox:

`Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://127.0.0.1:5000/socket.io/?EIO=4&transport=polling&t=OmoJlG2. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing). Status code: 403.

13:51:29.306
XHRGET
http://127.0.0.1:5000/socket.io/?EIO=4&transport=polling&t=OmoJmUN
[HTTP/1.1 403 Forbidden 0ms]

13:51:29.307 Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://127.0.0.1:5000/socket.io/?EIO=4&transport=polling&t=OmoJmUN. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing). Status code: 403.`

Safari:

XMLHttpRequest cannot load http://127.0.0.1:5000/socket.io/?EIO=4&transport=polling&t=OmoNvV7 due to access control checks.

I’ve tried several different solutions from stackoverflow (googling), but none of them seem to work..

For example,

# Configure application
app = Flask(__name__, static_url_path='/static')
CORS(app, support_credentials=True)
app.config['CORS_HEADERS'] = 'Content-Type'

socketio = SocketIO(app, cors_allowed_origins="*")


<snip>


@app.route("/plot", methods=["GET", "POST"])
@cross_origin(supports_credentials=True)
@login_required
def plot():
    if request.method == "GET":
        response = make_response(render_template("plot.html", current_session=sensor_data.s_san))
        response.headers.add("Access-Control-Allow-Origin", "*")
        response.headers.add("Access-Control-Allow-Headers", "*")
        response.headers.add("Access-Control-Allow-Methods", "*")
        return response


<snip>

if __name__ == '__main__':
    # https://realpython.com/intro-to-python-threading/
    import threading
    threading.Thread(target=plot_temperature, args=(sensor_data,), daemon=True).start()
    socketio.run(app, debug=True, host='0.0.0.0', port=5000)

I can’t figure out how to get Flask to send the missing “Access-Control-Allow-Origin: *” header.. Could appreciate some guidance on this.

Tried several solutions mentioned with CORS. I even tried removing the if (GET) so this applies to any method.

@app.route("/plot", methods=["GET", "OPTIONS"])
@login_required
def plot():
    response = make_response(render_template("plot.html", current_session=sensor_data.s_san))
    response.headers.add("Access-Control-Allow-Origin", "http://192.168.1.190:5000")
    response.headers.add("Access-Control-Allow-Headers", "Content-Type")
    response.headers.add("Access-Control-Allow-Methods", "GET")
    return response

Let me know if there’s anything else you need.

Ta.

How to display user input data in chart using next.js?

I am working on a school project using Next.js, Firebase, and Chart.js. My goal is to create a Doughnut chart using Chart.js that displays the category name and total amount spent for each category. The application allows users to input their spending and income data, which is then directed to a transactions page. On this page, the transactions are split up into categories, and users can view each spending or income item by clicking on the category name. Here is a link to the Vercel Application for better understanding: Vercel

UserSpendingData.js:

export default function UserSpendingData({ onAddSpending }) {
    const [name, setName] = useState('');
    const [amount, setAmount] = useState('');
    const [date, setDate] = useState('');
    const [category, setCategory] = useState('salary');
    const [error, setError] = useState('');

    const handleNameChange = (event) => setName(event.target.value);
    const handleAmountChange = (event) => setAmount(event.target.value);
    const handleDateChange = (event) => setDate(event.target.value);
    const handleCategoryChange = (event) => setCategory(event.target.value);

    const handleSubmit = (event) => {
        event.preventDefault();
        if (!name || !amount || !category || !date) {
            setError('Please fill out all fields.');
            return;
        }

        const inputData = { name, amount, date, category };
        onAddSpending(inputData);

        setName('');
        setAmount('');
        setDate('');
        setCategory('salary');
        setError('');
    };

Transactions.js:

import React, { useState } from 'react';
import Item from '@/components/item';
import { FaChevronDown, FaChevronUp } from 'react-icons/fa';
import Budget from '@/app/pages/budget';


function Transactions({ spendingItems = [], incomeItems = [] }) {
  const [showSpendingDetails, setShowSpendingDetails] = useState(false);
  const [showIncomeDetails, setShowIncomeDetails] = useState(false);
  const [expandedCategories, setExpandedCategories] = useState([]);

  const toggleSpendingDetails = () => {
    setShowSpendingDetails(!showSpendingDetails);
  };

  const toggleIncomeDetails = () => {
    setShowIncomeDetails(!showIncomeDetails);
  };

  const calculateTotal = (items) => {
    return items.reduce((sum, item) => sum + parseFloat(item.amount), 0);
  };

  const totalSpending = calculateTotal(spendingItems);
  const totalIncome = calculateTotal(incomeItems);

  const groupByCategory = (items) => {
    const grouped = {};
    items.forEach((item) => {
      if (!grouped[item.category]) {
        grouped[item.category] = [];
      }
      grouped[item.category].push(item);
    });
    return grouped;
  };

  const groupedSpending = groupByCategory(spendingItems);
  const groupedIncome = groupByCategory(incomeItems);

  const toggleCategory = (category) => {
    if (expandedCategories.includes(category)) {
      setExpandedCategories(expandedCategories.filter((cat) => cat !== category));
    } else {
      setExpandedCategories([...expandedCategories, category]);
    }
  };

BudgetCharts.js:

import React from 'react';
import DoughnutChart from '@/components/DoughnutChart';

function BudgetCharts({ categoryBudgets }) {
  if (!categoryBudgets || categoryBudgets.length === 0) {
    return null;
  }

  // Extract category labels and spending data from categoryBudgets
  const labels = categoryBudgets.map((item) => item.category);
  const spendingData = categoryBudgets.map((item) => item.totalSpent);

  // Define colors for the charts
  const colors = ['#FF5733', '#33FF57', '#3366FF', '#FF33E0', '#E0FF33'];

  return (
    <div>
      <div style={{ display: 'flex', flexDirection: 'row' }}>
        <div style={{ flex: 1 }}>
          {/* Create a DoughnutChart for spending */}
          <DoughnutChart
            chartData={{
              labels,
              data: spendingData,
              backgroundColor: colors,
              borderColor: colors,
            }}
            title="Spending"
          />
        </div>
      </div>
    </div>
  );
}

export default BudgetCharts;

I have been trying to figure out how to display the information on the chart for the past few hours, but nothing seems to be working. I have tried passing information from file to file, as well as storing the data in a JSON file, but I have not been successful. I would like to have the Spending/Income and Total Amount displayed above the chart on the transactions page. Additionally, I want the categories to be split into sections with their respective spending amounts for each category. I am confused as to why this works on the transactions page but I am unable to get it to work for the chart.

I would really appreciate it if someone could help me understand what I am doing wrong or guide me in the right direction. Thank you so much in advance!

not knowing how to open a react & firebase website that I created

So I just made a website following this toturial https://www.youtube.com/watch?v=zQyrwxMPm88
I followed it and I have the code one to one
but when I looked at the firebase page of mine it doesn’t tell me what is the URL of the website that I created so know I am stuck with a website not knowing how to run it or open it
PS. if I need to run some sort of script that I made from the toturial please tell me because I have no Idea

Hacking javascript to go with 2 + 2 = 5

Alright, this is not serious at all but here goews. Is there a hackisch way to accomplish this in javascript:

2 + 2 = 5

I had some ideas involving strings and string-casting, bitwise or, or anything that would produce a good-looking line where the result of 2+2 equals 5. Anyone feeling inventious with their anything-goes-martial-art-skills today? 😀

How do I re-use expressions in Cucumber?

I have this scenario where I want to check if a banner element exists on each page.

I have created a separate banners.js file that contains the (Selenium Webdriver) Javascript that does the check:

./components/banner.js

const { By } = require('selenium-webdriver');

async function checkBannerExists(webdriver, bannerClass) {
    var banner = await webdriver.driver.findElement(By.className(bannerClass)).getRect();
    return banner.height;
  };

module.exports = { checkBannerExists };

And I can simply call it in a step’s file expression when I need it:

const banners = require("../../components/banners");

Given('I am on the home page',  async function () {
    this.driver = new Builder()
        .forBrowser('firefox')
        .build();
    
    this.driver.wait(until.elementLocated(By.tagName('h1')));
    await this.driver.get('https://www.awebsite.com');
});

Then('there should be a banner', async function() {
    var homeBanner = await banners.checkBannerExists(this, 'banner-home');
    assert.ok(homeBanner!==null);
});

All good there.

But if I add this same expression to another page, eg:

const banners = require("../../components/banners");

Given('I am on the about us page',  async function () {
    this.driver = new Builder()
        .forBrowser('firefox')
        .build();
    
    this.driver.wait(until.elementLocated(By.tagName('h1')));
    await this.driver.get('https://www.awebsite.com/about');
});

Then('there should be a banner', async function() {
    var homeBanner = await banners.checkBannerExists(this, 'banner-home');
    assert.ok(homeBanner!==null);
});

I get the error Multiple step definitions match:

Is there a way I can re-use the same expression across multiple steps and features files?

How to fix Declaration or Statement expected?

So I was working on my project and the following code I put down (It is a lot so yeah)

function Oregon_Trail() {
    Music = 1
    Weapon = 0
    scroller.setLayerImage(scroller.BackgroundLayer.Layer0, assets.image`Background Level`)
    tiles.setCurrentTilemap(tilemap`Oregon Trail`)
    mySprite = sprites.create(assets.image`Felix 13`, SpriteKind.Player)
    mySprite4 = sprites.create(assets.image`Jack 5`, SpriteKind.Jack_)
    mySprite2 = sprites.create(assets.image`Wagon 2`, SpriteKind.Wagon)
    scene.cameraFollowSprite(mySprite)
    tiles.placeOnTile(mySprite, tiles.getTileLocation(4, 7))
    tiles.placeOnTile(mySprite2, tiles.getTileLocation(3, 10))
    tiles.placeOnTile(mySprite4, tiles.getTileLocation(3, 7))
    color.startFadeFromCurrent(color.originalPalette, 1000)
    pause(1500)
    if (_1stScene1stTime == 0) {
        story.printCharacterText("Let's rest for now. I got the campfire lit.", "Felix")
        story.printCharacterText("Alright man. I'll rest in the wagon.", "Jack")
        story.printCharacterText("It's busted for now, but I got some supplies.", "Jack")
    }
    mySprite4.follow(mySprite2, 50)
    pause(1000)
    mySprite.setImage(assets.image`Felix 12`)
    pause(1000)
    Title2 = sprites.create(assets.image`CinemaBars 4`, SpriteKind.Nothing)
    Title2.setStayInScreen(true)
    tileUtil.centerCameraOnTile(tiles.getTileLocation(10, 3))
    pause(1000)
    mySprite3 = sprites.create(assets.image`Zombie 14`, SpriteKind.First_Kill)
    tiles.placeOnTile(mySprite3, tiles.getTileLocation(10, 3))
    animation.runImageAnimation(
        mySprite3,
        assets.animation`Slow Zombie Spawn`,
        200,
        false
    )
    pause(1600)
    Zombie_Look()
    pause(1000)
    story.printCharacterText("Brrr!!", "Zombie")
    scene.cameraFollowSprite(mySprite)
    sprites.destroy(Title2)
    Title2 = sprites.create(assets.image`CinemaBars 3`, SpriteKind.Nothing)
    Title2.setStayInScreen(true)
    pause(500)
    if (_1stScene1stTime == 0) {
        story.printCharacterText("Jesus Christ!", "Felix")
        story.printCharacterText("Jack, there is a zombie!!", "Felix")
        animation.runImageAnimation(
            Title2,
            assets.animation`Action Time 2`,
            400,
            false
        )
        story.printCharacterText("Don't you remember how to defend yourself?", "Jack")
        pause(1000)
        sprites.destroy(Title2)
        mySprite8 = sprites.create(assets.image`WASD Tutorial`, SpriteKind.Nothing)
        animation.runImageAnimation(
            mySprite8,
            assets.animation`WASD Tutorial`,
            200,
            true
        )
        mySprite8.x = mySprite.x
        mySprite8.y = mySprite.y
        mySprite8.z = 1e+31
        Notification.notify("WASD to move around!", 4, assets.image`Movement Icon`)
        Moving = true
        sprites.destroy(mySprite8)
        controller.moveSprite(mySprite, 75, 75)
        pause(5000)
        statusbar = statusbars.create(60, 6, StatusBarKind.Health)
        statusbar.setColor(2, 15)
        statusbar.positionDirection(CollisionDirection.Top)
        statusbar2 = statusbars.create(60, 6, StatusBarKind.None)
        statusbar2.positionDirection(CollisionDirection.Bottom)
        statusbar2.setColor(12, 15)
        Ammo = 6
        controller.moveSprite(mySprite, 0, 0)
        mySprite8 = sprites.create(assets.image`JKIL Tutorial`, SpriteKind.Nothing)
        animation.runImageAnimation(
            mySprite8,
            assets.animation`JKIL Tutorial`,
            200,
            true
        )
        mySprite8.x = mySprite.x
        mySprite8.y = mySprite.y
        mySprite8.z = 1e+31
        Notification.notify("JKIL to shoot zombies!", 4, assets.image`Gun Icon`)
        controller.moveSprite(mySprite, 75, 75)
        sprites.destroy(mySprite8)
        Shooting = true
    } else {
        animation.runImageAnimation(
            Title2,
            assets.animation`Action Time 2`,
            400,
            false
        )
        pause(3000)
        statusbar = statusbars.create(60, 6, StatusBarKind.Health)
        statusbar.setColor(2, 15)
        statusbar.positionDirection(CollisionDirection.Top)
        statusbar2 = statusbars.create(60, 6, StatusBarKind.None)
        statusbar2.positionDirection(CollisionDirection.Bottom)
        statusbar2.setColor(12, 15)
        Ammo = 6
        sprites.destroy(Title2)
        controller.moveSprite(mySprite, 75, 75)
        Moving = true
        Shooting = true
        }
    }
}

I tried to add { to certain parts to maybe fix it, but I’m not experienced with this kind of code, so I hit a block and has no where else to go. I don’t really know what to do, and from what I know, it’s usually a problem of not adding ] or } or ). So if I could get help I would be grateful, since I have to finish this project for a very bid tournament ending in January.

Uncaught TypeError: Cannot read properties of null (reading ‘querySelector’) at main.js:7:38 [duplicate]

I am building a sticky app in which when I click the + button, a new note space will be created. However, upon clicking the + button, no new note is created.

When I check the console after running the code, I see

ncaught TypeError: Cannot read properties of null (reading ‘querySelector’)
at main.js:7:38
(anonymous) @ main.js:7

I see .add-note class is defined in the indexl.html. Can you help resolve this issue?

main.js and index.html files are below.

I expect to see a new sticky note when I click the + button


main.js


//make reference to the main #app container by declaring notesContainer

const notesContainer = document.getElementById("app");

// make reference to a button to add a new note
const addNoteButton = notesContainer.querySelector(".add-note");

//above two const do exist as html


getNotes().forEach(note => {

const noteElement = createNoteElement(note.id, note.content); 

notesContainer.insertBefore(noteElement, addNoteButton);

});

addNoteButton.addEventListener("click", () => addNote());


function getNotes() {

    return JSON.parse(localStorage.getItem("stickynotes-notes") || "[]");
}

function saveNotes(notes) {

    //takes  in (notes) and stringify it with JSON and put it into local storage key to save the notes!


    localStorage.setItem("stickynotes-notes", JSON.stringify(notes));

}

// build new element to represent a note 
function createNoteElement(id, content)
{
    const element = document.createElement("textarea");

    element.classList.add("note");
    element.value = content;
    //below will fill the sticky note when there is no sticky note input
    element.placeholder = "Empty sticky note";

    element.addEventListener("change", () => {

        updateNote(id, element.value);
    })

    element.addEventListener("dblclick", () => {

        const doDelete = confirm("are you sure you wish to delete this sticky note?");

        if(doDelete) {

            deleteNote(id, element);
        }
    })


    return element;

}

// add note not only to html but also to local storage
function addNote() {

    const notes = getNotes();
    const noteObject = {

        id: Math.floor(Math.random() * 100000),
        content: ""
    };

    const noteElement = createNoteElement(noteObject.id, noteObject.content);
    notesContainer.insertBefore(noteElement, addNoteButton);

    notes.push(noteObject);
    saveNotes(notes);

}

function updateNote(id, newContent) {

    const notes = getNotes();
    const tartgetNote = notes.filter(note => note.id == id)[0];

    tartgetNote.content = newContent;
    saveNotes(notes);

}

function deleteNote(id, element) {


    //basically this means get every note except the target note because we want to keep every note except the one we
    //want to delete
    const notes = getNotes().filter(note => note.id != id);

    saveNotes(notes);
    notesContainer.removeChild(element);
}

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Sticky Notes</title>
    <link rel = "stylesheet" href = "src/main.css">
    <script src = "src/main.js" der></script>
</head>

<body>

    <div id="app">


        <button class = "add-note"  type = "button">+</button>
    </div>
    
</body>
</html>

How do I get my tailwind and css to work in production? [closed]

It turns out that I uploaded my page to netlify. It is made with htm, css, tailwind and javascript. But when I uploaded it, it didn’t show me the styles or anything like that. I asked technical support the question and they told me it was because the files were linked incorrectly.

That’s how I have it

<link rel="stylesheet" href="../css/style.css">
<link rel="stylesheet" href="../css/normalize.css">
<link href="/dist/output.css" rel="stylesheet">   

Could someone help me how to link them? Thanks in advance

Django not processing javascript files

New to django here. I’m having trouble connecting with javascript code from django python. I think I’ve followed the documentation on project configuration.

HTML template:

<!DOCTYPE html>
<html lang="en">
  <body>
    Test template<br>
    {% csrf_token %} 
    {% load static %}     
    {{ form | safe }}
    <script type="text/javascript" src="{% static '/grid_1/test_script.js' %}"></script>
    Test template end<br>
  </body>

View function:

def test_view(req: djhp.HttpRequest):
  form = forms.TestForm(); vals = dict()
  vals["test_val"] = "This is a test"
  return djsc.render(req, "test_template.html", vals)

JavaScript code:

alert("test script start")
var x = "{{ test_val }}"
alert(x)

The second javascript alert displays “{{ test_val }}” instead of “This is a test”. So it looks like django is not processing the .js file. Any help for this newbie is much appreciated!