问:
AssertionError on unit testing a celery task with autoretry, backoff and jitter
Using celery 4.3.0. I tried to write a unit test for the following task.

```<code>    from django.core.exceptions import ObjectDoesNotExist

    @shared_task(autoretry_for=(ObjectDoesNotExist,), max_retries=5, retry_backoff=10)
    def process_something(data):
        product = Product()
        product.process(data)
</code>```

Unit test:

```<code>@mock.patch('proj.tasks.Product')
@mock.patch('proj.tasks.process_something.retry')
def test_process_something_retry_failed_task(self, process_something_retry, mock_product):

    mock_object = mock.MagicMock()
    mock_product.return_value = mock_object
    mock_object.process.side_effect = error = ObjectDoesNotExist()

    with pytest.raises(ObjectDoesNotExist):
        process_something(self.data)

    process_something_retry.assert_called_with(exc=error)
</code>```

This is the error I get after running the test:

```<code>    @wraps(task.run)
    def run(*args, **kwargs):
        try:
            return task._orig_run(*args, **kwargs)
        except autoretry_for as exc:
            if retry_backoff:
                retry_kwargs['countdown'] = \
                    get_exponential_backoff_interval(
                        factor=retry_backoff,
                        retries=task.request.retries,
                        maximum=retry_backoff_max,
                        full_jitter=retry_jitter)
>           raise task.retry(exc=exc, **retry_kwargs)
E           TypeError: exceptions must derive from BaseException
</code>```

I understand it is because of the exception. I replaced ObjectDoesNotExist everywhere with Exception instead. After running the test, I get this error:

```<code>    def assert_called_with(self, /, *args, **kwargs):
        """assert that the last call was made with the specified arguments.

            Raises an AssertionError if the args and keyword args passed in are
            different to the last call to the mock."""
        if self.call_args is None:
            expected = self._format_mock_call_signature(args, kwargs)
            actual = 'not called.'
            error_message = ('expected call not found.\nExpected: %s\nActual: %s'
                    % (expected, actual))
            raise AssertionError(error_message)

        def _error_message():
            msg = self._format_mock_failure_message(args, kwargs)
            return msg
        expected = self._call_matcher((args, kwargs))
        actual = self._call_matcher(self.call_args)
        if expected != actual:
            cause = expected if isinstance(expected, Exception) else None
>           raise AssertionError(_error_message()) from cause
E           AssertionError: expected call not found.
E           Expected: retry(exc=Exception())
E           Actual: retry(exc=Exception(), countdown=7)
</code>```

Please let me know how I can fix both the errors.

答:
I had the similar issue, while I was working on tests to ensure that the celery retry logic was covering my specific scenarios. What worked for me was to use explicit retry instead of the autoretry_for parameter.

I have adjusted your code to my solution. Although my solution didn't use
shared_task I think It should work likewise. Tested on celery==5.1.2

task:

```<code>from django.core.exceptions import ObjectDoesNotExist

@shared_task(bind=True, max_retries=5, retry_backoff=10)
def process_something(self, data):
   try:
      product = Product()
      product.process(data)
   except ObjectDoesNotExist as exc:
      raise self.retry(exc=exc)
</code>```

test:

```<code>from proj.tasks import Product # I assume the Product class is located here
from django.core.exceptions import ObjectDoesNotExist
import celery

@mock.patch.object(Product, "__init__", Mock(return_value=None)) # just mocking the init method
@mock.patch.object(Product, "process")
@mock.patch('proj.tasks.process_something.retry')
def test_process_something_retry_failed_task(self, retry_mock, process_mock):
   exc = ObjectDoesNotExist()
   process_mock.side_effect = exc
   retry_mock.side_effect = celery.exceptions.Retry

   with pytest.raises(celery.exceptions.Retry):
      process_something(self.data)

   retry_mock.assert_called_with(exc=exc)
</code>```

In my problem I also was using custom exceptions. With this solution I didnt need change the type of my exceptions.

Body:
Using celery 4.3.0. I tried to write a unit test for the following task.

    from django.core.exceptions import ObjectDoesNotExist

    @shared_task(autoretry_for=(ObjectDoesNotExist,), max_retries=5, retry_backoff=10)
    def process_something(data):
        product = Product()
        product.process(data)

Unit test:

@mock.patch('proj.tasks.Product')
@mock.patch('proj.tasks.process_something.retry')
def test_process_something_retry_failed_task(self, process_something_retry, mock_product):

    mock_object = mock.MagicMock()
    mock_product.return_value = mock_object
    mock_object.process.side_effect = error = ObjectDoesNotExist()

    with pytest.raises(ObjectDoesNotExist):
        process_something(self.data)

    process_something_retry.assert_called_with(exc=error)

This is the error I get after running the test:

    @wraps(task.run)
    def run(*args, **kwargs):
        try:
            return task._orig_run(*args, **kwargs)
        except autoretry_for as exc:
            if retry_backoff:
                retry_kwargs['countdown'] = \
                    get_exponential_backoff_interval(
                        factor=retry_backoff,
                        retries=task.request.retries,
                        maximum=retry_backoff_max,
                        full_jitter=retry_jitter)
>           raise task.retry(exc=exc, **retry_kwargs)
E           TypeError: exceptions must derive from BaseException

I understand it is because of the exception. I replaced ObjectDoesNotExist everywhere with Exception instead. After running the test, I get this error:

    def assert_called_with(self, /, *args, **kwargs):
        """assert that the last call was made with the specified arguments.

            Raises an AssertionError if the args and keyword args passed in are
            different to the last call to the mock."""
        if self.call_args is None:
            expected = self._format_mock_call_signature(args, kwargs)
            actual = 'not called.'
            error_message = ('expected call not found.\nExpected: %s\nActual: %s'
                    % (expected, actual))
            raise AssertionError(error_message)

        def _error_message():
            msg = self._format_mock_failure_message(args, kwargs)
            return msg
        expected = self._call_matcher((args, kwargs))
        actual = self._call_matcher(self.call_args)
        if expected != actual:
            cause = expected if isinstance(expected, Exception) else None
>           raise AssertionError(_error_message()) from cause
E           AssertionError: expected call not found.
E           Expected: retry(exc=Exception())
E           Actual: retry(exc=Exception(), countdown=7)

Please let me know how I can fix both the errors.

Body:
I had the similar issue, while I was working on tests to ensure that the celery retry logic was covering my specific scenarios. What worked for me was to use explicit retry instead of the autoretry_for parameter.

I have adjusted your code to my solution. Although my solution didn't use
shared_task I think It should work likewise. Tested on celery==5.1.2

task:

from django.core.exceptions import ObjectDoesNotExist

@shared_task(bind=True, max_retries=5, retry_backoff=10)
def process_something(self, data):
   try:
      product = Product()
      product.process(data)
   except ObjectDoesNotExist as exc:
      raise self.retry(exc=exc)

test:

from proj.tasks import Product # I assume the Product class is located here
from django.core.exceptions import ObjectDoesNotExist
import celery

@mock.patch.object(Product, "__init__", Mock(return_value=None)) # just mocking the init method
@mock.patch.object(Product, "process")
@mock.patch('proj.tasks.process_something.retry')
def test_process_something_retry_failed_task(self, retry_mock, process_mock):
   exc = ObjectDoesNotExist()
   process_mock.side_effect = exc
   retry_mock.side_effect = celery.exceptions.Retry

   with pytest.raises(celery.exceptions.Retry):
      process_something(self.data)

   retry_mock.assert_called_with(exc=exc)

In my problem I also was using custom exceptions. With this solution I didnt need change the type of my exceptions.


来源: stackexchange

问:
Does anybody know about the output "Module is optimized and the debugger option 'Just My Code' is Enabled"?
As I said in my previous question I'm migrating my app to windows Metro app.

I'm getting an output like this

I don't understand this output, if anybody knows then this please say!

答:
In VS Code, if you do not want to disable "Just My Code" (because you're fine with debugging just your own code), then you can get rid of these messages by adding this to you launch.json configs:

```<code>"logging": {
    "moduleLoad": false
}
</code>```

On the other hand, if you really want to debug external code, then add this to your launch.json config instead:

```<code>"justMyCode": false
</code>```

Find below a full sample config in launch.json for debug just your own code:

```<code>{
    // Use IntelliSense to find out which attributes exist for C# debugging
    // Use hover for the description of the existing attributes
    // For further information visit https://github.com/OmniSharp/omnisharp-vscode/blob/master/debugger-launchjson.md
    "name": ".NET Core Launch (web)",
    "type": "coreclr",
    "request": "launch",
    "preLaunchTask": "build",
    // If you have changed target frameworks, make sure to update the program path.
    "program": "${workspaceFolder}/src/YourProject/bin/Debug/netcoreapp3.1/YourProject.dll",
    "args": [],
    "cwd": "${workspaceFolder}/src/YourProject",
    "stopAtEntry": false,
    "justMyCode": true, // You can change to false if you wanna debug 3rd-party code
    "logging": {
        "moduleLoad": false
    },
    // Enable launching a web browser when ASP.NET Core starts. For more information: https://aka.ms/VSCode-CS-LaunchJson-WebBrowser
    "serverReadyAction": {
        "action": "openExternally",
        "pattern": "\\bNow listening on:\\s+(https?://\\S+)"
    },
    "env": {
        "ASPNETCORE_ENVIRONMENT": "Development"
    },
    "sourceFileMap": {
        "/Views": "${workspaceFolder}/Views"
    }
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
In VS Code, if you do not want to disable "Just My Code" (because you're fine with debugging just your own code), then you can get rid of these messages by adding this to you launch.json configs:

"logging": {
    "moduleLoad": false
}

On the other hand, if you really want to debug external code, then add this to your launch.json config instead:

"justMyCode": false

Find below a full sample config in launch.json for debug just your own code:

{
    // Use IntelliSense to find out which attributes exist for C# debugging
    // Use hover for the description of the existing attributes
    // For further information visit https://github.com/OmniSharp/omnisharp-vscode/blob/master/debugger-launchjson.md
    "name": ".NET Core Launch (web)",
    "type": "coreclr",
    "request": "launch",
    "preLaunchTask": "build",
    // If you have changed target frameworks, make sure to update the program path.
    "program": "${workspaceFolder}/src/YourProject/bin/Debug/netcoreapp3.1/YourProject.dll",
    "args": [],
    "cwd": "${workspaceFolder}/src/YourProject",
    "stopAtEntry": false,
    "justMyCode": true, // You can change to false if you wanna debug 3rd-party code
    "logging": {
        "moduleLoad": false
    },
    // Enable launching a web browser when ASP.NET Core starts. For more information: https://aka.ms/VSCode-CS-LaunchJson-WebBrowser
    "serverReadyAction": {
        "action": "openExternally",
        "pattern": "\\bNow listening on:\\s+(https?://\\S+)"
    },
    "env": {
        "ASPNETCORE_ENVIRONMENT": "Development"
    },
    "sourceFileMap": {
        "/Views": "${workspaceFolder}/Views"
    }
}

ContentLicense: CC BY-SA 4.0


问:
React: trigger an event or value outside the root component
Somebody could help me with this idea? I don't know if it were possible or should I use any library or skill.

Component (This is usually and common)

import React, { useState } from "react";

export default function App() {
  const [anyVal, setAnyVal] = useState(0);

  return (

Any Value: {anyVal}

      <button onClick={() => setAnyVal(anyVal + 1)}>Change value</button>

  );
}
```
<p><strong>Connection HTML + React Dom  (This is usually and common)</strong></p>
<pre class="lang-js prettyprint-override"><code>import { StrictMode } from "react";
import ReactDOM from "react-dom";

import App from "./App";

const rootElement = document.getElementById("root");
ReactDOM.render(
  <StrictMode>
    <App />
  </StrictMode>,
  rootElement
);
</code>```

Here the part that I don't know if it were possible

```

答:
If you are declaring the function in a script tag like that, it exists in the global window scope so you can just call it like this from your react component:

window.externalFn('any value')
```

Body:
Somebody could help me with this idea? I don't know if it were possible or should I use any library or skill.

Component (This is usually and common)

import React, { useState } from "react";

export default function App() {
  const [anyVal, setAnyVal] = useState(0);

  return (

Any Value: {anyVal}

      <button onClick={() => setAnyVal(anyVal + 1)}>Change value</button>

  );
}

Connection HTML + React Dom  (This is usually and common)

import { StrictMode } from "react";
import ReactDOM from "react-dom";

import App from "./App";

const rootElement = document.getElementById("root");
ReactDOM.render(
  <StrictMode>
    <App />
  </StrictMode>,
  rootElement
);

Here the part that I don't know if it were possible


问:
C# threads and backgroundworker problem
In my main thread I run Backgroundworker. His todo work is method that Invoke "Method" from main thread. When I wish to cancel my backgroundworker it stops running but "Method" invoked on mainthread still run what cause problems. Any idea how to solve it?</p>

答: MSDN notes that you must check for CancellationPending inside Method (do you do that?)

Title: C# threads and backgroundworker problem


问:
Updating table_2 data using table_1 and table_2 data / T-SQL
Scenario

user@website.com needs to have the same user profiles in table 2 as admin@website.com.

Currently user@website.com have user_profile 50 instead of having user_profile 10 and 20.

Description

I want to create a query that enters into Table_2 the same id_profiles for user_email user@website.com as currently have admin@website.com.

The only knowledge that we have is user_email for both users and table/column names.

Table 1

id_user
user_email

1
admin@website.com

2
user@website.com

Table 2

id_user
user_profile

1
10

1
20

2
50

Table 2 (expected data):

id_user
user_profile

1
10

1
20

2
10

2
20

Below query doesn't work as expected as it only inserts data when there are no rows with user_id '2' in Table_2.

```<code>DECLARE @adminEmail nvarchar(255) = 'admin@website.com'
DECLARE @userEmail nvarchar(255) = 'user@website.com'
DECLARE @adminEmailID int = (SELECT id_user FROM Table_1
                             WHERE user_profile = @adminEmail);

INSERT INTO Table_2 (id_user, user_profile)
    SELECT
        (SELECT id_user FROM Table_1
         WHERE user_email = @userEmail) AS id_user,
        b.user_profile
    FROM
        Table_2 b
    INNER JOIN
        Table_1 a ON a.id_user = b.id_user
    WHERE
        NOT EXISTS (SELECT * FROM Table_2
                    WHERE id_user = (SELECT id_user FROM Table_1
                                     WHERE user_email = @userEmail))
</code>```

答:
You can use MERGE for this.

Note the following:

You must pre-filter the source and target tables, using CTEs, views or derived tables, because otherwise you will end up deleting the whole table. Do not fall into the trap of putting all the conditions in the ON.

You need to find the ID of the target user, in order to insert against that ID. You cannot do this in the MERGE as there will be no matching row due to the JOIN.

DECLARE @adminEmail nvarchar(255) = 'admin@website.com';
DECLARE @userEmail nvarchar(255) = 'user@website.com';
DECLARE @userEmailID int = (SELECT id_user FROM Table_1
                             WHERE user_email = @userEmail);

WITH Source AS (
    SELECT t2.*
    FROM Table_2 t2
    JOIN Table_1 t1 ON t1.id_user = t2.id_user
    WHERE t1.user_email = @adminEmail
),
Target AS (
    SELECT t2.*
    FROM Table_2 t2
    WHERE t2.id_user = @userEmailID
)
MERGE Target t
USING Source s ON s.user_profile = t.user_profile
WHEN NOT MATCHED BY TARGET THEN
    INSERT (id_user, user_profile)
    VALUES (@userEmailID, s.user_profile)
WHEN NOT MATCHED BY SOURCE THEN
    DELETE
;
```
<p>db<>fiddle</p>
<ul>
<li>Depending on the complexity of the joins, it may be easier and more performant to do this as separate <code>INSERT</code> and <code>DELETE</code> statements</li>
</ul>
<pre class="lang-sql prettyprint-override"><code>DECLARE @adminEmail nvarchar(255) = 'admin@website.com';
DECLARE @userEmail nvarchar(255) = 'user@website.com';

INSERT Table_2 (id_user, user_profile)
SELECT t1User.id_user, t2.user_profile
FROM Table_2 t2
JOIN Table_1 t1Admin ON t1Admin.id_user = t2.id_user
    AND t1Admin.user_email = @adminEmail
JOIN Table_1 t1User ON t1User.user_email = @userEmail
WHERE NOT EXISTS (SELECT 1
    FROM Table_2 t2Existing
    WHERE t2Existing.id_user = t1User.id_user
      AND t2Existing.user_profile = t2.user_profile);

DELETE t2
FROM Table_2 t2
JOIN Table_1 t1User ON t1User.id_user = t2.id_user
    AND t1User.user_email = @userEmail
WHERE NOT EXISTS (SELECT 1
    FROM Table_2 t2Admin
    JOIN Table_1 t1Admin ON t1Admin.id_user = t2Admin.id_user
    WHERE t1Admin.user_email = @adminEmail
      AND t2Admin.user_profile = t2.user_profile);
</code>```

db<>fiddle

Body:
Scenario

user@website.com needs to have the same user profiles in table 2 as admin@website.com.

Currently user@website.com have user_profile 50 instead of having user_profile 10 and 20.

Description

I want to create a query that enters into Table_2 the same id_profiles for user_email user@website.com as currently have admin@website.com.

The only knowledge that we have is user_email for both users and table/column names.

Table 1

id_user
user_email

1
admin@website.com

2
user@website.com

Table 2

id_user
user_profile

1
10

1
20

2
50

Table 2 (expected data):

id_user
user_profile

1
10

1
20

2
10

2
20

Below query doesn't work as expected as it only inserts data when there are no rows with user_id '2' in Table_2.

DECLARE @adminEmail nvarchar(255) = 'admin@website.com'
DECLARE @userEmail nvarchar(255) = 'user@website.com'
DECLARE @adminEmailID int = (SELECT id_user FROM Table_1
                             WHERE user_profile = @adminEmail);

INSERT INTO Table_2 (id_user, user_profile)
    SELECT
        (SELECT id_user FROM Table_1
         WHERE user_email = @userEmail) AS id_user,
        b.user_profile
    FROM
        Table_2 b
    INNER JOIN
        Table_1 a ON a.id_user = b.id_user
    WHERE
        NOT EXISTS (SELECT * FROM Table_2
                    WHERE id_user = (SELECT id_user FROM Table_1
                                     WHERE user_email = @userEmail))

Body:
You can use MERGE for this.

Note the following:

You must pre-filter the source and target tables, using CTEs, views or derived tables, because otherwise you will end up deleting the whole table. Do not fall into the trap of putting all the conditions in the ON.

You need to find the ID of the target user, in order to insert against that ID. You cannot do this in the MERGE as there will be no matching row due to the JOIN.

DECLARE @adminEmail nvarchar(255) = 'admin@website.com';
DECLARE @userEmail nvarchar(255) = 'user@website.com';
DECLARE @userEmailID int = (SELECT id_user FROM Table_1
                             WHERE user_email = @userEmail);

WITH Source AS (
    SELECT t2.*
    FROM Table_2 t2
    JOIN Table_1 t1 ON t1.id_user = t2.id_user
    WHERE t1.user_email = @adminEmail
),
Target AS (
    SELECT t2.*
    FROM Table_2 t2
    WHERE t2.id_user = @userEmailID
)
MERGE Target t
USING Source s ON s.user_profile = t.user_profile
WHEN NOT MATCHED BY TARGET THEN
    INSERT (id_user, user_profile)
    VALUES (@userEmailID, s.user_profile)
WHEN NOT MATCHED BY SOURCE THEN
    DELETE
;

db<>fiddle

Depending on the complexity of the joins, it may be easier and more performant to do this as separate INSERT and DELETE statements

DECLARE @adminEmail nvarchar(255) = 'admin@website.com';
DECLARE @userEmail nvarchar(255) = 'user@website.com';

INSERT Table_2 (id_user, user_profile)
SELECT t1User.id_user, t2.user_profile
FROM Table_2 t2
JOIN Table_1 t1Admin ON t1Admin.id_user = t2.id_user
    AND t1Admin.user_email = @adminEmail
JOIN Table_1 t1User ON t1User.user_email = @userEmail
WHERE NOT EXISTS (SELECT 1
    FROM Table_2 t2Existing
    WHERE t2Existing.id_user = t1User.id_user
      AND t2Existing.user_profile = t2.user_profile);

DELETE t2
FROM Table_2 t2
JOIN Table_1 t1User ON t1User.id_user = t2.id_user
    AND t1User.user_email = @userEmail
WHERE NOT EXISTS (SELECT 1
    FROM Table_2 t2Admin
    JOIN Table_1 t1Admin ON t1Admin.id_user = t2Admin.id_user
    WHERE t1Admin.user_email = @adminEmail
      AND t2Admin.user_profile = t2.user_profile);

db<>fiddle


问:
Integromat Scenario: One-shot module after iterating through a loop
I have created a scenario where I iterate through multiple modules with an array of data. This works fine.

After this completes, I want to run a module once before the scenario completes.

How do I add a module that won't get called in the loop?

答:
If you're interested in doing something on the last iteration only, you can use a filter to check if the current bundle is equal to the total number of bundles
last bundle filter

They won't let me paste pics sigh


问:
VS2022: Debug doesn't stop at breakpoint. The debugger is not properly installed. Cannot debug the requested type of code
I encountered this issue after unloading and reloading a unit test project (MSUNIT), and the debug didn't stop at any breakpoints and skipped all of them, but the tests were running fine. Other projects within the same solution can debug normally, but only this project skipped breakpoints during debugging. I realize this could be from a number of reasons but none of the answers in SO helped.</p>

答:
In my case, this is due to a missing debug profile for the project. I'm not sure how did it go disappear, I assume this happened after I unloaded and reloaded my project. So if you have tried other solutions and it didn't work, this is worth a try.

Make sure the current startup project is the project you want to look at, for eg: Application.UnitTests.

Next to the Startup Project's drop down list, select [project name] Debug properties. Note: WSL is the default option if no profile is found.

A new window will pop up and a profile should be available there to allow the debug to work but in my case, I couldn't see any profile.

Create a new project profile by clicking this icon and choose Project:

Rename the profile by clicking this icon:

This is how it should look like after adding and renaming a Project profile, that's it:

Close the window.

Next to the Startup Project's drop down list, select the new profile.

Try to debug again, it should start working again and stop skipping the breakpoints.


问:
Why does the star rotation slows down automatically after some time
I have a program where I have to use internal Timer event to rotate a star in circular motion. There is a button in the frame that changes the direction of the star and a slider which changes the speed of the star rotation.

This is my Main Class

```<code>import javax.swing.JFrame;

public class Main {
    public static void main(String args[]) {
//      Making an instance of the class that makes the frame
        MainFrame frame = new MainFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(500, 500);
        frame.setVisible(true);
    }
}
</code>```

MainFrame Class that makes the frame.

```<code>import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;

import javax.swing.*;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;

@SuppressWarnings("serial")
public class MainFrame extends JFrame{
    private StarGraphics frameStar;
    private JButton starToggle;
    public JSlider starSpeed;

    public MainFrame() {
//      Setting some properties of the frame
        setTitle("Star Moving with Internal Events");
        setLayout(new BorderLayout());

//      Initializing the panel which has rotating star
        frameStar = new StarPainter(this);

//      Adding the bottom toggle button and slider
        addToggler();
    }

//  Getter for the slider value
    public int sliderSpeed() {
        return starSpeed.getValue();
    }

//  Adds Button to change the direction of the star
    private void addToggler() {
//      Adding another jpanel which has layout set to null so i can add button of my size
        JPanel panel = new JPanel();
        panel.setLayout(null);
        panel.setPreferredSize(new Dimension(20,80));
        panel.setBackground(Color.WHITE);

//      Initializing button and its action listener to change star direction
        starToggle = new JButton("Toggle");
        starToggle.setBounds(190, 0, 80, 20);
        starToggle.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                if(e.getSource() == starToggle) {
                    frameStar.ChangeDirections();
                }
            }
        });

//      Adding button to panel
        panel.add(starToggle);

//      Adding slider to the panel
        addSlider(panel);

//      Adding panel to the main Panel at the bottom
        add(panel, BorderLayout.SOUTH);
    }

    private void addSlider(JPanel panel) {
//      Adding Slider and it's properties
        starSpeed = new JSlider(JSlider.HORIZONTAL, 0, 20, 5);
        starSpeed.setMajorTickSpacing(10);
        starSpeed.setMinorTickSpacing(1);
        starSpeed.setPaintTicks(true);
        starSpeed.setPaintLabels(true);
        starSpeed.setBounds(70,30,400, 45);

//      Adding Slider-ChangeListener to change the rotation speed of the star
        starSpeed.addChangeListener(new ChangeListener() { // anonymous inner class
            // handle change in slider value
            @Override
            public void stateChanged(ChangeEvent e) {
                frameStar.ChangeSpeed(starSpeed.getValue());
            }
         }
      );

//      Adding label besides the slider
        JLabel label = new JLabel("Speed : ");
        label.setBounds(10 , 10, 80, 80);
        panel.add(label);
        panel.add(starSpeed);
    }
}
</code>```

Class to create the panel that has star rotation

```<code>import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.*;

@SuppressWarnings("serial")
public class StarGraphics extends JPanel{
    private boolean toggleDir = false;
    private int speed = 10;
    private Timer timer;
    protected double angleOfStarRotation = 0;

    public StarGraphics(JFrame frame) {

        setPreferredSize(new Dimension(500, 470));
        setBackground(Color.BLACK);
        setLayout(new BorderLayout());
        frame.add(this, BorderLayout.CENTER);

        startTimer();
    }

    public void startTimer() {
        timer = new Timer(speed, new ActionListener() {
            public void actionPerformed(ActionEvent e){
//              System.out.println(angleOfStarRotation);
                if(!toggleDir)  //rotates clockwise
                    angleOfStarRotation = angleOfStarRotation + 1;
                else        //rotates counterclockwise
                    angleOfStarRotation = angleOfStarRotation - 1;

//                if (angleOfStarRotation == 360 || angleOfStarRotation == -360)  // If there is a full circle, it will reset the angle to zero
//                    angleOfStarRotation = 0;

                repaint();
            }});
        timer.start();
    }

    public void ChangeSpeed(int newSpeed) {
        this.speed = newSpeed;
        timer.setDelay(speed);
    }
    public void ChangeDirections() {toggleDir = !toggleDir; }

}

</code>```

And a class that paints the star into the panel

```<code>import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.geom.GeneralPath;
import java.security.SecureRandom;

import javax.swing.JFrame;

@SuppressWarnings("serial")
public class StarPainter extends StarGraphics{
    private int[] starXPoints = {55, 67, 109, 73, 83, 55, 27, 37, 1, 43};
    private int[] starYPoints = {0, 36, 36, 54, 96, 72, 96, 54, 36, 36};
    GeneralPath starDesign = new GeneralPath();

    public StarPainter(JFrame frame) {
        super(frame);
    }

    public void drawStar(GeneralPath path) {
        path.moveTo(starXPoints[0], starYPoints[0]);

        for(int i=0; i<10; i++)
           path.lineTo(starXPoints[i], starYPoints[i]);

        path.closePath();
    }

    public void starActions(Graphics2D g) {
        int startAngle = 360;
        // For Random Color
        SecureRandom random = new SecureRandom();

        // rotate around origin and draw stars in random colors
        for (int count = 1; count <= 1; count++)
        {
            double angle = startAngle - 90;
            // rotate coordinate system
            g.rotate(angleOfStarRotation * Math.PI / angle); //rotates as per the rotated angle    //
           // set random drawing color
            g.setColor(new Color(random.nextInt(256), random.nextInt(256), random.nextInt(256)));
          // draw filled star
            g.fill(starDesign);
          // dispose the star
            g.dispose();
        }
    }

    @Override
    public void paintComponent(Graphics g)
    {
       super.paintComponent(g);

       Graphics2D g2d = (Graphics2D) g;

       drawStar(starDesign);

       g2d.translate(250,150);

       starActions(g2d);

    }
}
</code>```

After running the code, the output will show a frame with coloring star rotating around the panel in circular motion, but after 2 full rotation, the star rotation slow down automatically. Does anyone know why that happens?

答:
Your "core" problem is right here...

```<code>public void drawStar(GeneralPath path) {
    path.moveTo(starXPoints[0], starYPoints[0]);

    for(int i=0; i<10; i++)
       path.lineTo(starXPoints[i], starYPoints[i]);

    path.closePath();
}
</code>```

This gets called each time you re-draw the component, which means, you're adding new points to the shape, making it infinitely more complex on each paint pass.

Instead, just create the shape in the constructor...

```<code>public StarPainter() {
    starDesign.moveTo(starXPoints[0], starYPoints[0]);

    for (int i = 0; i < 10; i++) {
        starDesign.lineTo(starXPoints[i], starYPoints[i]);
    }

    starDesign.closePath();
}
</code>```

As has already been pointed out, you're disposing of a Graphics context which you did not create.

If your going to change the transformation of the context, you should always create a copy of your own, for example...

```<code>public void starActions(Graphics2D g) {
    int startAngle = 360;
    // For Random Color
    SecureRandom random = new SecureRandom();

    g = (Graphics2D) g.create();
    // rotate around origin and draw stars in random colors
    //for (int count = 1; count <= 1; count++) {
        double angle = startAngle - 90;
        // rotate coordinate system
        g.rotate(angleOfStarRotation * Math.PI / angle); //rotates as per the rotated angle    //
        // set random drawing color
        g.setColor(new Color(random.nextInt(256), random.nextInt(256), random.nextInt(256)));
        // draw filled star
        g.fill(starDesign);
        // dispose the star
        g.dispose();
    //}
}

@Override
public void paintComponent(Graphics g) {
    super.paintComponent(g);

    Graphics2D g2d = (Graphics2D) g.create();
    g2d.translate(250, 150);
    starActions(g2d);
    g2d.dispose();

}
</code>```

Also, passing a reference of the JFrame to the component...

```<code>public StarGraphics(JFrame frame) {

    setPreferredSize(new Dimension(500, 470));
    setBackground(Color.BLACK);
    setLayout(new BorderLayout());
    frame.add(this, BorderLayout.CENTER);

    startTimer();
}
</code>```

is a bad idea.  The component has no need for, nor is it its responsibility too, interact with the frame.  You're just exposing implementation detail unnecessarily.

Runnable example

```<code>import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.geom.GeneralPath;
import java.security.SecureRandom;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSlider;
import javax.swing.Timer;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;

public class Main {

    public static void main(String[] args) {
        new Main();
    }

    public Main() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                MainFrame frame = new MainFrame();
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setSize(500, 500);
                frame.setVisible(true);
            }
        });
    }

    public class MainFrame extends JFrame {

        private StarGraphics frameStar;
        private JButton starToggle;
        public JSlider starSpeed;

        public MainFrame() {
            //      Setting some properties of the frame
            setTitle("Star Moving with Internal Events");
            setLayout(new BorderLayout());

            //      Initializing the panel which has rotating star
            frameStar = new StarPainter();
            add(frameStar);

            //      Adding the bottom toggle button and slider
            addToggler();
        }

        //  Getter for the slider value
        public int sliderSpeed() {
            return starSpeed.getValue();
        }

        //  Adds Button to change the direction of the star
        private void addToggler() {
            //      Adding another jpanel which has layout set to null so i can add button of my size
            JPanel panel = new JPanel();
            panel.setLayout(null);
            panel.setPreferredSize(new Dimension(20, 80));
            panel.setBackground(Color.WHITE);

            //      Initializing button and its action listener to change star direction
            starToggle = new JButton("Toggle");
            starToggle.setBounds(190, 0, 80, 20);
            starToggle.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    if (e.getSource() == starToggle) {
                        frameStar.ChangeDirections();
                    }
                }
            });

            //      Adding button to panel
            panel.add(starToggle);

            //      Adding slider to the panel
            addSlider(panel);

            //      Adding panel to the main Panel at the bottom
            add(panel, BorderLayout.SOUTH);
        }

        private void addSlider(JPanel panel) {
            //      Adding Slider and it's properties
            starSpeed = new JSlider(JSlider.HORIZONTAL, 0, 20, 5);
            starSpeed.setMajorTickSpacing(10);
            starSpeed.setMinorTickSpacing(1);
            starSpeed.setPaintTicks(true);
            starSpeed.setPaintLabels(true);
            starSpeed.setBounds(70, 30, 400, 45);

            //      Adding Slider-ChangeListener to change the rotation speed of the star
            starSpeed.addChangeListener(new ChangeListener() { // anonymous inner class
                // handle change in slider value
                @Override
                public void stateChanged(ChangeEvent e) {
                    frameStar.ChangeSpeed(starSpeed.getValue());
                }
            }
            );

            //      Adding label besides the slider
            JLabel label = new JLabel("Speed : ");
            label.setBounds(10, 10, 80, 80);
            panel.add(label);
            panel.add(starSpeed);
        }
    }

    public class StarGraphics extends JPanel {

        private boolean toggleDir = false;
        private int speed = 10;
        private Timer timer;
        protected double angleOfStarRotation = 0;

        public StarGraphics() {
            setPreferredSize(new Dimension(500, 470));
            setBackground(Color.BLACK);
            setLayout(new BorderLayout());
            startTimer();
        }

        public void startTimer() {
            timer = new Timer(speed, new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    //              System.out.println(angleOfStarRotation);
                    if (!toggleDir) //rotates clockwise
                    {
                        angleOfStarRotation = angleOfStarRotation + 1;
                    } else //rotates counterclockwise
                    {
                        angleOfStarRotation = angleOfStarRotation - 1;
                    }

                    System.out.println("tick");
                    //                if (angleOfStarRotation == 360 || angleOfStarRotation == -360)  // If there is a full circle, it will reset the angle to zero
                    //                    angleOfStarRotation = 0;
                    repaint();
                }
            });
            timer.start();
        }

        public void ChangeSpeed(int newSpeed) {
            this.speed = newSpeed;
            timer.setDelay(speed);
        }

        public void ChangeDirections() {
            toggleDir = !toggleDir;
        }

    }

    public class StarPainter extends StarGraphics {

        private int[] starXPoints = {55, 67, 109, 73, 83, 55, 27, 37, 1, 43};
        private int[] starYPoints = {0, 36, 36, 54, 96, 72, 96, 54, 36, 36};
        GeneralPath starDesign = new GeneralPath();

        public StarPainter() {
            starDesign.moveTo(starXPoints[0], starYPoints[0]);

            for (int i = 0; i < 10; i++) {
                starDesign.lineTo(starXPoints[i], starYPoints[i]);
            }

            starDesign.closePath();
        }

        public void starActions(Graphics2D g) {
            int startAngle = 360;
            // For Random Color
            SecureRandom random = new SecureRandom();

            g = (Graphics2D) g.create();
            // rotate around origin and draw stars in random colors
            //for (int count = 1; count <= 1; count++) {
            double angle = startAngle - 90;
            // rotate coordinate system
            g.rotate(angleOfStarRotation * Math.PI / angle); //rotates as per the rotated angle    //
            // set random drawing color
            g.setColor(new Color(random.nextInt(256), random.nextInt(256), random.nextInt(256)));
            // draw filled star
            g.fill(starDesign);
            // dispose the star
            g.dispose();
            //}
        }

        @Override
        public void paintComponent(Graphics g) {
            super.paintComponent(g);

            Graphics2D g2d = (Graphics2D) g.create();
            g2d.translate(250, 150);
            starActions(g2d);
            g2d.dispose();

        }
    }
}
</code>```

Body:
I have a program where I have to use internal Timer event to rotate a star in circular motion. There is a button in the frame that changes the direction of the star and a slider which changes the speed of the star rotation.

This is my Main Class

import javax.swing.JFrame;

public class Main {
    public static void main(String args[]) {
//      Making an instance of the class that makes the frame
        MainFrame frame = new MainFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(500, 500);
        frame.setVisible(true);
    }
}

MainFrame Class that makes the frame.

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;

import javax.swing.*;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;

@SuppressWarnings("serial")
public class MainFrame extends JFrame{
    private StarGraphics frameStar;
    private JButton starToggle;
    public JSlider starSpeed;

    public MainFrame() {
//      Setting some properties of the frame
        setTitle("Star Moving with Internal Events");
        setLayout(new BorderLayout());

//      Initializing the panel which has rotating star
        frameStar = new StarPainter(this);

//      Adding the bottom toggle button and slider
        addToggler();
    }

//  Getter for the slider value
    public int sliderSpeed() {
        return starSpeed.getValue();
    }

//  Adds Button to change the direction of the star
    private void addToggler() {
//      Adding another jpanel which has layout set to null so i can add button of my size
        JPanel panel = new JPanel();
        panel.setLayout(null);
        panel.setPreferredSize(new Dimension(20,80));
        panel.setBackground(Color.WHITE);

//      Initializing button and its action listener to change star direction
        starToggle = new JButton("Toggle");
        starToggle.setBounds(190, 0, 80, 20);
        starToggle.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                if(e.getSource() == starToggle) {
                    frameStar.ChangeDirections();
                }
            }
        });

//      Adding button to panel
        panel.add(starToggle);

//      Adding slider to the panel
        addSlider(panel);

//      Adding panel to the main Panel at the bottom
        add(panel, BorderLayout.SOUTH);
    }

    private void addSlider(JPanel panel) {
//      Adding Slider and it's properties
        starSpeed = new JSlider(JSlider.HORIZONTAL, 0, 20, 5);
        starSpeed.setMajorTickSpacing(10);
        starSpeed.setMinorTickSpacing(1);
        starSpeed.setPaintTicks(true);
        starSpeed.setPaintLabels(true);
        starSpeed.setBounds(70,30,400, 45);

//      Adding Slider-ChangeListener to change the rotation speed of the star
        starSpeed.addChangeListener(new ChangeListener() { // anonymous inner class
            // handle change in slider value
            @Override
            public void stateChanged(ChangeEvent e) {
                frameStar.ChangeSpeed(starSpeed.getValue());
            }
         }
      );

//      Adding label besides the slider
        JLabel label = new JLabel("Speed : ");
        label.setBounds(10 , 10, 80, 80);
        panel.add(label);
        panel.add(starSpeed);
    }
}

Class to create the panel that has star rotation

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.*;

@SuppressWarnings("serial")
public class StarGraphics extends JPanel{
    private boolean toggleDir = false;
    private int speed = 10;
    private Timer timer;
    protected double angleOfStarRotation = 0;

    public StarGraphics(JFrame frame) {

        setPreferredSize(new Dimension(500, 470));
        setBackground(Color.BLACK);
        setLayout(new BorderLayout());
        frame.add(this, BorderLayout.CENTER);

        startTimer();
    }

    public void startTimer() {
        timer = new Timer(speed, new ActionListener() {
            public void actionPerformed(ActionEvent e){
//              System.out.println(angleOfStarRotation);
                if(!toggleDir)  //rotates clockwise
                    angleOfStarRotation = angleOfStarRotation + 1;
                else        //rotates counterclockwise
                    angleOfStarRotation = angleOfStarRotation - 1;

//                if (angleOfStarRotation == 360 || angleOfStarRotation == -360)  // If there is a full circle, it will reset the angle to zero
//                    angleOfStarRotation = 0;

                repaint();
            }});
        timer.start();
    }

    public void ChangeSpeed(int newSpeed) {
        this.speed = newSpeed;
        timer.setDelay(speed);
    }
    public void ChangeDirections() {toggleDir = !toggleDir; }

}

And a class that paints the star into the panel

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.geom.GeneralPath;
import java.security.SecureRandom;

import javax.swing.JFrame;

@SuppressWarnings("serial")
public class StarPainter extends StarGraphics{
    private int[] starXPoints = {55, 67, 109, 73, 83, 55, 27, 37, 1, 43};
    private int[] starYPoints = {0, 36, 36, 54, 96, 72, 96, 54, 36, 36};
    GeneralPath starDesign = new GeneralPath();

    public StarPainter(JFrame frame) {
        super(frame);
    }

    public void drawStar(GeneralPath path) {
        path.moveTo(starXPoints[0], starYPoints[0]);

        for(int i=0; i<10; i++)
           path.lineTo(starXPoints[i], starYPoints[i]);

        path.closePath();
    }

    public void starActions(Graphics2D g) {
        int startAngle = 360;
        // For Random Color
        SecureRandom random = new SecureRandom();

        // rotate around origin and draw stars in random colors
        for (int count = 1; count <= 1; count++)
        {
            double angle = startAngle - 90;
            // rotate coordinate system
            g.rotate(angleOfStarRotation * Math.PI / angle); //rotates as per the rotated angle    //
           // set random drawing color
            g.setColor(new Color(random.nextInt(256), random.nextInt(256), random.nextInt(256)));
          // draw filled star
            g.fill(starDesign);
          // dispose the star
            g.dispose();
        }
    }

    @Override
    public void paintComponent(Graphics g)
    {
       super.paintComponent(g);

       Graphics2D g2d = (Graphics2D) g;

       drawStar(starDesign);

       g2d.translate(250,150);

       starActions(g2d);

    }
}

After running the code, the output will show a frame with coloring star rotating around the panel in circular motion, but after 2 full rotation, the star rotation slow down automatically. Does anyone know why that happens?

Body:
Your "core" problem is right here...

public void drawStar(GeneralPath path) {
    path.moveTo(starXPoints[0], starYPoints[0]);

    for(int i=0; i<10; i++)
       path.lineTo(starXPoints[i], starYPoints[i]);

    path.closePath();
}

This gets called each time you re-draw the component, which means, you're adding new points to the shape, making it infinitely more complex on each paint pass.

Instead, just create the shape in the constructor...

public StarPainter() {
    starDesign.moveTo(starXPoints[0], starYPoints[0]);

    for (int i = 0; i < 10; i++) {
        starDesign.lineTo(starXPoints[i], starYPoints[i]);
    }

    starDesign.closePath();
}

As has already been pointed out, you're disposing of a Graphics context which you did not create.

If your going to change the transformation of the context, you should always create a copy of your own, for example...

public void starActions(Graphics2D g) {
    int startAngle = 360;
    // For Random Color
    SecureRandom random = new SecureRandom();

    g = (Graphics2D) g.create();
    // rotate around origin and draw stars in random colors
    //for (int count = 1; count <= 1; count++) {
        double angle = startAngle - 90;
        // rotate coordinate system
        g.rotate(angleOfStarRotation * Math.PI / angle); //rotates as per the rotated angle    //
        // set random drawing color
        g.setColor(new Color(random.nextInt(256), random.nextInt(256), random.nextInt(256)));
        // draw filled star
        g.fill(starDesign);
        // dispose the star
        g.dispose();
    //}
}

@Override
public void paintComponent(Graphics g) {
    super.paintComponent(g);

    Graphics2D g2d = (Graphics2D) g.create();
    g2d.translate(250, 150);
    starActions(g2d);
    g2d.dispose();

}

Also, passing a reference of the JFrame to the component...

public StarGraphics(JFrame frame) {

    setPreferredSize(new Dimension(500, 470));
    setBackground(Color.BLACK);
    setLayout(new BorderLayout());
    frame.add(this, BorderLayout.CENTER);

    startTimer();
}

is a bad idea.  The component has no need for, nor is it its responsibility too, interact with the frame.  You're just exposing implementation detail unnecessarily.

Runnable example

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.geom.GeneralPath;
import java.security.SecureRandom;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSlider;
import javax.swing.Timer;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;

public class Main {

    public static void main(String[] args) {
        new Main();
    }

    public Main() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                MainFrame frame = new MainFrame();
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setSize(500, 500);
                frame.setVisible(true);
            }
        });
    }

    public class MainFrame extends JFrame {

        private StarGraphics frameStar;
        private JButton starToggle;
        public JSlider starSpeed;

        public MainFrame() {
            //      Setting some properties of the frame
            setTitle("Star Moving with Internal Events");
            setLayout(new BorderLayout());

            //      Initializing the panel which has rotating star
            frameStar = new StarPainter();
            add(frameStar);

            //      Adding the bottom toggle button and slider
            addToggler();
        }

        //  Getter for the slider value
        public int sliderSpeed() {
            return starSpeed.getValue();
        }

        //  Adds Button to change the direction of the star
        private void addToggler() {
            //      Adding another jpanel which has layout set to null so i can add button of my size
            JPanel panel = new JPanel();
            panel.setLayout(null);
            panel.setPreferredSize(new Dimension(20, 80));
            panel.setBackground(Color.WHITE);

            //      Initializing button and its action listener to change star direction
            starToggle = new JButton("Toggle");
            starToggle.setBounds(190, 0, 80, 20);
            starToggle.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    if (e.getSource() == starToggle) {
                        frameStar.ChangeDirections();
                    }
                }
            });

            //      Adding button to panel
            panel.add(starToggle);

            //      Adding slider to the panel
            addSlider(panel);

            //      Adding panel to the main Panel at the bottom
            add(panel, BorderLayout.SOUTH);
        }

        private void addSlider(JPanel panel) {
            //      Adding Slider and it's properties
            starSpeed = new JSlider(JSlider.HORIZONTAL, 0, 20, 5);
            starSpeed.setMajorTickSpacing(10);
            starSpeed.setMinorTickSpacing(1);
            starSpeed.setPaintTicks(true);
            starSpeed.setPaintLabels(true);
            starSpeed.setBounds(70, 30, 400, 45);

            //      Adding Slider-ChangeListener to change the rotation speed of the star
            starSpeed.addChangeListener(new ChangeListener() { // anonymous inner class
                // handle change in slider value
                @Override
                public void stateChanged(ChangeEvent e) {
                    frameStar.ChangeSpeed(starSpeed.getValue());
                }
            }
            );

            //      Adding label besides the slider
            JLabel label = new JLabel("Speed : ");
            label.setBounds(10, 10, 80, 80);
            panel.add(label);
            panel.add(starSpeed);
        }
    }

    public class StarGraphics extends JPanel {

        private boolean toggleDir = false;
        private int speed = 10;
        private Timer timer;
        protected double angleOfStarRotation = 0;

        public StarGraphics() {
            setPreferredSize(new Dimension(500, 470));
            setBackground(Color.BLACK);
            setLayout(new BorderLayout());
            startTimer();
        }

        public void startTimer() {
            timer = new Timer(speed, new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    //              System.out.println(angleOfStarRotation);
                    if (!toggleDir) //rotates clockwise
                    {
                        angleOfStarRotation = angleOfStarRotation + 1;
                    } else //rotates counterclockwise
                    {
                        angleOfStarRotation = angleOfStarRotation - 1;
                    }

                    System.out.println("tick");
                    //                if (angleOfStarRotation == 360 || angleOfStarRotation == -360)  // If there is a full circle, it will reset the angle to zero
                    //                    angleOfStarRotation = 0;
                    repaint();
                }
            });
            timer.start();
        }

        public void ChangeSpeed(int newSpeed) {
            this.speed = newSpeed;
            timer.setDelay(speed);
        }

        public void ChangeDirections() {
            toggleDir = !toggleDir;
        }

    }

    public class StarPainter extends StarGraphics {

        private int[] starXPoints = {55, 67, 109, 73, 83, 55, 27, 37, 1, 43};
        private int[] starYPoints = {0, 36, 36, 54, 96, 72, 96, 54, 36, 36};
        GeneralPath starDesign = new GeneralPath();

        public StarPainter() {
            starDesign.moveTo(starXPoints[0], starYPoints[0]);

            for (int i = 0; i < 10; i++) {
                starDesign.lineTo(starXPoints[i], starYPoints[i]);
            }

            starDesign.closePath();
        }

        public void starActions(Graphics2D g) {
            int startAngle = 360;
            // For Random Color
            SecureRandom random = new SecureRandom();

            g = (Graphics2D) g.create();
            // rotate around origin and draw stars in random colors
            //for (int count = 1; count <= 1; count++) {
            double angle = startAngle - 90;
            // rotate coordinate system
            g.rotate(angleOfStarRotation * Math.PI / angle); //rotates as per the rotated angle    //
            // set random drawing color
            g.setColor(new Color(random.nextInt(256), random.nextInt(256), random.nextInt(256)));
            // draw filled star
            g.fill(starDesign);
            // dispose the star
            g.dispose();
            //}
        }

        @Override
        public void paintComponent(Graphics g) {
            super.paintComponent(g);

            Graphics2D g2d = (Graphics2D) g.create();
            g2d.translate(250, 150);
            starActions(g2d);
            g2d.dispose();

        }
    }
}


问:
Define an anonymous function without using the `function` keyword
I can define and use an anonymous function and call it like this

```<code>x <- 1:3
sapply(x, function(x) x)
</code>```

Sometimes I feel that using function like this is too verbose. Is there another way to define an anonymous function?

In the purrr package, one can define an anonymous function like this

```<code>map(x, ~.x)
</code>```

but this only works in the purrr context.

答:
New in R 4.1.0

Backslash can now be used as shorthand for creating anonymous functions. For example, \(x) x + 1 is now parsed as function(x) x + 1.

```<code>sapply(1:3, \(x) x + 1)
# [1] 2 3 4
</code>```

Body:
I can define and use an anonymous function and call it like this

x <- 1:3
sapply(x, function(x) x)

Sometimes I feel that using function like this is too verbose. Is there another way to define an anonymous function?

In the purrr package, one can define an anonymous function like this

map(x, ~.x)

but this only works in the purrr context.

Body:
New in R 4.1.0

Backslash can now be used as shorthand for creating anonymous functions. For example, \(x) x + 1 is now parsed as function(x) x + 1.

sapply(1:3, \(x) x + 1)
# [1] 2 3 4


问:
Creating SVN Repo and Accessing from within a CentOS 7 Machine
We have a CentOS 7 machine where multiple users are working in some project. We want to create a local svn repository which can be accessed from within CentOS server.

The normal svn commands such as "svn checkout" always needs an URL
such as "svn checkout http:///svn/repo/path/."

Is there a way to use this commands locally without http such as "svn checkout /svn/repo/path/".

It's a very basic question but I don't seem to find answer of it. If anybody has any help, will be very thankful...

答:
It is technically possible to use the local file:// access protocol to work with a repository without deploying any Subversion server at all. See https://subversion.apache.org/quick-start#setting-up-a-local-repo and https://svnbook.red-bean.com/nightly/en/svn.basic.in-action.html#svn.advanced.reposurls.

However, you need to deploy a server if the repository has multiple users. See the following information in SVNBook:

Do not be seduced by the simple idea of having all of your users
access a repository directly via file:// URLs. Even if the repository
is readily available to everyone via a network share, this is a bad
idea. It removes any layers of protection between the users and the
repository: users can accidentally (or intentionally) corrupt the
repository database, it becomes hard to take the repository offline
for inspection or upgrade, and it can lead to a mess of file
permission problems (see the section called “Supporting Multiple
Repository Access Methods”). Note that this is also one of the reasons
we warn against accessing repositories via svn+ssh:// URLs—from a
security standpoint, it's effectively the same as local users
accessing via file://, and it can entail all the same problems if the
administrator isn't careful.


问:
How to set default encoding in Python (setdefaultencoding() function does not exist)?

Possible Duplicate:

  Changing default encoding of python?

I am reading dive in python and it mentions setting python's default encoding scheme in the XML parsing chapter.

The setdefaultencoding is used in   python-installed-dir/site-packages/pyanaconda/sitecustomize.py

```<code>import sys
sys.setdefaultencoding('utf-8')
</code>```

But when I run the script, it raises:

```<code>AttributeError: 'module' object has no attribute 'setdefaultencoding'
</code>```

How to set the default encoding,anyway?

I am using python 2.7

Solution:
find the site.py in the python installation.

Edit the setencoding function

```<code>def setencoding():
    encoding = "ascii"
    if 0:
        import locale
        loc = locale.getdefaultlocale()
        if loc[1]:
            encoding = loc[1]
    if 0: #changes comes here, change 0 to 1
        encoding = "undefined" #the encoding you want
    if encoding != "ascii":
        sys.setdefaultencoding(encoding)
</code>```

I am using python 2.7

答:
How to set the default encoding,anyway?

Run sys.setdefaultencoding in the file sitecustomize.py, which needs to be in sys.path (e.g. lib/site-packages) when Python starts up. You can verify the change with sys.getdefaultencoding.

Edit for anonymous downvoter:

Whoever downvoted this answer, would you care to explain? This question is for Python 2.x only. There is no sys.setdefaultencoding in Python 3 if that's your problem. I stand by my explanation of how to use this function if one wants to in Python 2. I wasn't defending its use or recommending its use. A library should never touch it, which is why it's removed from the sys namespace after site.py and sitecustomize.py have a chance to call it. A library should also never assume the default encoding is ASCII in 2.x. It's up to the system. Personally I leave it as ASCII.

Body:
Possible Duplicate:

  Changing default encoding of python?

I am reading dive in python and it mentions setting python's default encoding scheme in the XML parsing chapter.

The setdefaultencoding is used in   python-installed-dir/site-packages/pyanaconda/sitecustomize.py

import sys
sys.setdefaultencoding('utf-8')

But when I run the script, it raises:

AttributeError: 'module' object has no attribute 'setdefaultencoding'

How to set the default encoding,anyway?

I am using python 2.7

Solution:
find the site.py in the python installation.

Edit the setencoding function

def setencoding():
    encoding = "ascii"
    if 0:
        import locale
        loc = locale.getdefaultlocale()
        if loc[1]:
            encoding = loc[1]
    if 0: #changes comes here, change 0 to 1
        encoding = "undefined" #the encoding you want
    if encoding != "ascii":
        sys.setdefaultencoding(encoding)

I am using python 2.7


问:
shopify api for page
I am having trouble trying to add page by using the shopify api using just node js. it does work without the meta fields but as soon as i try to add metafield it tanks. can anyone suggest what I might be doing wrong

const Shopify = require('shopify-api-node');

const shopify = new Shopify({

shopName: 'my-store-name',

accessToken: 'access-token'

});

shopify.page

.create({"title":user.title,"body_html":"","published":false,"template_suffix":"Recipies", "metafields": {

"key": "ingredient",

"type": "json",

"value": "{"ingredient":["3 tablespoons finely chopped cilantro, or more to taste","3 tablespoons finely chopped cilantro, or more to taste","anything you want","1 small carrot, peeled"]}",

"namespace": "values"}

})

答:
Couldn't figure out a direct way so solved it by creating the page without the metafields and creating metafields in. Then section using id of the page just created.</p>
```<code>  shopify.page
  .create({"title":user.title,"body_html":"","published":false,
})
  .then((thispage) => {

  console.log(thispage);

  shopify.metafield
  .create({
    key: 'warehouse',
    value: 25,
    value_type: 'integer',
    namespace: 'inventory',
    owner_resource: 'page',
    owner_id: thispage.id
  })
  .then(
    (metafield) => console.log(metafield),
    (err) => console.error(err)
  );
}).catch((err) => console.error(err));
});
</code>```

Title: shopify api for page

Body:
Couldn't figure out a direct way so solved it by creating the page without the metafields and creating metafields in. Then section using id of the page just created.

  shopify.page
  .create({"title":user.title,"body_html":"","published":false,
})
  .then((thispage) => {

  console.log(thispage);

  shopify.metafield
  .create({
    key: 'warehouse',
    value: 25,
    value_type: 'integer',
    namespace: 'inventory',
    owner_resource: 'page',
    owner_id: thispage.id
  })
  .then(
    (metafield) => console.log(metafield),
    (err) => console.error(err)
  );
}).catch((err) => console.error(err));
});


问:
p5js one tough puzzle returning not enough numbers to console
i'm trying to create a one tough puzzle solver thing, can anyone help me on why this is only showing 4 numbers in console instead of 8.

```<code>s1 = [1,-4,-1,2];
s2 = [2,-4,-3,4];
s3 = [4,-1,-3,3];
s4 = [3,-3,-4,4];
s5 = [2,-4,-3,2];
s6 = [4,-2,-4,3];
s7 = [1,-2,-4,2];
s8 = [1,-1,-4,4];
s9 = [1,-3,-3,4];
pieces = [s1,s2,s3,s4,s5,s6,s7,s8,s9];
correct =[];
pog = 0;

function setup() {
  createCanvas(400, 400);
  for(i=0;i<8;i++){
    for (h=1;h<8;h++){
      if(h==i){
        i++;
      }
      for(j=0;j<4;j++){
        if(pieces.at(i).at(1) == -pieces.at(h).at(3)){
          console.log(h);
          break
          i=h;
        } else {
          shiftL(pieces.at(h));
        }
      }
    }
  }
}

//BTW the piece above another piece is 3 pieces away!!!!

function draw() {
  background(220);
  frameRate(1);
}

function shiftL(array) {
  let sV = array.at(0);
  array.splice(0,1);
  array.splice(array.length-1,0,sV);
}
</code>```

i'm trying to output more but it only shows 1,3,7,2.
i'm adding more text so that this is able to be published.

答:
It is pretty hard to tell what you are trying to do and your for loop logic is very convoluted, here it is with comments and log statements:

  for (i = 0; i < 8; i++) {
    console.log(`begin i = ${i}`);
    for (h = 1; h < 8; h++) {
      console.log(`begin h = ${h}`);
      // When i == 0 this will be false
      if (h == i) {
        // when i == 1 and h == 1, this increments i to 2
        // on the next pass through the for loop that increments h,
        //     i == 2 and h == 2, this increments i to 3
        // so on, for each iteration of the inner loop, i gets incremented
        i++;
        console.log(`incremented i to ${i}`);
      }
      // this loop should happen just 14 times, 7 times for i = 0 and then 7
      // times starting with i = 1
      for (j = 0; j < 4; j++) {
        if (pieces.at(i).at(1) == -pieces.at(h).at(3)) {
          console.log(h);
          // exits the loop for j
          break;
          // unreachable, never happens
          console.log("never happens");
          i = h;
        } else {
          console.log(`shiftL(piecese.at(${h}))`);
          shiftL(pieces.at(h));
        }
      }
    }
  }
```

Hopefully this helps you figure out why this code is not working properly.

Body:
i'm trying to create a one tough puzzle solver thing, can anyone help me on why this is only showing 4 numbers in console instead of 8.

s1 = [1,-4,-1,2];
s2 = [2,-4,-3,4];
s3 = [4,-1,-3,3];
s4 = [3,-3,-4,4];
s5 = [2,-4,-3,2];
s6 = [4,-2,-4,3];
s7 = [1,-2,-4,2];
s8 = [1,-1,-4,4];
s9 = [1,-3,-3,4];
pieces = [s1,s2,s3,s4,s5,s6,s7,s8,s9];
correct =[];
pog = 0;

function setup() {
  createCanvas(400, 400);
  for(i=0;i<8;i++){
    for (h=1;h<8;h++){
      if(h==i){
        i++;
      }
      for(j=0;j<4;j++){
        if(pieces.at(i).at(1) == -pieces.at(h).at(3)){
          console.log(h);
          break
          i=h;
        } else {
          shiftL(pieces.at(h));
        }
      }
    }
  }
}

//BTW the piece above another piece is 3 pieces away!!!!

function draw() {
  background(220);
  frameRate(1);
}

function shiftL(array) {
  let sV = array.at(0);
  array.splice(0,1);
  array.splice(array.length-1,0,sV);
}

i'm trying to output more but it only shows 1,3,7,2.
i'm adding more text so that this is able to be published.

Body:
It is pretty hard to tell what you are trying to do and your for loop logic is very convoluted, here it is with comments and log statements:

  for (i = 0; i < 8; i++) {
    console.log(`begin i = ${i}`);
    for (h = 1; h < 8; h++) {
      console.log(`begin h = ${h}`);
      // When i == 0 this will be false
      if (h == i) {
        // when i == 1 and h == 1, this increments i to 2
        // on the next pass through the for loop that increments h,
        //     i == 2 and h == 2, this increments i to 3
        // so on, for each iteration of the inner loop, i gets incremented
        i++;
        console.log(`incremented i to ${i}`);
      }
      // this loop should happen just 14 times, 7 times for i = 0 and then 7
      // times starting with i = 1
      for (j = 0; j < 4; j++) {
        if (pieces.at(i).at(1) == -pieces.at(h).at(3)) {
          console.log(h);
          // exits the loop for j
          break;
          // unreachable, never happens
          console.log("never happens");
          i = h;
        } else {
          console.log(`shiftL(piecese.at(${h}))`);
          shiftL(pieces.at(h));
        }
      }
    }
  }

Hopefully this helps you figure out why this code is not working properly.


问:
how to modify an array of objects with certain groups in to and array of object with group and related items?
I have the following array of object that I want to chance its structure , I am trying to use reduce to get a new object with element that have the same group..

const arr = [{id: 'c8c443', group: 'a', equipment: 'ball'},
              {id: 'c84445', group: 'a', equipment: 'ball'},
              {id: 'c8c655', group: 'b', equipment: 'basketball'},
              {id: 'c8c634', group: 'b', equipment: 'basketball'}]

 const newArr = arr.reduce(
    (obj: any, value: any, i) => [
      ...obj,
      {
        group: value.map((el: any) => el.group),
        items: value.map((el: any) => el.equipment),
      },
    ],
    []
  );
// Results  [{group: 'a', items: ['ball','ball']}, {group: 'b', items: ['basketball','basketball']}]```

答:
Here is an example:

const arr = [{id: 'c8c443', group: 'a', equipment: 'ball'},
             {id: 'c84445', group: 'a', equipment: 'ball'},
             {id: 'c8c655', group: 'b', equipment: 'basketball'},
             {id: 'c8c634', group: 'b', equipment: 'basketball'}]

const newArr = arr.reduce((acc, item) => {
  if (acc.some(key => key.group === item.group)) {
    acc = acc.map(i => i.group === item.group ? {...i, items: [...i.items, item.equipment]} : i)
  } else {
    acc.push({
      group: item.group,
      items: [item.equipment]
    })
  }

  return acc
}, [])

console.log(newArr)```


问:
Faster ExtJs 4 learning methodology
How can a JQuery Ninja cross over to ExtJS as fast as possible? Given that ExtJS 3.x is now obsolete, how can one quickly grip concepts in Ext JS 4. Hardly can one find a book on Ext JS 4 online. The documentation is quite forward but complex. Ext Js has many components, and each component has several APIs e.g. a Grid has very many ways of manipulating its view e.t.c. What learning flow may work for me to quickly not skip anything on components, views, controllers e.t.c. I would want to write good Ext JS code in a period of 2 months from now.
please suggest methods of learning Ext JS 4

NOTE: the writer has never used Ext Js wether in older versions of it or the new

答: Two months ago I've started with Ext JS project without having previous experience with it. Can't say it was hard to learn. Ext JS is designed really cleverly. I've been learning only from official documentation and google. First I've read the official tutorials, after that was exploring reference, many helpful examples can be found there. Books about libraries and frameworks, especially about such well-documented like Ext JS are wasting of time in my opinion. If you have previous experience with JS and know about OOP it should be easy to learn Ext JS. </p>

Title: Faster ExtJs 4 learning methodology


问:
Nonparametric tolerance interval with MASS package
In R, using the 'geyser' dataset from the MASS library, we are building a nonparametric tolerance interval cont. 90% of geyser eruptions w/ 99% CI

Please, find below the equation I am using:

```<code>no_param_pi <- function(x, conf.level = 0.90) {
  n <- length(x)
  x <- sort(x)
  j <- max(floor((n + 1) * (1 - conf.level) / 2), 1)
  conf.level <- (n + 1 - 2 * j)/(n + 1)
  interval <- c(x[j], x[n + 1 - j])
  attr(interval, "conf.level") <- conf.level
  interval
}
</code>```

Here is the code I am playing with, and in which I am missing something... :

```<code>library(MASS)
library(tolerance)
head(geyser)

eruptions = subset(geyser, select = waiting:duration, increasing)

nptol.int(eruptions, alpha = 1 - 0.99, P = 0.9)
</code>```

Looking for both

答:
Can you try these few lines of code:

```<code>eruptions <- geyser
nptol.int(eruptions$duration, alpha = 1 - 0.99, P = 0.9, side = 1)
nptol.int(eruptions$duration, alpha = 1 - 0.99, P = 0.9, side = 2)
nptol.int(eruptions$waiting, alpha = 1 - 0.99, P = 0.9, side = 1)
nptol.int(eruptions$waiting, alpha = 1 - 0.99, P = 0.9, side = 2)
</code>```

Is this what are you looking for? You have many variations, so I suggest you look documentation under Help. ?nptol.int

Body:
In R, using the 'geyser' dataset from the MASS library, we are building a nonparametric tolerance interval cont. 90% of geyser eruptions w/ 99% CI

Please, find below the equation I am using:

no_param_pi <- function(x, conf.level = 0.90) {
  n <- length(x)
  x <- sort(x)
  j <- max(floor((n + 1) * (1 - conf.level) / 2), 1)
  conf.level <- (n + 1 - 2 * j)/(n + 1)
  interval <- c(x[j], x[n + 1 - j])
  attr(interval, "conf.level") <- conf.level
  interval
}

Here is the code I am playing with, and in which I am missing something... :

library(MASS)
library(tolerance)
head(geyser)

eruptions = subset(geyser, select = waiting:duration, increasing)

nptol.int(eruptions, alpha = 1 - 0.99, P = 0.9)

Looking for both

Body:
Can you try these few lines of code:

eruptions <- geyser
nptol.int(eruptions$duration, alpha = 1 - 0.99, P = 0.9, side = 1)
nptol.int(eruptions$duration, alpha = 1 - 0.99, P = 0.9, side = 2)
nptol.int(eruptions$waiting, alpha = 1 - 0.99, P = 0.9, side = 1)
nptol.int(eruptions$waiting, alpha = 1 - 0.99, P = 0.9, side = 2)

Is this what are you looking for? You have many variations, so I suggest you look documentation under Help. ?nptol.int


问:
Why I failed to connect to the django server?
I'm following a tutorial, using this command in a Docker container to start the Django server:

```<code>python3 manage.py runserver 0.0.0.0:8000
</code>```

But I can not connect to it by IP.

I am sure that I have already open the 8000 port and this port is on listening. By the way, I use the ubuntu and set the server in the aliyun.

答: At First Django works on port 8000 not on 8080. So you should use python manage.py runserver 0.0.0.0:8000. You can eazly kill port in linux server by type: fuser 8080/tcp

Body:
I'm following a tutorial, using this command in a Docker container to start the Django server:

python3 manage.py runserver 0.0.0.0:8000

But I can not connect to it by IP.

I am sure that I have already open the 8000 port and this port is on listening. By the way, I use the ubuntu and set the server in the aliyun.


问:
Best way to use MySQL for image galleries?

Possible Duplicate:

  What is the best way to store a series of images in MySQL?

This is the first website that I built for a friend a few months ago:
http://www.jpsinghphotography.co.uk

I want to rebuild it as my first PHP/MySQL project, but I had a couple of questions regarding how to structure the database.

1) Is it best to put the actual image files in the database using BLOB data types; or store the file names and use these to look up the images from another folder on the server?

2) I'm new to SQL and I'd initially imagined a seperate table for each gallery I want to create. In what ways is one table sorted by category better?

Thanks for any and all advice

答:
I would stick to providing a reference ie. the file name in the MySQL table. Putting the images in the table as BLOBs would mean you're now maintaining two copies of your pics. If you're primary application is to store history, this makes sense, but otherwise, a simple reference to the original is probably better.
A secondary issue may be storage space: you'd obviously be dealing with some very large tables if you BLOB the pictures. That may or may not be a problem.
As others posted, creating multiple tables for each gallery is a definite no-no and against the whole philosophy of using a relational database. Simple add a column to the pictures table that holds the gallery id and make it part of the unique key. You may also want a separate gallery table too, to be more 'normalized' about it.</p>


问:
How to fix vscode GnuCOBOL setup "configuration error: default.conf: No such file or directory"

we are using cobol now, but this config error keeps on appearing and I do not know how to fix this thing. Any help would really mean alot. (Just a beginner and trying to learn vscode)

答:
Late, but perhaps worth it. Currently there is a cobenv.bat or .sh (if you are on linux). The whole path to the file may differ for me is this:

```<code>C:\msys64\mingw64\bin\cobenv.cmd
</code>```

You'll notice that if you execute the file and run the compiler everything works fine, but once you close that bash the error shows up again.

That's because the scope of those variables was just that session. You may execute it every time you run the compiler or you can make those variables to persist on your system. In my case I did the later, modifying cobenv.cmd

But not those lines with the variable PATH.

So this lines, i.e., whenever we encounter this same three variables. For instance, after a certain if in that file we encounter:

```<code>  setx "COB_LIBRARY_PATH" "%MINGW_ROOT_PATH%lib\gnucobol%COB_LIBRARY_PATH%"
  setx "COB_COPY_DIR" "%MINGW_ROOT_PATH%share\gnucobol\copy"
  setx "COB_CONFIG_DIR" "%MINGW_ROOT_PATH%share\gnucobol\config"
</code>```

Default value: set.

New value: setx.

Delete the = to comply with the correct syntax. Check the compiler with different new session.

Body:
Late, but perhaps worth it. Currently there is a cobenv.bat or .sh (if you are on linux). The whole path to the file may differ for me is this:

C:\msys64\mingw64\bin\cobenv.cmd

You'll notice that if you execute the file and run the compiler everything works fine, but once you close that bash the error shows up again.

That's because the scope of those variables was just that session. You may execute it every time you run the compiler or you can make those variables to persist on your system. In my case I did the later, modifying cobenv.cmd

But not those lines with the variable PATH.

So this lines, i.e., whenever we encounter this same three variables. For instance, after a certain if in that file we encounter:

  setx "COB_LIBRARY_PATH" "%MINGW_ROOT_PATH%lib\gnucobol%COB_LIBRARY_PATH%"
  setx "COB_COPY_DIR" "%MINGW_ROOT_PATH%share\gnucobol\copy"
  setx "COB_CONFIG_DIR" "%MINGW_ROOT_PATH%share\gnucobol\config"

Default value: set.

New value: setx.

Delete the = to comply with the correct syntax. Check the compiler with different new session.


问:
Problem concatenating strings using JavaScript template literals
I'm using the prisma.io library and having trouble working with template literals to do what I want. Maybe I don't understand them well enough.

I have this call:

```<code>const result = await prisma.$queryRaw`SELECT * FROM User WHERE active = ${activeSetting}`
</code>```

And this works exactly the way I want.

However, I want to optionally append a string at the end without having to redo the full statement.

That is, I want something like:

```<code>let result;
if (orderBy === "ASC") {
  const result = await prisma.$queryRaw`SELECT * FROM User WHERE active =
      ${activeSetting} ORDER BY ASC`
} else if {
  const result = await prisma.$queryRaw`SELECT * FROM User WHERE active =
      ${activeSetting} ORDER BY DESC`
}

</code>```

Basically, I don't want to have to have to complete statements that start with const result = await.  I realize this is a short example, but my problem is when I have fairly long SQL statements and I find myself doing a lot of cutting and pasting huge SQL which gets error prone.

答:
You can use a ternary operator like so:

const result = await prisma.$queryRaw`SELECT * FROM User WHERE active =
      ${activeSetting} ORDER BY ${orderBy === 'ASC' ? 'ASC' : 'DESC'}`
```

But it is better not to write raw SQL strings because you could leave yourself vulnerable to SQL Injection

Body:
I'm using the prisma.io library and having trouble working with template literals to do what I want. Maybe I don't understand them well enough.

I have this call:

const result = await prisma.$queryRaw`SELECT * FROM User WHERE active = ${activeSetting}`

And this works exactly the way I want.

However, I want to optionally append a string at the end without having to redo the full statement.

That is, I want something like:

let result;
if (orderBy === "ASC") {
  const result = await prisma.$queryRaw`SELECT * FROM User WHERE active =
      ${activeSetting} ORDER BY ASC`
} else if {
  const result = await prisma.$queryRaw`SELECT * FROM User WHERE active =
      ${activeSetting} ORDER BY DESC`
}

Basically, I don't want to have to have to complete statements that start with const result = await.  I realize this is a short example, but my problem is when I have fairly long SQL statements and I find myself doing a lot of cutting and pasting huge SQL which gets error prone.

Body:
You can use a ternary operator like so:

const result = await prisma.$queryRaw`SELECT * FROM User WHERE active =
      ${activeSetting} ORDER BY ${orderBy === 'ASC' ? 'ASC' : 'DESC'}`

But it is better not to write raw SQL strings because you could leave yourself vulnerable to SQL Injection


问:
Saving structured data in android
Android provides some ways to save application information. http://developer.android.com/guide/topics/data/data-storage.html

Now, my issue is that I have some structured data comparable with tasks, that have categories and some other related settings. Everything is fetched from a web service and has to get saved for performance and offline use.

Which would be the best option to use on Android? I think the choice is really between SQLite Database or Internal storage. What would I expect from the performance and implementation choosing one of the options?

答:
One really easy way to cache data is to just Serialize your objects and save them to the internal cache e.g:</p>

```<code>// Example object which implements Serializable
Example example = new Example();

// Save an object
ObjectOutput out = new ObjectOutputStream(new FileOutputStream(new File(getCacheDir(),"")+"cacheFile.srl"));
out.writeObject((Example) example);
out.close();

// Load in an object
ObjectInputStream in = new ObjectInputStream(new FileInputStream(new File(new File(getCacheDir(),"")+"cacheFile.srl")));
Example example_loaded = (Example) in.readObject();
in.close();
</code>```

Title: Saving structured data in android

Body:
One really easy way to cache data is to just Serialize your objects and save them to the internal cache e.g:

// Example object which implements Serializable
Example example = new Example();

// Save an object
ObjectOutput out = new ObjectOutputStream(new FileOutputStream(new File(getCacheDir(),"")+"cacheFile.srl"));
out.writeObject((Example) example);
out.close();

// Load in an object
ObjectInputStream in = new ObjectInputStream(new FileInputStream(new File(new File(getCacheDir(),"")+"cacheFile.srl")));
Example example_loaded = (Example) in.readObject();
in.close();


问:
Applying k-folds (stratified 10-fold) to my text classification model
I need help in the following, I have a data frame with Columns: Class (0,1) and text.
After cleansing (lemmatizing, removing stopwords, etc), I split the data like the following:

```<code>#splitting datset

from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(dataset['text_lemm_nostop'], dataset['class'],test_size=0.3, random_state=50)
</code>```

Then I used n-gram:

```<code>#using n-gram

from sklearn.feature_extraction.text import CountVectorizer
vect=CountVectorizer(min_df=5,ngram_range=(2,2), max_features=5000).fit(X_train)
print('No. of features:')
len(vect.get_feature_names_out()) # how many features
</code>```

Then I did the vectorizing:

```<code>X_train_vectorized=vect.transform(X_train)
X_test_vectorized=vect.transform(X_test)
</code>```

Then I started applying ML algorithms like (logistic regression, Naive Bayes, RF,..etc)
and I will share only the logistic regression

```<code>#Logistic regression

from sklearn.linear_model import LogisticRegression
model=LogisticRegression()
model.fit(X_train_vectorized, y_train)

from sklearn.metrics import classification_report, accuracy_score
from sklearn.metrics import roc_auc_score
from sklearn import metrics
predictions=model.predict(vect.transform(X_test))
print("AUC Score is: ", roc_auc_score(y_test, predictions),'\n')
print("Accuracy:",metrics.accuracy_score(y_test, predictions),'\n')
print('Classification Report:\n',classification_report(y_test,predictions))

</code>```

My Questions:

1. Is what I am doing is fine in case I am going with normal splitting (30% test)?
(I feel having issues with n-gram code!)

2. If I want to engage the K-fold cross-validation (ie. Stratified 10-fold), how could I do that in my code?

Appreciate any help and support!!

答:
A few comments:

Generally I don't see any obvious mistake, seems fine to me.

Do you really mean to use only bigrams (n=2)? This implies that you don't use unigrams (single words), so you might miss some information this way. It's more common to use ngram_range=(1,2) for instance. It's probably worth trying unigrams only, at least to compare the performance.

To perform 10-fold cross-validation, I'd suggest you use KFold because it's the simplest method. In this case it's almost the same code, except that you insert it inside a loop which iterates the 10 folds. Every time you fit the model on a specific training set (90%) and evaluate it on the remaining 10% test set. Both training and test set are obtained by selecting the corresponding indexes indexes returned by KFold.

Body:
I need help in the following, I have a data frame with Columns: Class (0,1) and text.
After cleansing (lemmatizing, removing stopwords, etc), I split the data like the following:

#splitting datset

from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(dataset['text_lemm_nostop'], dataset['class'],test_size=0.3, random_state=50)

Then I used n-gram:

#using n-gram

from sklearn.feature_extraction.text import CountVectorizer
vect=CountVectorizer(min_df=5,ngram_range=(2,2), max_features=5000).fit(X_train)
print('No. of features:')
len(vect.get_feature_names_out()) # how many features

Then I did the vectorizing:

X_train_vectorized=vect.transform(X_train)
X_test_vectorized=vect.transform(X_test)

Then I started applying ML algorithms like (logistic regression, Naive Bayes, RF,..etc)
and I will share only the logistic regression

#Logistic regression

from sklearn.linear_model import LogisticRegression
model=LogisticRegression()
model.fit(X_train_vectorized, y_train)

from sklearn.metrics import classification_report, accuracy_score
from sklearn.metrics import roc_auc_score
from sklearn import metrics
predictions=model.predict(vect.transform(X_test))
print("AUC Score is: ", roc_auc_score(y_test, predictions),'\n')
print("Accuracy:",metrics.accuracy_score(y_test, predictions),'\n')
print('Classification Report:\n',classification_report(y_test,predictions))

My Questions:

1. Is what I am doing is fine in case I am going with normal splitting (30% test)?
(I feel having issues with n-gram code!)

2. If I want to engage the K-fold cross-validation (ie. Stratified 10-fold), how could I do that in my code?

Appreciate any help and support!!


问:
Unable to create process using 'C:\Users\Abhishek Anand\AppData\Local\Programs\Python\Python310\python.exe manage.py runserver'
I'm trying to use runserver command over vs code terminal. But now it is giving me the error. " Unable to create process using 'C:\Users\Abhishek Anand\AppData\Local\Programs\Python\Python310\python.exe manage.py runserver'". But I have the python interpreter in my environment path. Also, I have my virtual environment which I created while initiating the project but still and using the interpreter in my environment I was getting the same error..

Please help me out with that.enter image description here

答:
Try running server on cmd. Go to Folder and type python manage.py runserver.
(Instead of use py use python or python3)</p>


问:
Spacy: Creating empty or error Token instance?
I'm collecting some of the tokens in a Dict for further use.
The problem is that I need one token to play the role of None/NIL in case I don't find what I need in the doc to act as the no-value case i.e. still have all the attributes (the string value could be say some special char) ... i.e. act like Token, but not be a token from the doc.

Is there a way to create such Token ? Or may be copy some but modify .dep_, .pos_ etc.

答:
One approach would be to create a doc containing just one character (e.g. a space or * or any other character of your choice), i.e. nlp('<special character>'), and take the token at index 0. For example, if your special character is a #, this would look like:

```<code>empty_token = nlp('#')[0]
</code>```

empty_token is a normal token, so it has all the attributes. Running the code below produces the corresponding output:

```<code>print('text:', empty_token.text)
print('pos:', empty_token.pos_)
print('dep:', empty_token.dep_)
</code>```

Output:

```<code>text: #
pos: SYM
dep: ROOT
</code>```

Body:
One approach would be to create a doc containing just one character (e.g. a space or * or any other character of your choice), i.e. nlp('<special character>'), and take the token at index 0. For example, if your special character is a #, this would look like:

empty_token = nlp('#')[0]

empty_token is a normal token, so it has all the attributes. Running the code below produces the corresponding output:

print('text:', empty_token.text)
print('pos:', empty_token.pos_)
print('dep:', empty_token.dep_)

Output:

text: #
pos: SYM
dep: ROOT


问:
Problem with GIT pull overriding previous code
I am new to GIT and face scenario as follow:

 push file below:

index.php

```<code>$name = "steve";

echo("good morning");
echo($name);
</code>```

 pull the file and then remove the $name variable by accidentally.

```<code>echo("good morning");
echo($name);
</code>```

Without realizing it,  pull and push the new code to server. Problem is the code is broke and no longer working, GIT won't prompt for removal of the line. Is there anyway to solve such scenario?

答:
To be able to handle this, Git would need to have a knowledge of the content that you're pusing. In your case, Git would have to know that removing $name = "steve"; in a .php file would produce an error.

But this could be perfectly fine for plain .txt file where you're just writing text.

Not the pull overrides the previous code but you did. You removed the line, you told Git to commit that version, you pulled that version from the remote repo. And all that went good.

The best way to solve such a scenario is avoiding it by testing your code before pushing.

If that scenario occurs in spite of careful testing, you could of course use Git to restore the last version that was checked in and working using

```<code>git checkout <SHA-HASH> -- index.php
</code>```

where <SHA-HASH> is the commit-ID of the last good version of index.php.

Body:
I am new to GIT and face scenario as follow:

 push file below:

index.php

$name = "steve";

echo("good morning");
echo($name);

 pull the file and then remove the $name variable by accidentally.

echo("good morning");
echo($name);

Without realizing it,  pull and push the new code to server. Problem is the code is broke and no longer working, GIT won't prompt for removal of the line. Is there anyway to solve such scenario?

Body:
To be able to handle this, Git would need to have a knowledge of the content that you're pusing. In your case, Git would have to know that removing $name = "steve"; in a .php file would produce an error.

But this could be perfectly fine for plain .txt file where you're just writing text.

Not the pull overrides the previous code but you did. You removed the line, you told Git to commit that version, you pulled that version from the remote repo. And all that went good.

The best way to solve such a scenario is avoiding it by testing your code before pushing.

If that scenario occurs in spite of careful testing, you could of course use Git to restore the last version that was checked in and working using

git checkout <SHA-HASH> -- index.php

where <SHA-HASH> is the commit-ID of the last good version of index.php.


问:
is it possible to round the last 3 digits of a number in c?
i would like to round the last 3 digits of the float number 169786.122 and leaving only 3 digits

is it possible to do it with the math.h library and the ceil function?

in case of 169786.122 == 170

in case of 169121.122 == 169

in case of 171126.122 == 171

in case of 179911.122 == 180

.. and so on

float aNum = 169726.122;

int main() {

    printf("%.0f\n",aNum); // result 169726
    return 0;
}
```

答:
If:

breaking ties by choosing the even multiple of 1000 is satisfactory,

the desired multiple of 1000 is representable in the float format, and

the float format uses base two or ten,

then (x - remainderf(x, 1000)) / 1000 calculates the desired result.

This works because the remainderf function always produces an exact result (has no rounding error) and, if the desired multiple of 1000 is representable, then the subtraction produces that multiple with no rounding error. If the floating-point format uses base ten, the division just changes the exponent and has no rounding error. If the format uses base two, the division of a multiple of 125 by 125 times a power of two cannot increase the number of significant bits, so the result must fit in the significand, so there is no rounding error.

These caveats are not strict; I expect various improvements are available. In particular, if nearbyint((x - remainderf(x, 1000)) / 1000) is used, with the IEEE-754 “single precision” format (binary32), it gets correct results for all cases in which the desired result is representable.


问:
How to check valid number in pandas dataframe column?
I am working on a project for university in which I received a dataframe:

```<code>      import pandas as pd

      df = pd.DataFrame({'id': [0,1,2,3,4,5,6,7,8],
                         'number': ['00005485', '9999', '11111', '458426', '9999999999',
                                    '11111111', '800000', '99999', '1111']})

      print(df)

      id    number
      0    00005485
      1    9999
      2    11111
      3    458426
      4    9999999999
      5    11111111
      6    800000
      7    99999
      8    1111
</code>```

I would like to generate a dataframe with only the lines that have a valid 'number'. For a 'number' to be considered valid, it cannot have more than four repeating digits that are the same.

I made a code using filter by 'number' column as follows:

```<code>      df_result = df[(df['number'] != '9999') & (df['number'] != '99999') &
                     (df['number'] != '999999') & (df['number'] != '9999999') &
                     (df['number'] != '99999999') & (df['number'] != '999999999') &
                     (df['number'] != '9999999999') & (df['number'] != '9999999999') &
                     (df['number'] != '1111') & (df['number'] != '11111') &
                     (df['number'] != '111111') & (df['number'] != '1111111') &
                     (df['number'] != '111111111') & (df['number'] != '11111111')]

       print(df_result)

       id   number
       0    00005485
       3    458426
       6    800000

</code>```

The output is correct. However, I would like to discover another way to do this operation on the dataframe.

答:
You can use regular expression for this, in particular, \1, which matches the first group:

```<code>valid = df[~df['number'].astype(str).str.match(r'^(\d)\1{3,}$')]
</code>```

So that basically says to select all rows that have the start of the string (^), a digit (\d), and then 3+ more ({3,}) of that same digit (\1), and then the end of the string ($).

Output:

```<code>>>> valid
     number
0  00005485
3    458426
6    800000
</code>```

If you want to select invalid numbers instead of valid ones, remove the tilde ~ in the condition:

```<code>invalid = df[df['number'].astype(str).str.match(r'^(\d)\1{3,}$')]
</code>```

Output:

```<code>>>> invalid
       number
1        9999
2       11111
4  9999999999
5    11111111
7       99999
8        1111
</code>```

Body:
I am working on a project for university in which I received a dataframe:

      import pandas as pd

      df = pd.DataFrame({'id': [0,1,2,3,4,5,6,7,8],
                         'number': ['00005485', '9999', '11111', '458426', '9999999999',
                                    '11111111', '800000', '99999', '1111']})

      print(df)

      id    number
      0    00005485
      1    9999
      2    11111
      3    458426
      4    9999999999
      5    11111111
      6    800000
      7    99999
      8    1111

I would like to generate a dataframe with only the lines that have a valid 'number'. For a 'number' to be considered valid, it cannot have more than four repeating digits that are the same.

I made a code using filter by 'number' column as follows:

      df_result = df[(df['number'] != '9999') & (df['number'] != '99999') &
                     (df['number'] != '999999') & (df['number'] != '9999999') &
                     (df['number'] != '99999999') & (df['number'] != '999999999') &
                     (df['number'] != '9999999999') & (df['number'] != '9999999999') &
                     (df['number'] != '1111') & (df['number'] != '11111') &
                     (df['number'] != '111111') & (df['number'] != '1111111') &
                     (df['number'] != '111111111') & (df['number'] != '11111111')]

       print(df_result)

       id   number
       0    00005485
       3    458426
       6    800000

The output is correct. However, I would like to discover another way to do this operation on the dataframe.

Body:
You can use regular expression for this, in particular, \1, which matches the first group:

valid = df[~df['number'].astype(str).str.match(r'^(\d)\1{3,}$')]

So that basically says to select all rows that have the start of the string (^), a digit (\d), and then 3+ more ({3,}) of that same digit (\1), and then the end of the string ($).

Output:

>>> valid
     number
0  00005485
3    458426
6    800000

If you want to select invalid numbers instead of valid ones, remove the tilde ~ in the condition:

invalid = df[df['number'].astype(str).str.match(r'^(\d)\1{3,}$')]

Output:

>>> invalid
       number
1        9999
2       11111
4  9999999999
5    11111111
7       99999
8        1111