问:
How to disable ripple effect on primary action in react material lists
I was trying to have two action buttons on the left and right end of the list component.

on click of secondary action (right side delete icon) the ripple is limited to the only icon.

on click of primary action(left delete icon) the ripple effect is on the whole row.

Expected Behaviour :

I want the ripple effect on the primary, similar to that of the secondary action button.

And important I cannot disable the text ripple effect as temporary solution.

Code Sample:

Code-Sandbox link

```<code>import React from "react";
import { makeStyles } from "@material-ui/core/styles";
import List from "@material-ui/core/List";
import ListItem from "@material-ui/core/ListItem";
import ListItemIcon from "@material-ui/core/ListItemIcon";
import ListItemText from "@material-ui/core/ListItemText";

import ListItemSecondaryAction from "@material-ui/core/ListItemSecondaryAction";
import DeleteIcon from "@material-ui/icons/Delete";
import IconButton from "@material-ui/core/IconButton";

const useStyles = makeStyles((theme) => ({
  root: {
    width: "100%",
    maxWidth: 360,
    backgroundColor: theme.palette.background.paper
  }
}));

export default function SelectedListItem() {
  const classes = useStyles();
  const [selectedIndex, setSelectedIndex] = React.useState(1);

  const handleListItemClick = (event, index) => {
    setSelectedIndex(index);
  };

  return (
    <div className={classes.root}>
      <List component="nav" aria-label="main mailbox folders">
        <ListItem
          button
          selected={selectedIndex === 0}
          onClick={(event) => handleListItemClick(event, 0)}
        >
          <ListItemIcon>
            <IconButton edge="end" aria-label="delete">
              <DeleteIcon />
            </IconButton>
          </ListItemIcon>
          <ListItemText primary="Inbox" />
          <ListItemSecondaryAction>
            <IconButton edge="end" aria-label="delete">
              <DeleteIcon />
            </IconButton>
          </ListItemSecondaryAction>
        </ListItem>
        <ListItem
          button
          selected={selectedIndex === 1}
          onClick={(event) => handleListItemClick(event, 1)}
        >
          <ListItemIcon>
            <IconButton edge="end" aria-label="delete">
              <DeleteIcon />
            </IconButton>
          </ListItemIcon>
          <ListItemText primary="Drafts" />
          <ListItemSecondaryAction>
            <IconButton edge="end" aria-label="delete">
              <DeleteIcon />
            </IconButton>
          </ListItemSecondaryAction>
        </ListItem>
      </List>
    </div>
  );
}
</code>```

答:
I think it's because  is used to add secondary action to button so when you click on the secondary action area it prevent primaryAction to happen. So in your case when you click on right icon it contains the ripple affect inside ListItemSecondaryAction area. If you want to disable ripple on the List you can add prop 'disableRipple' on your ListItem and it will be disabled but if you want it conditional ie. when user clicks on icon ripple should happen only on icon and if clicked on button only in button than you can try stop propagation when clicked on button ( might not work ) but you can give it a try.

I've created a work around sharing codesandbox link with you

https://codesandbox.io/s/material-demo-forked-i7k7e?file=/demo.js

```<code>        <ListItem
          button
          disableRipple
          selected={selectedIndex === 0}
          onClick={(event) => handleListItemClick(event, 0)}
          style={{ position: "relative" }}
        >
          <div style={{ zIndex: 1 }}>
            <ListItemIcon>
              <IconButton edge="end" aria-label="delete">
                <DeleteIcon />
              </IconButton>
            </ListItemIcon>
            <ListItemText primary="Inbox" />
            <ListItemSecondaryAction>
              <IconButton edge="end" aria-label="delete">
                <DeleteIcon />
              </IconButton>
            </ListItemSecondaryAction>
          </div>
          <ButtonBase
            style={{
              position: "absolute",
              bottom: 0,
              top: 0,
              left: 0,
              right: 0,
              width: "100%",
              zIndex: 0
            }}
          />
        </ListItem>
</code>```

Body:
I was trying to have two action buttons on the left and right end of the list component.

on click of secondary action (right side delete icon) the ripple is limited to the only icon.

on click of primary action(left delete icon) the ripple effect is on the whole row.

Expected Behaviour :

I want the ripple effect on the primary, similar to that of the secondary action button.

And important I cannot disable the text ripple effect as temporary solution.

Code Sample:

Code-Sandbox link

import React from "react";
import { makeStyles } from "@material-ui/core/styles";
import List from "@material-ui/core/List";
import ListItem from "@material-ui/core/ListItem";
import ListItemIcon from "@material-ui/core/ListItemIcon";
import ListItemText from "@material-ui/core/ListItemText";

import ListItemSecondaryAction from "@material-ui/core/ListItemSecondaryAction";
import DeleteIcon from "@material-ui/icons/Delete";
import IconButton from "@material-ui/core/IconButton";

const useStyles = makeStyles((theme) => ({
  root: {
    width: "100%",
    maxWidth: 360,
    backgroundColor: theme.palette.background.paper
  }
}));

export default function SelectedListItem() {
  const classes = useStyles();
  const [selectedIndex, setSelectedIndex] = React.useState(1);

  const handleListItemClick = (event, index) => {
    setSelectedIndex(index);
  };

  return (

      <List component="nav" aria-label="main mailbox folders">
        <ListItem
          button
          selected={selectedIndex === 0}
          onClick={(event) => handleListItemClick(event, 0)}
        >
          <ListItemIcon>
            <IconButton edge="end" aria-label="delete">
              <DeleteIcon />
            </IconButton>
          </ListItemIcon>
          <ListItemText primary="Inbox" />
          <ListItemSecondaryAction>
            <IconButton edge="end" aria-label="delete">
              <DeleteIcon />
            </IconButton>
          </ListItemSecondaryAction>
        </ListItem>
        <ListItem
          button
          selected={selectedIndex === 1}
          onClick={(event) => handleListItemClick(event, 1)}
        >
          <ListItemIcon>
            <IconButton edge="end" aria-label="delete">
              <DeleteIcon />
            </IconButton>
          </ListItemIcon>
          <ListItemText primary="Drafts" />
          <ListItemSecondaryAction>
            <IconButton edge="end" aria-label="delete">
              <DeleteIcon />
            </IconButton>
          </ListItemSecondaryAction>
        </ListItem>
      </List>

  );
}

Body:
I think it's because  is used to add secondary action to button so when you click on the secondary action area it prevent primaryAction to happen. So in your case when you click on right icon it contains the ripple affect inside ListItemSecondaryAction area. If you want to disable ripple on the List you can add prop 'disableRipple' on your ListItem and it will be disabled but if you want it conditional ie. when user clicks on icon ripple should happen only on icon and if clicked on button only in button than you can try stop propagation when clicked on button ( might not work ) but you can give it a try.

I've created a work around sharing codesandbox link with you

https://codesandbox.io/s/material-demo-forked-i7k7e?file=/demo.js

        <ListItem
          button
          disableRipple
          selected={selectedIndex === 0}
          onClick={(event) => handleListItemClick(event, 0)}
          style={{ position: "relative" }}
        >
          <div style={{ zIndex: 1 }}>
            <ListItemIcon>
              <IconButton edge="end" aria-label="delete">
                <DeleteIcon />
              </IconButton>
            </ListItemIcon>
            <ListItemText primary="Inbox" />
            <ListItemSecondaryAction>
              <IconButton edge="end" aria-label="delete">
                <DeleteIcon />
              </IconButton>
            </ListItemSecondaryAction>
          </div>
          <ButtonBase
            style={{
              position: "absolute",
              bottom: 0,
              top: 0,
              left: 0,
              right: 0,
              width: "100%",
              zIndex: 0
            }}
          />
        </ListItem>


来源: stackexchange

问:
How To Convert base64 String to PDF in React.js
I have a base 64 string that is coming from an API call. I am testing with a sample base64 string and I am trying to convert it to pdf or an image to view in my react.js website.

I've tried many solutions, but nothing seems to work. I found a react js package that is called base64topdf I installed it and tried to decode the base64 string to PDF, but it gives me this error "TypeError: fs.writeFileSync is not a function"

I don't know what i am doing wrong.

How can I convert a base64 string to a PDF or an image in reactjs?

Documentation to the package https://www.npmjs.com/package/base64topdf

Here is my code:

```<code> const base64 = require('base64topdf');

 const base64STR = "JVBERi0xLjQKJeLjz9M...." //base64 string

 const decodedBase64 = base64.base64Decode(base64STR, 'waybill');

 console.log(decodedBase64)
</code>```

答:
It seems that the functions base64Decode and base64Encode should be used in NodeJS only, your React env should not be able to access fs or Buffer.

Look at he file here: https://github.com/rpsankar001/base64topdf/blob/master/index.js

Also this package seems very empty, I would prefer const decodedBase64 = atob("JVBERi0xLjQKJeLjz9M...."); //base64 string

ContentLicense: CC BY-SA 4.0

Body:
I have a base 64 string that is coming from an API call. I am testing with a sample base64 string and I am trying to convert it to pdf or an image to view in my react.js website.

I've tried many solutions, but nothing seems to work. I found a react js package that is called base64topdf I installed it and tried to decode the base64 string to PDF, but it gives me this error "TypeError: fs.writeFileSync is not a function"

I don't know what i am doing wrong.

How can I convert a base64 string to a PDF or an image in reactjs?

Documentation to the package https://www.npmjs.com/package/base64topdf

Here is my code:

 const base64 = require('base64topdf');

 const base64STR = "JVBERi0xLjQKJeLjz9M...." //base64 string

 const decodedBase64 = base64.base64Decode(base64STR, 'waybill');

 console.log(decodedBase64)


问:
ITMS-90338: Non-public API usage - The app references non-public selectors in [App]
I am building a Xamarin.Forms app that is building properly and deploying to the Apple App Store but keeps getting rejected for the following reasons:

ITMS-90338: Non-public API usage - The app references non-public
selectors in [App].Mobile.iOS: accessibilityBrailleMapRenderRegion,
accessibilityBrailleMapRenderer, accessibilityColumnRange,
accessibilityRowRange, activePlayer, beginAuthorizationWithRequest:,
cancelAuthorizationWithRequest:, errorForCHIPErrorCode:,
errorToCHIPErrorCode:, playerId, serviceExtensionWillTerminate,
session:didReceiveData:fromPlayer:,
session:didReceiveMessage:withData:fromPlayer:,
session:player:didChangeConnectionState:, session:player:didSaveData:,
setAccessibilityBrailleMapRenderRegion:,
setAccessibilityBrailleMapRenderer:. If method names in your source
code match the private Apple APIs listed above, altering your method
names will help prevent this app from being flagged in future
submissions. In addition, note that one or more of the above APIs may
be located in a static library that was included with your app.

I coded the app on a PC in Visual Studio Community 2019 v16.9.1. And built and deployed the app via Appcenter.ms.

Packages that I am using are:

Microsoft.AppCenter.Analytics v4.5.0

Microsoft.AppCenter.Crashes v4.5.0

Xamarin.Essentials v1.7.1

Xamarin.Forms v5.0.0.2337

Target Framework: .NET Standard 2.0

Information that I have confirmed from other sources:

Build Configuration: Release

Linker Behavior: Link Framework SDKs Only

Additional mtouch arguments: --linkskip=[selectors]

Additional mtouch arguments: --linkplatform

I have found all of the non-public selectors in xamarin/xamarin-macios and xamarin/apple-api-docs but I have not been able to find out how to fix the errors.

Thanks

Edit: I was not able to fix the issue. Instead, I got a Mac VM and was able to publish the code that way.

答: Add --linkplatform to the Additional mmp arguments.</p>


问:
Maximum and Minimum using loops
I had to rearrange code so that when I run the program the output is:

My attempt allowed the output to do everything except print the maximum or the minimum. Have tried moving count = count + 1 outside the loop to no avail. Still a beginner, any help is appreciated. my attempt:

```<code>value = int(input("Enter an input value: "))
number = int(input("How many numbers would you like to enter: "))
count = 1
largest = value
smallest = value
while count <= number :
    value = int(input("Enter an input value: "))
    count = count + 1
    if value > largest :
        largest = value
        print("The maximum is: ", largest)
    if value < smallest :
        smallest = value
        print("The minimum is: ", smallest)
</code>```

expected output:

```<code>Enter an input value: 3
How many numbers would you like to enter: 7
Enter an input value: 2
Enter an input value: 9
Enter an input value: 23
Enter an input value: 4
Enter an input value: 1
Enter an input value: 8
Enter an input value: 3
The maximum is:  23
The minimum is:  1
</code>```

答:
You just need to move the print at the end of your code, only after you have tested all elements:

```<code>value = int(input("Enter an input value: "))
number = int(input("How many numbers would you like to enter: "))
count = 1
largest = value
smallest = value
while count <= number :
    value = int(input("Enter an input value: "))
    count = count + 1
    if value > largest :
        largest = value
    if value < smallest :
        smallest = value
print("The maximum is: ", largest)
print("The minimum is: ", smallest)
</code>```

output:

```<code>Enter an input value: 3
How many numbers would you like to enter: 7
Enter an input value: 2
Enter an input value: 9
Enter an input value: 23
Enter an input value: 4
Enter an input value: 1
Enter an input value: 8
Enter an input value: 3
The maximum is:  23
The minimum is:  1
</code>```

Title: Maximum and Minimum using loops

Body:
I had to rearrange code so that when I run the program the output is:

My attempt allowed the output to do everything except print the maximum or the minimum. Have tried moving count = count + 1 outside the loop to no avail. Still a beginner, any help is appreciated. my attempt:

value = int(input("Enter an input value: "))
number = int(input("How many numbers would you like to enter: "))
count = 1
largest = value
smallest = value
while count <= number :
    value = int(input("Enter an input value: "))
    count = count + 1
    if value > largest :
        largest = value
        print("The maximum is: ", largest)
    if value < smallest :
        smallest = value
        print("The minimum is: ", smallest)

expected output:

Enter an input value: 3
How many numbers would you like to enter: 7
Enter an input value: 2
Enter an input value: 9
Enter an input value: 23
Enter an input value: 4
Enter an input value: 1
Enter an input value: 8
Enter an input value: 3
The maximum is:  23
The minimum is:  1

Body:
You just need to move the print at the end of your code, only after you have tested all elements:

value = int(input("Enter an input value: "))
number = int(input("How many numbers would you like to enter: "))
count = 1
largest = value
smallest = value
while count <= number :
    value = int(input("Enter an input value: "))
    count = count + 1
    if value > largest :
        largest = value
    if value < smallest :
        smallest = value
print("The maximum is: ", largest)
print("The minimum is: ", smallest)

output:

Enter an input value: 3
How many numbers would you like to enter: 7
Enter an input value: 2
Enter an input value: 9
Enter an input value: 23
Enter an input value: 4
Enter an input value: 1
Enter an input value: 8
Enter an input value: 3
The maximum is:  23
The minimum is:  1


问:
My buttons expand to container width, how can I stop this and just wrap them around the text?
My buttons keep expanding to container width. I want to make them normal, just wrapped around the text. The size depends on how long the text is.
Does anyone know what I'm doing wrong?

Thanks!

.btn {
    display: inline-block;
    padding: 10px 30px;
    cursor: pointer;
    background: var(--orange-color);
    color: white;
    border-radius: 5px;
    box-shadow: 0 3px 10px rgba(0,0,0,0.2);
}```

答:
Most probably you have a width: 100% on your button in some part of your CSS file.

Or the containing element is a flex-container with flex-direction: column. This also may cause the button to stretch to the width of the container. (caused by the default align-items: stretch)

.btn {
    display: inline-block;
    padding: 10px 30px;
    cursor: pointer;
    background: var(--orange-color);
    color: white;
    border-radius: 5px;
    box-shadow: 0 3px 10px rgba(0,0,0,0.2);

    width: max-content; /* pushes the width to be the size of the content */
    max-width: 100%; /* ensures the button doesn't overflow the container */
}
```


问:
How to handle one-shot operations in Jetpack Compose?
Note - This question is pretty much the same as this one.

I am looking for a better approach if there is any.

As per Android Docs,

Once the transient message has been shown, the UI needs to notify the
ViewModel of that, causing another UI state update:

For example, when I show a Toast message on a button click, should the UI notify the ViewModel that the toast is shown successfully?

Is that the intended best approach to handle one-shot operations like toasts, snackbar, etc?

Sample code,

```<code>@Composable
fun OneShotOperation(
    viewmodel: OneShotOperationViewModel = viewModel(),
) {
    val context = LocalContext.current

    LaunchedEffect(
        key1 = viewmodel.toastMessage,
    ) {
        if (viewmodel.toastMessage.isNotBlank()) {
            Toast.makeText(
                context,
                viewmodel.toastMessage,
                Toast.LENGTH_SHORT,
            ).show()
            viewmodel.toastMessage = "" // Is this the correct way?
        }
    }

    Button(
        onClick = {
            viewmodel.toastMessage = "Sample Toast"
        },
    ) {
        Text(text = "Show Toast")
    }
}

class OneShotOperationViewModel : ViewModel() {
    var toastMessage by mutableStateOf(
        value = "",
    )
}
</code>```

If I remove this line,

viewmodel.toastMessage = "" // Is this the correct way?

The toast is shown only once, the subsequent button press do not show a toast since the mutable state has not changed.

答:
I prefer using SharedFlow for a job like this:

```<code>class OneShotOperationViewModel : ViewModel() {
    private val _toastMessage = MutableSharedFlow<String>()
    val toastMessage = _toastMessage.asSharedFlow()

    fun sendMessage(message: String) {
        viewModelScope.launch {
            _toastMessage.emit(message)
        }
    }
}

@Composable
fun TestScreen() {
    val context = LocalContext.current

    val viewModel = viewModel<OneShotOperationViewModel>()
    LaunchedEffect(Unit) {
        viewModel
            .toastMessage
            .collect { message ->
                Toast.makeText(
                    context,
                    message,
                    Toast.LENGTH_SHORT,
                ).show()
            }
    }
    Button(
        onClick = {
            viewModel.sendMessage("Sample Toast")
        },
    ) {
        Text(text = "Show Toast")
    }
}
</code>```

Note that if you send a message from another view while collect is not running, it will not show toast when you finally start it. It does not store the value, it only passes it on to all the collectors that are currently connected.

Body:
Note - This question is pretty much the same as this one.

I am looking for a better approach if there is any.

As per Android Docs,

Once the transient message has been shown, the UI needs to notify the
ViewModel of that, causing another UI state update:

For example, when I show a Toast message on a button click, should the UI notify the ViewModel that the toast is shown successfully?

Is that the intended best approach to handle one-shot operations like toasts, snackbar, etc?

Sample code,

@Composable
fun OneShotOperation(
    viewmodel: OneShotOperationViewModel = viewModel(),
) {
    val context = LocalContext.current

    LaunchedEffect(
        key1 = viewmodel.toastMessage,
    ) {
        if (viewmodel.toastMessage.isNotBlank()) {
            Toast.makeText(
                context,
                viewmodel.toastMessage,
                Toast.LENGTH_SHORT,
            ).show()
            viewmodel.toastMessage = "" // Is this the correct way?
        }
    }

    Button(
        onClick = {
            viewmodel.toastMessage = "Sample Toast"
        },
    ) {
        Text(text = "Show Toast")
    }
}

class OneShotOperationViewModel : ViewModel() {
    var toastMessage by mutableStateOf(
        value = "",
    )
}

If I remove this line,

viewmodel.toastMessage = "" // Is this the correct way?

The toast is shown only once, the subsequent button press do not show a toast since the mutable state has not changed.

Body:
I prefer using SharedFlow for a job like this:

class OneShotOperationViewModel : ViewModel() {
    private val _toastMessage = MutableSharedFlow<String>()
    val toastMessage = _toastMessage.asSharedFlow()

    fun sendMessage(message: String) {
        viewModelScope.launch {
            _toastMessage.emit(message)
        }
    }
}

@Composable
fun TestScreen() {
    val context = LocalContext.current

    val viewModel = viewModel<OneShotOperationViewModel>()
    LaunchedEffect(Unit) {
        viewModel
            .toastMessage
            .collect { message ->
                Toast.makeText(
                    context,
                    message,
                    Toast.LENGTH_SHORT,
                ).show()
            }
    }
    Button(
        onClick = {
            viewModel.sendMessage("Sample Toast")
        },
    ) {
        Text(text = "Show Toast")
    }
}

Note that if you send a message from another view while collect is not running, it will not show toast when you finally start it. It does not store the value, it only passes it on to all the collectors that are currently connected.


问:
Python Loop and Range function
Can anyone please explain this python code, how the answer is "5050" ?

total = 0
for number in range(0, 101):
    total += number
print(total)
```

答:
```<code>total = 0
for number in range(0, 101):
    total = total + number
</code>```

Initially total equals 0, range function range function sorts values from 0 to 101. The for loop adds 1 to the total value in the first step, At this stage the total is equal to 1, In the next step, the number 2 comes from the range function and adds 2 to the total value. Total is equal to 3 in the final case. The number produced by the range function is added to the total value each time. This situation continues until the for loop is completed and in the last step the total equals 5050. I hope I was able to explain.

Title: Python Loop and Range function

Body:
total = 0
for number in range(0, 101):
    total = total + number

Initially total equals 0, range function range function sorts values from 0 to 101. The for loop adds 1 to the total value in the first step, At this stage the total is equal to 1, In the next step, the number 2 comes from the range function and adds 2 to the total value. Total is equal to 3 in the final case. The number produced by the range function is added to the total value each time. This situation continues until the for loop is completed and in the last step the total equals 5050. I hope I was able to explain.


问:
Using Redhat Developer subscription for creating openshift cluster
I have RedHat Developer Subscription For Individual users in my active subscriptions I had already bought that one. But I don't know how to use it while creating a new OpenShift Container Platform cluster. I was only able to create 60 day trial cluster. How can I use the developer subscription while creating the new cluster. If anyone know please help with this one.</p>

答:
RedHat has launched Openshift Developer Sandbox. You can try and deploy applications on this sandbox for free.

You can signup and Start using immediately: https://developers.redhat.com/developer-sandbox/get-started

RedHat Developer Subscription For Individual users is focused on providing no-cost RHEL to customers.


问:
Jquery function to find out max height of

I want to find out that out of the given
 which li has the maximum height?
how do i write such function?

If there are n
 elements of different size, content and height. I want to figure out the maximum height of the biggest
 element.

答:
If you want a one liner</p>

```<code>var max = Math.max.apply(Math, $("li").map(function() { return $(this).height(); }))
</code>```

ContentLicense: CC BY-SA 3.0

Title: Jquery function to find out max height of <li>

Body:
If you want a one liner

var max = Math.max.apply(Math, $("li").map(function() { return $(this).height(); }))


问:
how to write splunk query to create a dashboard
I have a Splunk log which contains a message at different time stamp with some case number

"message":"Welcome home user case num 1ABCD-201901-765-2  UserId - 1203 XV - 543 UserAd - 76542 Elect - 5789875 Later Code - QWERZX"

In below log few log message also get printed at different timestamp if certain conditions are met

```<code>"message":"Passed First class case num 1ABCD-201901-765-2"

"message":"Failed First class case num 1ABCD-201901-765-2"

"message":"Passed Second class case num 1ABCD-201901-765-2"

"message":"Fully Failed case num 1ABCD-201901-765-2"

"message":"Saved case num 1ABCD-201901-765-2"

"message":"Not saved case num 1ABCD-201901-765-2"

"message":"Not user to us case num 1ABCD-201901-765-2"
</code>```

I want to create a table in Splunk dashboard to view using Splunk query with these columns list all the case numbers with the details

Case Num | XV | UserId | UserAd | Elect | Later Code | Passed First class | Passed Second class | Failed First class | Saved | Not saved | Not user to us

How to print true and false for these columns  Passed First class | Passed Second class | Failed First class | Saved | Not saved | Not user to us I want to check for each case num whether the case num is present in those logs if its present then print true for that column else false

答:
I'm going to presume you have no field extractions yet built (except for message) for the sample data you provided, and that - as provided - it's in the correct format (though, since it seems to be missing timestamps, I can tell something is likely amiss)

This should get you down the right road:

```<code>index=ndx sourcetype=srctp message=*
| rex field=message "Passed (?<passed_attempt>\w+)"
| rex field=message "Failed (?<failed_attempt>\w+)"
| rex field=message "case num (?<case_num>\S+)"
| rex field=message "(?<saved>Not saved)"
| rex field=message "(?<saved>Saved)"
| rex field=message "UserId - (?<userid>\w+)"
| rex field=message "XV - (?<xv>\w+)"
| rex field=message "UserAd - (?<userad>\w+)"
| rex field=message "Elect - (?<elect>\w+)"
| rex field=message "Later Code - (?<later_code>\w+)"
| fields passed_attempt failed_attempt _time case_num xv userid elect later_code saved userad
| stats max(_time) as _time values(*) as * by userid case_num
</code>```

I've used separate regular expressions to pull the fields because they're easier to read - they may (or may not) be more performant to combine.

Body:
I have a Splunk log which contains a message at different time stamp with some case number

"message":"Welcome home user case num 1ABCD-201901-765-2  UserId - 1203 XV - 543 UserAd - 76542 Elect - 5789875 Later Code - QWERZX"

In below log few log message also get printed at different timestamp if certain conditions are met

"message":"Passed First class case num 1ABCD-201901-765-2"

"message":"Failed First class case num 1ABCD-201901-765-2"

"message":"Passed Second class case num 1ABCD-201901-765-2"

"message":"Fully Failed case num 1ABCD-201901-765-2"

"message":"Saved case num 1ABCD-201901-765-2"

"message":"Not saved case num 1ABCD-201901-765-2"

"message":"Not user to us case num 1ABCD-201901-765-2"

I want to create a table in Splunk dashboard to view using Splunk query with these columns list all the case numbers with the details

Case Num | XV | UserId | UserAd | Elect | Later Code | Passed First class | Passed Second class | Failed First class | Saved | Not saved | Not user to us

How to print true and false for these columns  Passed First class | Passed Second class | Failed First class | Saved | Not saved | Not user to us I want to check for each case num whether the case num is present in those logs if its present then print true for that column else false

Body:
I'm going to presume you have no field extractions yet built (except for message) for the sample data you provided, and that - as provided - it's in the correct format (though, since it seems to be missing timestamps, I can tell something is likely amiss)

This should get you down the right road:

index=ndx sourcetype=srctp message=*
| rex field=message "Passed (?<passed_attempt>\w+)"
| rex field=message "Failed (?<failed_attempt>\w+)"
| rex field=message "case num (?<case_num>\S+)"
| rex field=message "(?<saved>Not saved)"
| rex field=message "(?<saved>Saved)"
| rex field=message "UserId - (?<userid>\w+)"
| rex field=message "XV - (?<xv>\w+)"
| rex field=message "UserAd - (?<userad>\w+)"
| rex field=message "Elect - (?<elect>\w+)"
| rex field=message "Later Code - (?<later_code>\w+)"
| fields passed_attempt failed_attempt _time case_num xv userid elect later_code saved userad
| stats max(_time) as _time values(*) as * by userid case_num

I've used separate regular expressions to pull the fields because they're easier to read - they may (or may not) be more performant to combine.


问:
How to place a label on a single row/ on a single line
Two labels get separated by a line. I need to fix that(Look at First Name, Last Name)

```<code><section id="names">
    <B>First Name:</B><input type="text" name="Name" id="name">
    <B>Last Name:</B><input type="text" name="Surname" id="surname">
</section>
</code>```

I don't know if they will help but here I wrote some useless css for it

```<code>#names {
    display:flex;
    flex-direction: row;
    float: left;
}
</code>```

答:
Not sure what you really want. I think you want them to be seperate by a new line. If you change the flex-direction to "column" instead of "row". It will divide them by space instead of being up against eachother.

#names {
    display:flex;
    flex-direction: column;
    float: left;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><section id="names">
    <B>First Name:</B><input type="text" name="Name" id="name">
    <B>Last Name:</B><input type="text" name="Surname" id="surname">
</section></code>```

Body:
Two labels get separated by a line. I need to fix that(Look at First Name, Last Name)

    First Name:<input type="text" name="Name" id="name">
    Last Name:<input type="text" name="Surname" id="surname">

I don't know if they will help but here I wrote some useless css for it

#names {
    display:flex;
    flex-direction: row;
    float: left;
}

Body:
Not sure what you really want. I think you want them to be seperate by a new line. If you change the flex-direction to "column" instead of "row". It will divide them by space instead of being up against eachother.

#names {
    display:flex;
    flex-direction: column;
    float: left;
}

<section id="names">
    <B>First Name:</B><input type="text" name="Name" id="name">
    <B>Last Name:</B><input type="text" name="Surname" id="surname">
</section>


问:
Core app logging requests but not traces to app insights
I noticed that my .net core app is logging requests, but not traces to my azure app insights.

I'm setting up app insights in my Startup.cs

```<code>services.AddApplicationInsightsTelemetry(options =>
            {
                options.InstrumentationKey = Configuration["ApplicationInsightsInstrumentationKey"];
            });
</code>```

I'm injecting ILogger in my controller like such

```<code>private readonly ILogger<HealthCheckController> _logger;

public HealthCheckController(ILogger<HealthCheckController> logger)
{
    _logger = logger;
}

[HttpGet]
public IActionResult HealthCheck()
{
    // Custom EventId for logging
    var eventId = EventDefinition.TestMicroservice.HealthCheckController.HealthCheck;

    _logger.LogInformation(eventId, "Test Microservice health check successful.");

    return Ok("Test Microservice is running!");
}
</code>```

Am I missing something?  I've hit my controller multiple times and I'm seeing requests getting logged, but my custom log messages are nowhere to be found under traces.

答:
So what I found was that I was able to inject TelemetryClient despite wanting to use ILogger.  While I kept the above code in, I had to add the .ConfigureLogging

```<code>        protected override IEnumerable<ServiceInstanceListener> CreateServiceInstanceListeners()
        {
            return new ServiceInstanceListener[]
            {
                new ServiceInstanceListener(serviceContext =>
                    new KestrelCommunicationListener(serviceContext, "ServiceEndpoint", (url, listener) =>
                    {
                        ServiceEventSource.Current.ServiceMessage(serviceContext, $"Starting Kestrel on {url}");

                        return new WebHostBuilder()
                                    .UseKestrel()
                                    .ConfigureServices(
                                        services => services
                                            .AddSingleton<StatelessServiceContext>(serviceContext))
                                    .UseContentRoot(Directory.GetCurrentDirectory())
                                    .ConfigureAppConfiguration((context, config) =>
                                    {
                                        var configurationPackage = FabricRuntime.GetActivationContext()?.GetConfigurationPackageObject("Config");

                                        // Add Key Vault
                                        var kv = configurationPackage.Settings.Sections[KeyVaultOptions.Position].Parameters;
                                        var credential = new ClientSecretCredential(kv["TenantId"].Value, kv["ClientId"].Value, kv["ClientSecret"].Value);
                                        var client = new SecretClient(new Uri(kv["Url"].Value), credential);

                                        config.AddAzureKeyVault(client, new AzureKeyVaultConfigurationOptions());
                                        config.Build();
                                    })
                                    .ConfigureLogging((context, logging) =>
                                    {
                                        logging.AddApplicationInsights(
                                            context.Configuration["ApplicationInsightsInstrumentationKey"]);
                                        logging.AddFilter<ApplicationInsightsLoggerProvider>("", LogLevel.Trace);
                                    })
                                    .UseStartup<Startup>()
                                    .UseServiceFabricIntegration(listener, ServiceFabricIntegrationOptions.None)
                                    .UseUrls(url)
                                    .Build();
                    }))
            };
</code>```

Body:
I noticed that my .net core app is logging requests, but not traces to my azure app insights.

I'm setting up app insights in my Startup.cs

services.AddApplicationInsightsTelemetry(options =>
            {
                options.InstrumentationKey = Configuration["ApplicationInsightsInstrumentationKey"];
            });

I'm injecting ILogger in my controller like such

private readonly ILogger<HealthCheckController> _logger;

public HealthCheckController(ILogger<HealthCheckController> logger)
{
    _logger = logger;
}

[HttpGet]
public IActionResult HealthCheck()
{
    // Custom EventId for logging
    var eventId = EventDefinition.TestMicroservice.HealthCheckController.HealthCheck;

    _logger.LogInformation(eventId, "Test Microservice health check successful.");

    return Ok("Test Microservice is running!");
}

Am I missing something?  I've hit my controller multiple times and I'm seeing requests getting logged, but my custom log messages are nowhere to be found under traces.

Body:
So what I found was that I was able to inject TelemetryClient despite wanting to use ILogger.  While I kept the above code in, I had to add the .ConfigureLogging

        protected override IEnumerable<ServiceInstanceListener> CreateServiceInstanceListeners()
        {
            return new ServiceInstanceListener[]
            {
                new ServiceInstanceListener(serviceContext =>
                    new KestrelCommunicationListener(serviceContext, "ServiceEndpoint", (url, listener) =>
                    {
                        ServiceEventSource.Current.ServiceMessage(serviceContext, $"Starting Kestrel on {url}");

                        return new WebHostBuilder()
                                    .UseKestrel()
                                    .ConfigureServices(
                                        services => services
                                            .AddSingleton<StatelessServiceContext>(serviceContext))
                                    .UseContentRoot(Directory.GetCurrentDirectory())
                                    .ConfigureAppConfiguration((context, config) =>
                                    {
                                        var configurationPackage = FabricRuntime.GetActivationContext()?.GetConfigurationPackageObject("Config");

                                        // Add Key Vault
                                        var kv = configurationPackage.Settings.Sections[KeyVaultOptions.Position].Parameters;
                                        var credential = new ClientSecretCredential(kv["TenantId"].Value, kv["ClientId"].Value, kv["ClientSecret"].Value);
                                        var client = new SecretClient(new Uri(kv["Url"].Value), credential);

                                        config.AddAzureKeyVault(client, new AzureKeyVaultConfigurationOptions());
                                        config.Build();
                                    })
                                    .ConfigureLogging((context, logging) =>
                                    {
                                        logging.AddApplicationInsights(
                                            context.Configuration["ApplicationInsightsInstrumentationKey"]);
                                        logging.AddFilter<ApplicationInsightsLoggerProvider>("", LogLevel.Trace);
                                    })
                                    .UseStartup<Startup>()
                                    .UseServiceFabricIntegration(listener, ServiceFabricIntegrationOptions.None)
                                    .UseUrls(url)
                                    .Build();
                    }))
            };


问:
Access forbidden to folders in /Users/user/ on Monterey
I am trying to setup nginx on an Apple silicon mac with MacOs Monterey.

Nginx has been installed with brew

If I edit the config file (/opt/homebrew/etc/nginx/nginx.conf) to set a new root directory, it works if I point it at a folder that is not associated with my user folder. For example

```<code>location / {
    root   /var/www/sites;
    index  index.html index.htm index.php;
}
</code>```

However, if I set root to a folder in my home directory, e.g

```<code>location / {
    root   /Users/name/sites;
    index  index.html index.htm index.php;
}
</code>```

I get a 403 Forbidden error.

Although this seems to be a common setup, lots of tutorials say to put your various sites in /User/username/Sites.

I've tried changing the permissions with chmod 755 sites and I've tried changing the owner of the sites directory to the root user. However none of these worked. I had similar issue when trying to setup apache.

Any ideas what I'm doing wrong with my permissions?
Should nginx (and/or apache) be able to access folders in /Users/user/..?

答: Add user username staff; to nginx.conf. That worked for me. Not sure it is good for security.

Body:
I am trying to setup nginx on an Apple silicon mac with MacOs Monterey.

Nginx has been installed with brew

If I edit the config file (/opt/homebrew/etc/nginx/nginx.conf) to set a new root directory, it works if I point it at a folder that is not associated with my user folder. For example

location / {
    root   /var/www/sites;
    index  index.html index.htm index.php;
}

However, if I set root to a folder in my home directory, e.g

location / {
    root   /Users/name/sites;
    index  index.html index.htm index.php;
}

I get a 403 Forbidden error.

Although this seems to be a common setup, lots of tutorials say to put your various sites in /User/username/Sites.

I've tried changing the permissions with chmod 755 sites and I've tried changing the owner of the sites directory to the root user. However none of these worked. I had similar issue when trying to setup apache.

Any ideas what I'm doing wrong with my permissions?
Should nginx (and/or apache) be able to access folders in /Users/user/..?


问:
Error: Rule can only have one resource source (provided resource and test + include + exclude)
hello I have the following error, I have an app in vuejs, it was working fine, the error appeared suddenly, reinstalled everything, clean cache and I can't find a way to solve it, I hope your help

Error: Rule can only have one resource source (provided resource and test + include + exclude) in

```<code>  "exclude": [
    null
  ],
  "use": [
    {
      "loader": "/Users/juanpablo/front-treatments/node_modules/cache-loader/dist/cjs.js",
      "options": {
        "cacheDirectory": "/Users/juanpablo/front-treatments/node_modules/.cache/babel-loader",
        "cacheIdentifier": "81fef5a6"
      },
      "ident": "clonedRuleSet-38[0].rules[0].use[0]"
    },
    {
      "loader": "/Users/juanpablo/front-treatments/node_modules/babel-loader/lib/index.js",
      "options": "undefined",
      "ident": "undefined"
    }
  ]
} ````
A complete log of this run can be found in:
0 info it worked if it ends with ok
1 verbose cli [
1 verbose cli   '/Users/juanpablo/.nvm/versions/node/v12.19.0/bin/node',
1 verbose cli   '/Users/juanpablo/.nvm/versions/node/v12.19.0/bin/npm',
1 verbose cli   'run',
1 verbose cli   'serve'
1 verbose cli ]
2 info using npm@6.14.8
3 info using node@v12.19.0
4 verbose run-script [ 'preserve', 'serve', 'postserve' ]
5 info lifecycle vue-dashboard@0.1.0~preserve: vue-dashboard@0.1.0
6 info lifecycle vue-dashboard@0.1.0~serve: vue-dashboard@0.1.0
7 verbose lifecycle vue-dashboard@0.1.0~serve: unsafe-perm in lifecycle true
8 verbose lifecycle vue-dashboard@0.1.0~serve: PATH: /Users/juanpablo/.nvm/versions/node/v12.19.0/lib/node_modules/npm/node_modules/npm-lifecycle/node-gyp-bin:/Users/juanpablo/front-treatments/node_modules/.bin:/Users/juanpablo/.nvm/versions/node/v12.19.0/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/Users/juanpablo/.rvm/bin
9 verbose lifecycle vue-dashboard@0.1.0~serve: CWD: /Users/juanpablo/front-treatments
10 silly lifecycle vue-dashboard@0.1.0~serve: Args: [ '-c', 'vue-cli-service serve' ]
11 silly lifecycle vue-dashboard@0.1.0~serve: Returned: code: 1  signal: null
12 info lifecycle vue-dashboard@0.1.0~serve: Failed to exec serve script
13 verbose stack Error: vue-dashboard@0.1.0 serve: `vue-cli-service serve`
13 verbose stack Exit status 1
13 verbose stack     at EventEmitter.<anonymous> (/Users/juanpablo/.nvm/versions/node/v12.19.0/lib/node_modules/npm/node_modules/npm-lifecycle/index.js:332:16)
13 verbose stack     at EventEmitter.emit (events.js:314:20)
13 verbose stack     at ChildProcess.<anonymous> (/Users/juanpablo/.nvm/versions/node/v12.19.0/lib/node_modules/npm/node_modules/npm-lifecycle/lib/spawn.js:55:14)
13 verbose stack     at ChildProcess.emit (events.js:314:20)
13 verbose stack     at maybeClose (internal/child_process.js:1021:16)
13 verbose stack     at Process.ChildProcess._handle.onexit (internal/child_process.js:286:5)
14 verbose pkgid vue-dashboard@0.1.0
15 verbose cwd /Users/juanpablo/front-treatments
16 verbose Darwin 19.6.0
17 verbose argv "/Users/juanpablo/.nvm/versions/node/v12.19.0/bin/node" "/Users/juanpablo/.nvm/versions/node/v12.19.0/bin/npm" "run" "serve"
18 verbose node v12.19.0
19 verbose npm  v6.14.8
20 error code ELIFECYCLE
21 error errno 1
22 error vue-dashboard@0.1.0 serve: `vue-cli-service serve`
22 error Exit status 1
23 error Failed at the vue-dashboard@0.1.0 serve script.
23 error This is probably not a problem with npm. There is likely additional logging output above.
24 verbose exit [ 1, true ]
```

答:
These are the highest versions I could achieve on the package.json without triggering the mentioned issue. You can add Vue 2 or 3 and remaining libraries without problems.

Recommended required versions after npm audit fix

Remove 'node-sass' and add 'sass'

```<code>"dependencies": {
    "core-js": "^3.21.0"
},
"devDependencies": {
    "sass": "^1.60.0",
    "sass-loader": "^10.2.1",
    "webpack": "^5.77.0"
},
</code>```

Minimum required with deprecation warnings

```<code>"dependencies": {
    "core-js": "^3.21.0"
},
"devDependencies": {
    "node-sass": "^6.0.1",
    "sass-loader": "^10.2.1",
    "webpack": "^4.46.0"
},
</code>```

After that run npm update

Body:
hello I have the following error, I have an app in vuejs, it was working fine, the error appeared suddenly, reinstalled everything, clean cache and I can't find a way to solve it, I hope your help

Error: Rule can only have one resource source (provided resource and test + include + exclude) in

  "exclude": [
    null
  ],
  "use": [
    {
      "loader": "/Users/juanpablo/front-treatments/node_modules/cache-loader/dist/cjs.js",
      "options": {
        "cacheDirectory": "/Users/juanpablo/front-treatments/node_modules/.cache/babel-loader",
        "cacheIdentifier": "81fef5a6"
      },
      "ident": "clonedRuleSet-38[0].rules[0].use[0]"
    },
    {
      "loader": "/Users/juanpablo/front-treatments/node_modules/babel-loader/lib/index.js",
      "options": "undefined",
      "ident": "undefined"
    }
  ]
} ````
A complete log of this run can be found in:
0 info it worked if it ends with ok
1 verbose cli [
1 verbose cli   '/Users/juanpablo/.nvm/versions/node/v12.19.0/bin/node',
1 verbose cli   '/Users/juanpablo/.nvm/versions/node/v12.19.0/bin/npm',
1 verbose cli   'run',
1 verbose cli   'serve'
1 verbose cli ]
2 info using npm@6.14.8
3 info using node@v12.19.0
4 verbose run-script [ 'preserve', 'serve', 'postserve' ]
5 info lifecycle vue-dashboard@0.1.0~preserve: vue-dashboard@0.1.0
6 info lifecycle vue-dashboard@0.1.0~serve: vue-dashboard@0.1.0
7 verbose lifecycle vue-dashboard@0.1.0~serve: unsafe-perm in lifecycle true
8 verbose lifecycle vue-dashboard@0.1.0~serve: PATH: /Users/juanpablo/.nvm/versions/node/v12.19.0/lib/node_modules/npm/node_modules/npm-lifecycle/node-gyp-bin:/Users/juanpablo/front-treatments/node_modules/.bin:/Users/juanpablo/.nvm/versions/node/v12.19.0/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/Users/juanpablo/.rvm/bin
9 verbose lifecycle vue-dashboard@0.1.0~serve: CWD: /Users/juanpablo/front-treatments
10 silly lifecycle vue-dashboard@0.1.0~serve: Args: [ '-c', 'vue-cli-service serve' ]
11 silly lifecycle vue-dashboard@0.1.0~serve: Returned: code: 1  signal: null
12 info lifecycle vue-dashboard@0.1.0~serve: Failed to exec serve script
13 verbose stack Error: vue-dashboard@0.1.0 serve: `vue-cli-service serve`
13 verbose stack Exit status 1
13 verbose stack     at EventEmitter.<anonymous> (/Users/juanpablo/.nvm/versions/node/v12.19.0/lib/node_modules/npm/node_modules/npm-lifecycle/index.js:332:16)
13 verbose stack     at EventEmitter.emit (events.js:314:20)
13 verbose stack     at ChildProcess.<anonymous> (/Users/juanpablo/.nvm/versions/node/v12.19.0/lib/node_modules/npm/node_modules/npm-lifecycle/lib/spawn.js:55:14)
13 verbose stack     at ChildProcess.emit (events.js:314:20)
13 verbose stack     at maybeClose (internal/child_process.js:1021:16)
13 verbose stack     at Process.ChildProcess._handle.onexit (internal/child_process.js:286:5)
14 verbose pkgid vue-dashboard@0.1.0
15 verbose cwd /Users/juanpablo/front-treatments
16 verbose Darwin 19.6.0
17 verbose argv "/Users/juanpablo/.nvm/versions/node/v12.19.0/bin/node" "/Users/juanpablo/.nvm/versions/node/v12.19.0/bin/npm" "run" "serve"
18 verbose node v12.19.0
19 verbose npm  v6.14.8
20 error code ELIFECYCLE
21 error errno 1
22 error vue-dashboard@0.1.0 serve: `vue-cli-service serve`
22 error Exit status 1
23 error Failed at the vue-dashboard@0.1.0 serve script.
23 error This is probably not a problem with npm. There is likely additional logging output above.
24 verbose exit [ 1, true ]

Body:
These are the highest versions I could achieve on the package.json without triggering the mentioned issue. You can add Vue 2 or 3 and remaining libraries without problems.

Recommended required versions after npm audit fix

Remove 'node-sass' and add 'sass'

"dependencies": {
    "core-js": "^3.21.0"
},
"devDependencies": {
    "sass": "^1.60.0",
    "sass-loader": "^10.2.1",
    "webpack": "^5.77.0"
},

Minimum required with deprecation warnings

"dependencies": {
    "core-js": "^3.21.0"
},
"devDependencies": {
    "node-sass": "^6.0.1",
    "sass-loader": "^10.2.1",
    "webpack": "^4.46.0"
},

After that run npm update


问:
How to animate spining wheel in CSS?
I don't know how to form the question. I have old animation that was done in Flash, that I'm not able to translate to CSS animation.

This is an animation of a Spinning Wheel.

The question is: How can I implement the CSS animation for the crank/handle that drives the wheel? It should work like a Piston but connected to a circe in id="rotator" (inside SVG). The handle is located at 0,0 on the image above. Both small circles should match when the rotator is rotating. I already tried to use translate, and used transform-origin but I have no idea how to implement the animation. I have Action Script code as a reference, but I don't know how to map it to CSS or SCSS.

I was able to convert SWF into SVG, using pyswf. And I have a hard time understanding the math behind the logic I've created long ago and translating it into CSS (I've also tried with JS approach).

The code in Action Script I've extracted long ago, probably some decompiler from the swf file.

```<code>// copyright (c) 2006 Jakub "JCubic" Jankiewicz
var
    factor1 = 180.0 / Math.PI,              // współczynniki dla zamiany
    factor2 = Math.PI / 180.0;              // radiany stopinie i odwrotnie

// radiany na katy
function rad2deg(rad){
    return rad * factor1;
}
// katy na radiany
function deg2rad(deg){
    return deg * factor2;
}
// dlugosc odcinka
function line_length(x1, y1, x2, y2){
    return Math.sqrt((x2 - x1)*(x2 - x1) + (y2 - y1)*(y2 - y1));
}
// funkcja testowa przenoszaca krzyzyk
function show(x, y){ cross._x = x; cross._y = y; }
// funkcja testowa rysująca linie
function line_(x1, y1, x2, y2, ang){
    line._height = Math.sqrt((x2 - x1)*(x2 - x1) + (y2 - y1)*(y2 - y1));
    line._x = (x2 + x1) / 2;
    line._y = (y2 + y1) / 2;
    line._rotation = ang;
}

function getSpeed(){
    return step;
}

function setSpeed(value){
    // inicjacja zmiennych
    var Ox = 0,
        Oy = 360,                               // punkt zaczepienia
        r = 83.0,                               // promien odleglosc od rotatora
        angle = 0,
        step = value,
        rad = deg2rad(step),                    // cosinnus i sinus stopnia
        sinA = Math.sin(rad),                   // jednostkowego
        cosA = Math.cos(rad),
        sinAlpha;

    onEnterFrame = function() {
        if (angle == 0) {
            napedzacz._x = 0;       // poczatek obrotu
            napedzacz._y = r;
        } else {
            Bx = napedzacz._x * cosA + napedzacz._y * sinA;
            By = napedzacz._y * cosA - napedzacz._x * sinA;
            napedzacz._x = Bx;
            napedzacz._y = By;
            sinAlpha = (Ox - Bx) / line_length(Bx, By, Ox, Oy);
            napedzacz._rotation = - rad2deg(Math.asin(sinAlpha));
            kolo._rotation = 180 - angle;
            szpulka._rotation = 180 - angle * 2;
            rotator._rotation = 180 - angle;
        }
        angle = (angle+step) % 360;
    }
}
</code>```

It has Polish comments but they don't explain how to modify the code.

Here is my CodePen demo where I've tried to create SVG+CSS animation. I was able to rotate part of the spinning wheel, but don't know how to animate the handle (that is used to drive the wheel).

I've wanted to use SCSS and trigonometry functions (included in Pen) to generate every frame of the animation, but I'm not sure how I should go about it.

I have the original SWF file but I'm not able to play it, since the only SWF player I've found doesn't execute code. And I'm not able to install Gnash on Fedora (even that I've written article how to do that long go, the solution doesn't work anymore). That's why I want to create something modern with SVG.

If you have something to open the SWF file here is the link to the original file:

https://jcubic.pl/kolowrotek.swf

the problem is that constants in the Action Script code use different coordinate systems and different scales, I have no idea how to map that code into JavaScript (I was able to run it, but it has issues, there are two commented-out lines in Pen). I also have no idea why the animation rotate in different direction than CSS, I was not able to reverse it. I would prefer not to use JavaScript since it will hard to match CSS animation with JavaScript, and doing aninmation in JavaScript make some delay when handle is in wrong position.

答:
This is a basic implementation of the movement that you want.

I have set only keyframes at every 90 deg , it will get better as you add values.

I have guessed this values, bout you should calculate them and set the appropiate values in the counter rotation.

#wheel {
  width: 300px;
  height: 300px;
  border-radius: 100%;
  border: solid 1px blue;
  animation: rotate 15s infinite linear;
}

#dot {
  width: 5px;
  height: 5px;
  border-radius: 100%;
  border: solid 1px red;
  position: absolute;
  top: 2px;
  left: 150px;
}

#arm {
  width: 500px;
  height: 5px;
  border: solid 1px green;
  position: absolute;
  top: 2px;
  left: 150px;
  transform-origin: 0px 0px;
  animation: crotate 15s infinite linear;
}

@keyframes rotate {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

@keyframes crotate {
  0% {
    transform: rotate(15deg);
  }
  25% {
    transform: rotate(-90deg);
  }
  50% {
    transform: rotate(-195deg);
  }
  75% {
    transform: rotate(-270deg);
  }
  99.99% {
    transform: rotate(-345deg);
  }
  100% {
    transform: rotate(15deg);
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="wheel">
  <div id="dot"></div>
  <div id="arm"></div>
</div></code>```

Title: How to animate spining wheel in CSS?

Body:
I don't know how to form the question. I have old animation that was done in Flash, that I'm not able to translate to CSS animation.

This is an animation of a Spinning Wheel.

The question is: How can I implement the CSS animation for the crank/handle that drives the wheel? It should work like a Piston but connected to a circe in id="rotator" (inside SVG). The handle is located at 0,0 on the image above. Both small circles should match when the rotator is rotating. I already tried to use translate, and used transform-origin but I have no idea how to implement the animation. I have Action Script code as a reference, but I don't know how to map it to CSS or SCSS.

I was able to convert SWF into SVG, using pyswf. And I have a hard time understanding the math behind the logic I've created long ago and translating it into CSS (I've also tried with JS approach).

The code in Action Script I've extracted long ago, probably some decompiler from the swf file.

// copyright (c) 2006 Jakub "JCubic" Jankiewicz
var
    factor1 = 180.0 / Math.PI,              // współczynniki dla zamiany
    factor2 = Math.PI / 180.0;              // radiany stopinie i odwrotnie

// radiany na katy
function rad2deg(rad){
    return rad * factor1;
}
// katy na radiany
function deg2rad(deg){
    return deg * factor2;
}
// dlugosc odcinka
function line_length(x1, y1, x2, y2){
    return Math.sqrt((x2 - x1)*(x2 - x1) + (y2 - y1)*(y2 - y1));
}
// funkcja testowa przenoszaca krzyzyk
function show(x, y){ cross._x = x; cross._y = y; }
// funkcja testowa rysująca linie
function line_(x1, y1, x2, y2, ang){
    line._height = Math.sqrt((x2 - x1)*(x2 - x1) + (y2 - y1)*(y2 - y1));
    line._x = (x2 + x1) / 2;
    line._y = (y2 + y1) / 2;
    line._rotation = ang;
}

function getSpeed(){
    return step;
}

function setSpeed(value){
    // inicjacja zmiennych
    var Ox = 0,
        Oy = 360,                               // punkt zaczepienia
        r = 83.0,                               // promien odleglosc od rotatora
        angle = 0,
        step = value,
        rad = deg2rad(step),                    // cosinnus i sinus stopnia
        sinA = Math.sin(rad),                   // jednostkowego
        cosA = Math.cos(rad),
        sinAlpha;

    onEnterFrame = function() {
        if (angle == 0) {
            napedzacz._x = 0;       // poczatek obrotu
            napedzacz._y = r;
        } else {
            Bx = napedzacz._x * cosA + napedzacz._y * sinA;
            By = napedzacz._y * cosA - napedzacz._x * sinA;
            napedzacz._x = Bx;
            napedzacz._y = By;
            sinAlpha = (Ox - Bx) / line_length(Bx, By, Ox, Oy);
            napedzacz._rotation = - rad2deg(Math.asin(sinAlpha));
            kolo._rotation = 180 - angle;
            szpulka._rotation = 180 - angle * 2;
            rotator._rotation = 180 - angle;
        }
        angle = (angle+step) % 360;
    }
}

It has Polish comments but they don't explain how to modify the code.

Here is my CodePen demo where I've tried to create SVG+CSS animation. I was able to rotate part of the spinning wheel, but don't know how to animate the handle (that is used to drive the wheel).

I've wanted to use SCSS and trigonometry functions (included in Pen) to generate every frame of the animation, but I'm not sure how I should go about it.

I have the original SWF file but I'm not able to play it, since the only SWF player I've found doesn't execute code. And I'm not able to install Gnash on Fedora (even that I've written article how to do that long go, the solution doesn't work anymore). That's why I want to create something modern with SVG.

If you have something to open the SWF file here is the link to the original file:

https://jcubic.pl/kolowrotek.swf

the problem is that constants in the Action Script code use different coordinate systems and different scales, I have no idea how to map that code into JavaScript (I was able to run it, but it has issues, there are two commented-out lines in Pen). I also have no idea why the animation rotate in different direction than CSS, I was not able to reverse it. I would prefer not to use JavaScript since it will hard to match CSS animation with JavaScript, and doing aninmation in JavaScript make some delay when handle is in wrong position.

Body:
This is a basic implementation of the movement that you want.

I have set only keyframes at every 90 deg , it will get better as you add values.

I have guessed this values, bout you should calculate them and set the appropiate values in the counter rotation.

#wheel {
  width: 300px;
  height: 300px;
  border-radius: 100%;
  border: solid 1px blue;
  animation: rotate 15s infinite linear;
}

#dot {
  width: 5px;
  height: 5px;
  border-radius: 100%;
  border: solid 1px red;
  position: absolute;
  top: 2px;
  left: 150px;
}

#arm {
  width: 500px;
  height: 5px;
  border: solid 1px green;
  position: absolute;
  top: 2px;
  left: 150px;
  transform-origin: 0px 0px;
  animation: crotate 15s infinite linear;
}

@keyframes rotate {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

@keyframes crotate {
  0% {
    transform: rotate(15deg);
  }
  25% {
    transform: rotate(-90deg);
  }
  50% {
    transform: rotate(-195deg);
  }
  75% {
    transform: rotate(-270deg);
  }
  99.99% {
    transform: rotate(-345deg);
  }
  100% {
    transform: rotate(15deg);
  }
}

<div id="wheel">
  <div id="dot"></div>
  <div id="arm"></div>
</div>


问:
Django howto progessively write data into a huge zipfile FileField
I have a django model like this:

class Todo(models.Model):
    big_file = models.FileField(blank=True)
    status = models.PositiveSmallIntegerField(default=0)
    progress = models.IntegerField(default=0)
```
<p>I'd like to do two operations:</p>
<ul>
<li>first make an empty zipfile out of <code>big_file</code> (less important)</li>
<li>and then progressively add files into my zipfile (and save it iteratively)</li>
</ul>
<p>The overall process would look like that:</p>
<pre class="lang-py prettyprint-override"><code>from django.core.files.base import File
import io, zipfile

def generate_data(todo):
    io_bytes = io.BytesIO(b'')
    # 1. save an empty Zip archive:
    with zipfile.ZipFile(io_bytes, 'w') as zip_fd:
        todo.generated_data.save('heavy_file.zip', File(zip_fd))

    # 2. Progressively fill the Zip archive:
    with zipfile.ZipFile(io_bytes, 'w') zip_fd:
        for filename, data_bytes in long_iteration(todo):
            with zip_fd.open(filename, 'w') as in_zip:
                in_zip.write(data_bytes)
            if condition(something):
                todo.generated_data.save()  # that does not work
                todo.status = 1
                todo.progress = 123
                todo.save()
    todo.status = 2
    todo.save()
</code>```

But I can't figure out the right filedescriptor / file-like object / Filepath / django-File object combination ...
And it seems that in django I always have to  save(filename, content). But my content could be Gigabytes, so it does not sound reasonable to store it all into a "content" variable?

答:
Ok I found following solution for myself; first create an empty file and then use the <my_file_field>.path attribute:

def generate_data(todo):
    # 1. save an empty Zip archive:
    todo.big_file.save('filename.zip', ContentFile(''))
    with zipfile.ZipFile(todo.big_file.path, 'w') as zip_fd:
        pass

    # 2. Progressively fill the Zip archive:
    with zipfile.ZipFile(todo.big_file.path, 'w') zip_fd:
        ... # do the stuff

```

Body:
I have a django model like this:

class Todo(models.Model):
    big_file = models.FileField(blank=True)
    status = models.PositiveSmallIntegerField(default=0)
    progress = models.IntegerField(default=0)

I'd like to do two operations:

first make an empty zipfile out of big_file (less important)

and then progressively add files into my zipfile (and save it iteratively)

The overall process would look like that:

from django.core.files.base import File
import io, zipfile

def generate_data(todo):
    io_bytes = io.BytesIO(b'')
    # 1. save an empty Zip archive:
    with zipfile.ZipFile(io_bytes, 'w') as zip_fd:
        todo.generated_data.save('heavy_file.zip', File(zip_fd))

    # 2. Progressively fill the Zip archive:
    with zipfile.ZipFile(io_bytes, 'w') zip_fd:
        for filename, data_bytes in long_iteration(todo):
            with zip_fd.open(filename, 'w') as in_zip:
                in_zip.write(data_bytes)
            if condition(something):
                todo.generated_data.save()  # that does not work
                todo.status = 1
                todo.progress = 123
                todo.save()
    todo.status = 2
    todo.save()

But I can't figure out the right filedescriptor / file-like object / Filepath / django-File object combination ...
And it seems that in django I always have to  save(filename, content). But my content could be Gigabytes, so it does not sound reasonable to store it all into a "content" variable?


问:
Which react hook to use with firestore onsnapshot?
I use a lot of firestore snapshots in my react native application. I am also using React hooks. The code looks something like this:

```<code>useEffect(() => {
    someFirestoreAPICall().onSnapshot(snapshot => {

        // When the component initially loads, add all the loaded data to state.
        // When data changes on firestore, we receive that update here in this
        // callback and then update the UI based on current state

    });;
}, []);
</code>```

At first I assumed useState would be the best hook to store and update the UI. However, based on the way my useEffect hook is set up with an empty dependency array, when the snapshot callback gets fired with updated data and I try to modify the current state with the new changes, the current state is undefined. I believe this is because of a closure. I am able to get around it using useRef with a forceUpdate() like so:

```<code>const dataRef = useRef(initialData);

const [, updateState] = React.useState();
const forceUpdate = useCallback(() => updateState({}), []);

useEffect(() => {
    someFirestoreAPICall().onSnapshot(snapshot => {

       // if snapshot data is added
       dataRef.current.push(newData)
       forceUpdate()

       // if snapshot data is updated
       dataRef.current.find(e => some condition) = updatedData
       forceUpdate()

    });;
}, []);

return(
// JSX that uses dataRef.current directly
)
</code>```

My question is am I doing this correct by using useRef along with a forceUpdate instead of useState in a different way? It doesn't seem right that I'm having to update a useRef hook and call forceUpdate() all over my app. When trying useState I tried adding the state variable to the dependency array but ended up with an infinite loop. I only want the snapshot function to be initialized once and the stateful data in the component to be updated over time as things change on the backend (which fires in the onSnapshot callback).

答:
A simple useEffect worked for me, i don't need to create a helper function or anything of sorts,</p>
```<code>useEffect(() => {
        const colRef = collection(db, "data")
        //real time update
        onSnapshot(colRef, (snapshot) => {
            snapshot.docs.forEach((doc) => {
                setTestData((prev) => [...prev, doc.data()])
                // console.log("onsnapshot", doc.data());
            })
        })
    }, [])
</code>```

Body:
I use a lot of firestore snapshots in my react native application. I am also using React hooks. The code looks something like this:

useEffect(() => {
    someFirestoreAPICall().onSnapshot(snapshot => {

        // When the component initially loads, add all the loaded data to state.
        // When data changes on firestore, we receive that update here in this
        // callback and then update the UI based on current state

    });;
}, []);

At first I assumed useState would be the best hook to store and update the UI. However, based on the way my useEffect hook is set up with an empty dependency array, when the snapshot callback gets fired with updated data and I try to modify the current state with the new changes, the current state is undefined. I believe this is because of a closure. I am able to get around it using useRef with a forceUpdate() like so:

const dataRef = useRef(initialData);

const [, updateState] = React.useState();
const forceUpdate = useCallback(() => updateState({}), []);

useEffect(() => {
    someFirestoreAPICall().onSnapshot(snapshot => {

       // if snapshot data is added
       dataRef.current.push(newData)
       forceUpdate()

       // if snapshot data is updated
       dataRef.current.find(e => some condition) = updatedData
       forceUpdate()

    });;
}, []);

return(
// JSX that uses dataRef.current directly
)

My question is am I doing this correct by using useRef along with a forceUpdate instead of useState in a different way? It doesn't seem right that I'm having to update a useRef hook and call forceUpdate() all over my app. When trying useState I tried adding the state variable to the dependency array but ended up with an infinite loop. I only want the snapshot function to be initialized once and the stateful data in the component to be updated over time as things change on the backend (which fires in the onSnapshot callback).

Body:
A simple useEffect worked for me, i don't need to create a helper function or anything of sorts,

useEffect(() => {
        const colRef = collection(db, "data")
        //real time update
        onSnapshot(colRef, (snapshot) => {
            snapshot.docs.forEach((doc) => {
                setTestData((prev) => [...prev, doc.data()])
                // console.log("onsnapshot", doc.data());
            })
        })
    }, [])


问:
What is a good method for making a huge test file?
I'm trying to test some streaming file upload/download code that I've just written, but I need a huge (bigger than my memory, as in > 4GB) file to test on.  What's a good way to quickly generate a file of a specific size (but no particular data inside)?

I know that I could just look around my hard drive for an appropriately-sized file, but I'm curious if there are any other good ways for generating test files, especially if I want a specific size.  Downloading files is no good either, since my connection is slow.

答:
I used to use an eatbits.exe utility back in the day. Where you could create these files. They are very valuable for installation testing.

I couldn't find eatbits anywhere online, it might have been an internal utility at the company I was working for.

OwnerDisplayName: Daniel Lew

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: ModelTester


问:
Programmatically interacting with gdb using java
I'm writing an application that uses GDB to access information through java.

Using Runtime.getRuntime.exec, I'm able to attach GDB to any processes.

The problem is that I am unable to send inputs to GDB after it has been started.

**EDIT (19/8/2011):

At the line "out.println(gdbcommand)", gdb is started. How do I get the stdout of the newly spawned gdb, write inputs to it and then read the stdin. So far, I'm only able get the output up till "out.println(gdbcommand)". All attempts at trying to programmatically send inputs to gdb have not been working so far.**

Refer to trojanfoe's comments below my question.
Below is an edited sample of my code:

```<code>try {
    String gdbcommand = "/data/bin/gdb " + pidS + " " + pidS;
    String line;

    Process process = Runtime.getRuntime().exec("su");

    if (process != null) {
        BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream()));
        PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(process.getOutputStream())),true);

        out.println(gdbcommand);

        //Note this line does not get sent to gdb's interface after starting gdb.
        //Is it possible to connect to the new stdout of gdb's interface?
        out.println("info registers");

        out.flush();
        out.close();

        while ((line = in.readLine()) != null) {
            System.out.println(line);
        }

        process.destroy();
    }

} catch (Exception e) {
    e.printStackTrace();
}
</code>```

Note that "info registers" is not sent to GDB's interface and after calling out.close(), gdb's interface quits. (As seen below)

```<code>08-18 14:40:36.595: INFO/System.out(4408): 0xafd0c51c in epoll_wait () from /system/lib/libc.so

08-18 14:40:36.595: INFO/System.out(4408): (gdb) Hangup detected on fd 0

08-18 14:40:36.595: INFO/System.out(4408): error detected on stdin

08-18 14:40:36.595: INFO/System.out(4408): The program is running.  Quit anyway (and detach it)? (y or n) [answered Y; input not from terminal]
</code>```

答:
You need GDB/MI.

GDB/MI is a line based machine oriented text interface to GDB. It is
  specifically intended to support the development of systems which use
  the debugger as just one small component of a larger system.

Try and initiage GDB with --interpreter=mi

Body:
I'm writing an application that uses GDB to access information through java.

Using Runtime.getRuntime.exec, I'm able to attach GDB to any processes.

The problem is that I am unable to send inputs to GDB after it has been started.

**EDIT (19/8/2011):

At the line "out.println(gdbcommand)", gdb is started. How do I get the stdout of the newly spawned gdb, write inputs to it and then read the stdin. So far, I'm only able get the output up till "out.println(gdbcommand)". All attempts at trying to programmatically send inputs to gdb have not been working so far.**

Refer to trojanfoe's comments below my question.
Below is an edited sample of my code:

try {
    String gdbcommand = "/data/bin/gdb " + pidS + " " + pidS;
    String line;

    Process process = Runtime.getRuntime().exec("su");

    if (process != null) {
        BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream()));
        PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(process.getOutputStream())),true);

        out.println(gdbcommand);

        //Note this line does not get sent to gdb's interface after starting gdb.
        //Is it possible to connect to the new stdout of gdb's interface?
        out.println("info registers");

        out.flush();
        out.close();

        while ((line = in.readLine()) != null) {
            System.out.println(line);
        }

        process.destroy();
    }

} catch (Exception e) {
    e.printStackTrace();
}

Note that "info registers" is not sent to GDB's interface and after calling out.close(), gdb's interface quits. (As seen below)

08-18 14:40:36.595: INFO/System.out(4408): 0xafd0c51c in epoll_wait () from /system/lib/libc.so

08-18 14:40:36.595: INFO/System.out(4408): (gdb) Hangup detected on fd 0

08-18 14:40:36.595: INFO/System.out(4408): error detected on stdin

08-18 14:40:36.595: INFO/System.out(4408): The program is running.  Quit anyway (and detach it)? (y or n) [answered Y; input not from terminal]


问:
Update React State variable inside an Interval
I create this simple example script to animate a player position using a simple setInterval function but impossible to make it works..

Everytime it go into the interval function the playerPos is back to is initial value..

import React, { useEffect, useState } from 'react';

const App = () => {

  let [playerPos, setPlayerPos] = useState({x:128, y:128})

  useEffect(() => {

    setInterval(() => {

      console.log(`Current player pos ${JSON.stringify(playerPos)}`);
      setPlayerPos({x:128, y:playerPos.y + 10});

    }, 1000);

  }, []);

  return <div style={{position: "absolute", top: `${playerPos.x}px`, left: `${playerPos.y}px`}}>

}
```
<p>Strangely, my console only showing:</p>
```Current player pos {"x":128,"y":128}
Current player pos {"x":128,"y":128}
Current player pos {"x":128,"y":128}
...
```

What did I misunderstood in hooks and effects ??!

答:
After the first render, you set up the interval, and the code closes over the playerPos that existed at that time. That's an object with {x: 128, y: 128}, and it always will be. The empty dependency array means the effect will never run again, and setting state does not (and can not) replace the local variable playerPos.

Since all you're doing is setting state, you can fix this by using the function version of set state. React will pass you the most recent value of the state, and then you can calculate your new state based on that.

```<code>useEffect(() => {
  const id = setInterval(() => {
    setPlayerPos(prev => {
      console.log("Current player pos", JSON.stringify(prev));
      return { x: 128, y: prev.y + 10 }
    });
  }, 1000);

  return () => {
    clearInterval(id);
  }
}, []);
</code>```

Your other option is to change the way you do the effect so that you set up a new timeout every time the position changes. That way, each new timeout closes over the most recent version of the state.

```<code>useEffect(() => {
  const id = setTimeout(() => {
    console.log("Current player pos", JSON.stringify(playerPos));
    setPlayerPos({ x: 128, y: playerPos.y + 10 });
  }, 1000);

  return () => {
    clearTimeout(id);
  }
}, [playerPos]
</code>```

Body:
I create this simple example script to animate a player position using a simple setInterval function but impossible to make it works..

Everytime it go into the interval function the playerPos is back to is initial value..

import React, { useEffect, useState } from 'react';

const App = () => {

  let [playerPos, setPlayerPos] = useState({x:128, y:128})

  useEffect(() => {

    setInterval(() => {

      console.log(`Current player pos ${JSON.stringify(playerPos)}`);
      setPlayerPos({x:128, y:playerPos.y + 10});

    }, 1000);

  }, []);

  return <div style={{position: "absolute", top: `${playerPos.x}px`, left: `${playerPos.y}px`}}>

}

Strangely, my console only showing:

Current player pos {"x":128,"y":128}
Current player pos {"x":128,"y":128}
Current player pos {"x":128,"y":128}
...

What did I misunderstood in hooks and effects ??!

Body:
After the first render, you set up the interval, and the code closes over the playerPos that existed at that time. That's an object with {x: 128, y: 128}, and it always will be. The empty dependency array means the effect will never run again, and setting state does not (and can not) replace the local variable playerPos.

Since all you're doing is setting state, you can fix this by using the function version of set state. React will pass you the most recent value of the state, and then you can calculate your new state based on that.

useEffect(() => {
  const id = setInterval(() => {
    setPlayerPos(prev => {
      console.log("Current player pos", JSON.stringify(prev));
      return { x: 128, y: prev.y + 10 }
    });
  }, 1000);

  return () => {
    clearInterval(id);
  }
}, []);

Your other option is to change the way you do the effect so that you set up a new timeout every time the position changes. That way, each new timeout closes over the most recent version of the state.

useEffect(() => {
  const id = setTimeout(() => {
    console.log("Current player pos", JSON.stringify(playerPos));
    setPlayerPos({ x: 128, y: playerPos.y + 10 });
  }, 1000);

  return () => {
    clearTimeout(id);
  }
}, [playerPos]


问:
GitLab Runner fails to upload artifacts with "invalid argument" error
I'm completely new to trying to implement GitLab's CI/CD pipelines, but it's been going quite well. In fact, for my ASP.NET project, if I specify a Publish Profile in the msbuild command that uses Web Deploy, it actually deploys the code successfully to the web server.

However, I'm now wanting to have the "build" job create artifacts which are uploaded to GitLab that I can then subsequently deploy. We're using a self-hosted instance of GitLab, for which I'm not an admin, but I can speak to the admin if I know what I'm asking for!

So I've configured my gitlab-ci.yml file like this:

```<code>variables:
  NUGET_PATH: 'C:\Program Files\Nuget\Nuget.exe'
  NUGET_SOURCES: 'https://api.nuget.org/v3/index.json'
  MSBUILD_PATH: 'C:\Program Files (x86)\Microsoft Visual Studio\2022\BuildTools\MSBuild\Current\Bin\msbuild.exe'

stages:
- build

build-job:
  variables:
    CI_DEBUG_TRACE: "true"
  stage: build
  script:
    - '& "$env:NUGET_PATH" restore ApplicationTemplate.sln  -Source "$env:NUGET_SOURCES"'
    - '& "$env:MSBUILD_PATH" ApplicationTemplate\ApplicationTemplate.csproj /p:DeployOnBuild=true /p:Configuration=Release /p:PublishProfile=FolderPublish.pubxml'
  artifacts:
    paths:
      - '.\ApplicationTemplate\bin\Release\Publish\'
</code>```

The output shows that this builds the code just fine, and it also seems to successfully find the artifacts for upload. However, when it uploads the artifacts, even though the request gets a 200 OK response, the process fails. Here is the log output:

So, it finds the artifacts, it attempts to upload them and even gets a 200 OK response (in contrast to the handful of similar reports of this error I've been able to find online), but it still fails due to an invalid argument.

I've already enabled verbose debugging, as you can see from the output, but I'm none the wiser. Looking at the GitLab Runner entries in the Windows Event Log on the box where the runner is hosted doesn't shed any light on things either. The total size of the artifacts is 61.1MB, so I don't think my issue is related to that.

Can anyone see from this output what's invalid? Can I identify which argument is invalid and/or why it's invalid?

Edit: Things I've tried

Specifying a value for artifacts:expire_in.

Setting artifacts:public to FALSE, since I'm using a self-hosted GitLab environment and the default value for this setting (TRUE) is not valid in such an environment.

Trying every format I can think of for the value of the artifacts:paths setting (this seems to be incredibly robust - regardless of the format I use, the Runner seems to have no problem parsing it and finding the files to upload).

Taking a cue from this question I created a new project with a very simple build job to upload a single file:

```<code>stages:
  - build

build-job:
  variables:
    CI_DEBUG_TRACE: "true"
  stage: build
  script:
    - echo "Test" > test.txt
  artifacts:
    paths:
      - test.txt
</code>```

About 50% of the time this job hangs on the uploading of the artifacts and I have to cancel it. The other half of the time it fails in exactly the same way as the my previous project:

答:
After countless hours working on this, it seems that ultimately the issue was that our internal Web Application Firewall was blocking some part of the transfer of artefacts to the server, or the response back from it. With the WAF reconfigured not to block traffic from the machine running the GitLab Runner, the artefacts are successfully uploaded and the job succeeds.

This would have been significantly easier to diagnose if the logging from GitLab was better. As per my comment on this issue, it should be possible to see the content of the response from the GitLab server after uploading artefacts, even when the response code is 200.

What's strange - and made diagnosing the issue even harder - is that when I worked through the issue with the admin of our GitLab instance, digging through logs and running it in debug mode, the artefact upload process was uploading something successfully. We could see, for example, the GitLab Runner's log had been uploaded to the server. Clearly the WAF's blocking was selective and didn't block everything in both directions.

Body:
I'm completely new to trying to implement GitLab's CI/CD pipelines, but it's been going quite well. In fact, for my ASP.NET project, if I specify a Publish Profile in the msbuild command that uses Web Deploy, it actually deploys the code successfully to the web server.

However, I'm now wanting to have the "build" job create artifacts which are uploaded to GitLab that I can then subsequently deploy. We're using a self-hosted instance of GitLab, for which I'm not an admin, but I can speak to the admin if I know what I'm asking for!

So I've configured my gitlab-ci.yml file like this:

variables:
  NUGET_PATH: 'C:\Program Files\Nuget\Nuget.exe'
  NUGET_SOURCES: 'https://api.nuget.org/v3/index.json'
  MSBUILD_PATH: 'C:\Program Files (x86)\Microsoft Visual Studio\2022\BuildTools\MSBuild\Current\Bin\msbuild.exe'

stages:
- build

build-job:
  variables:
    CI_DEBUG_TRACE: "true"
  stage: build
  script:
    - '& "$env:NUGET_PATH" restore ApplicationTemplate.sln  -Source "$env:NUGET_SOURCES"'
    - '& "$env:MSBUILD_PATH" ApplicationTemplate\ApplicationTemplate.csproj /p:DeployOnBuild=true /p:Configuration=Release /p:PublishProfile=FolderPublish.pubxml'
  artifacts:
    paths:
      - '.\ApplicationTemplate\bin\Release\Publish\'

The output shows that this builds the code just fine, and it also seems to successfully find the artifacts for upload. However, when it uploads the artifacts, even though the request gets a 200 OK response, the process fails. Here is the log output:

So, it finds the artifacts, it attempts to upload them and even gets a 200 OK response (in contrast to the handful of similar reports of this error I've been able to find online), but it still fails due to an invalid argument.

I've already enabled verbose debugging, as you can see from the output, but I'm none the wiser. Looking at the GitLab Runner entries in the Windows Event Log on the box where the runner is hosted doesn't shed any light on things either. The total size of the artifacts is 61.1MB, so I don't think my issue is related to that.

Can anyone see from this output what's invalid? Can I identify which argument is invalid and/or why it's invalid?

Edit: Things I've tried

Specifying a value for artifacts:expire_in.

Setting artifacts:public to FALSE, since I'm using a self-hosted GitLab environment and the default value for this setting (TRUE) is not valid in such an environment.

Trying every format I can think of for the value of the artifacts:paths setting (this seems to be incredibly robust - regardless of the format I use, the Runner seems to have no problem parsing it and finding the files to upload).

Taking a cue from this question I created a new project with a very simple build job to upload a single file:

stages:
  - build

build-job:
  variables:
    CI_DEBUG_TRACE: "true"
  stage: build
  script:
    - echo "Test" > test.txt
  artifacts:
    paths:
      - test.txt

About 50% of the time this job hangs on the uploading of the artifacts and I have to cancel it. The other half of the time it fails in exactly the same way as the my previous project:


问:
Process audio sounds from microphone using Qt
I am developing a sound processing application using Qt as a front end.
How can I get data samples from the microphone? I tried overriding qint64 writeData(const char *data, qint64 len) in  QIODevice, but I was unable to get data samples.

答:
Use QAudioInput class.

see : QAudioInput Class ref in Qt Doc


问:
Do records generate overrides for inherited positional properties?
Consider the following record definitions:

```<code>public record BaseRecord(string Text)
{
    public string Text { get; init; } = Normalize(Text);

    // ...
}

public record DerivedRecord(string Text) : BaseRecord(Text)
{
    // ...
}
</code>```

BaseRecord will have the normalized value for Text. But does DerivedRecord reuse the Test property from BaseRecord, or does it generate a new one that ignores the normalized base value?

Further: What if BaseRecord did not have Text as a positional parameter, but only as a regular property?

答:
Shortly after finishing writing the question, I came up with this test code.

This experiment answered my question directly, but an answer that provided more details, insight, or generally explained in more detail the way code is generated for derived records would be valuable.

```<code>public class Program
{
    public static void Main()
    {
        var x = new DerivedRecord("text", "derived other");
        var (text, other) = x;
        Console.WriteLine(text);
        Console.WriteLine(other);
    }
}

public record BaseRecord(string Text)
{
    public string Text { get; init; } = Text.ToUpper();
    public string Other { get; init; } = "base other";

    // ...
}

public record DerivedRecord(string Text, string Other) : BaseRecord(Text)
{
    // ...
}
</code>```

Running it on https://dotnetfiddle.net/ printed "TEXT" rather than "text", which suggests to me that the base property is being used in DerivedRecord. Additionally, the second line said "base other" rather than "derived other", which suggests not only that DerivedType even re-used the base Other property, but maybe also that it completely ignores the value given to the constructor as a result.

Body:
Consider the following record definitions:

public record BaseRecord(string Text)
{
    public string Text { get; init; } = Normalize(Text);

    // ...
}

public record DerivedRecord(string Text) : BaseRecord(Text)
{
    // ...
}

BaseRecord will have the normalized value for Text. But does DerivedRecord reuse the Test property from BaseRecord, or does it generate a new one that ignores the normalized base value?

Further: What if BaseRecord did not have Text as a positional parameter, but only as a regular property?

Body:
Shortly after finishing writing the question, I came up with this test code.

This experiment answered my question directly, but an answer that provided more details, insight, or generally explained in more detail the way code is generated for derived records would be valuable.

public class Program
{
    public static void Main()
    {
        var x = new DerivedRecord("text", "derived other");
        var (text, other) = x;
        Console.WriteLine(text);
        Console.WriteLine(other);
    }
}

public record BaseRecord(string Text)
{
    public string Text { get; init; } = Text.ToUpper();
    public string Other { get; init; } = "base other";

    // ...
}

public record DerivedRecord(string Text, string Other) : BaseRecord(Text)
{
    // ...
}

Running it on https://dotnetfiddle.net/ printed "TEXT" rather than "text", which suggests to me that the base property is being used in DerivedRecord. Additionally, the second line said "base other" rather than "derived other", which suggests not only that DerivedType even re-used the base Other property, but maybe also that it completely ignores the value given to the constructor as a result.


答:
The useEffect only ran once, when the component initially loaded, and at the time only had the initial value of the playerPos state.  So you effectively have a closure around that one value that's just repeating.

Instead of using setInterval, rely on useEffect to run multiple times whenever the state changes by adding that state value to its dependency array.  Then just use setTimeout to add the delay each time.  For example:

```<code>useEffect(() => {
  setTimeout(() => {
    console.log(`Current player pos ${JSON.stringify(playerPos)}`);
    setPlayerPos({x:128, y:playerPos.y + 10});
  }, 1000);
}, [playerPos]);
</code>```

So each time the component renders, useEffect will re-run if playerPos has changed.  And each time it runs, playerPos will be changed one second later, triggering a re-render.

Note that this would always leave an active timeout when the component unloads.  So as an additional step you'll want to provide useEffect with a way to cancel the timeout.  How one does this is by returning a "cleanup" function form the useEffect operation, which would release any resources held by the logic within the operation.

In this case it's just a simple call to clearTimeout:

```<code>useEffect(() => {
  const timeout = setTimeout(() => {
    console.log(`Current player pos ${JSON.stringify(playerPos)}`);
    setPlayerPos({x:128, y:playerPos.y + 10});
  }, 1000);
  return () => clearTimeout(timeout);
}, [playerPos]);
</code>```

Title: Update React State variable inside an Interval

Body:
The useEffect only ran once, when the component initially loaded, and at the time only had the initial value of the playerPos state.  So you effectively have a closure around that one value that's just repeating.

Instead of using setInterval, rely on useEffect to run multiple times whenever the state changes by adding that state value to its dependency array.  Then just use setTimeout to add the delay each time.  For example:

useEffect(() => {
  setTimeout(() => {
    console.log(`Current player pos ${JSON.stringify(playerPos)}`);
    setPlayerPos({x:128, y:playerPos.y + 10});
  }, 1000);
}, [playerPos]);

So each time the component renders, useEffect will re-run if playerPos has changed.  And each time it runs, playerPos will be changed one second later, triggering a re-render.

Note that this would always leave an active timeout when the component unloads.  So as an additional step you'll want to provide useEffect with a way to cancel the timeout.  How one does this is by returning a "cleanup" function form the useEffect operation, which would release any resources held by the logic within the operation.

In this case it's just a simple call to clearTimeout:

useEffect(() => {
  const timeout = setTimeout(() => {
    console.log(`Current player pos ${JSON.stringify(playerPos)}`);
    setPlayerPos({x:128, y:playerPos.y + 10});
  }, 1000);
  return () => clearTimeout(timeout);
}, [playerPos]);


问:
Application is not centered on 4K monitor
I'm having trouble running a simple application created in Delphi / Firemonkey, running on Windows with 4K monitor.

The application is not centered correctly on the screen, I am placing the Position = ScreenCenter property.

When the application is created in Delphi / VCL, I don't have this problem.

Could anyone help?

I'm using:

Delphi 10.4.1 Professional

Windows 10 Pro 64-bit

Monitor 4K Ultra HD 2160p (Philips Brilliance 288P)

Even forcing via code, it doesn't solve (FormShow):

```<code>Self.Top: = Trunc((Screen.Height - Self.Height) div 2);
Self.Left: = Trunc((Screen.Width - Self.Width) div 2);
</code>```

答:
It looks like FireMonkey has a bug that does not properly consider screen scaling for 4k monitors.  You will need to find the active scaling on your screen to fix this.  Try the following.  It works on Delphi 10.3.  I leave the Position property set to "Designed":</p>
```<code>unit uForm1;

interface

uses
  System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
  FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs,
  FMX.Controls.Presentation, FMX.StdCtrls;

type
  TForm1 = class(TForm)
    function Scale: Single;
    procedure FormCreate(Sender: TObject);
  private
    { Private declarations }
    procedure Center;
  public
    { Public declarations }
  end;

var
  Form1: TForm1;

implementation

uses
  FMX.Platform;

{$R *.fmx}

procedure TForm1.FormCreate(Sender: TObject);
begin
  Center;
end;

procedure TForm1.Center;
begin
  Self.Left := Trunc((Screen.Width  - (Self.Width  * Scale)) / 2);
  Self.Top  := Trunc((Screen.Height - (Self.Height * Scale)) / 2);
end;

function TForm1.Scale: Single;
var
  ScrService: IFMXScreenService;
begin
  Result := 0.0;
  if TPlatformServices.Current.SupportsPlatformService(IFMXScreenService, ScrService) then
  begin
    Result := ScrService.GetScreenScale;
  end;
end;

end.

//FMX form
object Form1: TForm1
  Left = 0
  Top = 0
  Caption = 'Form4'
  ClientHeight = 231
  ClientWidth = 327
  Position = Designed
  FormFactor.Width = 320
  FormFactor.Height = 480
  FormFactor.Devices = [Desktop]
  OnCreate = FormCreate
  DesignerMasterStyle = 0
end
</code>```

Body:
I'm having trouble running a simple application created in Delphi / Firemonkey, running on Windows with 4K monitor.

The application is not centered correctly on the screen, I am placing the Position = ScreenCenter property.

When the application is created in Delphi / VCL, I don't have this problem.

Could anyone help?

I'm using:

Delphi 10.4.1 Professional

Windows 10 Pro 64-bit

Monitor 4K Ultra HD 2160p (Philips Brilliance 288P)

Even forcing via code, it doesn't solve (FormShow):

Self.Top: = Trunc((Screen.Height - Self.Height) div 2);
Self.Left: = Trunc((Screen.Width - Self.Width) div 2);

Body:
It looks like FireMonkey has a bug that does not properly consider screen scaling for 4k monitors.  You will need to find the active scaling on your screen to fix this.  Try the following.  It works on Delphi 10.3.  I leave the Position property set to "Designed":

unit uForm1;

interface

uses
  System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
  FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs,
  FMX.Controls.Presentation, FMX.StdCtrls;

type
  TForm1 = class(TForm)
    function Scale: Single;
    procedure FormCreate(Sender: TObject);
  private
    { Private declarations }
    procedure Center;
  public
    { Public declarations }
  end;

var
  Form1: TForm1;

implementation

uses
  FMX.Platform;

{$R *.fmx}

procedure TForm1.FormCreate(Sender: TObject);
begin
  Center;
end;

procedure TForm1.Center;
begin
  Self.Left := Trunc((Screen.Width  - (Self.Width  * Scale)) / 2);
  Self.Top  := Trunc((Screen.Height - (Self.Height * Scale)) / 2);
end;

function TForm1.Scale: Single;
var
  ScrService: IFMXScreenService;
begin
  Result := 0.0;
  if TPlatformServices.Current.SupportsPlatformService(IFMXScreenService, ScrService) then
  begin
    Result := ScrService.GetScreenScale;
  end;
end;

end.

//FMX form
object Form1: TForm1
  Left = 0
  Top = 0
  Caption = 'Form4'
  ClientHeight = 231
  ClientWidth = 327
  Position = Designed
  FormFactor.Width = 320
  FormFactor.Height = 480
  FormFactor.Devices = [Desktop]
  OnCreate = FormCreate
  DesignerMasterStyle = 0
end