Edited values in row is not getting saved if we scroll down in UI Grid in Angular

I am experincing one issue where I am updating some randows rows in UI grid and then scroll down. When the request lands on my UI method –

gridApi.edit.on.afterCellEdit($scope, function(rowEntity, colDef, newValue, oldValue) {
if (newValue !== oldValue)
the newValue is completely different than what I have edited and oldValue is the correct one.

I tried using gridApi.core.on.scrollEnd($scope, function(grid, scrollEvent)
but everytime scrollEvent is coming as undefined.

Language Input Method Editor Software is interfering with my input validation

I have this javascript function for allowing numeric input only

window.addNumericInputValidation = function (elementId) {
    var $element = $("#" + elementId);

    // First remove any existing handlers to prevent stacking
    $element.off("keydown.numericValidation");
    $element.off("paste.numericValidation");

    // Handle keydown for typing
    $element.on("keydown.numericValidation", function (e) {
        console.log("key code", e.keyCode);
        // Allow: backspace, delete, tab, escape, enter, etc.
        if ($.inArray(e.keyCode, [46, 8, 9, 27, 13]) !== -1 ||
            // Allow: Ctrl+A, Ctrl+C, Ctrl+V, Ctrl+X
            (e.keyCode === 65 && (e.ctrlKey || e.metaKey)) ||
            (e.keyCode === 67 && (e.ctrlKey || e.metaKey)) ||
            (e.keyCode === 86 && (e.ctrlKey || e.metaKey)) ||
            (e.keyCode === 88 && (e.ctrlKey || e.metaKey)) ||
            // Allow: home, end, left, right
            (e.keyCode >= 35 && e.keyCode <= 39)) {
            return;
        }

        // Ensure that it's a number and stop the keypress if not
        if ((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) &&
            (e.keyCode < 96 || e.keyCode > 105)) {
            e.preventDefault();
        }
    });

    // Handle paste events
    $element.on("paste.numericValidation", function (e) {
        // Get pasted data via clipboard API
        var clipboardData = e.originalEvent.clipboardData || window.clipboardData;
        var pastedData = clipboardData.getData('Text');

        // Check if pasted data contains only numbers
        if (!/^d*$/.test(pastedData)) {
            e.preventDefault();
        }
    });
};

The problem happens when I turn on Unikey – which is a Vietnamese input editor for Vietnamese characters (For example the software will convert “dd” into the vietnamese “đ”). If Unikey is on, when I type numbers, it works normally but if i type “d” twice, it starts deleting the the number input.

After debugging, I found out that after you type “d” key twice, Unikey will insert 2 delete key and one “đ” key, to replace “dd” with “đ”, and because my validation don’t allow non-numeric characters, only the deletion happens.

This is the console after I input “d” twice

key code 68 (for 'd')
key code 231 (for 'đ')
key code 8 (for delete)
key code 8 (for delete)
key code 231 (for 'đ')

I can’t really tell the customer to turn off their language editor software so what are my options here?

How to interpret “numFmt” in ExcelJS to display cell values as HTML text?

I have read an Excel file using the ExcelJS library, but I am unable to interpret numFmt in a way that displays the cell value as it appears in Excel.

For example, I have different number formats applied to cells, such as:

  • "#,##0.00" ? Expected: 1,234.56
  • "0%" ? Expected: 50% for a cell value of 0.5
  • "0.00E+00" ? Expected: 1.23E+03 for a value of 1234.56

However, when reading these cells using ExcelJS, I often get only the raw value and the format string separately, without automatic interpretation.

const workbook = new ExcelJS.Workbook();
await workbook.xlsx.readFile('sample.xlsx');
const worksheet = workbook.getWorksheet(1);
const cell = worksheet.getCell('A1');

console.log(cell.value);   // Raw value: 1234.56
console.log(cell.numFmt);  // Format string: "#,##0.00"

Is there a way to correctly interpret and convert any numFmt formats using ExcelJS so that the displayed value reflects the formatting applied in Excel? Any guidance or examples would be greatly appreciated!

ORA-00001: unique constraint (SDESERP.UK_CODELKUP) violated, django inlineformset

Hi I am trying to create a form with parent-child models using python Django Inlineformset_factory but when I am trying to update the child, its giving me unique constraint error. Here I am sharing my model code, forms code, views code. I am trying to solve this issue since last two days but not succeeded. please help me to solve the issue.

Models code–>

class CodeList(models.Model):
    listname = models.CharField(db_column='LISTNAME', max_length=20, primary_key=True)
    description = models.CharField(db_column='DESCRIPTION', max_length=100)
    adddate = models.DateField(db_column='ADDDATE')
    addwho = models.CharField(db_column='ADDWHO', max_length=20)
    editdate = models.DateField(db_column='EDITDATE')
    editwho = models.CharField(db_column='EDITWHO', max_length=20)

    class Meta:
        db_table ='CODELIST'

    def __str__(self):
        return f"{self.listname}"
    
class CodeLkup(models.Model):
    listname = models.ForeignKey(CodeList, db_column='LISTNAME', on_delete=models.CASCADE)
    code = models.CharField(db_column='CODE', max_length=30, primary_key=True) #, 
    eng_desc = models.CharField(db_column='ENG_DESC', max_length=250)
    bl_desc = models.CharField(db_column='BL_DESC', max_length=250, blank=True)
    adddate = models.DateField(db_column='ADDDATE')
    addwho = models.CharField(db_column='ADDWHO', max_length=20)
    editdate = models.DateField(db_column='EDITDATE')
    editwho = models.CharField(db_column='EDITWHO', max_length=20)

    class Meta:
        db_table = 'CODELKUP'
        unique_together = ('listname', 'code')
    
    def __str__(self):
        return f"{self.code}-{self.eng_desc}"

forms code–>


    class CodeListForm(forms.ModelForm):
        class Meta:
            model = CodeList
    
            fields = ['listname','description']
    
            widgets ={
                'listname' : forms.TextInput(attrs={'class' : 'form-control form-control-sm', 'autocomplete' : 'off'}),
                'description' : forms.TextInput(attrs= {'class' : 'form-control form-control-sm' , 'autocomplete' : 'off'})
            }        
    
        def __init__(self, *args, **kwargs):
            is_edit = kwargs.pop('is_edit', False)
            self.request = kwargs.pop('request', None)
    
            super(CodeListForm, self).__init__(*args, **kwargs)
    
            if is_edit:
                self.fields['listname'].widget.attrs['readonly']=True
        
        def save(self, commit=True):
            codelist = super().save(commit=False)
    
            userid = self.request.session.get("UserId")
    
            if self.instance.pk and CodeList.objects.filter(pk=self.instance.pk).exists():
                codelist.editdate = timezone.now()
                codelist.editwho = userid
            else:
                codelist.adddate = timezone.now()
                codelist.addwho = userid
                codelist.editdate = timezone.now()
                codelist.editwho = userid
            
            if commit:
                codelist.save()
            return codelist   
    
    class CodeLkupForm(forms.ModelForm):
        class Meta:
            model = CodeLkup
            exclude = ['listname']
    
            fields = ['code', 'eng_desc', 'bl_desc']
            widgets = {
                'code': forms.TextInput(attrs={'class': 'form-control form-control-sm', 'autocomplete': 'off'}),
                'eng_desc': forms.TextInput(attrs={'class': 'form-control form-control-sm', 'autocomplete': 'off'}),
                'bl_desc': forms.TextInput(attrs={'class': 'form-control form-control-sm', 'autocomplete': 'off', 'dir': 'rtl'}),
            }
    
        def __init__(self, *args, **kwargs):
            self.is_edit = kwargs.pop('is_edit', False)
            self.request = kwargs.pop('request', None)
            #self.parent_instance = kwargs.pop('parent_instance', None)
            super().__init__(*args, **kwargs)
    
            # Only disable code field if this is an existing object
            if self.is_edit:
                self.fields['code'].widget.attrs['readonly']=True
    
        def save(self, commit=True):
            codelkup = super().save(commit=False)
            userid = self.request.session.get("UserId") if self.request and hasattr(self.request, 'session') else None
            
            if self.instance.pk:
                print("a")
                codelkup.instance = self.instance
                codelkup.editdate = timezone.now()
                codelkup.editwho = userid
            else:
                print("b")
                codelkup.adddate = timezone.now()
                codelkup.addwho = userid
                codelkup.editdate = timezone.now()
                codelkup.editwho = userid
                
            if commit:
                codelkup.save()
            return codelkup
    
    
    class CustomCodeLkupFormSet(BaseInlineFormSet):
        def __init__(self, *args, **kwargs):
            #form_kwargs = kwargs.pop('form_kwargs', {})
            form_kwargs = kwargs.pop('form_kwargs', {})
            self.request = form_kwargs.get('request', None)
            self.is_edit = form_kwargs.get('is_edit', False)
            #kwargs['form_kwargs'] = kwargs.pop('form_kwargs', {})
            kwargs['form_kwargs'] ={'request': self.request, 'is_edit': self.is_edit}
            #kwargs['form_kwargs'].update({'request': self.request, 'is_edit': self.is_edit})
            super().__init__(*args, **kwargs)
    
    
    CodeLkupFormSet = inlineformset_factory(
        CodeList,
        CodeLkup,
        form=CodeLkupForm,
        formset=CustomCodeLkupFormSet,
        extra=1,
        can_delete=True
    )

views code–>


    def edit_system_codes(request, listname):
        is_edit = True
        codelist = get_object_or_404(CodeList, listname=listname)
        instance = codelist
        codelkup =CodeLkup.objects.filter(listname=listname)
    
        if request.method == 'POST':
            form = CodeListForm(request.POST or None, request=request, instance=codelist, is_edit=is_edit)
            formset = CodeLkupFormSet(request.POST or None, instance=codelist, form_kwargs={
                'request': request, 
                'is_edit': True})
    
            if form.is_valid() and formset.is_valid():
                try:
                    master = form.save()
                    formset.instance = master
                    formset.save()
    
                    messages.success(request, _("LBL_SAVED"))
                    return redirect('codes_list')
                
                except IntegrityError as e:
                    error_msg = str(e)
                    print(error_msg)
                    messages.error(request, f'{{ error_msg }}')
                except DatabaseError as e:
                    messages.error(request, f'Database error occured: {str(e)}')
                except Exception as e:
                    messages.error(request, f'unexpected error: {str(e)}')
        else:
            form = CodeListForm(request=request, is_edit=is_edit, instance=codelist)
            formset = CodeLkupFormSet(instance=codelist, form_kwargs={
                'request': request,
                'is_edit': True})
        
        return render(request, 'system_codes/edit_system_codes.html', {'form' : form, 'formset' : formset})

html code–>

<div class="row p-1 pt-0"><!--justify-content-center-->
    <div class="col-md-10">
        <div class="card bg-light">
            <div class="card-header p-1">
                <i class="fa-solid fa-plus fa-lg"></i> {% trans "LBL_EDIT_CODES" %}
            </div>
            <form action="" method="POST" id="edit_system_codes_form">
            {% csrf_token %}
                <div class="card-body p-1">
                    <!--{{ form.as_p }}-->
                     <div class="row mb-2">
                        <div class="col-md-4">
                            <label class="form-label">{% trans "LBL_LISTNAME" %}<span Class="text-danger">*</span></label>
                            {{ form.listname }}
                        </div>
                     </div>
                     <div class="row mb-2">
                        <div class="col-md-10">
                            <label class="form-label">{% trans "LBL_DESCRIPTION" %}<span Class="text-danger">*</span></label>
                            {{ form.description }}
                        </div>
                     </div>
                     {{ formset.management_form }}
                     <div class="row">
                        <div class="col-md-12 text-center">
                            <h4>{% trans "LBL_CODELKUP_DETAIL" %}</h4>
                        </div>
                     </div>
                     <div class="row">
                        <div class="col-md-12">
                            <table class="table table-bordered custom-table">
                                <thead class="table-light">
                                    <tr>
                                        <th class="align-middle">{% trans "LBL_CODE" %}</th>
                                        <th class="align-middle">{% trans "LBL_DESCRIPTION" %}</th>
                                        <th class="align-middle">{% trans "LBL_BL_DESCRIPTION" %}</th>
                                        <th>
                                            <button type="button" class="btn btn-sm btn-success"
                                                title="{% trans 'LBL_ADD' %}">
                                                <i class="fa-solid fa-plus"></i>
                                            </button>
                                        </th>
                                    </tr>
                                </thead>
                                <tbody>
                                    {% for f in formset %}
                                    <tr>
                                        <td style="width:20%">{{ f.code }}</td>
                                        <td style="width:40%">{{ f.eng_desc }}</td>
                                        <td style="width:40%">{{ f.bl_desc }}</td>
                                        <td>
                                            <button type="button" class="btn btn-sm btn-danger"
                                                title="{% trans 'LBL_DELETE_BUTTON' %}">
                                                <i class="fa-solid fa-trash"></i>
                                            </button>
                                        </td>
                                    </tr>
                                    {% endfor %}
                                </tbody>
                            </table>
                        </div>
                     </div>
                </div>
                <div class="card-footer text-end pb-0">
                    <button type="button" id="edit_system_codes_save_button" class="btn btn-success">{% trans "LBL_SAVE_BUTTON" %}</button>
                    <a href="{% url 'codes_list' %}" class="btn btn-secondary">{% trans "LBL_CANCEL_BUTTON" %}</a>
                </div>
            </form>
        </div>
    </div>
</div>
{% include 'loader.html' %}
javascript code-->
<script>
    $(document).ready(function(){
        hideLoader();

        $('#edit_system_codes_save_button').click(function(){
            showLoader();
            document.getElementById('edit_system_codes_form').submit();
        })
    });
</script>

How to get a specific field value (e.namedValues) in Google Forms script?

I’m just starting to learn how to write a script for Google Forms. I’ve spent several days trying to solve this problem, but I still can’t figure it out. Can someone help me?

I’m trying to extract the value from a field called “notificar” in the form responses so I can use it to send an email later. But I can’t see what I’m doing wrong here.

Here is the relevant part of the code:

const datos = e.namedValues || {};
  const claveNotificar = Object.keys(datos).find(k => k === "notificar");
  const correoDestino = claveNotificar ? datos[claveNotificar][0] : "";

For context, the form has a question exactly named “notificar”, and I expect that value to be in e.namedValues after the form is submitted.

But when I check the logs, “claveNotificar” is undefined and “correoDestino” ends up empty. Am I missing something in how Google Forms passes data to the trigger?

Thank you in advance!

State management patterns in vanilla JavaScript?

When managing state in vanilla JavaScript—without using frameworks like React or Vue—which design pattern is most suitable.

My requirements are:

  • Reactivity
  • Time Travel (Undo/Redo)
  • Testing and Debugging should be easy
  • Single Source of Truth: Maintain state in one central location
  • Immutable Updates: Create new objects instead of mutating existing ones
  • Separation of Concerns: Keep state management separate from UI code
  • Performance: Only update what’s necessary when state changes

Currently I am considering Flux-like Pattern and Redux-like Pattern.

But can not make up my mind as i am not sure if there is a better solution than this.

Please help.

How to get the following jquery the second onclick to work

The following code below uses “off” to eleminate multiple tiggers on click messing up some other code. The function with “#del-bmarks” only excutes on click once and never again unless the web page is refreshed. What am I doing wrong? Please advise!

 $(document).ready(function() {

    $(document).off().on("click", ".ai-link", function () { 

     //CODE HERE   

    }):
    
    $(document).on("click", "#del-bmarks", function () {

    //EXECUTES ONLY ONCE ONCLICK    

    };
  });

Understanding Asynchronous Programming in JavaScript with Promises and Async/Await

I’m trying to understand how asynchronous programming works in JavaScript, specifically using Promises and async/await. I have a basic understanding of callbacks, but I’m struggling to grasp how Promises and async/await improve asynchronous code readability and error handling.

Could someone provide a clear example of how to use Promises and async/await in a simple scenario, such as fetching data from an API? I’m also interested in understanding how error handling works in both cases.

Here’s what I’ve tried so far:

Using Promises:

fetch('https://api.example.com/data')
  .then(response => response.json())
  .then(data => {
    console.log(data);
  })
  .catch(error => {
    console.error('Error:', error);
  });

Using async/await:

async function fetchData() {
  try {
    const response = await fetch('https://api.example.com/data');
    const data = await response.json();
    console.log(data);
  } catch (error) {
    console.error('Error:', error);
  }
}

fetchData();

I’m not sure if I’m using these correctly or if there’s a better way to handle asynchronous operations. Any guidance or best practices would be appreciated.

Bootstrap 5 tooltips not working when added after document ready

I have a page that loads a javascript file. At the top of the javascript file I am declaring my constants for Bootstrap 5 tooltips:

const tooltipTriggerList = document.querySelectorAll('[data-bs-toggle="tooltip"]');
const tooltipList = [...tooltipTriggerList].map(tooltipTriggerEl => new bootstrap.Tooltip(tooltipTriggerEl));

On the document ready, I am using moment.js to compare today versus the due date of a particular event. In a javascript function, if the event date 2 days or closer to today, then a span element is added to the page, with this markup:

$("#warning"+i).html('<span class="exp-warn" data-bs-toggle="tooltip" data-bs-title="This pick will expire soon." data-bs-placement="right"><i class="bi bi-exclamation-diamond-fill"></i></span>');

The javascript logic is working correctly and displaying the event’s warning, but the tooltip itself is not displaying when I hover over the element.

Is there any code I need to add for tooltips that are added to the page afterr or during the document ready?

Not sure what I’m doing wrong to implement a setTimeout for this Array

I tried multiple setups with this code, and I cannot find a solution any help would be appreciated.

function birdPics() {
     var ads = new Array(5);
      ads[0] = "15 images/bluejay.jpg";
      ads[1] = "15 images/falcon.jpg";
      ads[2] = "15 images/hawk.jpg";
      ads[3] = "15 images/owl.jpg";
      ads[4] = "15 images/prariewarbler.jpg";
      
      var ads = document.getElementById("animalPics");

I tried a few different implementations of the ‘setTimeout’, and nothing seemed to apply the changes made.

UG Print Workaround

As you might or might not know: the printing function of ultimate guitar has become a pro function and users can’t even print their own freely contributed material any more. Another case of enshittification. So I’m working on a workaround.

I had some success with bookmarklets (bookmark with javascript). It allows me to create my own print button and if I’m on a tab I can just click the bookmarklet to print. Here is the prettified code:

(() => {
    let t = document.title.substring(0, document.title.length - 22).replace("^(?:[0-9]*)", ""),
        w = window.open("", "PRINT", "height=400,width=600");
    w.document.write("<html><head><title>" + t + "</title></head><body><h2>" + t + "</h2><pre>");
    document.getElementsByTagName("pre")[0].innerHTML.replace(/<span ?[^>]*>(.*?)</span>/g, "$1").split(/r?n/).forEach(x => {
        if (x.match(/^(?:(?:s+|^)[CDEFGAB](?:##?|bb?)?(?:maj|min|m|sus|aug|dim)?[0-9]*(?:(?:add|##?|bb?)[0-9]*)*)+s*(?[xX]?[0-9]*[xX]?)?s*$/)) {
            w.document.write('<span style="font-weight:bold;">' + x + "</span>n")
        } else {
            w.document.write(x + "n")
        }
    });
    w.document.write("</pre></body></html>")
    w.document.close()
    w.focus()
    w.print()
    w.close()
})()

Logic

  1. The original document title is '(' #notifications ')' SONG_TITLE ('CHORDS'|'TABS') 'by' Artist '@ Ultimate-Guitar.com'. So I’m removing the number of notifications in front and the stuff in the end to use it as title and filename.

  2. Create new site with title and pre with chords.

  3. Remove spans from pre (some chords are in spans, some not, pretty random)

  4. Match lines with chords on them and make them bold.

  5. Print.

Problems

  1. Bolding the lines only works in Chrome, works in Firefox and Brave, but no bold chords, worked in Opera GX without the w.close(), doesn’t work at all in Edge. Can you help me make it more browser independent?

  2. The regex matching lines with chords on it is okay for most chords, but it is not perfect. It shouldn’t just work on lines, but detect individual chords (it has to because people write stuff like “fade”, “repeat”, “N.C.” and other stuff in-between the chords. But on the other hand you don’t want to make every “A” bold, probably need something with a lot of look-ahead and -behind to decide whether a potential chord symbol is used as such. Do you have better suggestions?

Testing Firebase GoogleAuthProvider on Localhost

Feeling a bit stuck after reading a ton of articles and following a bunch of other Stack answers (none of which have worked, most of which don’t relate to my exact problem).

I’ll describe the problem and behavior first, then talk through what I’ve tried so far, and then show the code.

Problem

Doing development locally using Vue/Vite with Firebase tools installed including the emulators and am adding Google signin. The behavior seems to be that both signInWithRedirect and signInWithPopup really want to use https for their URLs and nothing I can do has convinced them to do otherwise. This results in errors for both telling me that they cannot establish a secure connection (either in the redirect, because it tries to redirect to https://localhost:5173/, or it wants to popup an iframe and assign the iframe uri to https://localhost:5173). The host and port match what my project is running on, of course.

What I have tried

Oh, a lot of things. I may be forgetting some, but the most obvious ones include:

  • Ensuring that my Google OAuth project has whitelisted http://localhost:5173 as both a source and redirect URI
  • Ensuring that Firebase is connected to that Google Oauth project
  • Ensuring that my .env.local has an entry for the auth_domain to be overridden and that it’s successfully being overridden (though, note if I try and add the protocol it strips out the : so that it becomes https://http//localhost:5173/…)
  • Trying to pass the Auth emulator URL as a string to the signInWith<X>() function as described in one of the Firebase docs I found, this resulted in a firebase auth argument error, and looking at the actual API documentation, it doesn’t appear supported (or if it is, it’s not documented there).
  • Clearing the browser cache did nothing to affect any of this behavior (not sure why it would, given what’s happening, but it was one of the Stack recommendations that I found).

Code

The code I’ve tried both ways, but here you go:

        const auth = getAuth(app);
        const provider = new GoogleAuthProvider();
        console.log(import.meta.env.VITE_FIREBASE_AUTH_DOMAIN)
        // signInWithRedirect(auth, provider)
        // .then((result) => {
        //     console.log(result)
        // }).catch((err) => {
        //     console.log(err.message)
        // });

        signInWithPopup(auth, provider)
            .then((result) => {
                const credential = GoogleAuthProvider.credentialFromResult(result);
                const token = credential.accessToken;
                const user = result.user;
                console.log(JSON.stringify(user));
            }).catch((error) => {
                console.error(error.message);
            })

Is there a way to get the GoogleAuthProvider to recognize that I’m working on Localhost and therefore will never be able to work with HTTP?

Thanks!

Quantum metrics integration [closed]

I am using angular UI tool and I want to integrate Quantum Metrics that will help with live feedback and recorded replay sessions.

Could you please help me how to implement quantum metrics in angular solution.

Thanks in advance.