satoshi-2000/llms-suitable huggingface dataset:
Question: Ms Access running sum with dates and order inside dates

I am using MS Access to create a DB. I have different physical containers and I want to obtain the running sum of the liquid that has been added and taken out of the container to give the balance of the liquid inside the container.
The biggest problem is ordering liquid transactions. I have read lots of resources, and I found out one way of doing this is adding time to the dates so they can be ordered, but I am supposed to not use time, so I have decided to add a manual ordering number within a date which I am not sure is the best way of achieving this, but at least I can do the ordering.
The fields I have are:
-ContainerId
-DateTransaction
-OrderInDate
-Quantity

Quantity is "-" for withdrawal and "+" for additions, so if I can properly get a running total, I will get the balance.
I thought of adding OrderInDate as seconds to the Date to correctly order the data and I have written a query like this (qryInventoryTransactionsOrder):
SELECT ContainerId, Quantity, DateTransaction, OrderInDate,
DateAdd("s",OrderInDate,DateTransaction) AS Expr1,
DSum("Quantity","qryInventoryTransactionsOrder",
"[ContainerId]=" & [ContainerId] & " AND
[Expr1] <= #" & [Expr1] & "#") AS Balance
FROM InventoryTransactions
ORDER BY ContainerId, DateAdd("s",OrderInDate,DateTransaction);

This returns very interesting result like this :




ContainerId
DateTransaction
OrderInDate
Quantity
Expr1
Balance




1
29/05/2023
1
-50
29/05/2023 00:00:01
-50


1
31/05/2023
1
100
31/05/2023 00:00:01
50


1
31/05/2023
2
255
31/05/2023 00:00:02
305


1
01/06/2023
1
-155
01/06/2023 00:00:01



1
01/06/2023
2
-155
01/06/2023 00:00:02



1
01/06/2023
3
2500
01/06/2023 00:00:03



1
08/06/2023
1
-500
08/06/2023 00:00:01
1995




As you will see "Balance" is correct for the first 3 lines, then it returns 3 empty results, and then 1995.
What am I doing wrong here or is there a better way to achieve this result?


Answer:
I can't say anything about recursive queries in MS Access.It is interesting.
Try this query, where DSum counts sum from main table.
SELECT ContainerId, Quantity, DateTransaction, OrderInDate
    ,DateAdd("s",OrderInDate,DateTransaction) AS Expr1
    ,DSum("Quantity","InventoryTransactions"
       ,"[ContainerId]=" & [ContainerId] 
        & " AND Format(DateAdd(""s"",OrderInDate,DateTransaction),""yyyyMMddhhmmss"") <= " 
      & format(DateAdd("s",OrderInDate,DateTransaction),"yyyyMMddhhmmss") & "") 
    AS Balance
FROM InventoryTransactions
ORDER BY ContainerId, DateAdd("s",OrderInDate,DateTransaction);
Question: Why is my FParsec parser failing to recognize a block comment?

I'm trying to parse C style comments using FParsec.  Not sure why this is failing:
My parser code:
let openComment : Parser<_,unit>  = pstring "/*"
let closeComment : Parser<_,unit> = pstring "*/"
let comment = pstring "//" >>. restOfLine true
                <|> openComment >>. (charsTillString "*/" true System.Int32.MaxValue) |>> Comment
                //<|> openComment >>. manyCharsTill anyChar closeComment |>> Comment
let spaceComments = many ((spaces1 |>> IgnoreU) <|> comment)
let str s  = spaceComments >>. pstring s .>> spaceComments

Test Harness:
let testStr = @"
// test comment
/* a block comment
   */
   x  // another comment
   "
match run (str "x") testStr with
| Success(result, _, _)   -> printfn "Success: %A" result
| Failure(errorMsg, _, _) -> assert false
()


Error messager.  It is the same for both charsTillString and manyCharsTill
Error in Ln: 6 Col: 4
   
   ^
Note: The error occurred at the end of the input stream.
Could not find the string '*/'.

Comment and IgnoreU are both a discrimated type of string


Answer:
The problem is that the combinators in your comment parser don't have the precedence/associativity that you want. You can fix this by grouping with parens:
let comment = (pstring "//" >>. restOfLine true)
                <|> (openComment >>. (charsTillString "*/" true System.Int32.MaxValue)) |>> Comment

I find that choice is often easier to read than <|> for complex parsers:
let comment =
    choice [
        pstring "//" >>. restOfLine true
        openComment >>. (charsTillString "*/" true System.Int32.MaxValue)
    ] |>> Comment
Question: How can I create a code template in Android Studio to replicate the val template in Kotlin

Kotlin and Java code templates in Android Studio.
I tried to create a code template for the truth library that would work like the val template works i.e,

When you want to create a variable from the result of calling a function? you just type,
functionName().val.
When you press enter a variable is created ie, val f = functionName().

How would I replicate this behaviour on the truth library such that when I type f.assert for instance, I get Truth.assertThat(f)?


Answer:
This feature is named "Postfix completion"
You can find details here https://www.jetbrains.com/help/idea/settings-postfix-completion.html
I have tried now and it's allowed me to add and edit java and groovy templates but kotlin is not supported.
The other perfect feature of Idea is Live templates you can use them to implement required templates.
You can find details here https://www.jetbrains.com/help/idea/using-live-templates.html
Update: I have checked the current version of Idea, kotlin is not supported yet.
Question: Serialize property access exception to json

I have a simple class that one of properties is:
public TValue Value => IsSuccess
    ? _value
    : throw new InvalidOperationException("The value of a failure result can not be accessed.");

So it works like this, when some operation is a success assign value from this operation to property easy. But now I when I do sutch a thig:
var result = new Result (someValue) { IsSuccess = false }
var serialized =  JsonConvert.SerializeObject(result); // of course result type is marked as seriazable

So here I am setting such a result to false, and next I want to serilize it, problem is that exception is not serializing and I am getting just thrown exception. What am I missing here?


Answer:
I'm wondering whether there isn't a better design for what you're trying to achieve. Namely, it might be better to move the IsSuccess check logic into a method so that it doesn't get hit during serialization. But if you really decide to do it this way, you could use a JsonConverter to catch and serialize the exception for you:
public class ValueOrExceptionConverter : JsonConverter
{
    public override void WriteJson(JsonWriter writer, object? value, JsonSerializer serializer)
    {
        if (value == null)
        {
            return;
        }

        try
        {
            serializer.Serialize(writer, ((dynamic)value).Value);
        }
        catch (Exception ex)
        {
            serializer.Serialize(writer, new { Value = new { ex.Message } });
        }
    }

    public override object? ReadJson(JsonReader reader, Type objectType, object? existingValue, JsonSerializer serializer)
    {
        throw new NotImplementedException();
    }

    public override bool CanConvert(Type objectType) => true;
}

I'm assuming your Result class is generic so using this converter would look like this:
[JsonConverter(typeof(ValueOrExceptionConverter))]
public class Result<TValue>

This is all assuming that you're using Newtonsoft.Json. The result of using that converter is something like this:
{"Value":"Message":"The value of a failure result can not be accessed."}}

A few notes about the converter code:

Instead of casting to dynamic, you might be better of using an interface or abstract class if you have it. Or if you know exactly which generics you might use for TValue then perhaps you can cast even more specifically.
I've assumed that you don't want to serialize the entire exception. So if you need more than just the Message then you can add those properties like so for example: new { ex.Message, InnerMessage = ex.InnerException.Message }.
I've assumed that the Result class only has one property, named Value. You can add more properties in the same way you can add additional Exception properties.
I haven't implemented the ReadJson because deserializing the exception instead of the value makes that quite tricky. But I'm sure it's not impossible if you need to also deserialize the Result.
Question: React Router cancel loader

I'm throwing an error in my loaders when response.status.ok of fetch is false. Error component is then loaded.
But my server sometimes returns 429 status code (too many requests) upon which I don't want to load an error component but instead simply do nothing, or maybe display some message but certainly without reloading the already loaded component, or redirecting, etc.
How can that be implemented?
https://codesandbox.io/s/hungry-hooks-yuucsp?file=/src/App.js


Answer:
You can check the response status code specifically for a 429 status and return any defined value back to the UI. I think the important detail here that you should return something instead of undefined. null appears to work and not throw any extraneous errors
function loader() {
  let response = imitateFetch();
  console.log(response);

  if (response.status === 429) {
    console.log(429);
    return null; // <-- return null
  }

  if (!response.ok) {
    throw "loader error";
  }
  return {};
}

but you can return anything you like, for example, change the response status to 200.
function loader() {
  let response = imitateFetch();
  console.log(response);

  if (response.status === 429) {
    console.log(429);
    response.status = 200;
    response.ok = true;
    return response;
  }

  if (!response.ok) {
    throw "loader error";
  }
  return {};
}


It's really up to your app's, or code's, specific use case what it returns and how the UI handles it.
Question: How to mock string as content of file for pytest?

How can I provide string to function in pytest, so that function under test treat it as content of file ?
I have function that is parsing file. File is custom text format.
I want to test multiple different input files.
Initial idea was to use pytest is this way:
import pytest
import mymodule as t

# this is all valid one line config file, starting simple
@pytest.mark.parametrize("input_file", [
    "#",
    "##",
    "",
    "   ",
    "  ",
])

def test_is_input_file_valid(input_file):
    assert t.myclass(input_file)

Problem that I have is each line need to be content of input file, because t.myclass(input_file) is expecting file not string. So, I need somehow to mock it.
I am assuming pytest have this functionality by default or plugin, but was not able to find it.


Answer:
I wrote a pytest plugin called pytest_tmp_files to solve this exact problem.  Here's how it would look for your example:
@pytest.mark.parametrize(
    'tmp_files', [
        {'f': '#'},
        {'f': '##'},
        {'f': ''},
        {'f': '   '},
        {'f': '  '},
    ],
    indirect=['tmp_files'],
)
def test_is_input_file_valid(tmp_files):
    assert t.myclass(tmp_files / 'f')

Some things worth noting:

The parameters are dictionaries where the keys are file names and the values are files contents.  This is a bit more verbose that just specifying the file contents, but much more flexible.
I'm assuming that your parser accepts pathlib.Path objects, which is what tmp_files / 'f' is.  If not, you might have to do some sort of conversion here, but it should be straight forward.
The specified files are actually created in a real temporary directory (unique for each test case), so you can treat them exactly like real files.
I wrote another pytest plugin called parametrize_from_file that allows you to specify test parameters in structured data files (e.g. YAML), separate from the test code.  I'd recommend checking it out as well.  File contents often end up being long, multi-line strings that mess up the indentation of the parameter list and make the whole test script hard to read.  Moving these parameters to a separate file can really help readability.

See also this discussion on GitHub, where I tried to get this feature added to pytest proper.
Question: defaultValue for input type 'date' is not working in Nextjs

I am using Nextjs and I would like to use the html tag, input type of 'date'. I also would like to set a defaultValue and I did something like this and it is not working:
const [dDate, setdDate] = useState('17/11/2022');


const ReactComponent = ()=>{
  
    return(
       
          <input type="date" className=" border-2 py-1 px-2 rounded-md" 
         onChange={(text)=>handleDepositeDate(text.target.value, index)} defaultValue={dDate} 
      />
     )

 };

It does not display on the screen. I also tried using value instead of defaultValue, still didn't work. I also tried other date input on the application and defaultValue didn't work.


Answer:
Try using a different date format with the value attribute, like so:
<input type="date" value="2022-11-17"/>
Question: Can't use assume role to accesss aws eks which is created by assume role api

I created a aws eks using assume role api. Role A assume role B to performe create EKS api. I create the eks and specify that the EKS's cluster role is role C. As I know,the role C's arn will be stored in eks aws-auth configMap.
When A assume role C to access the created EKS, "Failed to get namespaces: Unauthorized" returned.
I always use assume role to invoke API. Does anyone know, whether aws-auth store role C's arn like 'arn:aws:iam::C:role/k8s-cluster-role' or eks store the role arn in aws-auth in another way.


Answer:
You have some misconception; The role that is stored in aws-auth configmap for system:masters group in your cluster is not the cluster role, but the iam principal that creates the cluster itself, as per official doc.

When you create an Amazon EKS cluster, the IAM principal that creates the cluster is automatically granted system:masters permissions in the cluster's role-based access control (RBAC) configuration in the Amazon EKS control plane.

From what you have written, if the sequence is right, and that assume-role approach you are following works properly, you should be able to query your cluster api resources with role-b not role-c, since b is the one you used to create the cluster. In your current setup, you are expecting role C to be able to access cluster resources, though you created with role b.
Question: Description bug in DEB file created by jpackage when opened with QApt installer

Adding description with --description while creating deb package on linux creates deb file, which when opened with QApt package installer (double click installation) shows defined text in description section, which seems like a bold header and underneath there is that description again with first character stripped:

Command:
jpackage -t deb \
--app-version 1.0.0 \
--icon books256.png \
--name hello \
--description 'my testing text' \
--dest target/jpackage_outputdir/ \
--temp target/jpackage_tempdir \
--input target/jpackage_inputdir \
--main-class core.Main \
--main-jar jarfile.jar \
--linux-menu-group Office \
--linux-shortcut

Is there a way to prevent this unprofessional look by finely setting bold header and text underneath separately or at least by removing this duplication in description section?
Using Kubuntu 23.0.4, JDK - openjdk 17.0.7 2023-04-18 LTS


Answer:
A solution to this problem might be to use multi-line description. First line is then bold text and second line is below it, altough bug still remains when using single-line description.
jpackage -t deb \
--app-version 1.0.0 \
--icon books256.png \
--name hello \
--description 'first line
second line' \
--dest target/jpackage_outputdir/ \
--temp target/jpackage_tempdir \
--input target/jpackage_inputdir \
--main-class core.Main \
--main-jar jarfile.jar \
--linux-menu-group Office \
--linux-shortcut
Question: How to type Material UI Icon's fontSize prop?

I've composed the component below, and I need to apply a type for the custom iconFontSize prop. How can I do this?
import { SvgIconComponent } from '@mui/icons-material'
import { Typography, TypographyProps} from '@mui/material'

type Props = TypographyProps & {
  Icon: SvgIconComponent
  iconFontSize: /* insert type here! */
}

export const IconTypography = ({
  Icon,
  iconFontSize = 'inherit',
  columnGap = 1,
  children,
  ...props
}: Props) => {
  return (
    <Typography display="flex" alignItems="center" columnGap={columnGap} {...props}>
      <Icon fontSize={iconFontSize} />
      {children}
    </Typography>
  )
}

Thanks in advance!


Answer:
You can type iconFontSize as a union type of  'inherit' | 'large' | 'medium' | 'small':
type Props = TypographyProps & {
  Icon: SvgIconComponent
  iconFontSize: "inherit" | "small" | "medium" | "large" 
}

If you want to use the exact type from the MUI type definition file, you can alternatively use:

import { OverridableStringUnion } from '@mui/types';

fontSize?: OverridableStringUnion<
  'inherit' | 'large' | 'medium' | 'small',
  SvgIconPropsSizeOverrides
>;

The OverridableStringUnion type is in turn defined as such:
export type OverridableStringUnion<T extends string | number, U = {}> = GenerateStringUnion<
  Overwrite<Record<T, true>, U>
>;

See the type definition in the MUI docs here: https://mui.com/material-ui/api/svg-icon/
Question: Cloning a texture created with THREE.WebGLRenderTarget

I'm using three.js and I need to create a few clones of a texture made with THREE.WebGLRenderTarget().
I can use the original texture, e.g.:
scene.background = renderTarget.texture;
But if I try to use a clone of it:
const tex = renderTarget.texture.clone();
scene.background = tex;
I get the following error:
THREE.WebGLState: TypeError: Failed to execute 'texSubImage2D' on 'WebGL2RenderingContext': Overload resolution failed.
If I add the line:
tex.isRenderTargetTexture = true;
Now I don't get any error, but the texture is all black.
I have also tried to clone the render target (instead of its texture) but it didn't work either. Can you please help me?
Thank you in advance.


Answer:
Problem solved: I created a framebuffer texture, and I copied the texture by using method renderer.copyFramebufferToTexture() of class THREE.WebGLRenderer.
Question: Jolt not printing anything

I am writing jolt for transforming this data but not getting desired result
If practice_loc,prac_num and topId are same for two or more data then they will be combined together with separate S1 and S2 within subList. Else they would pass as it is with addition of subList only.
Data
[
  {
    "practice_loc": "120",
    "prac_num": "oswal",
    "topId": "t1",
    "S1": "A1",
    "S2": "B1"
  },
  {
    "practice_loc": "120",
    "prac_num": "oswal",
    "topId": "t1",
    "S1": "A2",
    "S2": ""
  },
  {
    "practice_loc": "334",
    "prac_num": "L3",
    "topId": "plumcherry",
    "S1": "A3",
    "S2": ""
  },
  {
    "practice_loc": "987",
    "prac_num": "L3",
    "topId": "artica",
    "S1": "A5",
    "S2": "B7"
  }
]

Expected Output:
[
  {
    "practice_loc": "120",
    "prac_num": "oswal",
    "topId": "t1"
    "subList": [
      {
        "S1": "A1",
        "S2": "B1"
      },
      {
        "S1": "A2",
        "S2": ""
      }
    ]
  },
  {
    "practice_loc": "334",
    "prac_num": "L3",
    "topId": "plumcherry"
    "subList": [
      {
        "SubID1": "A3",
        "SubID2": ""
      }
    ]
  },
  {
    "practice_loc": "987",
    "prac_num": "L3",
    "topId": "artica",
    "subList": [
      {
        "SubID1": "A5",
        "SubID2": "B7"
      }
    ]
  }
]

Here is what I tried but didnt get desired result Its not printing anything
[
  {
    "operation": "shift",
    "spec": {
      "*": {
        "@": "@(1,practice_loc).@(1,prac_num).@(1,topId)"
      }
    }
  },
  {
    "operation": "cardinality",
    "spec": {
      "*": {
        "*": "MANY"
      }
    }
  },
  {
    "operation": "shift",
    "spec": {
      "*": {
        "*": {
          "*": {
            "practice_loc": "[#4].&",
            "prac_num": "[#4].&",
            "topId": "[#4].&",
            "S*": "[#4].subList[&1].&"
          }
        }
      }
    }
  },
  {
    "operation": "cardinality",
    "spec": {
      "*": {
        "practice_loc": "ONE",
        "prac_num": "ONE",
        "topId": "ONE"
      }
    }
  }
]



Answer:
Your current spec is pretty good. Would be suitable to rearrange it like that
[
  { // group by those three attributes
    "operation": "shift",
    "spec": {
      "*": {
        "*": "@1,practice_loc.@1,prac_num.@1,topId.&",
        "S*": "@1,practice_loc.@1,prac_num.@1,topId.subList[&1].&"
      }
    }
  },
  { // get rid of wrappers
    "operation": "shift",
    "spec": {
      "*": {
        "*": {
          "*": {
            "@": ""
          }
        }
      }
    }
  },
  {
    "operation": "cardinality",
    "spec": {
      "*": {
        "*": "ONE", // pick only single one from repeating components 
        "subList": "MANY"
      }
    }
  },
  { // get rid of generated nulls within subList arrays 
    "operation": "modify-overwrite-beta",
    "spec": {
      "*": "=recursivelySquashNulls"
    }
  }
]

Edit for illustration : Below, I have pasted the image what I get after toggling ADVANCED tab of Configure section for the JoltTransformJSON processor which has the version 1.21.0 as NiFi does. Btw, yours is a recent version as well.
Question: Can't find services package.json when running docker-compose

I am building a docker-compose.yml file inside a workspace, but when I try to run docker-compose, I can't start my services because of the following error ENOENT: no such file or directory, open '/entity-service/package.json' the same error happens when trying to start the agent-portal-service container as well but the error happens in this directory /agent-portal-service/package.json. But my projects indeed have a package.json file, I think that this is related to the context that docker-compose is running.
Here is my workspace structure:
├── agent-portal-service
├── data
├── docker-compose.yml
└── entity-service

My docker-compose.yml:
version: "3"

services:
  agent_portal_service:
    working_dir: /agent-portal-service
    container_name: agent_portal_service
    image: node:16
    volumes:
      - /agent-workspace:/agent-portal-service
    ports:
      - 3100:3100
    command: npm run start:debug
    tty: true

  entity_service:
    working_dir: /entity-service
    container_name: entity_service
    image: node:16
    volumes:
      - /agent-workspace:/entity-service
    ports:
      - 3101:3101
    command: npm run start:debug
    tty: true
    depends_on:
      - mongodb

  mongodb:
    container_name: mongodb
    image: mongo:4.4.6
    ports:
      - 27017:27017
    volumes:
      - ./data/db:/data/db
    command: mongod --port 27017
    restart: always

I am expecting to be able to run the agent_portal_service and entity_service containers successfully


Answer:
The important parts of your entity-service definition look like this
  entity_service:
    working_dir: /entity-service
    volumes:
      - /agent-workspace:/entity-service
    command: npm run start:debug

You map /agent-workspace to /entity-service in the volumes section. You also set your working directory to /entity-service. In effect, your working directory is /agent-workspace on your host machine. There's no package.json file in the /agent-workspace directory, so your npm command fails.
To fix it, I'd map /agent-workspace/entity-service to /entity-service instead. That way, you'll have a package.json file in your /entity-service directory inside the container.
Like this
volumes:
  - /agent-workspace/entity-service:/entity-service