satoshi-2000/llms-suitable huggingface dataset:
Question: import.meta.env.PROD runs in development mode

why below code run in the development mode? it should only run in production mode
Here is the running scripts in package.json
"build-watch-dev": "vite build --mode development --watch",
import { useStore } from '@/store';
import { register } from 'register-service-worker';

export function registerSW() {
    if (import.meta.env.PROD) {
        register(`${import.meta.env.BASE_URL}service-worker.js`, {
            ready() {
                console.log(
                    'App is being served from cache by a service worker.\n' +
                    'For more details, visit 
                )
            },
            registered() {
                console.log('Service worker has been registered.')
            },
            cached() {
                console.log('Content has been cached for offline use.')
            },
            updatefound() {
                console.log('New content is downloading.')
            },
            updated() {
                console.log('New content is available; please refresh.');
                const $store = useStore();
                $store.serviceWorkerUpdate = true;
            },
            offline() {
                console.log('No internet connection found. App is running in offline mode.')
            },
            error(error) {
                const $store = useStore();
                if ($store.isOnline) {
                    console.error('Error during service worker registration:', error)
                }
            }
        })
    }
}



Answer:
The --mode flag overrides the value of import.meta.env.MODE.
import.meta.env.PROD is effectively a boolean result of process.env.NODE_ENV === 'production'
You could try changing your conditional to something like:
if (import.meta.env.MODE !== 'development') {

Or you could look at setting NODE_ENV to development.
Question: Typescript class made up of an array of other classes gives an error

So im trying to make a typescript file for a network and there are three files involved.
a _Node.ts, Edge.ts, and a Graph.ts
These three files look like so:
_Node.ts
interface _Node {
  data: any;
  neighbours: number[];
}

class _Node {
  constructor(data) {
    // this data is an arbitrary thing with which I can create any object
    this.data = { ...data };
    // the neighbours bit is explicity set from the code outside
    this.neighbours = [];
  }
}

export { _Node };

Edge.ts
interface Edge {
  start: number;
  end: number;
  data: any;
}

class Edge {
  constructor(start, end, data) {
    this.start = start;
    this.end = end;
    this.data = { ...data };
  }
}

export { Edge };

Graph.ts
import { _Node } from "./_Node";
import { Edge } from "./Edge";

interface Graph {
  nodes: _Node[];
  edges: Edge[];
}

class Graph {
  constructor(nodes, edges) {
    this.nodes = nodes;
    this.edges = edges;
    // execute Internal methods
    // this.printData();
  }

  // test function
  printData() {
    const message =
      "This is a graph with " +
      this.nodes.size + // this gives an error "Property size doesn't exist on nodes"
      " nodes and " +
      this.edges.size +
      " edges";
    console.log(message);
  }
}


The last line of node.size and edges .size give a VS code error of something like the property size doesn't exist on them despite me declaring them as arrays of the nodes and things - is there a way to fix it?


Answer:
You're looking for
this.edges.length
as specified by
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/length
size is not a valid property or function
Question: Sqlalchemy count of records in the relation of one to many

Help me figure out what I'm doing wrong?
I need to get the number of comments in 24 hours in the relation one-to-many table.
class Comment(Base):
    __tablename__ = 'comments'
    id = Column(Integer, primary_key=True)
    task_id = Column(Integer(), ForeignKey('tasks.id'), nullable=False)
    post_link = Column(String, nullable=False)
    date = Column(DateTime, default=datetime.datetime.utcnow())

    def __init__(self, task_id: int, post_link: str):
        super().__init__()
        self.task_id = task_id
        self.post_link = post_link

    def __repr__(self):
        return f'id - {self.id} | task_id - {self.task_id} | date - {self.date}'

class Task(Base):
    __tablename__ = 'tasks'
    id = Column(Integer, primary_key=True)
    name = Column(String, nullable=False)

    comments = relationship('Comment', backref='tasks', lazy=True)

    def __init__(self, name: str):
        super().__init__()
        self.name = name

    def __repr__(self):
        return f'id - {self.id} | name - {self.name}'


I don't know if the query works correctly or if it even outputs the number of records.
Here's the request itself:
async def get_comments_for_day():
    start_day = datetime.utcnow() - timedelta(hours=23, minutes=50)
    async with get_async_session() as session:
        stmt = select(Comment.task_id, func.count(Comment.task_id).label('comments_found'))\
            .where(Comment.date >= start_day).subquery()
        main_stmt = select(Task, stmt.c.comments_found).outerjoin(stmt, Task.id == stmt.c.task_id)
        results = await session.execute(main_stmt)
        return results.scalars().all()

async def main():
    tasks = await get_comments_for_day()
    for task, comments_found in tasks:
        print(task.name, comments_found)

I get this error:
    for task, comments_found in tasks:
TypeError: cannot unpack non-iterable Task object



Answer:
async def get_comments_for_day():
    start_day = datetime.utcnow() - timedelta(hours=24)
    async with get_async_session() as session:
        stmt = (
            select(func.count(Comment.id), Task)
            .select_from(Task)
            .join(Comment, Task.id == Comment.task_id, isouter=True)
            .where(Comment.date >= start_day)
            .group_by(Task.id, Task.name)
        )
        results = await session.execute(stmt)
        return results.all()

If you're interested, I found a solution to the problem, which was to write return results.all() instead of return results.execute().all().
Question: How to change the tag column selection option

I have a tag column in the active admin index page like
tag_column :result, interactive: true, sortable: false

in my model I have a enum for result as
 enum result: { winner: 0, first_runner_up: 1, second_runner_up: 2}

In the index page when I click on drop down the selection options are being dispalyed as
winner
first_runner_up
second_runner_up
How can we display them as
Winner
First Runner Up
Second Runner Up
Can someone please help...
Thank you in advance


Answer:
I suggest you break the rules out to a hash.. then you will be free to validate against them later
WINNER_OPTIONS = {
  winner: {
    title: "Winner"
  },
  second: {
    title: "First Runner Up"
  },
  third: {
    title: "Second Runner Up"
  }

RESULT_ENUMS = WINNER_OPTIONS
  .keys
  .with_index
  .to_h

enum result: RESULT_ENUMS

tag_column :result, WINNER_OPTIONS.values.map{|e| e[:title]}.with_index.to_h
Question: How can I move specific values from one field in a JSON column to another in PostgreSQL?

Let's assume I have a table users with a JSON column "foo". Values of that column look like this:
"{ field1: ['bar', 'bar2', 'bar3'], field2: ['baz', 'baz2', 'baz3'] }"

where field1 and field2 are optional, so column value may look like this: "{}"
I want to move values 'bar2' and 'bar3' from field1 to field2 for all records in this table.
Sample Output:
"{ field1: ['bar'], field2: ['baz', 'baz2', 'baz3', 'bar2', 'bar3']}"

More examples:
"{ field1: ['bar3'], field2: ['baz', 'baz2', 'baz3'] }"

should be transformed into
"{ field1: [], field2: ['baz', 'baz2', 'baz3', 'bar3'] }"

etc.
Is there any way to do this?
Unfortunately I have no idea how to approach this problem.


Answer:
Using a series of subqueries with jsonb_array_elements
select jsonb_build_object('field1', coalesce((select jsonb_agg(v.value) 
       from jsonb_array_elements(u.foo -> 'field1') v 
       where v.value#>>'{}' not in ('bar2', 'bar3')), '[]'::jsonb),
   'field2', (u.foo -> 'field2') || (select jsonb_agg(v.value) 
       from jsonb_array_elements(u.foo -> 'field1') v 
       where v.value#>>'{}' in ('bar2', 'bar3'))) 
from users u 
where u.foo ? 'field1' and u.foo ? 'field2'

See fiddle
Question: How to add a list of specific object in a configuration file for a WorkerService

As far as what I understand:

WorkerService is the new way to define a Windows Service (app that run as as service).
By default, using the contextual menu on the project, the type of configuration file associated to a WorkerService is stil a xaml file: "App.config". See: How to: Add an application configuration file to a C# project
According to Microsoft documentation, I understand that I should use the section <appsettings>.

appSettings is a dictionary of key value pair. But I can't find how to add a list of item as the value. Also, I would like to add my own object as the value if possible.
Is there a way to add a List of MyConfigObject (List<MyConfigObject>)into a config file? If yes, how? Should I use another section or should I use another type of config file (json, yaml) to have the simplest way to read/write settings?


Answer:
Yes, you can, Like this:
appsettings.json
{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "AllowedHosts": "*",
  "MyConfigObject": [
    {
      "Prop1": "1",
      "Prop2": "2"
    },
    {
      "Prop1": "1",
      "Prop2": "2"
    }
  ]
}

MyConfigObject Class
public class MyConfigObject
{
    public string Prop1 { get; set; }
    public string Prop2 { get; set; }
}

In Startup, register the Configuration with the type MyConfigObject. Like this:
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddControllersWithViews();
        services.Configure<List<MyConfigObject>>(Configuration.GetSection("MyConfigObject"));
    }

Now you can use it in any service or controller, like this:
public class HomeController : Controller
    {
        private readonly ILogger<HomeController> _logger;
        private readonly List<MyConfigObject> myConfig;
        public HomeController(IOptions<List<MyConfigObject>> myConfig, ILogger<HomeController> logger)
        {
            _logger = logger;
            this.myConfig = myConfig.Value;
        }

        public IActionResult Index()
        {
            return View();
        }
}
Question: redux tookit when using a middleware builder function, an array of middleware must be returned

So I'm getting Uncaught Error: when using a middleware builder function, an array of middleware must be returned
This is my code
import {
  configureStore,
  compose,
  combineReducers,
  applyMiddleware
} from "@reduxjs/toolkit";
import thunk from "redux-thunk";

const rootReducer = combineReducers({});

const middleware = applyMiddleware(thunk);
const composeWithDevTools = 
  window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;
const composedMiddleWare = composeWithDevTools(middleware)

const store = configureStore({
  reducer: rootReducer,
  middleware: composedMiddleWare,
  devTools: 
    window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__()
})

export default store;

I have no idea what's wrong and searching doesn't seem to be returning any useful result.


Answer:
configureStore from redux-toolkit (RTK) works differently from the redux createStore function. The middleware property accepts an array of middleware to install and RTK handles applying them.
See configureStore

/**
 * An array of Redux middleware to install. If not supplied, defaults to
 * the set of middleware returned by `getDefaultMiddleware()`.
 */
middleware?: ((getDefaultMiddleware: CurriedGetDefaultMiddleware<S>) => M) | M


Note that while applyMiddleware is re-exported from redux that

You should not need to use this directly.

The following would be the code you'd use:
import { configureStore, combineReducers } from "@reduxjs/toolkit";
import thunk from "redux-thunk";

const rootReducer = combineReducers({});

const store = configureStore({
  reducer: rootReducer,
  middleware: [thunk], // <-- array of middlewares to install/apply
  devTools: window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__()
});

export default store;

RTK also ships with opinionated optimizations:

The devTools are enabled by default, you'll only use this if you have custom needs.

Thunk middleware is also already included with the default middleware, e.g. if no middleware property is provided, then getDefaultMiddleware is provided and returns the following middleware value, which includes the thunk middleware:
const middleware = [
  actionCreatorInvariant,
  immutableStateInvariant,
  thunk, // <-- included thunk middleware!
  serializableStateInvariant,
]

Again, you'll really only need to specify the middleware property if you need to customize the immutability or serialization middlewares.


Your store configuration can be reduced to the following:
import { configureStore, combineReducers } from "@reduxjs/toolkit";

const rootReducer = combineReducers({});

const store = configureStore({
  reducer: rootReducer,
});

export default store;

Both the thunk middleware and dev tools will be active and working.
Question: Different intercept values for linear regression using statsmodels and numpy polyfit

I get two different intercept values from using the statsmodels regression fit and the numpy polyfit. The model is a simple linear regression with a single variable.
From the statsmodels regression I use:
results1 = smf.ols('np.log(NON_UND) ~ (np.log(Food_consumption))', data=Data2).fit()

Where I recieve the following results:
                               coef    std err          t      P>|t|      [0.025      0.975]
--------------------------------------------------------------------------------------------
Intercept                    5.4433      0.270     20.154      0.000       4.911       5.976
np.log(Food_consumption)     1.1128      0.026     42.922      0.000       1.062       1.164

When plotting the data and adding a trendline using numpy polyfit, I recieve a different intercept value:
x = np.array((np.log(Data2.Food_consumption)))
y = np.array((np.log(Data2.NON_UND)*100))

z = np.polyfit(x, y, 1)

array([ 1.11278898, 10.04846693])

How come I get two different values for the intercept?
Thanks in advance!


Answer:
This is because you are using different linear models in the first and second regressions. In the first regression, you take logs of both the dependent and independent variables, while in the second regression, you are not, and additionally, you are multiplying y by 100.
In order to get the same results as the first regression in the second specification, you need to make sure the regression model is exactly the same as the first one. I suggest you do this:
x = np.log(np.array(((Data2.Food_consumption))))
y = np.log(np.array(((Data2.NON_UND))))

z = np.polyfit(x, y, 1)

And then the output you get with the second function should be the same as the one you get in the first one.
Question: I want get documents using ObjectId, but it's not getting that document

I am new to MongoDB and trying to get multiple documents using ObjectId
Below I have mentioned the demo data format.
db={
"store": [
{
  "_id": ObjectId("63da2f1f7662144569f78ddd"),
  "name": "bat",
  "price": 56,
  
},
{
  "id": ObjectId("63da2f1f7662144569f78ddc"),
  "name": "ball",
  "price": 58,
  
},
{
  "id": ObjectId("63da2f1f7662144569f78ddb"),
  "name": "cap",
  "price": 100,
  
},
{
  "id": ObjectId("63da2f1f7662144569f78dda"),
  "name": "red",
  "price": 50,
  
},

]}

and my query is this
db.store.aggregate([
{
$match: {
  id: {
    $in: [
      ObjectId("63da2f1f7662144569f78ddd"),
      ObjectId("63da2f1f7662144569f78ddb"),
      ObjectId("63da2f1f7662144569f78dda")
    ]
  }
}
},
{
$group: {
  _id: null,
  totalPrice: {
    $sum: "$price"
  }
}
},
{
$project: {
  _id: 0,
  
}
}
])

and output is
[
{
"totalPrice": 150
}
]

but I'm getting objectid like this
{
  "ids": 
  ["63da2f1f7662144569f78ddd","63da2f1f7662144569f78ddb","63da2f1f7662144569f78dda"]
}

if I pass this array it's not getting any documents. How can I pass this array in place of objectids????


Answer:
For your case, you can simply wrap the payload from client in a $map to convert them into ObjectIds with $toObjectId
db.store.aggregate([
  {
    $match: {
      $expr: {
        "$in": [
          "$id",
          {
            "$map": {
              // your payload from client here
              "input": [
                "63da2f1f7662144569f78ddd",
                "63da2f1f7662144569f78ddb",
                "63da2f1f7662144569f78dda"
              ],
              "as": "id",
              "in": {
                "$toObjectId": "$$id"
              }
            }
          }
        ]
      }
    }
  },
  {
    $group: {
      _id: null,
      totalPrice: {
        $sum: "$price"
      }
    }
  },
  {
    $project: {
      _id: 0,
      
    }
  }
])

Mongo Playground
Question: Firestore subscribed document change type

Whenever I subscribe to a collection of documents, I'm able to extract the changes to the documents, given that the listener returns DocumentChange. This way I can understand whether a given doc was created, modified or deleted.
How to get the DocumentChange when subscribing to a single document in the collection? The issue appears to be that this time the listener returns DocumentSnapshot instead of DocumentChange.


Answer:
The DocumentSnapshot contains everything you need to know about that one document.  Either it exists() with data, or it does not.  You can check this state with each new snapshot for that one document, and react to that any way you like.  Since you are not performing a query with variable set of results, there is no need for more information.
Question: Is it possible to deselect a ttk.Radiobutton?

These are the ttk.radiobuttons I am using:
    def radioButtonGen(self):
        self.var = tk.IntVar()
        self.arithButton = ttk.Radiobutton(self, text = "Arithmetic Series", variable = self.var, value = 1, command = lambda: self.buttons.seqChoice("arithmetic"))
        self.geomButton = ttk.Radiobutton(self, text = "Geometric Series", variable = self.var, value = 2, command = lambda: self.buttons.seqChoice("geometric"))

I have attempted to deselect them with deselect() but it only works for tk.radiobuttons, which don't look as good and the method still leaves them with a dash.
I want to deselect them so they are not highlighted


Answer:
Use the associated tkinter variable to deselect them:
self.var.set(0)
Question: How to match multiple occurrences of strings given a start and end pattern in R?

library(stringr)
string <- string <- c("pat1 hello333\n pat2 ok i mean pat1 again pat2 some more text pat1")

I want to match all strings that start with pat1 and end with pat2.
> str_extract_all(
  string,
  regex(
    "pat1.+pat2",
    dotall=TRUE
  )
)
[[1]]
[1] "pat1 hello333\n pat2 ok i mean pat1 again pat2"

This gives me 1 string that starts with pat1 and ends with pat2. However, my desired output is something like:
> output
[1] "pat1 hello333\n pat2"
[2] "pat1 again pat2"



Answer:
Change .+ to .+? to have non greedy match.
library(stringr)
str_extract_all(string, regex("pat1.+?pat2", dotall=TRUE))[[1]]
#[1] "pat1 hello333\n pat2" "pat1 again pat2" 

You can use gregexpr and regmatches with pat1.*?pat2 or in case they should be on a word boundary with \\bpat1\\b.*?\\bpat2\\b. Where .*? matches everything but minimal.
regmatches(string, gregexpr("pat1.*?pat2", string))[[1]]
#[1] "pat1 hello333\n pat2" "pat1 again pat2"     

regmatches(string, gregexpr("\\bpat1\\b.*?\\bpat2\\b", string))[[1]]
#[1] "pat1 hello333\n pat2" "pat1 again pat2"
Question: Dragging fields in CrafterCMS Studio

I'm currently teaching myself how to use a headless CMS (CrafterCMS) with Next.js.
I have the following simple content type in CrafterCMS studio (just a title and a text):

And the respective code:
export default async function TestPage() {
    const model = await getModel('/site/website/test/index.xml');
    return (
        <TestComponent model={model} />
    );
}

export default function TestComponent(props) {
    const { isAuthoring } = useCrafterAppContext();
    const { model } = props;

    return (
        <ExperienceBuilder path={model.craftercms.path} isAuthoring={isAuthoring}>
            <Model model={model} >
                <div className="space-y-4">
                    <RenderField
                        model={model}
                        fieldId="title_s"
                        className="text-xl text-gray-800"
                    />

                    <RenderField
                        model={model}
                        fieldId="text_t"
                        className="text-xl text-gray-800"
                    />
                </div>
            </Model>
        </ExperienceBuilder>
    );
}

Is it possible to use Studio functionality to drag and change the positions of my two fields? For example I want to drag the text to be the first element. It seems that i only have the option to change the content, dragging is not available:



Answer:
On CrafterCMS, you can drag & drop mainly 3 things:

Repeating group items
Component item references from an Item Selector control with a "Components" datasource
Media items into a media control (image or video)

The simplest way of achieving what you describe, would be to change your model to wrap with a repeat group the fields you want to reorder via drag & drop (i.e. create a repeat group and add the "title" input control inside of it; only 1, discard the other). Once you've done that, you'll need to update your TestComponent code to use <RenderRepeat ... /> and you should be able to reorder via drag & drop, via the contextual menu up/down buttons, or via the content form.
The rendering of the repeat with your title field, would roughly look something like this:
<RenderRepeat
  model={model}
  fieldId="yourRepeatGroupId_o"
  componentProps={{ className: "space-y-4" }}
  renderItem={(item, index) => (
    <RenderField
      model={model}
      fieldId="yourRepeatGroupId_o.title_s"
      index={index}
      className="text-xl text-gray-800"
    />
  )}
/>

As I mentioned, you could achieve it via components (Item selector control, Components datasource), but the repeat group is simplest for this case; specially to get started and learn.