How to use OpenAI Assistants with Openrouter

I recently came across a platform called apiepie.ai that offers GPT-4 access through something called openrouter. I would like to know if someone has used assistants with this option like with this code, because in the documentation there’s only the basic send message code :

async function createThread() {
    try {
        const thread = await openai.beta.threads.create();
        return thread.id;
    } catch (error) {
        console.error("Error al crear el hilo:", error);
        return null;
    }
}

async function sendMessageToOpenAI(threadId, message) {
    try {
        const response = await openai.beta.threads.messages.create(threadId, {
            role: "user",
            content: message
        });
        return response;
    } catch (error) {
        console.error("Error al enviar mensaje a OpenAI:", error);
        return null;
    }
}

async function getResponseFromOpenAI(threadId, assistantId) {
    try {
        const run = await openai.beta.threads.runs.create(threadId, {
            assistant_id: assistantId.id,
        });
        // console.log(`run : ${run}`)
        
        let runResponse = await openai.beta.threads.runs.retrieve(threadId, run.id);
        console.log(`runresponse : ${runResponse}`)
        
        while (runResponse.status !== "completed") {
            // Pausar brevemente para evitar hacer solicitudes continuas en un bucle rápido
            await new Promise(resolve => setTimeout(resolve, 1000)); // Espera 1 segundo
            runResponse = await openai.beta.threads.runs.retrieve(threadId, run.id);
            console.log(`runresponse 2  threadid: ${runResponse}`)
            console.log(runResponse.thread_id)
            
        }

        return runResponse;
    } catch (error) {
        console.error("Error al obtener respuesta de OpenAI:", error);
        return null;
    }
}

Angular-17 Event Listeners not working -No error code?

Withen my home page i have a link routing to the login page with a sign in button but apon clickign it no fucntion is ran and no erro code is displayed.I made sure the function is the same name and that there checked the script files to make sure nothing was overlapping.

Details-

  • Angular 17.3.5
  • usign bootstrap style and scripts
**Button in html -** 
<button class="btn btn-primary w-100 py-2" type="button"  (click)="onLogin()">Sign in</button>

**compnent.ts** -
@Component({
  selector: 'app-login-page',
  standalone: true,
  imports: [FormsModule],
  templateUrl: './login-page.component.html',
  styleUrl: './login-page.component.css'
})

export class LoginPageComponent {

  loginObj: any ={
    'username': '',
    'password': ''
  }

  constructor(private router: Router) { }


  onLogin(){
    console.log('Login Clicked');
    alert('Login Clicked');
  } 
}

I’ve tried different event listeners as well as checking to see if event listening works on other pages (it does not), as well as looking in the console to see if any errors related to the button are appearing.

Angular does not pop up any errors when using ng serve. Nor does the console show what I believe are related errors.

I really need help 🙁 i dont understand
if any more code snippets needed i will provide

i did see a simalar post talk about this in april but no derict answer other than debug was given 🙁

DOMException: Failed to execute ‘evaluate’ on ‘Document’: The string ‘//*[cac:Party]’ [duplicate]

DOMException: Failed to execute ‘evaluate’ on ‘Document’: The string ‘//*[cac:Party]’ contains unresolvable namespaces.
enter image description here

 const parser = new DOMParser();
            const xmlDoc = parser.parseFromString(xml, 'text/xml');
            const partyNode = xmlDoc.evaluate('//*[cac:Party]', xmlDoc, null, XPathResult.ANY_TYPE, null).iterateNext();

            const partyIdentification = partyNode.querySelector('cac\:PartyIdentification cbc\:ID').textContent;
            const partyName = partyNode.querySelector('cac\:PartyName cbc\:Name').textContent;
            const citySubdivisionName = partyNode.querySelector('cac\:PhysicalLocation cac\:Address cbc\:CitySubdivisionName').textContent;
            

Fill json 
  const jsonData = {
                partyIdentification,
                partyName,
                physicalLocation: {
                    citySubdivisionName,
                    cityName,
                    countrySubentity,
                    identificationCode
                },
                electronicMail
            };

Differentiate touchstart + touchend vs. click

With vanilla JS, and no touch framework, what condition makes a touchstart + touchend become a click event?

Is there an official specification like, for example:

touchstart followed by touchend, with delta_time < 100 ms    => triggers a "click" event

?

If so, is the standard followed by Chrome and Firefox?

How to use useSearchParams in NextJs 12?

I’m using next.js 12 and next-usequerystate npm library.

When I use it like this, it sets the ‘view’ correctly, but when I remove the comments, it sets whichever state is last, overriding the others.

const [queryFilter, setQueryFilter] = useQueryState('filter', {
 view: queryTypes.string
});

My other question/problem is I don’t wanna create a state for each query. How can ı make the object like this?

import { queryTypes, useQueryState } from 'next-usequerystate';

const [queryView, setQueryView] = useQueryState('view', queryTypes.string);
const [queryStatus, setQueryStatus] = useQueryState('selectedStatus', queryTypes.string);


useEffect(() => {
    if (!router.isReady || Object.keys(prevFilter).length === 0 || !prevFilter) return;
    if (prevFilter.view) {
        setQueryView(prevFilter.view);
    }
    // if (prevFilter.selectedStatus.length > 0) {
    //     setQueryStatus(prevFilter.selectedStatus.join('-'));
    // } else {
    //     setQueryStatus(null);
    // }

}, [prevFilter]);

How do I print Crash game data to the terminal? PYTHON.PY [closed]

I want to print game data automatically

print(“crash-timer__counter”)

print(“The time the plane flies”)

print(“the moment it exploded”)

You can update its code or fix it :

……………………………..

from selenium import webdriver

import time

CHROMEDRIVER_PATH = ‘/home/ali/Desktop/crash game/chromedriver_linux64/chromedriver’

chrome_options = webdriver.ChromeOptions()

chrome_options.add_argument(‘–headless’)

driver = webdriver.Chrome(options=chrome_options)

url = “https://1xbet.com/en/allgamesentrance/crash”

driver.get(url)

def extract_content():

elements = driver.find_elements_by_css_selector(“div.crash-game__wrap”)

for element in elements:

print(element.text)

def update_page():

driver.refresh()

time.sleep(0.001)

extract_content()

while True:

update_page()

……

Error resuming script execution with apps script after accepting user input

enter image description here

I’m running an apps script, which takes a Json string, converts it to an object and adds some of the key values to a Google sheet. The following code has worked for some JSON strings. However with others, I get the error in the title. When I check the execution log , I see:

enter image description here

Suggesting that it doesn’t restart after accepting the JSON string. Any idea why?
function importJsonToSheet() {
// Get the active spreadsheet
var spreadsheet = SpreadsheetApp.getActiveSpreadsheet();

  // Get the active sheet
  var sheet = spreadsheet.getActiveSheet();
  
  // Check if the active sheet is named "Sheet7"
  if (sheet.getName() === "sheet7") {
    // Prompt the user to input the JSON data
    var ui = SpreadsheetApp.getUi();
    var prompt = ui.prompt('Enter JSON data', 'Please paste your JSON data here:', ui.ButtonSet.OK_CANCEL);
    var response = prompt.getResponseText();
    var button = prompt.getSelectedButton();
    
    // Check if the user clicked "OK"
    if (button === ui.Button.OK) {
      // Parse the JSON string into an object
      var jsonObject;
      try {
        jsonObject = JSON.parse(response);
      } catch (e) {
        ui.alert("Invalid JSON format. Please enter valid JSON data.");
        return;
      }
      
        addRowFromObject(jsonObject.Single, sheet) ;


    } else {
      // If the user clicked "Cancel", display a message
      ui.alert("Operation canceled.");
    }
  } else {
    // If the active sheet is not named "Sheet7", display an alert
    SpreadsheetApp.getUi().alert("This script can only run on Sheet7. Please activate Sheet7.");
  }
}

How can I match any substring not equal to something?

I’ve been at this for a couple of hours now and I have nothing. Given this string:

"wolf AND horse AND NOT mountain goat OR cow AND NOT dog"

I need to match ‘wolf’, ‘horse’, ‘mountain goat’, ‘cow’ and ‘dog’. How can I filter out ‘AND’, ‘AND NOT’ and ‘OR’.

Regex flavor is JavaScript.

Thanks in advance!

How do i fix PHP headers? [duplicate]

How do i make it so that the page only redirects to data.php after the update query is submitted? when i click edit, it immediately redirects to data.php. But what i’am trying to do is when i click edit the update modal will pop up and when i finish the edits to be done and click update then and only then should the modal close and redirect.

i tried asking ai s but theyre suggestions dont work

beginner here so please enlighten me

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        .modal {
            display: none;
            position: fixed;
            top: 40%;
            left: 50%;
            transform: translate(-50%, -50%);
            z-index: 2;
            width: 270px;
            height: 100px;
            max-width: 90%;
            background-color: white;
            padding: 20px;
            border: 2px solid black;
        }
    </style>
</head>
<body>
    <?php
    $conn = new mysqli("localhost", "root", "", "dbsemi");
    $name = "";
    if ($conn->connect_error) {
        die("Connection failed: " . $conn->connect_error);
    }

    if (isset($_GET["txtname"])) {
        if (isset($_GET["txteditid"])) {
            $edit_id = $_GET["txteditid"];
            $edit_name = $_GET["txtname"];
            $edit_course = $_GET["txtcourse"];
            $edit_con = $_GET["txtcno"];
            $conn->query("UPDATE tbldata SET nams='$edit_name', cors='$edit_course', cno='$edit_con' WHERE id='$edit_id'");
            header("Location: data.php");
            exit();
        } else {
            $name = $_GET["txtname"];
            $course = $_GET["txtcourse"];
            $con = $_GET["txtcno"];
            $conn->query("INSERT INTO tbldata (nams, cors, cno) VALUES ('$name', '$course', '$con')");
        }
    }
    ?>
    <div id="modal" class="modal">
        <button onclick="closeModal()">x</button>
        <form method="get" action="data.php">
            Name: <input type="text" name="txtname" value='<?php echo $name; ?>' required><br>
            <?php if(isset($_GET["txteditid"])): ?>
                <input type="hidden" name="txteditid" value='<?php echo $_GET["txteditid"]; ?>'>
                Course:
            <select name="txtcourse" required>
                <option value="CPE">CPE</option>
                <option value="CCS">CCS</option>
                <option value="BSBA">BSBA</option>
            </select><br>
            ContactNo: <input type="text" name="txtcno" required><br>
            <input type="submit" value="UPDATE" onclick="closeModal()">

            <?php else: ?>
            Course:
            <select name="txtcourse" required>
                <option value="CPE">CPE</option>
                <option value="CCS">CCS</option>
                <option value="BSBA">BSBA</option>
            </select><br>
            ContactNo: <input type="text" name="txtcno" required><br>
            <input type="submit" value="ADD">
            <?php endif; ?>
        </form>
    </div>

    <button onclick="displayModal()">+</button>

    <table>
        <a href="print.php"><button>PRINT</button></a>
        <tr>
            <th>Edit</th>
            <th>Name</th>
            <th>Course</th>
            <th>ContactNo</th>
        </tr>
        <?php
            $result = $conn->query("SELECT * FROM tbldata");
            while($row = $result->fetch_assoc()){ 
                echo "<tr>
                <td><a href='data.php?txteditid={$row["id"]}&txtname={$row["nams"]}&txtcourse={$row["cors"]}&txtcno={$row["cno"]}'><button>EDIT</button></a></td>
                <td>{$row["nams"]}</td>
                <td>{$row["cors"]}</td>
                <td>{$row["cno"]}</td>
                </tr>";
            }
        ?>
    </table>
    <script>
        function displayModal() {
           let modal = document.getElementById('modal');
           modal.style.display = 'block';
           
        }
        function closeModal() {
            let modal = document.getElementById('modal');
            modal.style.display = 'none';
         
        }
   </script>
   <?PHP
        if (isset($_GET["txteditid"])){
            echo  " <script>
                    let m = document.getElementsByClassName('modal')[0];
                    m.style.display = 'block';
                    </script>";
        }
    ?>
    </body>
    </html>

i tried removing the header but the modal will not close automatically and the url will still have the previous query’s isset

Beginner’s Guide to Node.js [closed]

“As a beginner in Node.js, I want to be on the journey to becoming a Node.js developer. Could you provide me with a roadmap or guide that helps essential steps and resources I should follow to achieve this goal?”

answered my question in detail

give paddingLeft/ marginLeft to line chart apexcharts

I have below apexchart shown. as you can see, the first x-axis label “1.24.18 Develop” is placed after some margin from 0 of x axis. Earlier scenario, it would start right at 0 of X axis.

Apexchart LineCharts

I modified the apexchart state where i added below lines. These lines would add empty data to the chart and shift the starting point of the chart as shown above. The problem is that it moves little more than expected. Can i add a paddingLeft: ‘-20px’ or marginLeft: ‘-20px’ somewhere by which there is no huge gap between 0 of x-axis and the starting of the line graph

userNames.unshift('')
alteredResponse.corepass.unshift(null)
alteredResponse.atp.unshift(null)

let chartSt = {
      series: [
        { name: "Pass", data: alteredResponse.corepass },
        { name: "Fail", data: alteredResponse.atp },
      ],
      options: {
         xaxis: {
          type: "string",
          categories: userNames
         }
      }
}

A is only ever to be used as the child of element, never rendered directly. What should I do?

I’m trying to connect my react app to my fastapi app and enable authentication but I keep having this error: “A is only ever to be used as the child of element, never rendered directly”.

In my **app.js**, I have the following function:

const AllRoutes = () => {
  const Auth = React.useContext(AuthApi);
  return (
    <Routes>
      <Route path="/register" element={<Register />}/>
      
      <Route path="/login" element={<ProtectedLogin auth={Auth.auth} component={Login} />}/>
      <Route path="/" element={<ProtectedRoute auth={Auth.auth} component={Home} />}/>
    </Routes>
  );
};

This is my **ProtectedLogin**:

const ProtectedLogin = ({ auth, component: Component, ...rest }) => {
  return (
    <Route
      {...rest}
      render={() => (!auth ? <Component /> : <Navigate to="/" />)}
    />
  );
};

This is my **ProtectedRoute**:

const ProtectedRoute = ({ auth, component: Component, ...rest }) => {
  return (
    <Route
      {...rest}
      render={() => (auth ? <Component /> : <Navigate to="/login" />)}
    />
  );
};

When I change the **ProtectedRoute** and **ProtectedLogin** to:

const ProtectedRoute = ({ auth, component: Component}) => {
  return auth ? <Component /> : <Navigate to="/login" />;
};
const ProtectedLogin = ({ auth, component: Component}) => {
  return auth ? <Component /> : <Navigate to="/" />;
};

Only the Register page works. When I click Login or Home, It just hangs up on me. Please help!! Thank you.

Do Changes in Google Maps Location or Marker Position Require Additional API Calls?

I’m currently utilizing the Google Maps API for a mapping feature in my project. I’ve successfully downloaded the necessary JavaScript file by invoking the API. Now, I’m curious about whether additional API calls are required when updating the map’s location or a marker’s position.

Specifically, I’m wondering if creating a new object like new google.maps.Map() to change positions is solely managed within the already downloaded Google Maps JavaScript file, or if it involves sending requests to the Google server.

While I understand that such changes are typically handled client-side, I’m seeking clarity on the exact process. Could someone please explain whether each change necessitates a new call to the Google API for updated data, or if the changes are managed locally using the downloaded JavaScript file? Any insights would be greatly appreciated. Thank you!

next js 14 and i18n for i18next-http-backend

please, help me to get translations from backend. I use next js 14 version, and i18next. For backend api I use i18next-http-backend.
This is my files

i18n.js

`
  import { createInstance } from 'i18next';
  import { initReactI18next } from 'react-i18next/initReactI18next';
  import resourcesToBackend from 'i18next-resources-to-backend';
  import i18nConfig from '@/i18nConfig';
  const I18NextHttpBackend = require('i18next-http-backend');

  export default async function initTranslations(
    locale,
    namespaces,
     i18nInstance,
     resources
  ) 
  {
       i18nInstance = i18nInstance || createInstance();
        i18nInstance.use(initReactI18next);
        if (!resources) {
         i18nInstance.use(
        resourcesToBackend(
            (language, namespace) =>
                import(`@/locales/${language}/${namespace}.json`)
        )
    );
  }
   await i18nInstance.init({
      lng: locale,
      resources,
      fallbackLng: i18nConfig.defaultLocale,
      supportedLngs: i18nConfig.locales,
      defaultNS: namespaces[0],
      fallbackNS: namespaces[0],
      ns: namespaces,
      preload: resources ? [] : i18nConfig.locales,
      serializeConfig: false,
      use: [I18NextHttpBackend],
    });
   return {
      i18n: i18nInstance,
       resources: i18nInstance.services.resourceStore.data,
       t: i18nInstance.t
   };
}`

i18nConfig.js

  `
  const i18nConfig = {
      locales: ['am', 'en'],
      defaultLocale: 'am',
      backend: {
          loadPath: `${process.env.BACKEND_DOMAIN}/api/translations/all/{{lng}}`,
          reloadInterval: 1000,
          requestOptions: {
          cache: 'no-cache',
          credentials: 'same-origin',
         }
     },
    prefixDefault: true
  }

  module.exports = i18nConfig`

for locale translations its good working, but for backend api – its not working

Why is edit not working react-admin with custom dataProvider

I am using react-admin library
The thing is I am not sure what’s the issue, but the edit button does not work.
I tried

my component:

import { dataProvider } from '../helpers/usersDataProvider'
import UserCreate from './UserCreate'
const UsersManagement = () => {
  return (
    <Admin dataProvider={dataProvider}>
        <Resource name='users' list={UserList} create={UserCreate}/>
    </Admin>
  )

custom dataProvider:

const API_URL = "https://jsonplaceholder.typicode.com";

export const dataProvider = {
  getList: async (resource, params) => {
   //normal fetch func
  },
  update: async (resource, params) => {
    const response = await fetchUtils.fetchJson(
      `${API_URL}/${resource}/${params.id}`,{
        headers: {
            "Content-type": "application/json; charset=UTF-8",
          },
      },
      {
        method: "PUT",
        body: JSON.stringify(params.data),
      },
      
    );
    return { data: response.json };
  },
  delete: async (resource, params) => {
    const response = await fetchUtils.fetchJson(
      `${API_URL}/${resource}/${params.id}`,
      {
        method: "DELETE",
      }
    );
    return { data: response.json };
  },
};

It should show an edit view, but It calls getList function. The delete button excutes properly, I am just having issues with editButton