satoshi-2000/llms-suitable huggingface dataset:
Question: Count exact occurrences of number in array and return True or False

I have two arrays
Arr1 = [1,1,1,2,2,2,3,3]  and Arr2 =[1,1,2,1]
Comparing both arrays should return True as there are same occurrences of no. 1.
However If Arr2 = [1,1,2] it should return false as the no. Of occurrences of 1 or 2 don't match with the no. Of occurrences of 1 and 2 in Arr1
Even Arr2 = [1,1,2,3,1] should return True.
Thanks in advance! Cheers
I tried this but doesn't work for other instances.
function allElementsPresent(first, second) {
  return second.every((element) => first.includes(element));
}



Answer:
I believe I understand what you want to accomplish. You want to see if the number of occurrences in the second array matches the first. If that's the case, I've used this answer as a basis


function allElementsPresent(first, second, matchAll = false) {
  if (first.length > 0 && second.length === 0) return false;
  var counts1st = {};
  var counts2nd = {};

  for (var num of first) {
    counts1st[num] = counts1st[num] ? counts1st[num] + 1 : 1;
  }
  for (var num of second) {
    counts2nd[num] = counts2nd[num] ? counts2nd[num] + 1 : 1;
  }

  for (var count in counts2nd) {
    if (matchAll && (!counts1st[count] || counts1st[count] !== counts2nd[count])) return false;
    if (!matchAll && (counts1st[count] && counts1st[count] === counts2nd[count])) return true;
  }
  return matchAll ? true : false;
}
Question: IdentityServer - how to get grant_type from within a Protected API?

I have an API protected by IdentityServer with an associated allowed scope.
I have two Identity Server clients with permission to access that allowed scope - one accepts client_credentials (for machine-machine operations), and the other accepts authorization_code (for user-machine operations).
Within the API itself, how can I determine whether a given client has been authorised by client_credentials or by authorization_code?
I can find a few references to the "gty" claim but this is not included in tokens generated by identity server. Is there a way to force IdentityServer to include this claim, or is there some other convention for how to identify whether a request originated from a machine client, or from a user?


Answer:
you can have different clientID and client definitions for the different use cases (Authorization code flow cs. client credentials flow).
Then in the client definition for each one, you can add Client Claims, that will be included in the access token and will be included for any user.
See https://docs.duendesoftware.com/identityserver/v6/reference/models/client/#token
There settings there are related to this:

Claims

Allows settings claims for the client (will be included in the access token).

AlwaysSendClientClaims

If set, the client claims will be sent for every flow. If not, only for client credentials flow (default is false)

AlwaysIncludeUserClaimsInIdToken

When requesting both an id token and access token, should the user claims always be added to the id token instead of requiring the client to use the userinfo endpoint. Default is false.

ClientClaimsPrefix

If set, the prefix client claim types will be prefixed with. Defaults to client_. The intent is to make sure they don’t accidentally collide with user claims.
Question: React Native Component + Navigation with Paramameters not working error undefined is not a method

I have Reactive Component which passes data from one screen to another..., trying to call second component via Navigate(name,params) method. but it gives an error saying "undefined method is not a method". Copying component code below. Guid me to clear the error.
import React from 'react';
import {
  StyleSheet,
  Text,
  View,
  Pressable,
} from 'react-native';

import { NavigationContainer } from '@react-navigation/native';

export default function ScreenA(navigation:any) {
    const onPressHandler = () => {
        navigation.navigate("Screen_B",{ ItemName: 'Item from ScreenA', ItemId: 12 });
        // navigation.navigate("Screen_B");
    }



Answer:
Destructure navigation from function parameter:
import React from 'react';
import {
  StyleSheet,
  Text,
  View,
  Pressable,
} from 'react-native';

import { NavigationContainer } from '@react-navigation/native';

export default function ScreenA({navigation}) { // wrap navigation with curly brackets
    const onPressHandler = () => {
        navigation.navigate("Screen_B",{ ItemName: 'Item from ScreenA', ItemId: 12 });
    }
Question: Why mocking HuggingFace datasets library does not work?

I have a Python function that uses the HuggingFace datasets library to load a private dataset from HuggingFace Hub.
I want to write a unit test for that function, but it seems pytest-mock does not work for some reason. The real function keeps getting called, even if the mock structure should be correct.
This is the main function:
def load_data(token: str):
    dataset = load_dataset("MYORG/MYDATASET", use_auth_token=token, split="train")
    return dataset

And this is the test function I wrote:
def test_data(mocker):
    # Mocked data
    token_test = "test_token"
    mocked_dataset = [
        {'image': [[0.5, 0.3], [0.7, 0.9]], 'timestamp': datetime.date(2023, 1, 1)},
    ]
    mocker.patch('datasets.load_dataset', return_value=mocked_dataset)

    result = load_data(token_test)

    assert len(result) == 1

Could it be that there are some "unmockable" libraries which do stuff under the hood and make their functions impossible to stub?


Answer:
The official Python documentation has this part: where-to-patch.
If your module is called my_module, and it does from datasets import load_dataset then you should patch mocker.patch('my_module.load_dataset' so that your module is using the mock.
Patching datasets.load_dataset might be too late, since if the import in your module happened before that instruction, it has no effect.
Question: Is there an escape code to pause the terminal screen refresh?

I have an application that displays images using 8-bit ANSI-art. This is handy for viewing images on a remote machine via SSH. When the viewer starts, it replaces all the 8-bit palette values from 16-255 with my standard values. This runs fine on the Mac terminal, but the xterm display flickers because it is trying to refresh while it is still executing these 240 commands.
I get the same thing when the program exits, and I have to reset the colours.  Here is the code for resetting the palette when the program exits.
for (int N=16; N<256; ++N) printf("\e]104;%d\a", N);
I can see the colours changing in the terminal as it runs.
I have not found an escape code that resets the whole palette. Sending Ctrl-C resets some things but not the palette. All the examples I have found use a loop like this. It would be nice to find a reset escape sequence if there is one, but I will also need a way to pause the screen refresh until the commands have finished.
I tried running all the escape sequences into one big string and submitting all of them at once with puts(). That did not do the trick.
I hoped to find an escape sequence that pauses the screen refresh, and another that un-pauses it. It seems like something that ought to be there, and I am not seeing it. Or, if we know for sure that no such escape sequences exist, then I can stop looking. There may be other ways of fixing this other than escape codes. However, the application is handiest when working remotely, so I want it to work on whatever terminal is running at the time, not just xterm. I can ignore the flickering if I have to.
PS:
I have a workaround. Xterm supports 24-bit Truecolor. I can use that and not change the 8-bit palette.


Answer:
Not what the title asks for, but enabling the alternative screen buffer is a fix.
Print "\e[?1049h to enable when the program starts and and "\e[?1049l to disable.
The Wikipedia entry says little more than that, so it is easy to ignore. Enabling the alternative screen buffer means the application works with a terminal-sized window of characters. This is probably what an interactive terminal program needs rather than add all the screen refreshes to the current scrolling terminal buffer. Disabling restores the terminal to its previous state.
Question: How to add the data of this table in markers (pop-up) on map?

I imported this table from Excel into Jupyter. I was using pandas for this. But now I want to mark markers with cities from table below on my map with  popups with the data from colognes A1,A2,A3 and I don't know how to do this.
Example: I press on a definite marker and after this the popup appears with this data from colognes A1,A2,A3.
Image 1:

Image 2:

Can you tell me the corresponding code for this operation?


Answer:
To display the pop-up in tabular form at each location, a loop process is performed on each row of the data frame, converting one row from a series to a data frame, and then transposing it. I also adjust the width of the data frame.
import pandas as pd
import io
import folium

data = '''
Name A1 A2 A3 LAT LON
"Malibu Beach" 0.63 0.55 0.95 34.03194 -118.698387
Commerce 0.17 0.45 0.25 34.00031 -118.159770
"Long Beach" 0.19 0.21 0.09 33.77171 -118.181310
'''
df = pd.read_csv(io.StringIO(data), delim_whitespace=True)

import folium

m = folium.Map([df.LAT.mean(), df.LON.mean()], zoom_start=8)

for i in range(len(df)):
    html = df.loc[i,['Name','A1','A2','A3']].to_frame().T.to_html(
        classes="table table-striped table-hover table-condensed table-responsive"
    )
    popup = folium.Popup(html, max_width=500)
    folium.Marker([df.iloc[i]['LAT'], df.iloc[i]['LON']], popup=popup).add_to(m)

m
Question: RelativeLayout problem: how to set RecyclerView not to overlap a Button on bottom

This is my activity: SearchView on top, RecyclerView on middle, and a Button at bottom
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/app_background"
    tools:context=".ui.home.customer.CustomerListActivity">

    <androidx.appcompat.widget.SearchView
        android:background="@color/white"
        android:layout_marginLeft="20dp"
        android:layout_marginRight="20dp"
        android:layout_marginTop="20dp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/searchCustomer" />

    <androidx.recyclerview.widget.RecyclerView
        android:layout_marginLeft="20dp"
        android:clipToPadding="false"
        android:layout_marginRight="20dp"
        android:layout_marginTop="20dp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/searchCustomer"
        tools:listitem="@layout/row_item_customer"
        android:id="@+id/rvCustomers" />

    <com.google.android.material.button.MaterialButton
        android:id="@+id/btnAddCustomer"
        android:layout_marginLeft="20dp"
        android:layout_marginRight="20dp"
        android:layout_alignParentBottom="true"
        android:layout_marginBottom="20dp"
        android:textColor="@color/text_blue_1"
        app:backgroundTint="@color/white"
        android:layout_width="match_parent"
        android:layout_height="53dp"
        android:text="Add Customer" />

</RelativeLayout>


Turns out it doesn't work as I expected, because the RecyclerView overlaps/crosses the Button. I want the RecyclerView to "stay" on top of the Botton. How to fix this?


Answer:
Just add following line in recyclerView
android:layout_above="@id/btnAddCustomer"
Question: Writing a large collection of lists to a txt file in Python

I am trying to save links to photos in a topic on an internet forum in a txt file. I tried many ways, but the links of one page are saved in a txt file, and when the loop goes to the next page of the topic, the previous links are deleted and new links are replaced! I want to have all the links together.
This is my code:
from bs4 import BeautifulSoup
import requests

def list_image_links(url):
    response = requests.get(url)

    soup = BeautifulSoup(response.content, "html.parser")
    
    # Separation of download links
    image_links = []
    for link in soup.find_all('a'):
        href = link.get('href')
        if href is not None and 'attach' in href and href.endswith('image')==False:
            image_links.append(href)
    
    # Writing links in a txt file
    with open('my_file.txt', 'w') as my_file:
        my_file.write('image links:' + '\n')    
        for branch in image_links:
            my_file.write(branch + '\n')
            print('File created')
    
# Browse through different pages of the topic
i = 0
while i <= 5175:
    list_image_links(f'https://forum.ubuntu.ir/index.php?topic=211.{i}')
    i = i+15

It is clear from the comments what each section does.
Thank you in advance for your help.


Answer:
You need to append to the file. This can be achieved by using 'a' instead of 'w' as an argument to open().
When using 'w' a file will be created if it does not exist and it will always truncate the file first, meaning it will overwrite its contents. With 'a' on the other hand the file will also be created if it does not yet exists, but it won't truncate but instead append to the end of the file if it already exists, meaning the content will not be overridden.
See Python docs.
So for your example the line
with open('my_file.txt', 'w') as my_file:

would need to be changed to:
with open('my_file.txt', 'a') as my_file:
Question: change database based on request origin using expressjs & prisma

I want to change database dynamically based on request origin.
I create a globalMiddleware which is called on every routes.


// middlwares/global.middleware.js

import DBController from "../controllers/db.controller.js";
import { db1, db2 } from "../prisma/prismaClient.js";
export default (req, res, next) => {
  const dbcontroller = DBController();
  const domain = req.get("origin");
  switch (domain) {
    case "http://localhost:3000":
      dbcontroller.setDB(db1);
      break;
    case "http://localhost:3001":
      dbcontroller.setDB(db2);
      break;
  }
  next();
};



but when i set the db inside DBController by calling dbcontroller.setDB() method and  finally calling this.DB it is undefined.


// controller/db.controller.js

import autoBind from "auto-bind";
class DBController {
  constructor() {
    this.DB;
    autoBind(this);
  }
  setDB(prismaClient) {
    this.DB = prismaClient;
  }
}
export default DBController;





// conrtoller/controller.js

import { generateResponse } from "./../util/public.util.js";
import DBController from "./db.controller.js";
import autoBind from "auto-bind";
import createError from "http-errors";
class Controller extends DBController {
  constructor() {
    super();
    this.generateResponse = generateResponse;
    this.createError = createError;
    autoBind(this);
  }
}
export default Controller;





// controller/article.controller.js

import Controller from "./controller.js";
class ArticleController extends Controller {
  async get(req, res, next) {
    try {
      const articles = await this.DB.article.findMany(); //this.DB is undefined
      const response = this.generateResponse("success", articles);
      res.send(response);
    } catch (error) {
      next(error);
    }
  }
}
export default new ArticleController();



I don't know how should i set a global DB inside a top-level controller which can be used every where.
I also try js global.db vars and express app.set("db",db1) but i think these are not a good solution for this work.


Answer:
finally I modify global.middleware.js file and modify request instead of setting database in a high-level controller :


import {
  prisma_aramgostar,
  prisma_karen
} from "../prisma/prismaClient.js";
export default async(req, res, next) => {
  const domain = await req.get("x-forwarded-host");
  switch (domain) {
    case "localhost:3000":
      req.DB = prisma_aramgostar;
      console.log("db: aramgostar");
      break;
    case "127.0.0.1:3001":
      req.DB = prisma_karen;
      console.log("db: karen");
      break;
  }
  next();
};
Question: Codeigniter 4 unique name validation

My problem is that I have a modal and the input contains the value from the database. When I press the update button, the unique name validation check if the name already exists in the database. However, if I don't change it, it also checks the unique name validation, which I don't want to happen.
Here is the form.
<form action="<?= base_url('users/createRole'); ?> " method="post">
<div class="modal-body">
    <input type="hidden" name="roleID" id="roleID">
    <div class="mb-3">
        <label for="inputRoleName" class="form-label">Rolle hinzufügen</label>
        <input type="text" class="form-control" id="inputRoleName" name="inputRoleName" placeholder="Role Name">
    </div>
</div>
<div class="modal-footer">
    <button type="submit" class="btn btn-primary">Rolle speichern</button>
    <button type="button" class="btn btn-light" data-bs-dismiss="modal">Schließen</button>
</div>
</form>

        $(".btnEditRole").click(function() {
            const roleID = $(this).data('id');
            const inputRoleName = $(this).data('role');
            $('#modalTitle').html('Update Data Role');
            $('.modal-footer button[type=submit]').html('Update rolle');
            $('.modal-content form').attr('action', '<?= base_url('users/updateRole') ?>');
            $('#roleID').val(roleID);
            $('#inputRoleName').val(inputRoleName);
            $('.modal').on('hidden.bs.modal', function() {
                location.reload(); // Refresh the page when modal is closed
            });
        });

Here is the Function.
public function updateRole()
{
if (!$this->validate(['inputRoleName' => ['rules' => 'is_unique[user_role.role_name]']])) {
    session()->setFlashdata('notif_error', '<b>Das Hinzufügen eines neuen Benutzers ist fehlgeschlagen</b> Der Benutzer existiert bereits! ');
    return redirect()->to(base_url('users'));
}
$updateRole = $this->userModel->updateRole($this->request->getPost(null, FILTER_UNSAFE_RAW));
if ($updateRole) {
    session()->setFlashdata('notif_success', '<b>Benutzerdaten erfolgreich aktualisieren</b> ');
    return redirect()->to(base_url('users'));
} else {
    session()->setFlashdata('notif_error', '<b>Benutzerdaten konnten nicht aktualisiert werden</b> ');
    return redirect()->to(base_url('users'));
}
}



Answer:
When using unique values, you check them in this way:
(this assumes your AutoIncrement/Primary is roleID
For updating values
change this:
['rules' => 'is_unique[user_role.role_name]']])) {

to this:
['rules' => 'is_unique[user_role.role_name,roleID,{roleID}]])) {

More information on placeholders can be found here:
https://codeigniter.com/user_guide/libraries/validation.html?highlight=is_unique#validation-placeholders
Question: Reversing array in C with pointers

Trying to reverse the array. And then print it
I am trying to reverse the array by indenting from last to first element of array and copy it to another array. arra will be the reversed array :
Here's my code :
#include <stdio.h>
#include <stdlib.h>

int main()
{
    int num, *arr, i;
    scanf("%d", &num);
    arr = (int *)malloc(num * sizeof(int));
    for (i = 0; i < num; i++) {
        scanf("%d", arr + i);
    }
    
    int arra[] = {};
    /* Write the logic to reverse the array. */
    arra[0] = *(arr + num);
    for (int k = 1; k == num; k++) {
        int j = 1;
        arra[j] = *(arr + num -k);
        j++;
    }

    for (i = 0; i < num; i++)
        printf("%d ", *(arra + i));
    return 0;
}



Answer:
For starters this declaration
int arra[] = {};

is invalid in C and C++.
You should define the array also allocating dynamically memory for it as for the first array or in the worst case you could define a variable length array (provided that the compiler supports VLAs) like
int arra[num];

This for loop
for(int k = 1; k == num; k++){

will iterate only one time when num initially is set to 1.
Also within the body of the loop the variable j is created in each iteration of the loop (provided that the condition of the loop will be updated correctly) with the value 1
    int j = 1;
    arra[j] = *(arr + num -k);
    j++;

Thus this statement
    arra[j] = *(arr + num -k);

in each iteration of the loop is equivalent to
    arra[1] = *(arr + num -k);

that does not make sense.
To copy one array into another array using pointers the for loop can look for example the following way
for ( int *src = arr, *dsn = arra + n; src != arr + n; ++src )
{
    *--dsn = *src;
}
Question: Duplicate Buttons in xml file using android studio java

Duplicate buttons are in my xml file which is fragment_employee2
I'm only creating one xml file to list out all the list in one xml
Here is the code in my https://gist.github.com/Umen14/8d1a205f016fa970369d37f37d4bf15d
And here are the images:-
enter image description here
I tried by removing here and there but the code seems to be the same but there is a problem in the onclick listener in my EmployeeFragment.java
enter image description here


Answer:
This is showing duplicate because you are using same xml in recyclerView item   as well as activity layout. which R.layout.fragment_employee2 in your case. You need to define different layout in EmployeeAdapter without button. This will resolve you issue.
Question: Flutter: How to update locale in GetxController

my splash code this
class App extends StatelessWidget {
  const App();

  @override
  Widget build(BuildContext context) {
    Get.put(SplashController());
    Get.put(ThemeController());
    Get.put(HomeController());
    Get.put(LocaleController());
    var localeController = Get.find<LocaleController>();
    print('amirrrrrrrrrrr${localeController.locale}');
    return GetMaterialApp(
      debugShowCheckedModeBanner: false,
      translations: LocaleString(),
      locale: localeController.locale,
      initialBinding: MyBindings(),
      home: Splash(),
    );
  }
}

after update locale in controller
class LocaleController extends GetxController {
  Locale locale = const Locale('fa', 'FA');

  Future<void> saveLocale(Locale newLocale) async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    await prefs.setString('languageCode', newLocale.languageCode);
    await prefs.setString('countryCode', newLocale.countryCode.toString());
    locale = newLocale;
    update();
    print('amirrrrrrr$locale');
  }

  Future<Locale> loadLocale() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    String? languageCode = prefs.getString('languageCode');
    String? countryCode = prefs.getString('countryCode');
    Locale? locale;
    if (languageCode != null && countryCode != null) {
      locale = Locale(languageCode, countryCode);
      this.locale = locale;
    }
    update();
    print('amirrrrrrr$locale');
    return locale!;
  }
}

this code not updated
var localeController = Get.find<LocaleController>();
print('amirrrrrrrrrrr${localeController.locale}');

how to fix ?
It is updated in the LocaleController controller, but in the app class, it always returns fa_FA and does not show the updated locale.


Answer:
As documentation mentioned you need to call;
getx
Get.changeLocale(Locale("pt"));

You need to call this method with expected Locale.
Additionally, current locale can be checked with;
  Get.locale;