satoshi-2000/llms-suitable huggingface dataset:
Question: Multiple AJAX calls ; get all the failed calls

I am making multiple ajax calls as shown below. Below code works fine If all the calls succeed. But, let's say urlId 3 and 4 failed for some reason. Is it possible to get all the failed urlId's in the fail function?
var urlId = [1, 3, 4, 7]
let requests = [];
for (let i = 0; i < urlId.length; i++) {
    requests.push($.ajax(...));
}
$.when.apply($, requests).done(function () {
    $.each(arguments, function (idx, args) {
        //process args : urlId[idx]
    });
}).fail(function (jqXHR) {
    //how to get urlId's failed
});



Answer:
You would not be able to reliably get all of the failed IDs in the .fail handler because it will fire as soon as any of the deferreds becomes rejected, regardless of the state of the other deferreds.
If you want to keep track of which requests succeeded and which failed, I think your best option would be to attach a catch handler to each $.ajax call that will catch a failure and map it to an object that has a reference to the id and to the success/failure status. Catching errors this way will mean that all of the deferreds will succeed, so the handling of success and failed states will then need to be performed in the done handler attached to the $.when. For example:
var urlId = [1, 3, 4, 7]
let requests = [];

urlId.forEach(id => {
  requests.push(
    $.ajax(/*...*/)
      .then(response => {
        return {
          id,
          success: true,
          response
        };
      })
      .catch(error => {
        return {
          id,
          success: false,
          error
        }
      })
  );
});

$.when.apply($, requests)
  .done(function (values) {
    $.each(arguments, function (idx, obj) {
      console.log(`${obj.id}: success = ${obj.success}`);
    });
 });

Here is a fiddle for reference.
Question: Why is this one paragraph link showing up funky?

I am attaching some code in here, I have recently added in a link to my portfolio website and the paragraph link is doing something weird, it seems to be aligning funky and I'm not sure what the issue is. I'm wondering if it might be stemming from some other a stylings in the CSS (like nav_links) but I'm unsure how to correct this without messing up the other a stylings.
I added a class to the a href and tried to add in some CSS styling for it, it fixed some issues (like the size and color)but that gap


Answer:
You're making a mistake in your CSS, doing things like this:
.nav_link li, a

You need to remove those commas. I assume here you're trying to style an a within an li within an element with a class of .nav_link. But that's NOT what you're doing. Instead, this selector is applying a bunch of styles to .nav_link li and separately to all a elements. The selector should actually read like so:
.nav_link li a

You have this issue at several points in your CSS.
Question: TinyMCE insertHTML modifies some HTML tags

I have some content in tinymce 6 editor. I moved the cursor and placed it inside the content and executed
tinymce.activeEditor.insertContent(`<span class='dummy'>
                        <div><span style="font-style:italic;font-weight:bold;text-decoration:underline;">This Text is BOLD</span></div>
                        <div><span style="font-style:italic;">This text is Italic</span></div>
                        <div><span style="text-decoration:underline;">This Text is&#160; Underlined</span></div>
                      </span>`, {format: 'html'});

When I execute this the div elements are getting removed.
I can see the content inside the BeforeSetContent event. But on the SetContent event the content is getting modified and the div are removed. Is there any way to prevent this behaviour ?
I tried adding
valid_children: '+div[span], +span[div]' 

in the editor config.
I am expecting the html content to be added into the tinymce 6 editor without modifying the tags


Answer:
The default behavior is to remove certain elements, such as <div>, when they are inserted using the insertContent method.
But you can override this behavior by customizing the editor's schema and adding a rule to allow the <div> element:
tinymce.init({
  selector: '#your-selector',
  // other configurations...
  setup: function (editor) {
    editor.on('BeforeSetContent', function (e) {
      // Allow the <div> element in the content
      e.content = e.content.replace(/<div>/g, '<div data-mce-bogus="1">');
    });
  },
  valid_elements: 'div[*]' // Allow all attributes on <div> elements
});
Question: Do I need any environment variables set to execute some code, call openai's api, and return a response?

I was going through a course in OpenAI's API using an in-browser jupyter notebook page but wanted to copy some example code from there into a local IDE. I installed Python and the jupyter extention in VS Code and the OpenAI library. My code is below:
import openai
import os

# from dotenv import load_dotenv, find_dotenv
# _ = load_dotenv(find_dotenv()) # read local .env file

openai.api_key  = "my api key is here"

def get_completion(prompt, model="gpt-3.5-turbo"):
    messages = [{"role": "user", "content": prompt}]
    response = openai.ChatCompletion.create(
        model=model,
        messages=messages,
        temperature=0, # this is the degree of randomness of the model's output
    )
    return response.choices[0].message["content"]

prompt = f"""
Determine whether each item in the following list of \
topics is a topic in the text below, which
is delimited with triple backticks.

Give your answer as list with 0 or 1 for each topic.\

List of topics: {", ".join(topic_list)}

Text sample: '''{story}'''
"""
response = get_completion(prompt)
print(response)

I installed Python and imported the openai library. When I run I am getting the error:
APIConnectionError: Error communicating with OpenAI: ('Connection aborted.', RemoteDisconnected('Remote end closed connection without response'))

I'm assuming that's because I commented out lines 3 and 4 in the code because I am unsure what they do and do not know how to use the dotenv library. Is it simple to set this up just to make a basic call to the openai API? That's all I'm trying to do with this code right now.


Answer:
Usually, you load your API KEY from your .env file but, as you are hardcoding it, you don't need anything else.
The error you are getting might be related to the absence of the topic_list and story definitions.
Question: Why does my logo not appear in the Bootstrap navbar when using Ruby on Rails?

I'm working on Ruby on Rails and I'm trying to put a logo.png image in a bootstrap navbar.
so i used this code in app/views/home/_header.html.erb
<nav class="navbar navbar-expand-lg bg-primary " data-bs-theme="dark"> 
  <div class="container-fluid">
   <!-- <a class="navbar-brand" href="#">Estrutecnia</a> -->
 <a class="navbar-brand" href="#">
      <img src="logo.png" alt="Estrutecnia" width="30" height="24">
    </a>


    <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
      <span class="navbar-toggler-icon"></span>
    </button>
    <div class="collapse navbar-collapse" id="navbarSupportedContent">
      <ul class="navbar-nav me-auto mb-2 mb-lg-0">
        <li class="nav-item">
          <a class="nav-link active" aria-current="page" href="#">Home</a>
        </li>
        <li class="nav-item">
          <a class="nav-link" href="#">Link</a>
        </li>
        <li class="nav-item dropdown">
          <a class="nav-link dropdown-toggle" href="#" role="button" data-bs-toggle="dropdown" aria-expanded="false">
            Dropdown
          </a>
          <ul class="dropdown-menu">
            <li><a class="dropdown-item" href="#">Action</a></li>
            <li><a class="dropdown-item" href="#">Another action</a></li>
            <li><hr class="dropdown-divider"></li>
            <li><a class="dropdown-item" href="#">Something else here</a></li>
          </ul>
        </li>
        <li class="nav-item">
          <a class="nav-link disabled">Disabled</a>
        </li>
      </ul>
      <form class="d-flex" role="search">
        <input class="form-control me-2" type="search" placeholder="Search" aria-label="Search">
        <button class="btn btn-outline-success" type="submit">Search</button>
      </form>
    </div>
  </div>

</nav>

The problem is that the logo doesn't appear, look at the navbar

And the next errors display
Started GET "/logo.png" for 127.0.0.1 at 2023-06-02 20:05:47 -0500

ActionController::RoutingError (No route matches [GET] "/logo.png"):

I tried to put the logo.png file in the root directory that I guess is the folder where the Gemfile and the README.md files are.
I expect that the logo.png appears at the navbar, but a brocken file icon appears at the left side of the navbar, like described in the image above.


Answer:
Images are normally placed in the app/assets/images directory.
When you render a view using the ActionView image_tag helper, Rails automatically populates the image source for you:
image_tag('logo.png')
# => <img src='/assets/icon.png>

This would be the idiomatic way to handle images in Rails, but of course there's nothing that prevents you from including <image src='/assets/icon.png'> in your markup
Question: How can I add a chatter for many2many fields (tags) in Odoo 16?

I want to add chatter for Tags. But odoo does not support tracking of many2many fields.
What should i do?
Any Suggestions.
I tried to put tracking=true on tag_ids field but it does not work.
I am stuck here. Please give your suggestions.


Answer:
You can override the _track_mail function to track x2many fields.
Check the code just after # Many2many tracking comment in the project module
Example:
if len(changes) > len(tracking_value_ids):
    for changed_field in changes:
        if tracked_fields[changed_field]['type'] in ['one2many', 'many2many']:
            field = self.env['ir.model.fields']._get(self._name, changed_field)
            vals = {
                'field': field.id,
                'field_desc': field.field_description,
                'field_type': field.ttype,
                'tracking_sequence': field.tracking,
                'old_value_char': ', '.join(initial_values[changed_field].mapped('name')),
                'new_value_char': ', '.join(self[changed_field].mapped('name')),
            }
            tracking_value_ids.append(Command.create(vals))
Question: Accessibility Rules Check for Progress Bars

I am working on a React eCommerce website. The designs given to me show a flow for checking someone's credit for approval. When the user hits the "Submit Application" button, it takes them to a page that says "Reviewing Application" with a progress bar that takes about 12 seconds to load. When the bar is complete, the text says, "You're Approved" or "Sorry, you are not approved".
The designs then show that the Approved screen stays for a few seconds and then they are redirected to the checkout page. My question is, does this break any accessibility rules? It feels wrong to have a user click a button and then all these actions happen and if they are not paying attention, they could miss it telling them that they are approved.
The client is very keen on having a good accessibility score and wants to make sure that they don't break any rules. If this isn't allowed, can you please add a link to where it is stated more specifically? All I keep getting when Googleing this are examples of how to build a progress bar. TIA!


Answer:
There two WCAG checkpoints at play here.
The first is dynamic content added to the page. "Reviewing application..." and then "you're approved (or not)".  That falls under WCAG 4.1.3 Status Messages. Just make sure the "reviewing application" indicates that the process is running. I'm guessing you have some kind of animation during the 12 seconds or so that it takes to approve or disapprove?  You could potentially use aria-busy="true" during the 12 seconds then set it to false when done.
Alternatively, you can use an aria-live region and then update the contents of that region to say "reviewing application..." and then maybe update it every 5 seconds or so to say "still reviewing...".  You'll probably need aria-atomic="true" if you update the region with the same text ("still reviewing...") multiple times, otherwise the live region won't think anything changed.
The second checkpoint is WCAG 2.2.1 Timing Adjustable because you are redirecting the user on your own timing, and like you said, they might miss the approval status.  Or they might not have had time to read the approval page.
There are 6 ways to fix 2.2.1 as noted in the guideline itself.  "Extend" is the most common and you typically see this in "log off" situations where you're about to be logged off due to inactivity but are given a chance to extend your session. The same would be applied to your redirect. You can show the user the approval or denial message and then have a "you will be redirected to the checkout page in XX seconds" message with an option to extend the time limit.
Personally, I think the redirection should be avoided altogether. Just tell the user they've been approved or denied and then have a call to action button (CTA) and let the user navigate to the checkout screen on their own time. Then you avoid the 2.2.1 issue.
Question: about the remove() function,how can i del the last element only?

I have the problem is that,When i press remove button,whole list is deleted,
for example,i add ABC and DEF,this 2 parts,
I press one time and ABC also gone!
how can i fix it?
<!DOCTYPE html>
<html>
  <head>
    <title>To-Do List</title>
  </head>
  <body>
    <h1>To-Do List</h1>`
    <input type="text" class="task" placeholder="Enter a task">
    <button class="Add">Add Task</button>
    <button class="removeTask">Remove</button>
    <ul class="taskList"></ul>
  </body>
  <script>



const taskList = document.querySelector(".taskList");
const RemoveEl = document.querySelector(".removeTask");
const addTask = document.querySelector(".Add");


addTask.addEventListener("click", (e)=>{ 
  const taskInput = document.querySelector(".task");
const newTask = document.createElement("li");
let task = taskInput.value;

  if (task.trim() != "") {
    
    newTask.innerText = task;
    taskList.appendChild(newTask);
    taskInput.value = "";};
  
    if(newTask){
  RemoveEl.addEventListener("click",()=>{

    taskList.remove();

  })
}});
  </script>
</html>

thank you so much!


Answer:
The issue you're facing is because in the event handler for the Remove button, you are calling remove() on the taskList, which is the ul containing all your tasks. This will remove the entire ul element from the DOM, thereby deleting all tasks.
Instead, you should remove only the last task added to the list. Here's how you can do it:
<!DOCTYPE html>
<html>
  <head>
    <title>To-Do List</title>
  </head>
  <body>
    <h1>To-Do List</h1>`
    <input type="text" class="task" placeholder="Enter a task">
    <button class="Add">Add Task</button>
    <button class="removeTask">Remove</button>
    <ul class="taskList"></ul>
  </body>
  <script>
    const taskList = document.querySelector(".taskList");
    const RemoveEl = document.querySelector(".removeTask");
    const addTask = document.querySelector(".Add");

    addTask.addEventListener("click", () => {
      const taskInput = document.querySelector(".task");
      const newTask = document.createElement("li");
      let task = taskInput.value;

      if (task.trim() != "") {
        newTask.innerText = task;
        taskList.appendChild(newTask);
        taskInput.value = "";
      }
    });

    RemoveEl.addEventListener("click", () => {
      if (taskList.lastChild) {
        taskList.lastChild.remove();
      }
    });
  </script>
</html>

This updated script adds an event listener to the Remove button outside of the Add button's event listener. When the Remove button is clicked, it checks if there is a last child element in the task list (the last task added). If there is, it removes that element, leaving the rest of the task list intact.
Question: How to solve Fatal error: Maximum execution time of 300 seconds exceeded in Drupal installation on line 171?

Fatal error: Maximum execution time of 300 seconds exceeded on line 171
I am new in the world of drupal My port no.80 is assigned to my ASP server so I changed my Apache server from 80 to 8080 in httpd.conf , BTW I am using XAMPP server I got Error "Fatal error: Maximum execution time of 300 seconds exceeded in C:\xampp\htdocs\MyDemoWebsite\core\modules\mysql\src\Driver\Database\mysql\Connection.php on line 171" while install site after Set up database in core instal Set up database Image
Maximum execution time of 300 seconds exceeded in
May be I am doing somthing wrong in Set Up Database enter image description here   I have tried by changing the port no. to 8080port no. to 8080


Answer:
Maybe you're doing it first time. So, you have confused Apache port with mysql port.

You can see, I have started Xampp, here I am running Apache, with http and https, in ports (80, and 443) now according to the availability of ports in your pc, you can change them
Now, comes the database i.e. MySQL, whose port is normally 3306, or you can change to something else, according to your availability.
During Drupal installation. The database port which you have put as 8080, will be 3306, if you have not changed it either, which you can check from your xampp control panel, as I have added screenshot.
Now, as apache is running on port 8080, then your site will run on localhost:8080/<folder-name>, by default apache port is 80 which is omitted by browser, if that changed to anything else, which requires to be mentioned on http address
Question: Where to host Django project files on deployment server

New to Django here. I have developed a minimum working django website with Postgres as database back-end and nginx/gunicorn as web server on Ubuntu linux. Currently all the files are on my laptop in ~/workspace/djangoapp/src$ in my home directory. I want to now deploy the project to GCP. Which directory, on the production server, the files would go in? It can't be my home directory on the production server. Shouldn't they go in one of the system directories like /opt?


Answer:
If you want to deploy your project on Google Cloud Platform, you should follow GCP guidelines. There are step by step guide on how to deploy and run Django app on GCP as for example running "Django on App Engine standard environment".
It would be easier to follow the GCP guides for your production server.
Question: How to increase Kubeflow Jupyter notebook image name to see the complete path

I have a deployment of Kubeflow. During creation of Jupyter Notebook, we have image name tags that are longer than that can be displayed in the  Docker image name list.  See the image list in the attached image. Here the names are short, but for our customer the repository URL is a long fqdn of the harbor registry URL.   Is there any configuration that can increase the visible text ?

Looking for a configuration to increase the visible text. Tried adding tags to the docker image, but this is only a suffix for the name.


Answer:
As I understand it, you'd like to display the repository prefix for your Jupyter images. For this, you can set to false the hideRegistry key in the Jupyter Web App ConfigMap. By default, the value of this key is true, which hides the image repository in the user interface.
Search this ConfigMap in kubeflow namespace. In Kubeflow Manifests GitHub repository you can found in spawner_ui_config.yaml file.
Question: Filling NAN values in Pandas by using previous values

I have a Pandas DataFrame in the following format.

I am trying to fill the NaN value by using the most recent non-NaN value and adding one second to the time value. For example, in this case, the program should take the most recent non-NaN value of 8:30:20 and add one second to replace the NaN value. So, the replacement value should be 8:30:21. Is there a way in Pandas to simulate this process for the entire column?


Answer:
You can convert your data to_timedelta, ffill and add 1 second:
df['col1'] = pd.to_timedelta(df['col1'])

df['col1'] = df['col1'].ffill().add(df['col1'].isna()*pd.Timedelta('1s'))

Output:
             col1
0 0 days 08:30:18
1 0 days 08:30:19
2 0 days 08:30:20
3 0 days 08:30:21
4 0 days 08:30:22

Used input:
df = pd.DataFrame({'col1': ['8:30:18', '8:30:19', '8:30:20', np.nan, '8:30:22']})

converting back to strings
Use a custom function:
def to_str(s):
    h,m = s.dt.total_seconds().divmod(3600)
    m,s = m.divmod(60)
    return (h.astype(int).astype(str).str.zfill(2)
            +':'+
            m.astype(int).astype(str).str.zfill(2)
            +':'+
            s.astype(int).astype(str).str.zfill(2)
            )
    
df['col1'] = to_str(df['col1'])

Output:
       col1
0  08:30:18
1  08:30:19
2  08:30:20
3  08:30:21
4  08:30:22
Question: Can't use PHPickerViewController delegate with KMM

I'm trying to use the UiKit API PHPickerViewController using KMM and Compose for iOS.
import androidx.compose.runtime.Composable
import androidx.compose.ui.interop.LocalUIViewController
import platform.PhotosUI.PHPickerConfiguration
import platform.PhotosUI.PHPickerViewController
import platform.PhotosUI.PHPickerViewControllerDelegateProtocol
import platform.darwin.NSObject

@Composable
actual fun pickerController() {
    val uiViewController = LocalUIViewController.current
    val configuration = PHPickerConfiguration()
    val pickerController = PHPickerViewController(configuration)
    val pickerDelegate = object : NSObject(), PHPickerViewControllerDelegateProtocol {
        override fun picker(picker: PHPickerViewController, didFinishPicking: List<*>) {
            println("didFinishPicking: $didFinishPicking")
            picker.dismissViewControllerAnimated(flag = false, completion = {})
            uiViewController.dismissModalViewControllerAnimated(false)
        }
    }

    pickerController.setDelegate(pickerDelegate)
    uiViewController.presentViewController(pickerController, animated = false, completion = null)
}

This displays the image picker:

Unfortunately, when clicking on Cancel, the delegate callback is not called, and I get the following message on the console:
[Picker] PHPickerViewControllerDelegate doesn't respond to picker:didFinishPicking:

Is it possible to implement the callback in Kotlin?
What am I missing?


Answer:
Since pickerDelegate is NSObject, it's lifecycle follows ObjC rules, not KMM memory model.
So as soon as the execution leaves composable block, this objects gets released - as setDelegate takes it as weak reference.
You can fix it by storing it using remember.
Also using your function is dangerous because you're gonna call presentViewController on each recomposition - e.g. if some of your reactive data changes on the calling side.
You can update it to return an action that will present it, but store delegate and the action itself using remember:
@Composable
actual fun rememberOpenPickerAction(): () -> Unit {
    val uiViewController = LocalUIViewController.current
    val pickerDelegate = remember {
        object : NSObject(), PHPickerViewControllerDelegateProtocol {
            override fun picker(picker: PHPickerViewController, didFinishPicking: List<*>) {
                println("didFinishPicking: $didFinishPicking")
                picker.dismissViewControllerAnimated(flag = false, completion = {})
            }
        }
    }

    return remember {
        {
            val configuration = PHPickerConfiguration()
            val pickerController = PHPickerViewController(configuration)
            pickerController.setDelegate(pickerDelegate)
            uiViewController.presentViewController(pickerController, animated = true, completion = null)
        }
    }
}

Usage:
Button(onClick = rememberOpenPickerAction()) {

}