satoshi-2000/llms-suitable huggingface dataset:
Question: FutureProvider does not return data to UI

I'm new using Riverpod and its providers. I have 2 almost identical futureProviders but one of them does not return data to UI even though API returns data.
Here is UI part

class ProductDetailSimilarProductsWidget extends ConsumerWidget {
  const ProductDetailSimilarProductsWidget(this.product, {super.key});

  final ProductDetailModel product;

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    var value = ref.watch(getSimilarProductsFutureProvider([product.Id, product.KategoriId]));
    return Container(
      height: MediaQuery.of(context).size.height * 0.5,
      width: MediaQuery.of(context).size.width,
      child: value.when(
        data: (data) {
          print("data length:${data.length}");
          return ListView.builder(
            itemCount: data.length,
            shrinkWrap: true,
            scrollDirection: Axis.horizontal,
            itemBuilder: (context, index) {
              return Padding(
                padding: EdgeInsets.only(left: AppTheme.mediumPadding, right: AppTheme.mediumPadding),
                child: ProductGridContainerWidget(product: data[index]),
              );
            },
          );
        },
        error: (err, trace) {
          return Text(err.toString());
        },
        loading: () => AppTheme.spinkit,
      ),
    );
  }
}

Here is futureProvider object

final getSimilarProductsFutureProvider = FutureProvider.family<List<Products>, List<dynamic>>((ref, value) async {
  var result = await ProductDetailData().getSimilarProducts(productId: value[0], categoryId: value[1]);
  print("result: ${result.length}");
  return result;
});

Finally, the method does API call
    var service = ApiService();
    var sharedPreferencesManager = SharedPreferencesManager();
    await sharedPreferencesManager.init();
    var langId = await sharedPreferencesManager.getLanguageId();
    var countryId = await sharedPreferencesManager.getCountryId();
    var result =
        await service.getRequest(subUrl: "${ApiRoutes.getSimilarProducts}?productId=$productId&langId=$langId&countryId=$countryId&categoryId=$categoryId");
    List<Products> products = [];
    var elements = json.decode(result.body);
    await Future.forEach(elements, (element) => products.add(Products.fromMap(element as Map<String, dynamic>)));
    return products;

Inside provider object, result.length variable prints 10 and it is expected. But inside the UI part, widget stucks on loading part and does not print data.length variable.
Is there something wrong in my codes? Also API works fine and successfully returns data.


Answer:
Your mistake is probably using the list as an argument for .family.

Ideally, the parameter should either be a primitive (bool/int/double/String), a constant (providers), or an immutable object that overrides == and hashCode.

Try using Records or create an immutable object with the two required fields.
Question: Non-Repeating Random Numbers for Multiple Variables

I am trying to create a function that applies random values to a range of parameters that are used in another function where the random sequence does not repeat.
The reason: used for random hyper parameter tuning and to cut down on processing by not repeating sequence.
Example Code:

num_evals = 2500

parameters = {
        'n_parameter_1': range(2,100),
        'n_parameter_2': range(1,20),
        'n_parameter_3': range(2,150),
              }  

for i in range(num_evals):
        n_parameter_1 = random.choice(parameters['n_parameter_1'])
        n_parameter_2 = random.choice(parameters['n_parameter_2'])
        n_parameter_3 = random.choice(parameters['n_parameter_3'])


The results then get populated to a file with the random parameters used to generate.
I need help with the second bit.
As this function runs over time, you start getting sequences that look like this:
n_parameter_1 = 54, n_parameter_2 = 15, n_parameter_3 = 120
n_parameter_1 = 10, n_parameter_2 = 12, n_parameter_3 = 89
n_parameter_1 = 54, n_parameter_2 = 15, n_parameter_3 = 120
I want to avoid the last sequence by either capturing the sequences in a list or dataframe etc. (already saving the sequences) that the function checks and then generates a new/different sequence if there is a duplicate sequence in the list.
Thanks for the help in advance.


Answer:
You can store sequences in a set and then check if a sequence is already in the set.
num_evals = 2500
i = 0

parameters = {
        'n_parameter_1': range(2,100),
        'n_parameter_2': range(1,20),
        'n_parameter_3': range(2,150),
              }  

sequences = set()

while i < num_evals:
        n_parameter_1 = random.choice(parameters['n_parameter_1'])
        n_parameter_2 = random.choice(parameters['n_parameter_2'])
        n_parameter_3 = random.choice(parameters['n_parameter_3'])
        sequence = (n_parameter_1, n_parameter_2, n_parameter_3)
        if sequence not in sequences:
            sequences.add(sequence)
            i += 1

The for loop has been changed to a while loop to allow for the conditional increment.
Question: Algorithm to list all combinations from a table where data is present or NULL

I have an Excel file (which can optionally be loaded into a database, and into an array of arrays of course) with values such as:




A
B
C




NULL
NULL
zxy


xyz
xzy
NULL


xyz
xzy
xyy


yzy
yyx
yxy


NULL
NULL
xyx


xyz
NULL
yxx




and so on.
There are thousands of values.
Is there any known algorithm to come up with all possible combinations of rows where values are not "NULL"?
For example for the table above the result would be:




A
B
C
Number of occurrences




NULL
NULL
*
2


*
*
NULL
1


*
*
*
2


*
NULL
*
1




I feel like it is a typical task, but cannot find the algorithm anywhere. Would appreciate your help a lot.


Answer:
If you are tempted to use pandas :
#pip install pandas
import pandas as pd

df = pd.read_excel("file.xlsx")

out = (
    df.replace(".+", "*", regex=True).fillna("NULL")
        .groupby(list(df), group_keys=False, sort=False)
        .size().reset_index(name="Number of occurrences")
)

Output :
print(out)
    
      A     B     C  Number of occurrences
0  NULL  NULL     *                      2
1     *     *  NULL                      1
2     *     *     *                      2
3     *  NULL     *                      1
Question: Unable to extract id from json response in jmeter

My am calling POST on an API. The response has
{
  "id" : "1234”,
---
}

I have following regular expression extractor:

However in the DELETE HTTP Request on API/${id}, I am getting API/NOT FOUND.
Please suggest whats the issue with my regular expression ?


Answer:
JSON is not a regular language hence using regular expressions for it is not the best idea
Consider using JSON Extractor instead, the relevant JSONPath expression is just id
Demo:
Question: ESLint error: Failed to load 'eslint-plugin-jsdoc' in IntelliJ on Ubuntu - troubleshooting tips?

I am struggling with ESLint not being able to load in IntelliJ 2023.1 on Ubuntu 22.04.
It seems like there are several syntax errors in the libraries, but I just could not belive that.
What could I do?
Best regards
Peter
PS: error in detail:


If I correct this specific one (yes, I should not overwrite libraries, especially when I'm not an expert on that stuff), a new syntax error comes again.


Answer:
What Node.js version do you have? Looks like it doesn't support the nullish coalescing operator; please make sure that the interpreter set up in Settings | Languages & Frameworks | Node.js is v. 14 or higher, see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Nullish_coalescing#browser_compatibility
Question: Can't access localhost sites anymore

No access to localhost sites anymore.
I have IIS 6.0 running on a Windows 7 64 bit PC where I work on local websites.
I have 4 sites that were working until yesterday and now give me a 404 error when I try to access. I have tried IE, Chrome, Brave and Firefox.
One of the sites I'm working on for our karate club is a login for weekend courses where the member's card is checked by a webcam in a box to allow them to log in. It was working (they all were), but I needed this site to be HTTPS as the javascripts for the camera must be downloaded using this protocol. The location of the course may not have internet access so these must be loaded from the localhost site.
I was messing about trying creating self signed certificates for localhost which I managed to do, but i could not get the site to work using https. I then removed the certificates but the sites would not then access normally (http).
I cleared the cache of each browser and have reset IIS and restarted the pc. I also went through and disabled the world wide services, restarted the PC and restarted WWS.
Nothing has helped.
Any advice/pointers would be a great help.
Thanks in Advance,
Andy


Answer:
I solved the problem myself by doing a system restore to the point just before i installed the IIS toolkit. My sites are now back to working using http again.
I'm guessing that it was something in the toolkit that caused the problem.
Thanks for the advice anyway.
Regards,
Andy
Question: Why is data.posts undefined when accessing using subscriber method in redux?

How can I access complete state in redux?
const { createStore } = require("redux");

const initialState = {
  posts: [
    { id: 1, title: "Post one" },
    { id: 2, title: "Post two" },
  ],
};

My Posts Reducer
const PostsReducer = (state = initialState, action) => {
  switch (action.type) {
    case "add_post":
      return {
        ...state,
        posts: [...state.posts, action.payload],
      };

    case "delete_post":
      return {
        ...state,
        posts: state.posts.filter((post) => post.id !== action.payload),
      };

    case "get_all_posts":
      return state.posts;

    default:
      return state;
  }
};

const store = createStore(PostsReducer);

My Action Creators:
const GetAllPosts = () => {
  return {
    type: "get_all_posts",
  };
};

const AddPost = (payload) => {
  return { type: "add_post", payload };
};

const removePost = (payload) => {
  return { type: "delete_post", payload };
};

Accessing Store data:
store.subscribe(() => {
  const data = store.getState();
  console.log(data.posts);
});

store.dispatch(GetAllPosts());

While I am console logging data.posts it returns undefined.
I am accessing using subscriber method:
store.subscribe(() => {
  const data = store.getState();
  console.log(data.posts);
});

store.dispatch(GetAllPosts());

Note:
I am Using Redux(4.2.1)
By using GetAllPosts(), I am able to access data, but I cannot get data.posts in console.


Answer:
The get_all_posts case is returning the state.posts array directly instead of setting a state object with a posts property.
case "get_all_posts":
  return state.posts; // <-- just the posts array

Update get_all_posts case to return the correct state invariant, likely the initial state value with all the posts included.
Example:
const initialState = {
  posts: [
    { id: 1, title: "Post one" },
    { id: 2, title: "Post two" },
  ],
};

const PostsReducer = (state = initialState, action) => {
  switch (action.type) {
    case "add_post":
      return {
        ...state,
        posts: [...state.posts, action.payload],
      };

    case "delete_post":
      return {
        ...state,
        posts: state.posts.filter((post) => post.id !== action.payload),
      };

    case "get_all_posts":
      return { ...initialState };

    default:
      return state;
  }
};
Question: Why does my reactjs project on hostinger give a 404 error when opening a new tab or refreshing the page?

I have deployed reactjs project on hostinger where i open any new tab or refresh the page it give error 404
i have used latest version of react router dom
Index.js
<Browserrouter>
<App/>
<Browserrouter/>


App.js

<Routes>
<Route path="/" element={<Home/>}/>
        <Route path="/about-us" element={<Aboutus/>}/>
        <Route path="/contact-us" element={<Contactus/>}/>
        <Route path="/career" element={<Career/>}/>
        <Route path="/work" element={<Work/>}/> 
        <Route path="/services" element={<ServicesMain/>}/>

<Routes/>



Answer:
The issue is not with the React but your hosting config. You need to add rewrite rules by adding .htaccess file inside your 'public' folder with the following code.
<IfModule mod_rewrite.c>
  RewriteEngine On
  RewriteBase /
  RewriteRule ^index\.html$ - [L]
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteCond %{REQUEST_FILENAME} !-l
  RewriteRule . /index.html [L]
</IfModule>
Question: Passing variables to a variable in bash

I'm writing custom logging for the bash:
#!/usr/bin/env bash

set -e +x

SCRIPT_LOG_NAME='[MYSCRIPT]'
SCRIPT_LOG_DATETIME_FORMAT="+%Y-%m-%d %H:%M:%S"
SCRIPT_LOG_LEVEL_INFO='INFO'
SCRIPT_LOG_PATTERN="${SCRIPT_LOG_NAME} $(date "${SCRIPT_LOG_DATETIME_FORMAT}") $1 : $2"

log_general() {
  ...
}

log_info() {
  log_general "$SCRIPT_LOG_LEVEL_INFO" "$1"
}

And I want to pass variables $SCRIPT_LOG_LEVEL_INFO and "$1" as parameters to the function log_general(). And use this parameters in the $SCRIPT_LOG_PATTERN to achive output: 
[MYSCRIPT] 2023-01-01 10:10:10 INFO : Something logged
I tried something like:
log_general() {
  echo -e "$SCRIPT_LOG_PATTERN" "$1" "$2"
}

Or
SCRIPT_LOG_LEVEL=''
SCRIPT_LOG_PATTERN="${SCRIPT_LOG_NAME} $(date "${SCRIPT_LOG_DATETIME_FORMAT}") ${SCRIPT_LOG_LEVEL} : "

log_general() {
  SCRIPT_LOG_LEVEL=$SCRIPT_LOG_LEVEL_INFO
  echo -e "${SCRIPT_LOG_PATTERN}${1}"
}

log_info() {
  log_general "$1"
}

But I could not achieve the desired result. Can you help me, please?


Answer:
If you'd like to use ${SCRIPT_LOG_PATTERN} as a global variable and later on substitute the ${1} and ${2} you would have to escape the $ sign and then evaluate the string later on in log_general.
This would look something like this:
#!/bin/bash

set -e +x

SCRIPT_LOG_NAME='[MYSCRIPT]'
SCRIPT_LOG_DATETIME_FORMAT="+%Y-%m-%d %H:%M:%S"
SCRIPT_LOG_LEVEL_INFO='INFO'
SCRIPT_LOG_PATTERN="${SCRIPT_LOG_NAME} $(date "${SCRIPT_LOG_DATETIME_FORMAT}") \$1 : \$2"

log_general() {
        eval echo "${SCRIPT_LOG_PATTERN}"
}

log_info() {
        log_general "${SCRIPT_LOG_LEVEL_INFO}" "${1}"
}

Usage:
$ source logging_test.sh
$ log_info "my custom message"
[MYSCRIPT] 2023-06-02 14:03:27 INFO : my custom message


I'd also recommend escaping the date command since otherwise the date will be parsed once, here is what I mean:
$ log_info "asdads"; sleep 5; log_info "asdsad"
[MYSCRIPT] 2023-06-02 14:06:28 INFO : asdads
[MYSCRIPT] 2023-06-02 14:06:28 INFO : asdsad

As you can see the time does not change even with 5 seconds of sleep.
To fix this escape the date as well like this:
SCRIPT_LOG_PATTERN="${SCRIPT_LOG_NAME} \$(date '${SCRIPT_LOG_DATETIME_FORMAT}') \$1 : \$2"

Output now:
$ log_info "asdads"; sleep 5; log_info "asdsad"
[MYSCRIPT] 2023-06-02 14:09:19 INFO : asdads
[MYSCRIPT] 2023-06-02 14:09:25 INFO : asdsad
Question: Is there an equivalent of Vue's `v-show` in Angular so that the component is hidden, but still in DOM?

There are some situations where it's better to keep a hidden component in DOM. In Vue there the v-show in addition to the v-if. But in Angular I didn't find an equivalent? So the best solution is to use s.th. like [ngStyle]="{ 'display': showMe ? 'block' : 'none' }"?
EDIT: I also could set the hidden attribute, which should have a very similar effect, e.g. [hidden]="!showMe".
Is there actually a reason why Vue.js did include v-show instead of simply using :hidden?


Answer:
v-show is simply sugar syntax for adding style="display: none". While I'm not aware of anything like that built into angular, it's trivial to build your own directive that will achieve the same result (code not tested):
@Directive({
  selector: 'appHidden',
})
class HiddenDirective {
 @Input('appHidden')
 isHidden: boolean = false;

 @HostBinding('style.display')
 get displayStyle() {
   return this.isHidden ? 'none' : undefined;
 }
}

Usage:
<div [appHidden]="shouldBeHidden"></div>
Question: Spring Boot custom constraint validator with multiple values

I want to add 2 values for my custom constraint validator because I have 2 feature flags:
 @JsonProperty(value = "name")
    @BlockedWithoutEnabledFeatureFlag(feature = FeatureFlag.AAA, values = {"aaa", "bbb"})
    @BlockedWithoutEnabledFeatureFlag(feature = FeatureFlag.BBB, values = {"ccc", "ddd"})
    private String parameter;

where:
@Constraint(validatedBy = {BlockedWithoutEnabledFeatureFlagValidator.class})
@Target({FIELD, PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
@ReportAsSingleViolation
public @interface BlockedWithoutEnabledFeatureFlag {

    String message() default "{validation.constraints.BlockedWithoutEnabledFeatureFlag.message}";

    Class<?>[] groups() default {};

    Class<? extends Payload>[] payload() default {};

    FeatureFlag feature();

    String[] values() default {};
}

and implementation:
public class BlockedWithoutEnabledFeatureFlagValidator implements ConstraintValidator<BlockedWithoutEnabledFeatureFlag, Object> {
    private final FeatureFlagService featureFlagService;

    private List<String> blocked;
    private FeatureFlag feature;

    @Override
    public void initialize(BlockedWithoutEnabledFeatureFlag constraintAnnotation) {
        blocked = Arrays.asList(constraintAnnotation.values());
        feature = constraintAnnotation.feature();
    }

@Override
    public boolean isValid(Object value, ConstraintValidatorContext context) {


But now I get compilation error "Duplicate annotation". How to do that?


Answer:
You should make your BlockedWithoutEnabledFeatureFlag repeatable. To do this:

Create a new "top-level" annotation:

@Target({ ElementType.FIELD })
@Retention(RetentionPolicy.RUNTIME)
public @interface RepeatableBlockedWithoutEnabledFeatureFlag {
    BlockedWithoutEnabledFeatureFlag[] value();
}


Add @Repeatable to your BlockedWithoutEnabledFeatureFlag annotation

...
@Repeatable(RepeatableBlockedWithoutEnabledFeatureFlag.class)
public @interface BlockedWithoutEnabledFeatureFlag {
...

Then you should be able to add more than one @BlockedWithoutEnabledFeatureFlag annotation.
Question: clean data in r from image

I am trying to scan a text from an Ocr and clean it, I got a character that is divided to few lines, however I would like to have the text in similar to the way it is in the image
the code :
heraclitus<-"greek.png"
library(tidyverse)
library(tesseract)
library(magick)

image_greek<-image_read(heraclitus)

image_greek<-image_greek %>% image_scale("600") %>% 
  image_crop("600x400+220+150") %>% 
  image_convert(type = 'Grayscale') %>% 
  image_contrast(sharpen = 1) %>% 
  image_write(format="jpg")

heraclitus_sentences<-magick::image_read(image_greek)%>% 
  ocr() %>% str_split("\n")

As you can see from the output, I have white spaces and sentences that are divided to two lines. I would like to have it in a vector or a list, that each element will be a sentence




Answer:
You need to split on \n\n (not \n) then replace the middle \n values:
magick::image_read(image_greek) %>% 
  ocr() %>% 
  str_split("\n\n") %>%
  unlist() %>%
  str_replace_all("\n", " ")

Output:
[1] "© Much learning does not teach understanding."                                                       
[2] "© The road up and the road down is one and the same."                                                
[3] "© Our envy always lasts longer than the happiness of those we envy."                                 
[4] "© No man ever steps in the same river twice, for it's not the same river and he's not the same man. "
Question: Join values of two string lists to new string list and add characters in VB.NET using LINQ

In VB.NET i would like to create a list of string from the values of two given lists of string.
E.g.
        Dim varNames As New List(Of String)({"var1", "var2"})
        Dim varValues As New List(Of String)({"value1", "value2"})
        Dim finalList As List(Of String) = .....
        'Output should be:
        'finalList(0) -> "[var1] = 'value1'"
        'finalList(1) -> "[var2] = 'value2'"

I would like to do this in on line of code using LINQ. (I know how to do this using for loops)


Answer:
Use Zip to "concat" two lists via index:
Dim finalList As List(Of String) = varNames.
    Zip(varValues, Function(s1, s2) $"[{s1}] = '{s2}'").
    ToList()
Question: Why is my Python code not inserting data into PostgreSQL database from a JSON file?

I'm trying desing and implement database model in python from a json file but my python code seems like is not inserting data into table and i'm not sure where is the problem in my code
import json
import psycopg2


class Policy:
    def __init__(self, type, name, rule_exists):
        self.type = type
        self.name = name
        self.rule_exists = rule_exists


# load json data from the file
with open("demo_data.json", 'r') as file:
    policy_data = json.load(file)
    first_level = policy_data["uniconfig-topology:configuration"]
    second_level = first_level["Cisco-IOS-XR-infra-policymgr-cfg:policy-manager"]
    third_level = second_level["policy-maps"]
    forth_level = third_level["policy-map"]

table_of_policies = []
for item in forth_level:
    if "policy-map" in item:
    # forth_level = item
        type = forth_level['type']
        name = forth_level['name']
        rule_exists = 'policy-map-rule' in forth_level
        policy_map = Policy(type, name, rule_exists)
        table_of_policies.append(policy_map)
    #print(forth_level)


conn = psycopg2.connect(
    host="localhost",
    database="postgres",
    user="postgres",
    password="postgres",
    port="5432"
)


cursor = conn.cursor()
cursor.execute("DROP TABLE IF EXISTS policy_map")
cursor.execute('''create table policy_map
( type VARCHAR(255),
  name VARCHAR(255),
  rule_exists BOOLEAN)
''')

for policy_map in table_of_policies:
    insert_data = "INSERT INTO policy_map (type, name, rule_exists) VALUES (%s, %s, %s)"
    cursor.execute(insert_data, (policy_map.type,
                   policy_map.name, policy_map.rule_exists))


conn.commit()


I tried several different approach for dict in json file to be sure im on right level of dict but it never append any data to my list. Would like to know whats wrong with my code


Answer:
type is a built-in python function that returns the type of a variable. Overwriting it might cause your code to work unexpectedly.
You can check the documentation , avoid using build-in function names for variables.
Regarding table column naming you can refer to this question.
Apart from these you're looping over forth_level but not using the item:
type = forth_level['type']
name = forth_level['name']

I would expect this code to continue like:
    if "policy-map" in item:
    type = item['type']
    name = item['name']
    rule_exists = 'policy-map-rule' in item
    policy_map = Policy(type, name, rule_exists)
    table_of_policies.append(policy_map)

But without seeing the JSON I cannot tell for sure.