问:
I have migrated to null-safety (2.15.1) and this problem still persists
I get the error below when I compile the app.

```<code>The following NoSuchMethodError was thrown building MyApp(dirty, state: _MyAppState#73713):
The method 'call' was called on null.
Receiver: null
Tried calling: call(Instance of 'ChangeNotifierProvider<UserLoggedIn>')
</code>```

The error points me to the 'MyApp' part of the code and so I have no idea how to tackle this one.
My app ran with no error before migrating.
This is a part of my code where the cause for this error is.
I went through the code with and I can't find a possible syntax error.

```<code>    void main() {
  runApp(ProviderScope(child: MyApp()));
}

class MyApp extends StatefulHookWidget {
   @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {

  bool _amplifyConfigured = false;
  bool checkAuthStatus = false;

  late AmplifyAuthCognito auth;

  var userLoggedIn;
  var useProvider;

  @override

  void initState() {
    // TODO: implement initState
    super.initState();
    _configureAmplify();
  }

  void _configureAmplify() async {
    if (!mounted) return;

    auth = AmplifyAuthCognito();
    await Amplify.addPlugin(auth);

    try {
      await Amplify.configure(amplifyconfig);
    } on AmplifyAlreadyConfiguredException {
      print('Already configured');
    }

    try {
      getUserStatus();
      setState(() {
        _amplifyConfigured = true;
      });
    } catch (e) {
      print(e);
    }
  }

  @override
  Widget build(BuildContext context) {
    userLoggedIn = useProvider(userLoggedInProvider);

    ```
```

答:
Riverpod removed useProvider in version 1.0.0.  As described in the migration guide, you will need to use StatefulHookConsumerWidget instead of StatefulHookWidget to access that same functionality in the newest version:

class MyApp extends StatefulHookConsumerWidget {
   @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends ConsumerState<MyApp> {

  // ...

  @override
  Widget build(BuildContext context) {
    userLoggedIn = ref.watch(userLoggedInProvider);
    // ...
```

Body:
I get the error below when I compile the app.

The following NoSuchMethodError was thrown building MyApp(dirty, state: _MyAppState#73713):
The method 'call' was called on null.
Receiver: null
Tried calling: call(Instance of 'ChangeNotifierProvider<UserLoggedIn>')

The error points me to the 'MyApp' part of the code and so I have no idea how to tackle this one.
My app ran with no error before migrating.
This is a part of my code where the cause for this error is.
I went through the code with and I can't find a possible syntax error.

    void main() {
  runApp(ProviderScope(child: MyApp()));
}

class MyApp extends StatefulHookWidget {
   @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {

  bool _amplifyConfigured = false;
  bool checkAuthStatus = false;

  late AmplifyAuthCognito auth;

  var userLoggedIn;
  var useProvider;

  @override

  void initState() {
    // TODO: implement initState
    super.initState();
    _configureAmplify();
  }

  void _configureAmplify() async {
    if (!mounted) return;

    auth = AmplifyAuthCognito();
    await Amplify.addPlugin(auth);

    try {
      await Amplify.configure(amplifyconfig);
    } on AmplifyAlreadyConfiguredException {
      print('Already configured');
    }

    try {
      getUserStatus();
      setState(() {
        _amplifyConfigured = true;
      });
    } catch (e) {
      print(e);
    }
  }

  @override
  Widget build(BuildContext context) {
    userLoggedIn = useProvider(userLoggedInProvider);

    ```


来源: stackexchange

问:
Including External Python Packages with Python Executable
I have made my own Executable from a python script which I want to run on a computer that does not have Python installed on it. My only problem is there are packages I have included which are not default python packages (e.g. pynput). Otherwise, the Executable would run fine without Python installed. Is there a way to include Python packages with my executable? Can I put the packages in the same folder as the script and import them from there? If so, would I then be able to transport them along with my Executable? I have already googled a solution but I cannot find anything on it.</p>

答:
use following method :

```<code>pip install pyinstaller
</code>```

pyinstaller is a package for generating executable files for python and can be ran from command line or terminal

in the same directory of your pyhton file run following command

```<code>pyinstaller --onefile nameofyourfile.py
</code>```

after its done if you check your folder there should be a dist folder

inside that you can find an executable to your python file which has no dependencies to other packages

ContentLicense: CC BY-SA 4.0

Body:
use following method :

pip install pyinstaller

pyinstaller is a package for generating executable files for python and can be ran from command line or terminal

in the same directory of your pyhton file run following command

pyinstaller --onefile nameofyourfile.py

after its done if you check your folder there should be a dist folder

inside that you can find an executable to your python file which has no dependencies to other packages


问:
Testing an asynchronous throw error in a Promise catch with Jest
I have the following code that I'd like to test.

```<code>const Component: React.FC = () => {
   const handleSubmit = (action) => {
       doSomethingAsynchronous()
           .then(() => /* something on success */)
           .catch((err) => {
               // Display the error message
               action();

               // Rethrow the exception so it can be handled up the chain
               throw err;
           })
   }

   return <Form onSubmit={handleSubmit} />;
}

</code>```

This code performs a simple asynchronous action that fails or resolves. On a failure, the component is re-rendered to show an error message, and the error is rethrown to log to the console/our logging system and for parent components to deal with.

The problem comes when I am attempting to test the error handling behaviour to ensure that the error messages are being set. Simple testing such as:

```<code>describe('Component', () => {
   it('handles an error', async () => {
       // Setup
       const mockAction = jest.fn();
       const render = shallowRender(<Component />);
       submissionHandler = render.find(Component).invoke('onSubmit');

       // Act
       submissionHandler(mockAction);
       await () => new Promise(setImmediate); // To wait for promise execution

       // Assert
       expect(mockAction).toHaveBeenCalled();
   })
})
</code>```

Results in Jest failing the test as an error has been thrown in the test by the component, inside the catch block (as expected). However, my attempts to suppress this also result in the same error being thrown and failing the test.

```<code>try {
    // Act
    submissionHandler(mockAction);
    await () => new Promise(setImmediate); // To wait for promise execution
} catch (e) {}
</code>```

I also tried using expects().toThrow(), but this instead returns the jest error Received function did not throw. I assume this is because due to the promise the execution is no longer in the same function scope, so isn't being recognised by Jest as originating from that function?

```<code>await expect(async () => {
   submissionHandler(mockAction);
   await () => new Promise(setImmediate);
}).toThrow();
</code>```

Does anyone know the best way to test this? I'm aware I can cheat by making onSubmit return my promise here and catching the exception there, but I'd avoid doing that to stop my function returning for testing purposes.

答:
You need to unpack your errors from your promise with .rejects

try this:

```<code>import { spyOn } from 'jest-mock';
...

it("should error", async() => {
  spyOn(console, 'error'); #removes error from output
  await expect( yourAsyncMethod() ).rejects.toThrow() # .rejects unpacks errors from promises
}
</code>```

Body:
I have the following code that I'd like to test.

const Component: React.FC = () => {
   const handleSubmit = (action) => {
       doSomethingAsynchronous()
           .then(() => /* something on success */)
           .catch((err) => {
               // Display the error message
               action();

               // Rethrow the exception so it can be handled up the chain
               throw err;
           })
   }

   return <Form onSubmit={handleSubmit} />;
}

This code performs a simple asynchronous action that fails or resolves. On a failure, the component is re-rendered to show an error message, and the error is rethrown to log to the console/our logging system and for parent components to deal with.

The problem comes when I am attempting to test the error handling behaviour to ensure that the error messages are being set. Simple testing such as:

describe('Component', () => {
   it('handles an error', async () => {
       // Setup
       const mockAction = jest.fn();
       const render = shallowRender(<Component />);
       submissionHandler = render.find(Component).invoke('onSubmit');

       // Act
       submissionHandler(mockAction);
       await () => new Promise(setImmediate); // To wait for promise execution

       // Assert
       expect(mockAction).toHaveBeenCalled();
   })
})

Results in Jest failing the test as an error has been thrown in the test by the component, inside the catch block (as expected). However, my attempts to suppress this also result in the same error being thrown and failing the test.

try {
    // Act
    submissionHandler(mockAction);
    await () => new Promise(setImmediate); // To wait for promise execution
} catch (e) {}

I also tried using expects().toThrow(), but this instead returns the jest error Received function did not throw. I assume this is because due to the promise the execution is no longer in the same function scope, so isn't being recognised by Jest as originating from that function?

await expect(async () => {
   submissionHandler(mockAction);
   await () => new Promise(setImmediate);
}).toThrow();

Does anyone know the best way to test this? I'm aware I can cheat by making onSubmit return my promise here and catching the exception there, but I'd avoid doing that to stop my function returning for testing purposes.

Body:
You need to unpack your errors from your promise with .rejects

try this:

import { spyOn } from 'jest-mock';
...

it("should error", async() => {
  spyOn(console, 'error'); #removes error from output
  await expect( yourAsyncMethod() ).rejects.toThrow() # .rejects unpacks errors from promises
}


问:
remove all characters in every line starting from the character "\" in a text file using powershell
I have 50 lines text file ($file1) like and i need to remove the characters starting from an specific character "/" until,the end of the line.

Sample text file:

```<code>| Area | vserver | file-id |connection-id | session-id | open-mode | path |

| manphsan01 | manphs101 | 9980 | 4278018043 | 5065142205921760710 | rw | Share01\Mandaue\Data01 |

| manphsan01 | manphs101 | 1790 | 4278020659 | 5065142205921763223 | rwd | FinanceDept\ARCHIVING |

| manphsan01 | manphs101 | 1824 | 4278020659 | 5065142205921763223 | rwd | Share01\Cebu\Year2022 |

| manphsan01 | manphs101 | 1976 | 4278020659 | 5065142205921763223 | rwd | SGSDept\General\Document |
</code>```

My desired output sh0uld be like:

```<code>| Area | vserver | file-id |connection-id | session-id | open-mode | path |

| manphsan01 | manphs101 | 9980 | 4278018043 | 5065142205921760710 | rw | Share01 |

| manphsan01 | manphs101 | 1790 | 4278020659 | 5065142205921763223 | rwd | Finance |

| manphsan01 | manphs101 | 1824 | 4278020659 | 5065142205921763223 | rwd | Share01 |

| manphsan01 | manphs101 | 1976 | 4278020659 | 5065142205921763223 | rwd | SGSDept |
</code>```

the command i used is like this:

```<code>$var = Get-content $file1

$var.Substring(0, $var.IndexOf('\')) | FT -AutoSize or

$var.Substring(0, $var.IndexOf('backslash')) | FT -AutoSize
</code>```

My command will work if my data is only 1 line but multiple lines it wont work. I am not sure why the 'backslash' is not showing on the command when i posted it.

ny ideas how to make this work?

答:
You can get away with plain-text processing if you can assume that only one field on each line of your structured text file contains \ and that it and everything after it - up until the next field delimiter,  | - should be removed:

```<code># Transforms all matching lines and outputs them.
# Pipe to Set-Content to save back to a file; use -Encoding as needed.
(Get-Content $file) -replace '\\.+?(?= \|)'
</code>```

The above uses a -replace operation with a regex to remove the unwanted part of matching lines (lines that don't match are passed through as-is).

For an explanation of the regex and the ability to experiment with it, see this regex101.com page.

As for what you tried:

$var = Get-content $file1 stores the individual lines of file $file1 as an array in variable $var1.

To process the resulting lines one by one, you need a loop construct, such as a foreach statement or the ForEach-Object cmdlet; e.g. foreach ($line in $var) { ... }

While $line.Substring(0, $line.IndexOf('\')) works in principle, it will cause a statement-terminating error (exception) for every $line value that contains no \ character, as Theo notes, notably with your file's header line.

While this could easily be fixed with try { $line.Substring(0, $line.IndexOf('\')) } catch { $line }, the bigger problem is that it would remove everything through the end of the line, which contradicts your desired output, which shows that the next field seprator,  | should be retained.

The above -replace operation fixes both these problems; note that it implicitly loops over the array of input lines and performs the replacement operation on each, returning an array of (potentially) transformed lines.

Also note that a formatting cmdlet such as Format-Table (-FT) should only be used for for-display output; it doesn't produce usable data - see this answer for more information; also, it has no formatting effect on strings.

Body:
I have 50 lines text file ($file1) like and i need to remove the characters starting from an specific character "/" until,the end of the line.

Sample text file:

| Area | vserver | file-id |connection-id | session-id | open-mode | path |

| manphsan01 | manphs101 | 9980 | 4278018043 | 5065142205921760710 | rw | Share01\Mandaue\Data01 |

| manphsan01 | manphs101 | 1790 | 4278020659 | 5065142205921763223 | rwd | FinanceDept\ARCHIVING |

| manphsan01 | manphs101 | 1824 | 4278020659 | 5065142205921763223 | rwd | Share01\Cebu\Year2022 |

| manphsan01 | manphs101 | 1976 | 4278020659 | 5065142205921763223 | rwd | SGSDept\General\Document |

My desired output sh0uld be like:

| Area | vserver | file-id |connection-id | session-id | open-mode | path |

| manphsan01 | manphs101 | 9980 | 4278018043 | 5065142205921760710 | rw | Share01 |

| manphsan01 | manphs101 | 1790 | 4278020659 | 5065142205921763223 | rwd | Finance |

| manphsan01 | manphs101 | 1824 | 4278020659 | 5065142205921763223 | rwd | Share01 |

| manphsan01 | manphs101 | 1976 | 4278020659 | 5065142205921763223 | rwd | SGSDept |

the command i used is like this:

$var = Get-content $file1

$var.Substring(0, $var.IndexOf('\')) | FT -AutoSize or

$var.Substring(0, $var.IndexOf('backslash')) | FT -AutoSize

My command will work if my data is only 1 line but multiple lines it wont work. I am not sure why the 'backslash' is not showing on the command when i posted it.

ny ideas how to make this work?

Body:
You can get away with plain-text processing if you can assume that only one field on each line of your structured text file contains \ and that it and everything after it - up until the next field delimiter,  | - should be removed:

# Transforms all matching lines and outputs them.
# Pipe to Set-Content to save back to a file; use -Encoding as needed.
(Get-Content $file) -replace '\\.+?(?= \|)'

The above uses a -replace operation with a regex to remove the unwanted part of matching lines (lines that don't match are passed through as-is).

For an explanation of the regex and the ability to experiment with it, see this regex101.com page.

As for what you tried:

$var = Get-content $file1 stores the individual lines of file $file1 as an array in variable $var1.

To process the resulting lines one by one, you need a loop construct, such as a foreach statement or the ForEach-Object cmdlet; e.g. foreach ($line in $var) { ... }

While $line.Substring(0, $line.IndexOf('\')) works in principle, it will cause a statement-terminating error (exception) for every $line value that contains no \ character, as Theo notes, notably with your file's header line.

While this could easily be fixed with try { $line.Substring(0, $line.IndexOf('\')) } catch { $line }, the bigger problem is that it would remove everything through the end of the line, which contradicts your desired output, which shows that the next field seprator,  | should be retained.

The above -replace operation fixes both these problems; note that it implicitly loops over the array of input lines and performs the replacement operation on each, returning an array of (potentially) transformed lines.

Also note that a formatting cmdlet such as Format-Table (-FT) should only be used for for-display output; it doesn't produce usable data - see this answer for more information; also, it has no formatting effect on strings.


问:
How to set multiple output parameters in stored procedures
Is there a way to set multiple output parameters?

For example, in the stored procedure shown here, I wish to get the NUM_OF_ROWS and the TicketNumberz from the same stored procedure.

Since, I am new I don't know how to go about it...

```<code>DECLARE @TicketNumberz VARCHAR(15) OUT
DECLARE @NUM_OF_ROWS INT OUT
DECLARE @INIT INT=1 OUT

SET @TicketNumberz = (SELECT TICKETNUMBER
                      FROM TicketHistory s1
                      WHERE TICKETTIME IN (SELECT MAX(S2.TICKETTIME)
                                           FROM TicketHistory] S2
                                           WHERE s1.TICKETNUMBER = S2.TICKETNUMBER)
                        AND CURRENTSTATUS_ANALYST != 'Closed'
                        AND CURRENTSTATUS_ANALYST = 'Resolved'
                        AND TICKETTIME < GETDATE() - 5)

-- after getting all the list of ticket numbers, update query follows to update the ticket status to 'Closed'

WHILE (@INIT <= @NUM_OF_ROWS)
BEGIN
    INSERT INTO TicketHistory (CURRENTSTATUS_ANALYST, TICKETNUMBER,
                               PREVIOUSSTATUS_ANALYST, TICKETTIME, FIELD, CREATEDBY)
    VALUES ('Closed', @TicketNumberz,
            'Resolved', CURRENT_TIMESTAMP, 'Status', 'Auto.User')
END
</code>```

What this query basically does it, it would fetch all the ''Resolved' tickets which are older than 5 days and had not been 'Closed' automatically. So doing it manually through this stored procedure.

But, I am stuck because of the following error :

Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.

This is how the db looks like :

答:
Finally, I was able to achieve the desired result with the below code :</p>
```<code>    --Creating a table variable
    declare @TempTable table(ticketnum varchar(50))

    --Inserting values in table variable using procedure
    insert @TempTable
    select TICKETNUMBER
        FROM TicketHistory th
    WHERE TICKETTIME IN
    (
        SELECT MAX(S2.TICKETTIME)
        FROM TicketHistory S2
        WHERE th.TICKETNUMBER = S2.TICKETNUMBER
    )
        AND th.CURRENTSTATUS_ANALYST = 'Resolved'
        AND th.TICKETTIME < dateadd(day, -5, GETDATE())

    --Selecting values from table variable
    SELECT * from @TempTable

    DECLARE @ticket_number varchar(100)
    DECLARE cur CURSOR FOR SELECT ticketnum FROM @TempTable
    OPEN cur

    FETCH NEXT FROM cur INTO @ticket_number

    WHILE @@FETCH_STATUS = 0
        BEGIN
            insert into TicketHistory (CURRENTSTATUS_ANALYST,TICKETNUMBER,PREVIOUSSTATUS_ANALYST,TICKETTIME,FIELD,CREATEDBY)
              values('Closed', @ticket_number, 'Resolved', CURRENT_TIMESTAMP, 'Status', 'User.Auto')
            FETCH NEXT FROM cur INTO @ticket_number
        END

    CLOSE cur
    DEALLOCATE cur

    END
</code>```

Body:
Is there a way to set multiple output parameters?

For example, in the stored procedure shown here, I wish to get the NUM_OF_ROWS and the TicketNumberz from the same stored procedure.

Since, I am new I don't know how to go about it...

DECLARE @TicketNumberz VARCHAR(15) OUT
DECLARE @NUM_OF_ROWS INT OUT
DECLARE @INIT INT=1 OUT

SET @TicketNumberz = (SELECT TICKETNUMBER
                      FROM TicketHistory s1
                      WHERE TICKETTIME IN (SELECT MAX(S2.TICKETTIME)
                                           FROM TicketHistory] S2
                                           WHERE s1.TICKETNUMBER = S2.TICKETNUMBER)
                        AND CURRENTSTATUS_ANALYST != 'Closed'
                        AND CURRENTSTATUS_ANALYST = 'Resolved'
                        AND TICKETTIME < GETDATE() - 5)

-- after getting all the list of ticket numbers, update query follows to update the ticket status to 'Closed'

WHILE (@INIT <= @NUM_OF_ROWS)
BEGIN
    INSERT INTO TicketHistory (CURRENTSTATUS_ANALYST, TICKETNUMBER,
                               PREVIOUSSTATUS_ANALYST, TICKETTIME, FIELD, CREATEDBY)
    VALUES ('Closed', @TicketNumberz,
            'Resolved', CURRENT_TIMESTAMP, 'Status', 'Auto.User')
END

What this query basically does it, it would fetch all the ''Resolved' tickets which are older than 5 days and had not been 'Closed' automatically. So doing it manually through this stored procedure.

But, I am stuck because of the following error :

Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.

This is how the db looks like :

Body:
Finally, I was able to achieve the desired result with the below code :

    --Creating a table variable
    declare @TempTable table(ticketnum varchar(50))

    --Inserting values in table variable using procedure
    insert @TempTable
    select TICKETNUMBER
        FROM TicketHistory th
    WHERE TICKETTIME IN
    (
        SELECT MAX(S2.TICKETTIME)
        FROM TicketHistory S2
        WHERE th.TICKETNUMBER = S2.TICKETNUMBER
    )
        AND th.CURRENTSTATUS_ANALYST = 'Resolved'
        AND th.TICKETTIME < dateadd(day, -5, GETDATE())

    --Selecting values from table variable
    SELECT * from @TempTable

    DECLARE @ticket_number varchar(100)
    DECLARE cur CURSOR FOR SELECT ticketnum FROM @TempTable
    OPEN cur

    FETCH NEXT FROM cur INTO @ticket_number

    WHILE @@FETCH_STATUS = 0
        BEGIN
            insert into TicketHistory (CURRENTSTATUS_ANALYST,TICKETNUMBER,PREVIOUSSTATUS_ANALYST,TICKETTIME,FIELD,CREATEDBY)
              values('Closed', @ticket_number, 'Resolved', CURRENT_TIMESTAMP, 'Status', 'User.Auto')
            FETCH NEXT FROM cur INTO @ticket_number
        END

    CLOSE cur
    DEALLOCATE cur

    END


问:
dplyr: How to rearrange this dataframe and create new columns by extracting parts of other columns
Let's say I have this dataframe

```<code>> a
  T..Gene.names Intensity.Mut_125 Intensity.Mut_250 Intensity.Mut.1000 Intensity.Mut.500
1          NCAN               NaN           25.6628            23.8427               NaN
2          AMBP           22.8276           27.0801            25.4740           23.5596
3          CHGB           25.4463           30.0065            27.8181           27.3170
4           APP           25.0346           29.7784            27.0848           24.7314
</code>```

I need to re-arrange my dataframe so each a$T..Gene.names correspond to a new column. Then, I need a new column called a$sample that extracts the word between Intensity and the number (either 125, 250, 500, 1000 or 2000). An issue is that this word and following number is separated by either . or _ Finally, I need a column named a$volume that correspond to the number. NA should be converted to 0.

I tried several attempts with pivot_longer and pivot_wider but this is above my current skill level.

Expected output

```<code>sample     volume       NCAN         AMBP        CHGB        APP
   Mut        125          0      22.8276     25.4463    25.0346
   Mut        250    25.6638      27.0801     30.0065    29.7784
   Mut        500          0      23.5596     27.3170    24.7314
   Mut       1000    23.8427      25.4740     27.8181    27.0848
</code>```

I prefer a dplyr-solution

```<code>a <- structure(list(T..Gene.names = c("NCAN", "AMBP", "CHGB", "APP"
), Intensity.Mut_125 = c(NaN, 22.8276, 25.4463, 25.0346), Intensity.Mut_250 = c(25.6628,
27.0801, 30.0065, 29.7784), Intensity.Mut.1000 = c(23.8427, 25.474,
27.8181, 27.0848), Intensity.Mut.500 = c(NaN, 23.5596, 27.317,
24.7314)), row.names = c(NA, 4L), class = "data.frame")
</code>```

答:
Another possible solution using tidyr.

```<code>pivot_longer(a, cols = !"T..Gene.names",
             names_to = c('sample', 'volume'),
             names_prefix = "Intensity.",
             names_sep = '_|\\.',
             values_drop_na = T) %>%
pivot_wider(names_from = "T..Gene.names",
              values_fill = list(value = 0))

# A tibble: 4 × 6
  sample volume  NCAN  AMBP  CHGB   APP
  <chr>  <chr>  <dbl> <dbl> <dbl> <dbl>
1 Mut    250     25.7  27.1  30.0  29.8
2 Mut    1000    23.8  25.5  27.8  27.1
3 Mut    125      0    22.8  25.4  25.0
4 Mut    500      0    23.6  27.3  24.7

</code>```

names_prefix = "Intensity."removes "Intensity." from the column names.

names_sep = '_|\\.' separates the column names either by . or by _

Body:
Let's say I have this dataframe

> a
  T..Gene.names Intensity.Mut_125 Intensity.Mut_250 Intensity.Mut.1000 Intensity.Mut.500
1          NCAN               NaN           25.6628            23.8427               NaN
2          AMBP           22.8276           27.0801            25.4740           23.5596
3          CHGB           25.4463           30.0065            27.8181           27.3170
4           APP           25.0346           29.7784            27.0848           24.7314

I need to re-arrange my dataframe so each a$T..Gene.names correspond to a new column. Then, I need a new column called a$sample that extracts the word between Intensity and the number (either 125, 250, 500, 1000 or 2000). An issue is that this word and following number is separated by either . or _ Finally, I need a column named a$volume that correspond to the number. NA should be converted to 0.

I tried several attempts with pivot_longer and pivot_wider but this is above my current skill level.

Expected output

sample     volume       NCAN         AMBP        CHGB        APP
   Mut        125          0      22.8276     25.4463    25.0346
   Mut        250    25.6638      27.0801     30.0065    29.7784
   Mut        500          0      23.5596     27.3170    24.7314
   Mut       1000    23.8427      25.4740     27.8181    27.0848

I prefer a dplyr-solution

a <- structure(list(T..Gene.names = c("NCAN", "AMBP", "CHGB", "APP"
), Intensity.Mut_125 = c(NaN, 22.8276, 25.4463, 25.0346), Intensity.Mut_250 = c(25.6628,
27.0801, 30.0065, 29.7784), Intensity.Mut.1000 = c(23.8427, 25.474,
27.8181, 27.0848), Intensity.Mut.500 = c(NaN, 23.5596, 27.317,
24.7314)), row.names = c(NA, 4L), class = "data.frame")

Body:
Another possible solution using tidyr.

pivot_longer(a, cols = !"T..Gene.names",
             names_to = c('sample', 'volume'),
             names_prefix = "Intensity.",
             names_sep = '_|\\.',
             values_drop_na = T) %>%
pivot_wider(names_from = "T..Gene.names",
              values_fill = list(value = 0))

# A tibble: 4 × 6
  sample volume  NCAN  AMBP  CHGB   APP
  <chr>  <chr>  <dbl> <dbl> <dbl> <dbl>
1 Mut    250     25.7  27.1  30.0  29.8
2 Mut    1000    23.8  25.5  27.8  27.1
3 Mut    125      0    22.8  25.4  25.0
4 Mut    500      0    23.6  27.3  24.7

names_prefix = "Intensity."removes "Intensity." from the column names.

names_sep = '_|\\.' separates the column names either by . or by _


问:
Call function from another file without import clause?
Is is possible to call a function from another file without placing from import clause? I'd like to write Python code shorter and cleaner here, so I'm curious if there is a way to do that.

For example, usually we write like this and this works:

from tmpapp.forms import KakikomiForm

def kakikomi(request):
    f = KakikomiForm()
```
<p>I'd like to write something like this if possible, but this will be error:</p>
<pre class="lang-py prettyprint-override"><code># from tmpapp.forms import KakikomiForm

def kakikomi(request):
    f = tmpapp.forms.KakikomiForm()
</code>```

答:
Yes, you can, in some way... You can load the module using importlib, find the function and call it. Suppose we have following project structure:

```<code>your_project/
├── some_lib
│   └── some_module.py
└── test_dyn_import.py
</code>```

where some_module.py contains the function print_args we want to call without "import":

# Somewhere in some_module.py
def print_args(*argv):
    for v in argv:
        print(v)
```
<p>Then helping function <code>call_func</code> and caller's code will be:</p>
<pre class="lang-py prettyprint-override"><code># test_dyn_import.py
import importlib
from inspect import isfunction

def call_func(full_module_name, func_name, *argv):
    module = importlib.import_module(full_module_name)
    for attribute_name in dir(module):
        attribute = getattr(module, attribute_name)
        if isfunction(attribute) and attribute_name == func_name:
            attribute(*argv)

call_func('some_lib.some_module', 'print_args', 'foo', 'bar', 101)
</code>```

And the output will be

your_project/venv/bin/python test_dyn_import.py
foo
bar
101
```

Body:
Is is possible to call a function from another file without placing from import clause? I'd like to write Python code shorter and cleaner here, so I'm curious if there is a way to do that.

For example, usually we write like this and this works:

from tmpapp.forms import KakikomiForm

def kakikomi(request):
    f = KakikomiForm()

I'd like to write something like this if possible, but this will be error:

# from tmpapp.forms import KakikomiForm

def kakikomi(request):
    f = tmpapp.forms.KakikomiForm()

Body:
Yes, you can, in some way... You can load the module using importlib, find the function and call it. Suppose we have following project structure:

your_project/
├── some_lib
│   └── some_module.py
└── test_dyn_import.py

where some_module.py contains the function print_args we want to call without "import":

# Somewhere in some_module.py
def print_args(*argv):
    for v in argv:
        print(v)

Then helping function call_func and caller's code will be:

# test_dyn_import.py
import importlib
from inspect import isfunction

def call_func(full_module_name, func_name, *argv):
    module = importlib.import_module(full_module_name)
    for attribute_name in dir(module):
        attribute = getattr(module, attribute_name)
        if isfunction(attribute) and attribute_name == func_name:
            attribute(*argv)

call_func('some_lib.some_module', 'print_args', 'foo', 'bar', 101)

And the output will be

your_project/venv/bin/python test_dyn_import.py
foo
bar
101


问:
Django How to display either an image or pdf
I have a model with file upload field where users can upload either an image or a pdf. What is the best way to display the upload in a template when it can be either an image or a pdf.

I have seen a fairly complex ajax based solution. Is there a better way?

答:
hello  you can use python-magic in your view to get the file type

next you could use the type  got  for use img tag or pdf tag  in you html

exemple with image and video:

```<code>class post(models.Model):
titre=models.CharField(unique=True,null=True,max_length=100)
description=models.TextField(null=True,blank=True,max_length=400)
T=models.CharField(default="image",blank=True,max_length=50)
image=models.FileField(null=True)
cat=models.ForeignKey(categorie,on_delete=models.CASCADE,null=True)
datepost=models.DateTimeField(auto_now_add=True,blank=True)
user=models.ForeignKey(myuser,on_delete=models.CASCADE,null=True)
vue=models.IntegerField(default=0,blank=True)
def __str__(self):
    return self.titre

def save(self, *args ,**kwargs):
    #cette partie permet de generer un identifiant unique
    f=self.image.read(1000)
    self.image.seek(0)
    mime=magic.from_buffer(f,mime=True)
    if "video" in mime :
        self.T="short"
    super(post,self).save(*args,**kwargs)
</code>```

in my template:

```<code>{%if mpost.T == "image" %}
    <img src="{{mpost.image.url}}" style="max-width:100% ;max-height: 100%;flex-shrink: 0;">
{%else%}
    <video loop autoplay="true" src="{{mpost.image.url}}" style="max-width:100% ;max-height: 100%;flex-shrink: 0;"></video>
 {%endif%}
</code>```

Body:
hello  you can use python-magic in your view to get the file type

next you could use the type  got  for use img tag or pdf tag  in you html

exemple with image and video:

class post(models.Model):
titre=models.CharField(unique=True,null=True,max_length=100)
description=models.TextField(null=True,blank=True,max_length=400)
T=models.CharField(default="image",blank=True,max_length=50)
image=models.FileField(null=True)
cat=models.ForeignKey(categorie,on_delete=models.CASCADE,null=True)
datepost=models.DateTimeField(auto_now_add=True,blank=True)
user=models.ForeignKey(myuser,on_delete=models.CASCADE,null=True)
vue=models.IntegerField(default=0,blank=True)
def __str__(self):
    return self.titre

def save(self, *args ,**kwargs):
    #cette partie permet de generer un identifiant unique
    f=self.image.read(1000)
    self.image.seek(0)
    mime=magic.from_buffer(f,mime=True)
    if "video" in mime :
        self.T="short"
    super(post,self).save(*args,**kwargs)

in my template:

{%if mpost.T == "image" %}
    <img src="{{mpost.image.url}}" style="max-width:100% ;max-height: 100%;flex-shrink: 0;">
{%else%}
    <video loop autoplay="true" src="{{mpost.image.url}}" style="max-width:100% ;max-height: 100%;flex-shrink: 0;"></video>
 {%endif%}


问:
Azure Pipelines CI Not firing
My organization recently changed from using personal GitHub accounts to using GitHub Enterprise Managed Users. Since that change our pipeline continuous integration (in Azure Devops) has stopped working. We can still run the builds manually without issue, but it isn't even attempting to start the builds automatically. I've created new personal access tokens for the pipelines, but that hasn't fixed the continuous integration. Does anyone have any suggestions on what I should look at to get this working again?</p>

答: I wound up fixing this by going to the repository in Git Hub, go to settings on the repository, and then to Web Hooks. In there, the hook that Azure Pipelines uses had an error on it because when our tech group migrated the repo they did not bring the secret over. To fix it I just had to delete the web hook, go to the pipeline and a button appeared to restore the connection.</p>

Title: Azure Pipelines CI Not firing


问:
how to import md file when I use create-react-app with javascript?
I'm trying to run the blog example in material ui getting started page . the problem is that the source code is:

in blog.js

```<code>import post1 from './blog-post.1.md';

.
.
.
return( <Main>{post1}<Main/>);

</code>```

and in Main.js:

```<code>import ReactMarkdown from 'markdown-to-jsx';
export default function Main(props) {

  return <ReactMarkdown options={options} {...props} />;
}
</code>```

if I run the code I get this output:
/static/media/blog-post.1.0c315da1f0a7af641a3a.md instead of the data inside the MD file.

I want to do the same ,how can I import MD files in my create-react-app version? (without typescript)

答:
You'll need to read the markdown object and then load it into the ReactMarkdown component. Common methods of doing this use fetch as an intermediary. For example:

```<code>import * as React from "react";
import ReactMarkdown from "markdown-to-jsx";
import post from "./post.md";

export default function MarkdownImport() {
  let [readable, setReadable] = React.useState({ md: "" });

  React.useEffect(() => {
    fetch(post)
      .then((res) => res.text())
      .then((md) => {
        setReadable({ md });
      });
  }, []);

  return (
    <div>
      <ReactMarkdown children={readable.md} />
    </div>
  );
}
</code>```

Working example: https://codesandbox.io/s/reactmarkdown-example-20vmg

Body:
I'm trying to run the blog example in material ui getting started page . the problem is that the source code is:

in blog.js

import post1 from './blog-post.1.md';

.
.
.
return( {post1});

and in Main.js:

import ReactMarkdown from 'markdown-to-jsx';
export default function Main(props) {

  return <ReactMarkdown options={options} {...props} />;
}

if I run the code I get this output:
/static/media/blog-post.1.0c315da1f0a7af641a3a.md instead of the data inside the MD file.

I want to do the same ,how can I import MD files in my create-react-app version? (without typescript)

Body:
You'll need to read the markdown object and then load it into the ReactMarkdown component. Common methods of doing this use fetch as an intermediary. For example:

import * as React from "react";
import ReactMarkdown from "markdown-to-jsx";
import post from "./post.md";

export default function MarkdownImport() {
  let [readable, setReadable] = React.useState({ md: "" });

  React.useEffect(() => {
    fetch(post)
      .then((res) => res.text())
      .then((md) => {
        setReadable({ md });
      });
  }, []);

  return (
    <div>
      <ReactMarkdown children={readable.md} />
    </div>
  );
}

Working example: https://codesandbox.io/s/reactmarkdown-example-20vmg


问:
Plotting occurrences by date - Error in seq.int(0, to0 - from, by) : 'to' must be a finite number
I have a dataset of tweets made in this way:

```<code>mydata <- read.csv(header=TRUE, text='"tweet","Topic","created_at"
"text1","topic1","2020-08-13"
"text2","topic2","2020-08-11"
"text3","topic2","2020-08-11"
"text4","topic2","2020-08-10"
"text5","topic1","2020-08-13"
"text6","topic1","2020-08-14"
"text7","topic1","2020-08-15"')
</code>```

I want to plot the occurrence of each topic over time day by day (for example, if on 2020-08-11 there have been 5 tweets belonging to topic 1 and 2 tweets belonging to topic 2, the value of topic 1 for that day will be 5 and for topic 2 will be 2, and so on), and I'm trying to do it with this code:

```<code>mydata%>%
  mutate(created_at = lubridate::ymd_hms(created_at),
         date = as.Date(created_at)) %>%
  count(date, Topic) %>%
  ggplot(aes(date, n, color = Topic)) + geom_line()+
  labs(y="n° tweets")
</code>```

But I'm receiving this error:

```<code>Error in seq.int(0, to0 - from, by) : 'to' must be a finite number
</code>```

What can I do?
My goal is a result like this:

答:
created_at does not have the proper format for lubridate::ymd_hms() which creates NA-values in your dataset. You can simply remove it and use as.Date() and your code does what you want:

```<code>mydata %>%
  mutate(date = as.Date(created_at)) %>%
  count(date, Topic) %>%
  ggplot(aes(date, n, color = Topic)) + geom_line()+
  labs(y="n° tweets")
</code>```

Body:
I have a dataset of tweets made in this way:

mydata <- read.csv(header=TRUE, text='"tweet","Topic","created_at"
"text1","topic1","2020-08-13"
"text2","topic2","2020-08-11"
"text3","topic2","2020-08-11"
"text4","topic2","2020-08-10"
"text5","topic1","2020-08-13"
"text6","topic1","2020-08-14"
"text7","topic1","2020-08-15"')

I want to plot the occurrence of each topic over time day by day (for example, if on 2020-08-11 there have been 5 tweets belonging to topic 1 and 2 tweets belonging to topic 2, the value of topic 1 for that day will be 5 and for topic 2 will be 2, and so on), and I'm trying to do it with this code:

mydata%>%
  mutate(created_at = lubridate::ymd_hms(created_at),
         date = as.Date(created_at)) %>%
  count(date, Topic) %>%
  ggplot(aes(date, n, color = Topic)) + geom_line()+
  labs(y="n° tweets")

But I'm receiving this error:

Error in seq.int(0, to0 - from, by) : 'to' must be a finite number

What can I do?
My goal is a result like this:

Body:
created_at does not have the proper format for lubridate::ymd_hms() which creates NA-values in your dataset. You can simply remove it and use as.Date() and your code does what you want:

mydata %>%
  mutate(date = as.Date(created_at)) %>%
  count(date, Topic) %>%
  ggplot(aes(date, n, color = Topic)) + geom_line()+
  labs(y="n° tweets")


问:
SQLAlchemy Enum type field with integer value
There is an events model in which I want to add a memebers_count field to indicate the number of participants. The user will make a single selection from the select form. I am using Enum type for this. The model looks like this

```<code>class MembersQuantity(enum.Enum):
    two = 2
    three = 3
    four = 4
    five = 5
    six = 6
    ...
    nineteen = 19
    twenty = 20
    thirty = 30
    forty = 40
    fifty = 50
    unlimited = 1000

events = Table(
    "events",
    metadata,
    Column("id", Integer(), primary_key=True),
    ...
    Column("members_count", Enum(MembersQuantity, values_callable=lambda obj: [e.value for e in obj]),
           nullable=False,
           default=MembersQuantity.two.value,
           server_default=MembersQuantity.two.value),
    ....
</code>```

An error appears in the console when this entry is made

```<code>  File "/home/jekson/Projects/own/wplay/./models/events.py", line 64, in <module>
    Column("members_count", Enum(MembersQuantity, values_callable=lambda obj: [e.value for e in obj]),
  File "<string>", line 2, in __init__
  File "/home/jekson/virtualenvs/wplay/lib/python3.9/site-packages/sqlalchemy/util/deprecations.py", line 139, in warned
    return fn(*args, **kwargs)
  File "/home/jekson/virtualenvs/wplay/lib/python3.9/site-packages/sqlalchemy/sql/sqltypes.py", line 1383, in __init__
    self._enum_init(enums, kw)
  File "/home/jekson/virtualenvs/wplay/lib/python3.9/site-packages/sqlalchemy/sql/sqltypes.py", line 1425, in _enum_init
    length = max(len(x) for x in self.enums)
  File "/home/jekson/virtualenvs/wplay/lib/python3.9/site-packages/sqlalchemy/sql/sqltypes.py", line 1425, in <genexpr>
    length = max(len(x) for x in self.enums)
TypeError: object of type 'int' has no len()
</code>```

I assumed the problem was that [e.value for e in obj] should be str instead of int and replaced it with [str(e.value) for e in obj] but got another error

```<code>sqlalchemy.exc.ArgumentError: Argument 'arg' is expected to be of the type '<class 'str'>' or '<class 'sqlalchemy.sql.elements.ClauseElement'>' or '<class 'sqlalchemy.sql.elements.TextClause'>', got '<class 'int'>'
</code>```

What's wrong?

答:
The question is what do you want to persist? two or 2 or <MembersQuantity.two: 2>?

SQLAlchemy docs states:

```<code>Above, the string names of each element, e.g. “one”, “two”, “three”, are persisted to the database;
the values of the Python Enum, here indicated as integers, are not used;
the value of each enum can therefore be any kind of Python object whether or not it is persistable.
</code>```

So if you have integer values of enum, you probably should have something like this:

    Column(
       "members_count",
       Enum(MembersQuantity),
       nullable=False,
       default=MembersQuantity.two.name,
       server_default=MembersQuantity.two.name
    )
```

The name attribute is two, while value attribute is 2 in your case. But you persist only left-hand side strings.
You should use values_callable only if you want to persist values instead of names, but docs states also: value_callables - a callable which will be passed the PEP-435 compliant enumerated type, which should then return a list of string values to be persisted. So you can persist value only if it is a string.

Here is a topic that can be helpful: How to use Enum with SQLAlchemy and Alembic?

Body:
There is an events model in which I want to add a memebers_count field to indicate the number of participants. The user will make a single selection from the select form. I am using Enum type for this. The model looks like this

class MembersQuantity(enum.Enum):
    two = 2
    three = 3
    four = 4
    five = 5
    six = 6
    ...
    nineteen = 19
    twenty = 20
    thirty = 30
    forty = 40
    fifty = 50
    unlimited = 1000

events = Table(
    "events",
    metadata,
    Column("id", Integer(), primary_key=True),
    ...
    Column("members_count", Enum(MembersQuantity, values_callable=lambda obj: [e.value for e in obj]),
           nullable=False,
           default=MembersQuantity.two.value,
           server_default=MembersQuantity.two.value),
    ....

An error appears in the console when this entry is made

  File "/home/jekson/Projects/own/wplay/./models/events.py", line 64, in <module>
    Column("members_count", Enum(MembersQuantity, values_callable=lambda obj: [e.value for e in obj]),
  File "<string>", line 2, in __init__
  File "/home/jekson/virtualenvs/wplay/lib/python3.9/site-packages/sqlalchemy/util/deprecations.py", line 139, in warned
    return fn(*args, **kwargs)
  File "/home/jekson/virtualenvs/wplay/lib/python3.9/site-packages/sqlalchemy/sql/sqltypes.py", line 1383, in __init__
    self._enum_init(enums, kw)
  File "/home/jekson/virtualenvs/wplay/lib/python3.9/site-packages/sqlalchemy/sql/sqltypes.py", line 1425, in _enum_init
    length = max(len(x) for x in self.enums)
  File "/home/jekson/virtualenvs/wplay/lib/python3.9/site-packages/sqlalchemy/sql/sqltypes.py", line 1425, in <genexpr>
    length = max(len(x) for x in self.enums)
TypeError: object of type 'int' has no len()

I assumed the problem was that [e.value for e in obj] should be str instead of int and replaced it with [str(e.value) for e in obj] but got another error

sqlalchemy.exc.ArgumentError: Argument 'arg' is expected to be of the type '<class 'str'>' or '<class 'sqlalchemy.sql.elements.ClauseElement'>' or '<class 'sqlalchemy.sql.elements.TextClause'>', got '<class 'int'>'

What's wrong?

Body:
The question is what do you want to persist? two or 2 or <MembersQuantity.two: 2>?

SQLAlchemy docs states:

Above, the string names of each element, e.g. “one”, “two”, “three”, are persisted to the database;
the values of the Python Enum, here indicated as integers, are not used;
the value of each enum can therefore be any kind of Python object whether or not it is persistable.

So if you have integer values of enum, you probably should have something like this:

    Column(
       "members_count",
       Enum(MembersQuantity),
       nullable=False,
       default=MembersQuantity.two.name,
       server_default=MembersQuantity.two.name
    )

The name attribute is two, while value attribute is 2 in your case. But you persist only left-hand side strings.
You should use values_callable only if you want to persist values instead of names, but docs states also: value_callables - a callable which will be passed the PEP-435 compliant enumerated type, which should then return a list of string values to be persisted. So you can persist value only if it is a string.

Here is a topic that can be helpful: How to use Enum with SQLAlchemy and Alembic?


问:
Express js cors preflight request not successful despite enabling cors
I am using a self signed ssl certificate (for now) to run an https server using express. Here is my app.js

const express = require('express');
const BodyParser = require('body-parser');
const config = require('./config');
const Logger = require('./loaders/logger');
const cors = require('cors');
const fs = require('fs');
const https = require('https');
const app = express();
const router = express.Router();
const usersApi = require('./api/users');
const authMiddleWare = require('./middlewares/auth');

var whitelist = ['http://localhost:8080', 'https://somedomain.web.app']

var corsOptionsDelegate = function (req, callback) {
  var corsOptions;
  if (whitelist.indexOf(req.header('Origin')) !== -1) {
    corsOptions = { origin: true } // reflect (enable) the requested origin in the CORS response
  }else{
    corsOptions = { origin: false } // disable CORS for this request
  }
  callback(null, corsOptions) // callback expects two parameters: error and options
}

app.use(cors(corsOptionsDelegate));
app.use(BodyParser.json());
app.use('/user', usersApi);
app.get('/abc/:id', function (req, res, next) {
  return res.json({ foo: 'bar' });
});

async function startServer() {

  await require('./loaders').default({ expressApp: app });

  https.createServer({
    key: fs.readFileSync('server.key'),
    cert: fs.readFileSync('server.cert')
  },app).listen(config.port, err => {
    if (err) {
      Logger.error(err);
      process.exit(1);
      return;
    }
    Logger.info(`
      ################################################
        Server listening on port: ${config.port}
      ################################################
    `);
  });
}

startServer();
```

<p>When I try to access from my front end (vue js app using axios) on localhost:8080, it does not work if its running on remote server and I get this error:</p>

<blockquote>
  <p>Access to XMLHttpRequest at 'https://147.215.83.136/user/param' from origin 'http://localhost:8080' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.</p>
</blockquote>

<p>But if same thing runs on localhost, it works!
With the vue js app deployed remotely, it also does not work and I get the same error.
Other things I tried are:</p>

<pre class="lang-js prettyprint-override"><code>app.use(cors());
app.options("*",cors());
app.use(cors({origin: "http://localhost:8080"}) // also tried putting https url of the vue app instead of this one. Still same result
</code>```

So what is going on and why isn't it working(on mozilla or chrome)?

EDIT:
Network requests tab in chrome shows this:

答:
Also be carefull to not mix content on https site with content generated from api request on http,
As there is no way to fix this later</p>

Body:
I am using a self signed ssl certificate (for now) to run an https server using express. Here is my app.js

const express = require('express');
const BodyParser = require('body-parser');
const config = require('./config');
const Logger = require('./loaders/logger');
const cors = require('cors');
const fs = require('fs');
const https = require('https');
const app = express();
const router = express.Router();
const usersApi = require('./api/users');
const authMiddleWare = require('./middlewares/auth');

var whitelist = ['http://localhost:8080', 'https://somedomain.web.app']

var corsOptionsDelegate = function (req, callback) {
  var corsOptions;
  if (whitelist.indexOf(req.header('Origin')) !== -1) {
    corsOptions = { origin: true } // reflect (enable) the requested origin in the CORS response
  }else{
    corsOptions = { origin: false } // disable CORS for this request
  }
  callback(null, corsOptions) // callback expects two parameters: error and options
}

app.use(cors(corsOptionsDelegate));
app.use(BodyParser.json());
app.use('/user', usersApi);
app.get('/abc/:id', function (req, res, next) {
  return res.json({ foo: 'bar' });
});

async function startServer() {

  await require('./loaders').default({ expressApp: app });

  https.createServer({
    key: fs.readFileSync('server.key'),
    cert: fs.readFileSync('server.cert')
  },app).listen(config.port, err => {
    if (err) {
      Logger.error(err);
      process.exit(1);
      return;
    }
    Logger.info(`
      ################################################
        Server listening on port: ${config.port}
      ################################################
    `);
  });
}

startServer();

When I try to access from my front end (vue js app using axios) on localhost:8080, it does not work if its running on remote server and I get this error:

Access to XMLHttpRequest at 'https://147.215.83.136/user/param' from origin 'http://localhost:8080' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

But if same thing runs on localhost, it works!
With the vue js app deployed remotely, it also does not work and I get the same error.
Other things I tried are:

app.use(cors());
app.options("*",cors());
app.use(cors({origin: "http://localhost:8080"}) // also tried putting https url of the vue app instead of this one. Still same result

So what is going on and why isn't it working(on mozilla or chrome)?

EDIT:
Network requests tab in chrome shows this:


问:
Pass jq output to curl
I want to be use a number of values from jq piped to curl. I have json data with a structure that looks something like this

```<code>{
  "apps": {
    "code": "200",
    "name": "app1",
  },
  "result": "1"
}
{
  "apps": {
    "code": "200",
    "name": "app2",
  },
  "result": "5"
}
...
...
...

</code>```

What I want to do is to take the values of every apps.name and result and pass that to curl:

```<code>curl -XPOST http://localhost --data-raw 'app=$appsName result=$result'
</code>```

The curl command will then run X amount of times depending on how many objects there are.
In jq I came up with this but I don't know how or the best way of passing this to curl in a loop.

```<code>jq -r '.result as $result | .apps as $apps | $apps.name + " " + $result myfile.json
</code>```

答:
Maybe something like this?</p>
```<code>jq < data.json '[.apps.name, .result]|@tsv' -r | while read appsName result; do
    curl -XPOST http://localhost --data-raw "$appsName $result"
done
</code>```

Title: Pass jq output to curl

Body:
I want to be use a number of values from jq piped to curl. I have json data with a structure that looks something like this

{
  "apps": {
    "code": "200",
    "name": "app1",
  },
  "result": "1"
}
{
  "apps": {
    "code": "200",
    "name": "app2",
  },
  "result": "5"
}
...
...
...

What I want to do is to take the values of every apps.name and result and pass that to curl:

curl -XPOST http://localhost --data-raw 'app=$appsName result=$result'

The curl command will then run X amount of times depending on how many objects there are.
In jq I came up with this but I don't know how or the best way of passing this to curl in a loop.

jq -r '.result as $result | .apps as $apps | $apps.name + " " + $result myfile.json

Body:
Maybe something like this?

jq < data.json '[.apps.name, .result]|@tsv' -r | while read appsName result; do
    curl -XPOST http://localhost --data-raw "$appsName $result"
done


问:
Telerik RadTree bound to XML DataSource
I have a Telerik RadTree bound to an XMLDataSource.
I want to set a node's text to consist of 2 attributes (number and name).

See <telerik:RadTreeNodeBinding>

Example:

"1. How are you?"

"2. How old are you?"

XML:

```<code><questions>
  <question name="How are you?" number="1" imageurl="">
  </question>
  <question name="How old are you?" number="2" imageurl="">
  </question>
</questions>
</code>```

ASPX:

```<code><telerik:RadTreeView ID="RadTreeView1" runat="server">
  <DataBindings>
    <telerik:RadTreeNodeBinding DataMember="questions" Text="Questions"
       ImageUrl="/questions.png" Expanded="false" />
    <telerik:RadTreeNodeBinding DataMember="question"
       Text='[<%# DataBinder.Eval("number")%>].[<%# DataBinder.Eval("name")%>]'
       ImageUrlField="imageurl" FormatString="{0}" Expanded="false" />
  </DataBindings>
</telerik:RadTreeView>
</code>```

答:
Solved: I use the NodeTemplate applied to all nodes to prepend "number." if found in xpath...</p>

```<code><telerik:RadTreeView ID="RadTreeView1" runat="server">
    <NodeTemplate>
            <%# XPath("@number", "{0}.") %>
            <%# DataBinder.Eval(Container, "Text") %>
    </NodeTemplate>
    <DataBindings>
        <telerik:RadTreeNodeBinding DataMember="questions" Text="Questions" ImageUrl="/questions.png" Expanded="false" />
        <telerik:RadTreeNodeBinding DataMember="question" TextField="name" ImageUrlField="kpiimageurl" FormatString="{0}" Expanded="false" />
    </DataBindings>
</telerik:RadTreeView>
</code>```

OwnerDisplayName: Konrad

ContentLicense: CC BY-SA 3.0

Title: Telerik RadTree bound to XML DataSource

Body:
I have a Telerik RadTree bound to an XMLDataSource.
I want to set a node's text to consist of 2 attributes (number and name).

See <telerik:RadTreeNodeBinding>

Example:

"1. How are you?"

"2. How old are you?"

XML:

<questions>
  <question name="How are you?" number="1" imageurl="">
  </question>
  <question name="How old are you?" number="2" imageurl="">
  </question>
</questions>

ASPX:

<telerik:RadTreeView ID="RadTreeView1" runat="server">
  <DataBindings>
    <telerik:RadTreeNodeBinding DataMember="questions" Text="Questions"
       ImageUrl="/questions.png" Expanded="false" />
    <telerik:RadTreeNodeBinding DataMember="question"
       Text='[<%# DataBinder.Eval("number")%>].[<%# DataBinder.Eval("name")%>]'
       ImageUrlField="imageurl" FormatString="{0}" Expanded="false" />
  </DataBindings>
</telerik:RadTreeView>

Body:
Solved: I use the NodeTemplate applied to all nodes to prepend "number." if found in xpath...

<telerik:RadTreeView ID="RadTreeView1" runat="server">
    <NodeTemplate>
            <%# XPath("@number", "{0}.") %>
            <%# DataBinder.Eval(Container, "Text") %>
    </NodeTemplate>
    <DataBindings>
        <telerik:RadTreeNodeBinding DataMember="questions" Text="Questions" ImageUrl="/questions.png" Expanded="false" />
        <telerik:RadTreeNodeBinding DataMember="question" TextField="name" ImageUrlField="kpiimageurl" FormatString="{0}" Expanded="false" />
    </DataBindings>
</telerik:RadTreeView>

ContentLicense: CC BY-SA 2.5


问:
jQuery + C# code to resolve URL's from user-supplied text
I'd like to add some kind of simple URL resolution and formatting to my C# and jQuery-based ASP.NET web application.  I currently allow users to add simple text-based descriptions to items and leave simple comments ('simple' as in I only allow plain text).

What I need to support is the ability for a user to enter something like:

Check out this cool link: http://www.really-cool-site.com

...and have the URL above properly resolved as a link and automagically turned into a clickable link...kinda like the way the editor in StackOverflow works.  Except that we don't want to support BBCode or any of its variants.  The user experience would actually be more like the way Facebook resolves user-generated URL's.

What are some jQuery + C# solutions I should consider?

答:
There's another question with a solution that might help you. It uses a regex in pure JS.

Personally though, I would do it server-side when the user submits it. That way, you only need to do it once, rather than every time you display that text. You could use a similar regex in C#.


问:
Pyspark Cumulative sum within Partition for moving last 2 (N) rows
Let's say I have the following dataframe which is sorted for ease visually:

How would I utilize window functions to create a new column that sums the previous row ordered by Month column within each period partition:

The following is my attempt at it, but I'm obviously doing something wrong with respect to the rowsBetween function.

```<code>df = df.withColumn('CustLast2', sum('Cust').over(Window.partitionBy("period").orderBy('Month').rowsBetween(Window.currentRow, -1))
</code>```

答:
We made the Fugue project to port native Python or Pandas code to Spark or Dask. This lets you can keep the logic very readable by expressing it in native Python. Fugue can then port it to Spark for you with one function call.

First we start with a test Pandas DataFrame (we'll port to Spark later):

import pandas as pd
df = pd.DataFrame({"date": ["2020-01-01", "2020-01-02", "2020-01-03"] * 3,
                   "period": [0,0,0,1,1,1,2,2,2],
                   "val": [4,5,2] * 3})
```
<p>Then we make a Pandas based function. Notice this is meant to be applied per group. We will partition later.</p>
<pre class="lang-py prettyprint-override"><code>def rolling(df: pd.DataFrame) -> pd.DataFrame:
    df["cum_sum"] = df["val"].rolling(2).sum().fillna(df["val"])
    return df
</code>```

Now we can use the Fugue transform function to test on Pandas. This function handles the partition and presort also.

from fugue import transform
transform(df, rolling, schema="*, cum_sum:float", partition={"by":"period", "presort": "date asc"})
```
<p>Because this works, we can bring it to Spark just by specifying the engine:</p>
<pre class="lang-py prettyprint-override"><code>import fugue_spark
transform(df, rolling, schema="*, cum_sum:float", partition={"by":"period", "presort": "date asc"}, engine="spark").show()
</code>```
```<code>+----------+------+---+-------+
|      date|period|val|cum_sum|
+----------+------+---+-------+
|2020-01-01|     0|  4|    4.0|
|2020-01-02|     0|  5|    9.0|
|2020-01-03|     0|  2|    7.0|
|2020-01-01|     1|  4|    4.0|
|2020-01-02|     1|  5|    9.0|
|2020-01-03|     1|  2|    7.0|
|2020-01-01|     2|  4|    4.0|
|2020-01-02|     2|  5|    9.0|
|2020-01-03|     2|  2|    7.0|
+----------+------+---+-------+
</code>```

Notice you need .show() now because of Spark's lazy evaluation. The Fugue transform function can take in both Pandas and Spark DataFrames and will output

Body:
Let's say I have the following dataframe which is sorted for ease visually:

How would I utilize window functions to create a new column that sums the previous row ordered by Month column within each period partition:

The following is my attempt at it, but I'm obviously doing something wrong with respect to the rowsBetween function.

df = df.withColumn('CustLast2', sum('Cust').over(Window.partitionBy("period").orderBy('Month').rowsBetween(Window.currentRow, -1))

Body:
We made the Fugue project to port native Python or Pandas code to Spark or Dask. This lets you can keep the logic very readable by expressing it in native Python. Fugue can then port it to Spark for you with one function call.

First we start with a test Pandas DataFrame (we'll port to Spark later):

import pandas as pd
df = pd.DataFrame({"date": ["2020-01-01", "2020-01-02", "2020-01-03"] * 3,
                   "period": [0,0,0,1,1,1,2,2,2],
                   "val": [4,5,2] * 3})

Then we make a Pandas based function. Notice this is meant to be applied per group. We will partition later.

def rolling(df: pd.DataFrame) -> pd.DataFrame:
    df["cum_sum"] = df["val"].rolling(2).sum().fillna(df["val"])
    return df

Now we can use the Fugue transform function to test on Pandas. This function handles the partition and presort also.

from fugue import transform
transform(df, rolling, schema="*, cum_sum:float", partition={"by":"period", "presort": "date asc"})

Because this works, we can bring it to Spark just by specifying the engine:

import fugue_spark
transform(df, rolling, schema="*, cum_sum:float", partition={"by":"period", "presort": "date asc"}, engine="spark").show()

+----------+------+---+-------+
|      date|period|val|cum_sum|
+----------+------+---+-------+
|2020-01-01|     0|  4|    4.0|
|2020-01-02|     0|  5|    9.0|
|2020-01-03|     0|  2|    7.0|
|2020-01-01|     1|  4|    4.0|
|2020-01-02|     1|  5|    9.0|
|2020-01-03|     1|  2|    7.0|
|2020-01-01|     2|  4|    4.0|
|2020-01-02|     2|  5|    9.0|
|2020-01-03|     2|  2|    7.0|
+----------+------+---+-------+

Notice you need .show() now because of Spark's lazy evaluation. The Fugue transform function can take in both Pandas and Spark DataFrames and will output


问:
QUERY SQL ORACLE
I'm trying to solve this question
"Make a query that shows the name and the worker's bonus based on the years working in the company:
If he takes between 1 and 5 years, he will be given 100 euros.
If he has between 6 and 10 years, he will be given 50 euros per year.
If he has between 11 and 20 years, he will be given 70 euros per year.
If he has more than 21 years, he will be given 100 euros per year"

Thats what I tried...
I have a table (named workers) with the information of them (admissiondate, name...)

```<code>  SELECT name, (EXTRACT(YEAR FROM SYSDATE)-EXTRACT(YEAR FROM admissiondate))*(CASE EXTRACT(YEAR FROM SYSDATE)-EXTRACT(YEAR FROM admissiondate)
    WHEN EXTRACT(YEAR FROM SYSDATE)-EXTRACT(YEAR FROM admissiondate)>21 THEN 100
    WHEN EXTRACT(YEAR FROM SYSDATE)-EXTRACT(YEAR FROM admissiondate)<=21 AND AND EXTRACT(YEAR FROM SYSDATE)-EXTRACT(YEAR FROM admissiondate)>10 THEN 70
    WHEN EXTRACT(YEAR FROM SYSDATE)-EXTRACT(YEAR FROM admissiondate)<=10 AND EXTRACT(YEAR FROM SYSDATE)-EXTRACT(YEAR FROM admissiondate)>4 THEN 50
    ELSE 100 END) AS Gratification
    FROM workers;
</code>```

But it doesn't work. so, please, can you advice me anything useful?

答:
Thanks all of you.
I think I have founded the solution.</p>
```<code>SELECT name, CASE WHEN TRUNC(MONTHS_BETWEEN(SYSDATE, admissiondate)/12)>21 THEN 100*TRUNC(MONTHS_BETWEEN(SYSDATE, admissiondate)/12)
WHEN TRUNC(MONTHS_BETWEEN(SYSDATE, admissiondate)/12)<=21 AND TRUNC(MONTHS_BETWEEN(SYSDATE, admissiondate)/12)>10 THEN 70*TRUNC(MONTHS_BETWEEN(SYSDATE, admissiondate)/12)
WHEN TRUNC(MONTHS_BETWEEN(SYSDATE, admissiondate)/12)<=10 AND TRUNC(MONTHS_BETWEEN(SYSDATE, admissiondate)/12)>4 THEN 50*TRUNC(MONTHS_BETWEEN(SYSDATE, admissiondate)/12)
ELSE 100*TRUNC(MONTHS_BETWEEN(SYSDATE, admissiondate)/12) END AS "Gratification €"
    FROM workers
    ORDER BY name;
</code>```

Title: QUERY SQL ORACLE

Body:
I'm trying to solve this question
"Make a query that shows the name and the worker's bonus based on the years working in the company:
If he takes between 1 and 5 years, he will be given 100 euros.
If he has between 6 and 10 years, he will be given 50 euros per year.
If he has between 11 and 20 years, he will be given 70 euros per year.
If he has more than 21 years, he will be given 100 euros per year"

Thats what I tried...
I have a table (named workers) with the information of them (admissiondate, name...)

  SELECT name, (EXTRACT(YEAR FROM SYSDATE)-EXTRACT(YEAR FROM admissiondate))*(CASE EXTRACT(YEAR FROM SYSDATE)-EXTRACT(YEAR FROM admissiondate)
    WHEN EXTRACT(YEAR FROM SYSDATE)-EXTRACT(YEAR FROM admissiondate)>21 THEN 100
    WHEN EXTRACT(YEAR FROM SYSDATE)-EXTRACT(YEAR FROM admissiondate)<=21 AND AND EXTRACT(YEAR FROM SYSDATE)-EXTRACT(YEAR FROM admissiondate)>10 THEN 70
    WHEN EXTRACT(YEAR FROM SYSDATE)-EXTRACT(YEAR FROM admissiondate)<=10 AND EXTRACT(YEAR FROM SYSDATE)-EXTRACT(YEAR FROM admissiondate)>4 THEN 50
    ELSE 100 END) AS Gratification
    FROM workers;

But it doesn't work. so, please, can you advice me anything useful?

Body:
Thanks all of you.
I think I have founded the solution.

SELECT name, CASE WHEN TRUNC(MONTHS_BETWEEN(SYSDATE, admissiondate)/12)>21 THEN 100*TRUNC(MONTHS_BETWEEN(SYSDATE, admissiondate)/12)
WHEN TRUNC(MONTHS_BETWEEN(SYSDATE, admissiondate)/12)<=21 AND TRUNC(MONTHS_BETWEEN(SYSDATE, admissiondate)/12)>10 THEN 70*TRUNC(MONTHS_BETWEEN(SYSDATE, admissiondate)/12)
WHEN TRUNC(MONTHS_BETWEEN(SYSDATE, admissiondate)/12)<=10 AND TRUNC(MONTHS_BETWEEN(SYSDATE, admissiondate)/12)>4 THEN 50*TRUNC(MONTHS_BETWEEN(SYSDATE, admissiondate)/12)
ELSE 100*TRUNC(MONTHS_BETWEEN(SYSDATE, admissiondate)/12) END AS "Gratification €"
    FROM workers
    ORDER BY name;


问:
Python Pandas - Missing required dependencies ['numpy'] 1
Since yesterday I've had this error when I try to import packages on anaconda :

ImportError: Missing required dependencies ['numpy']

I have tried un-installing Anaconda and Python, switching to Python 2.7 but nothing works it's still the same error, here is the code I get :

Any help is really appreciated thanks !

答:
For those who couldn't solve with the above answers:

Ensure that you are running python3 with

```<code>$ python version
</code>```

If not, install python3.

Then change default python to python3 with

```<code>$ alias python=python3
</code>```

Next, close your jupyter lab/notebook environment and re-launch it with default python being python3.

Body:
For those who couldn't solve with the above answers:

Ensure that you are running python3 with

$ python version

If not, install python3.

Then change default python to python3 with

$ alias python=python3

Next, close your jupyter lab/notebook environment and re-launch it with default python being python3.


问:
T-SQL Exclude scenarios where two or more records have two or more fields with the same value but one is different
Given the table below:

```<code>DECLARE @Data TABLE
              (
                   Id INT,
                   Branch VARCHAR(50),
                   Color VARCHAR(50),
                   Name VARCHAR(50),
                   Model VARCHAR(50)
               )

INSERT INTO @Data
VALUES (1, 'London', 'Red', 'Mazda 3', '2015'),
       (2, 'London', NULL, 'Mazda 3', '2015'),
       (3, 'London', 'Red', 'Mazda 2', '2014'),
       (4, 'London', 'Red', 'Fiesta', '2020'),
       (5, 'London', 'Yellow', 'Focus', '2010'),
       (6, 'London', NULL, 'Fiesta', '2020')
</code>```

Id
Branch
Color
Name
Model

1
London
Red
Mazda 3
2015

2
London
null
Mazda 3
2015

3
London
Red
Mazda 2
2014

4
London
Red
Fiesta
2020

5
London
Yellow
Focus
2010

6
London
null
Fiesta
2020

I am aiming to exclude those records where the Branch, Name and Model are the same, but one of the rows has a specific Color value and the second row is null.

So, I would be only returning the id's below as the desired result, so Id's 1,2,4 and 6 should be excluded.:

Id
Branch
Color
Name
Model

4
London
Blue
Fiesta
2020

5
London
Yellow
Focus
2010

I have tried the query below:

```<code>SELECT Data1.*
FROM @Data Data1
INNER JOIN @Data Data2 ON Data1.Branch = Data2.Branch
                       AND Data1.Name = Data2.Name
                       AND Data1.Model = Data2.Model
                       AND Data1.Color = Data2.Color
</code>```

But I still get the ones where the Color is not null as shown below.

Id
Branch
Color
Name
Model

1
London
Red
Mazda 3
2015

3
London
Red
Mazda 2
2014

4
London
Blue
Fiesta
2020

5
London
Yellow
Focus
2010

Any guidance will be really appreciated !

答:
Not 100% sure what you are trying to achieve, but it appears you want to only list data where color is populated in each row if there is more than 1 row

Filter using Duplicate Count vs Color Count

```<code>;WITH cte_Count AS (
SELECT ID
    ,Branch
    ,Name
    ,Model
    ,DupCnt = COUNT(*) OVER (PARTITION BY Branch,Name,Model)
    ,ColorCnt = COUNT(Color) OVER (PARTITION BY Branch,Name,Model)
FROM @Data
)

SELECT *
FROM cte_Count
WHERE DupCnt = 1 /*Only 1 row for that combo of Branch-Name-Model*/
OR DupCnt = ColorCnt /*Color populated in each row*/
</code>```

Body:
Given the table below:

DECLARE @Data TABLE
              (
                   Id INT,
                   Branch VARCHAR(50),
                   Color VARCHAR(50),
                   Name VARCHAR(50),
                   Model VARCHAR(50)
               )

INSERT INTO @Data
VALUES (1, 'London', 'Red', 'Mazda 3', '2015'),
       (2, 'London', NULL, 'Mazda 3', '2015'),
       (3, 'London', 'Red', 'Mazda 2', '2014'),
       (4, 'London', 'Red', 'Fiesta', '2020'),
       (5, 'London', 'Yellow', 'Focus', '2010'),
       (6, 'London', NULL, 'Fiesta', '2020')

Id
Branch
Color
Name
Model

1
London
Red
Mazda 3
2015

2
London
null
Mazda 3
2015

3
London
Red
Mazda 2
2014

4
London
Red
Fiesta
2020

5
London
Yellow
Focus
2010

6
London
null
Fiesta
2020

I am aiming to exclude those records where the Branch, Name and Model are the same, but one of the rows has a specific Color value and the second row is null.

So, I would be only returning the id's below as the desired result, so Id's 1,2,4 and 6 should be excluded.:

Id
Branch
Color
Name
Model

4
London
Blue
Fiesta
2020

5
London
Yellow
Focus
2010

I have tried the query below:

SELECT Data1.*
FROM @Data Data1
INNER JOIN @Data Data2 ON Data1.Branch = Data2.Branch
                       AND Data1.Name = Data2.Name
                       AND Data1.Model = Data2.Model
                       AND Data1.Color = Data2.Color

But I still get the ones where the Color is not null as shown below.

Id
Branch
Color
Name
Model

1
London
Red
Mazda 3
2015

3
London
Red
Mazda 2
2014

4
London
Blue
Fiesta
2020

5
London
Yellow
Focus
2010

Any guidance will be really appreciated !

Body:
Not 100% sure what you are trying to achieve, but it appears you want to only list data where color is populated in each row if there is more than 1 row

Filter using Duplicate Count vs Color Count

;WITH cte_Count AS (
SELECT ID
    ,Branch
    ,Name
    ,Model
    ,DupCnt = COUNT(*) OVER (PARTITION BY Branch,Name,Model)
    ,ColorCnt = COUNT(Color) OVER (PARTITION BY Branch,Name,Model)
FROM @Data
)

SELECT *
FROM cte_Count
WHERE DupCnt = 1 /*Only 1 row for that combo of Branch-Name-Model*/
OR DupCnt = ColorCnt /*Color populated in each row*/


问:
Make { and } ignore lines containing only whitespace
When you navigate by paragraph in vim using { and } it skips lines that contain nothing but whitespace though they are otherwise 'blank'.

How can I convince vim to treat "whitespace only" lines as paragraph breaks so { and } will jump to them?

答:
I finally caved and did something similar to
eremite. I previously had
Z mapped to {gq}, which reformats text from last
blank line to the next blank line. If lines
containing only spaces are not recognized as
boundaries, it can destroy a lot of intricate code
structures, and days of work. Undo is not an
option if I've switched buffers a few times using
<C-^>.

I leveraged a custom command command! Trim execute "normal \<S-m>" | % s=\s*$== | execute "normal \<C-o>z.\<C-o>" | set nohlsearch to
"Trim" all trailing spaces in my file. I have
expandtab enabled so I only ever have spaces, not
tabs. But it's easy enough to delete all trailing
space using \_s instead of \s. My new Z
command is nmap Z mq:Trim<CR>`q{gq}`q. I use
marker q to store my current cursor position,
then use  `q to return to it after the
reformatting.


答:
Would this do it?

while read -r line; do
  curl -XPOST http://localhost --data-raw "$line"
done < <(jq -r '"app=\(.apps.name) result=\(.result)"' myfile.json)
```

Title: Pass jq output to curl


问:
How to prevent the script from running the files it produced?
I'm writing a script to run AutoDock Vina. The script will look for all files with .pdbqt ending with ligand in front of it. When the script is run, it produces an output file with the same name of the file, but including _out.pdbqt on it. For example ligand_1.pdbqt becomes ligand_1_out.pdbqt. How can I prevent the ligand_1_out.pdbqt from being run in the script. The script is written below.</p>
```<code>#!/bin/bash
for x in ligand_*.pdbqt;
do
./vina_1.2.3_mac_x86_64 --config conf.txt --ligand $x
done
</code>```

答:
You should be able to avoid files containing "out" with:</p>
```<code>for x in ligand_*.pdbqt ; do
    [[ "$x" == *out** ]] && continue
    ./vina ...
done
</code>```

Body:
I'm writing a script to run AutoDock Vina. The script will look for all files with .pdbqt ending with ligand in front of it. When the script is run, it produces an output file with the same name of the file, but including _out.pdbqt on it. For example ligand_1.pdbqt becomes ligand_1_out.pdbqt. How can I prevent the ligand_1_out.pdbqt from being run in the script. The script is written below.

#!/bin/bash
for x in ligand_*.pdbqt;
do
./vina_1.2.3_mac_x86_64 --config conf.txt --ligand $x
done

Body:
You should be able to avoid files containing "out" with:

for x in ligand_*.pdbqt ; do
    [[ "$x" == *out** ]] && continue
    ./vina ...
done


问:
git: where is <git-root>/.git/config stored on repo/server?
Where does the local /.git/config come from?
i.e. on a fresh git clone, .git/config has some content.  How is it configured/altered so that the next git clone will have them?

By experiment, you can't make modifications to .git/config and push them.

They are surely stored someplace on the repo, but github doesn't seem to show a .git directory.

thanks in advance

答:
Where does the local /.git/config come from? i.e. on a fresh git clone, .git/config has some content. How is it configured/altered so that the next git clone will have them?

It's not. This file is local to your repository and is created by the git command when initializing your local directory. There would be substantial security implications if this file came from the remote repository (because it would allow someone to run arbitrary code on your system).

If you want to have consistent settings for multiple developers, the solution is to distribute some sort of script or instructions that can be used to correctly configure the repository. For example, a lot of people use the pre-commit command to help configure pre-commit hooks.


问:
Is if(A | B) always faster than if(A || B)?
I am reading this book by Fedor Pikus and he has some very very interesting examples which for me were a surprise.

Particularly this benchmark caught me, where the only difference is that in one of them we use || in if and in another we use |.

```<code>void BM_misspredict(benchmark::State& state)
{

    std::srand(1);
    const unsigned int N = 10000;;
    std::vector<unsigned long> v1(N), v2(N);
    std::vector<int> c1(N), c2(N);

    for (int i = 0; i < N; ++i)
    {
        v1[i] = rand();
        v2[i] = rand();
        c1[i] = rand() & 0x1;
        c2[i] = !c1[i];
    }

    unsigned long* p1 = v1.data();
    unsigned long* p2 = v2.data();
    int* b1 = c1.data();
    int* b2 = c2.data();

    for (auto _ : state)
    {
        unsigned long a1 = 0, a2 = 0;
        for (size_t i = 0; i < N; ++i)
        {
            if (b1[i] || b2[i])  // Only difference
            {
                a1 += p1[i];
            }
            else
            {
                a2 *= p2[i];
            }
        }
        benchmark::DoNotOptimize(a1);
        benchmark::DoNotOptimize(a2);
        benchmark::ClobberMemory();

    }
    state.SetItemsProcessed(state.iterations());
}

void BM_predict(benchmark::State& state)
{

    std::srand(1);
    const unsigned int N = 10000;;
    std::vector<unsigned long> v1(N), v2(N);
    std::vector<int> c1(N), c2(N);

    for (int i = 0; i < N; ++i)
    {
        v1[i] = rand();
        v2[i] = rand();
        c1[i] = rand() & 0x1;
        c2[i] = !c1[i];
    }

    unsigned long* p1 = v1.data();
    unsigned long* p2 = v2.data();
    int* b1 = c1.data();
    int* b2 = c2.data();

    for (auto _ : state)
    {
        unsigned long a1 = 0, a2 = 0;
        for (size_t i = 0; i < N; ++i)
        {
            if (b1[i] | b2[i]) // Only difference
            {
                a1 += p1[i];
            }
            else
            {
                a2 *= p2[i];
            }
        }
        benchmark::DoNotOptimize(a1);
        benchmark::DoNotOptimize(a2);
        benchmark::ClobberMemory();

    }
    state.SetItemsProcessed(state.iterations());
}
</code>```

I will not go in all the details explained in the book why the latter is faster, but the idea is that hardware branch predictor is given 2 chances to misspredict in slower version and in the | (bitwise or) version. See the benchmark results below.

So the question is why don't we always use | instead of || in branches?

答:
Code readability, short-circuiting and it is not guaranteed that Ord will always outperform a || operand.
Computer systems are more complicated than expected, even though they are man-made.

There was a case where a for loop with a much more complicated condition ran faster on an IBM. The CPU didn't cool and thus instructions were executed faster, that was a possible reason. What I am trying to say, focus on other areas to improve code than fighting small-cases which will differ depending on the CPU and the boolean evaluation (compiler optimizations).

Body:
I am reading this book by Fedor Pikus and he has some very very interesting examples which for me were a surprise.

Particularly this benchmark caught me, where the only difference is that in one of them we use || in if and in another we use |.

void BM_misspredict(benchmark::State& state)
{

    std::srand(1);
    const unsigned int N = 10000;;
    std::vector<unsigned long> v1(N), v2(N);
    std::vector<int> c1(N), c2(N);

    for (int i = 0; i < N; ++i)
    {
        v1[i] = rand();
        v2[i] = rand();
        c1[i] = rand() & 0x1;
        c2[i] = !c1[i];
    }

    unsigned long* p1 = v1.data();
    unsigned long* p2 = v2.data();
    int* b1 = c1.data();
    int* b2 = c2.data();

    for (auto _ : state)
    {
        unsigned long a1 = 0, a2 = 0;
        for (size_t i = 0; i < N; ++i)
        {
            if (b1[i] || b2[i])  // Only difference
            {
                a1 += p1[i];
            }
            else
            {
                a2 *= p2[i];
            }
        }
        benchmark::DoNotOptimize(a1);
        benchmark::DoNotOptimize(a2);
        benchmark::ClobberMemory();

    }
    state.SetItemsProcessed(state.iterations());
}

void BM_predict(benchmark::State& state)
{

    std::srand(1);
    const unsigned int N = 10000;;
    std::vector<unsigned long> v1(N), v2(N);
    std::vector<int> c1(N), c2(N);

    for (int i = 0; i < N; ++i)
    {
        v1[i] = rand();
        v2[i] = rand();
        c1[i] = rand() & 0x1;
        c2[i] = !c1[i];
    }

    unsigned long* p1 = v1.data();
    unsigned long* p2 = v2.data();
    int* b1 = c1.data();
    int* b2 = c2.data();

    for (auto _ : state)
    {
        unsigned long a1 = 0, a2 = 0;
        for (size_t i = 0; i < N; ++i)
        {
            if (b1[i] | b2[i]) // Only difference
            {
                a1 += p1[i];
            }
            else
            {
                a2 *= p2[i];
            }
        }
        benchmark::DoNotOptimize(a1);
        benchmark::DoNotOptimize(a2);
        benchmark::ClobberMemory();

    }
    state.SetItemsProcessed(state.iterations());
}

I will not go in all the details explained in the book why the latter is faster, but the idea is that hardware branch predictor is given 2 chances to misspredict in slower version and in the | (bitwise or) version. See the benchmark results below.

So the question is why don't we always use | instead of || in branches?


问:
How do I manipulate specific components in React?
I'm learning ReactJS. I'm generating a sorting visualizer. What I did

```<code>function Box(props){
    return(<span x={props.xyz} className="box">
        {props.data}
    </span>)
}

const [mynums,setMynums] = useState([7,1,3,12,25,2,5,0])
  let numsList = mynums.map( (item,index) =>{
    return <Box data={item}  key={index} xyz={index}></Box>
  })
  return (
    <div className="App">
      <div className="App">
        {numsList}
        </div>
    </div>
</code>```

So basically I have Box with value inside based on my array.

I'm having trouble to select a specific box to sort it.
I know we can add a onClick to get the props of the component, but what if theres all the components are generated through an array of data? I want to manipulate a specific component base on the index of the array.

答:
I figure out just now that even though we use ReactJS , the fundamentals of WebAPI is still there.

To select a specific DOM from a State that holds Array.

Since i render the component all have the same class.

```<code>//To get the arrayBox
const arrayBox = document.getElementsByClassName("box");
thisBox[index].style.backgroundColor = "red";
setTimeout(() => { setMynums([...mynums]); }, 2000);
</code>```

Body:
I'm learning ReactJS. I'm generating a sorting visualizer. What I did

function Box(props){
    return(
        {props.data}
    )
}

const [mynums,setMynums] = useState([7,1,3,12,25,2,5,0])
  let numsList = mynums.map( (item,index) =>{
    return <Box data={item}  key={index} xyz={index}></Box>
  })
  return (

        {numsList}

So basically I have Box with value inside based on my array.

I'm having trouble to select a specific box to sort it.
I know we can add a onClick to get the props of the component, but what if theres all the components are generated through an array of data? I want to manipulate a specific component base on the index of the array.

Body:
I figure out just now that even though we use ReactJS , the fundamentals of WebAPI is still there.

To select a specific DOM from a State that holds Array.

Since i render the component all have the same class.

//To get the arrayBox
const arrayBox = document.getElementsByClassName("box");
thisBox[index].style.backgroundColor = "red";
setTimeout(() => { setMynums([...mynums]); }, 2000);


问:
Can I set up Wal Archiving on a three years old Postgres database?
If I set up Wal Archiving on a three years old Postgres database (used in production); do the Continuous Archiving and Point-in-Time Recovery (PITR) will work from the beginning? Will I have all the data?

For example: So if I enabled wal archiving 3 days ago, and I want to restore to yesterday. Will I have all the data from the beginning? Or only the data from 3 days ago to yesterday?

答: You need a valid base backup to go with your WAL archive, which is slightly newer than the archive is but is older than yesterday.  If you have that and restore to yesterday, then data from two years ago which was deleted today will be there, as it was present yesterday.  Data from two years ago deleted 5 days ago will of course not be there.</p>


问:
Find out which remote branch a local branch is tracking

See also:

  How can I see which Git branches are tracking which remote / upstream branch?

How can I find out which remote branch a local branch is tracking?

Do I need to parse git config output, or is there a command that would do this for me?

答:
git branch -vv | grep 'hardcode-branch-name'
# "git rev-parse --abbrev-ref head" will get your current branch name
# $(git rev-parse --abbrev-ref head) save it as string
#  find the tracking branch by grep filtering the current branch
git branch -vv | grep $(git rev-parse --abbrev-ref head)
```

OwnerDisplayName: Readonly


问:
Accessing QObject subclasses from other threads
I need some help understanding the details of accessing QObject subclasses from other threads.

From Qt documentation:

"If you are calling a function on an QObject subclass that doesn't live in the current thread and the object might receive events, you must protect all access to your QObject subclass's internal data with a mutex; otherwise, you may experience crashes or other undesired behavior."

Consider the following classes:

```<code>// Created on stack in main() => thread affinity = main thread
class Model : public QObject {
    Q_OBJECT
public:
    int getValue() const {
        return m_value;
    }
signals:
    void error(QString err);
public slots:
    void incrementValue() {
        m_value++;
    };
    void threadError(QString err) {
        emit error(err);
    }
private:
    std::atomic<int> m_value = 0;
}

class Thread : public QThread {
    Q_OBJECT
public:
    Thread(Model* model) : QThread(), m_model(model) {}
signals:
    void incrementValue();
    void error(QString err);
private:
    void run() override; // calls m_model->getValue(), emits incrementValue()
    Model* m_model;
};
</code>```

Also assume that there is a Widget class with a QPushButton that when clicked calls the incrementValue() slot. Thread also occasionally emits the incrementValue signal and this is connected to the incrementValue() slot.

There is a potential data race:
incrementValue() may be called simultaneously from the main thread by the user clicking the QPushButton as getValue() from a non main thread by Thread::run().
However since the m_value variable is atomic this is safe?

I guess it comes down to what constitutes the "QObject subclass's internal data".
In my example m_value clearly is internal data.
What else?
Does the Q_OBJECT macro expand to variables that I need to mutex protect?

There is nothing in the above that is specific to QObject.
In other words I have the same potential problems with multiple threads as if Model did not inherit from QObject.
Qt does not fix my multithread problems in this case for me, but do not either introduce any new problems.
Is this correct?

To simplify the discussion:
both Model and Thread are as pure C++ as possible.
I do not use QTimer, QTcpSocket, event loop inside Thread or anything else Qt. Nor do I call moveToThread. The only thing I use Qt for in this context is its signal/slot mechanism (and QString).

One possible, but cumbersome, solution that I see is:
rewrite Model to NOT subclass QObject.
Introduce:

```<code>class Gui2Model : public QObject {
Q_OBJECT
public:
   Gui2Model(Model* model) : m_model(model) {}
signals:
   void error(QString err);
public slots:
   void incrementValue() {
      m_model->incrementValue();
   }
   void errorSlot(QString err) {
     emit error(err);
   }
private:
   Model* m_model;
};
</code>```

Connect the increment QPushButton clicked signal to the Gui2Model::incrementValue() slot.

Signal errors from Thread by calling:

```<code>void Model::error(QString err) {
    QMetaObject::invokeMethod(m_gui2model, "errorSlot", Qt::QueuedConnection, Q_ARG(QString, err));
}
</code>```

That way I take the full burden of synchronizing Model, but at least it happens according to rules which I (should) know from standard C++.

答:
Is it sufficient to rewrite the m_value variable to be std::atomic?

Assuming you join the thread before the model is destroyed, I think yes.

There is nothing in the above that is specific to QObject.

I think they wanted to stress "the object might receive events" part, which may not be a direct call in your code, but a signal/slot connection. And signal/slot connections would be specific to QObject.

In a very twisted scenario, you could have both a signal from you thread and a direct call from your thread, which would create a race condition :-)

As a rule it may perhaps be OK to pass const Model* to the Thread object. It should be safe to call const methods on the Model since these do not change the state of the Model?

If the model is created const, then yes. Actually, there wouldn't be much choice in such case. But if the model is created non-const, and the value could change from the main thread while accessing it from your thread, then the access to it would still need to be synchronized.

Body:
I need some help understanding the details of accessing QObject subclasses from other threads.

From Qt documentation:

"If you are calling a function on an QObject subclass that doesn't live in the current thread and the object might receive events, you must protect all access to your QObject subclass's internal data with a mutex; otherwise, you may experience crashes or other undesired behavior."

Consider the following classes:

// Created on stack in main() => thread affinity = main thread
class Model : public QObject {
    Q_OBJECT
public:
    int getValue() const {
        return m_value;
    }
signals:
    void error(QString err);
public slots:
    void incrementValue() {
        m_value++;
    };
    void threadError(QString err) {
        emit error(err);
    }
private:
    std::atomic<int> m_value = 0;
}

class Thread : public QThread {
    Q_OBJECT
public:
    Thread(Model* model) : QThread(), m_model(model) {}
signals:
    void incrementValue();
    void error(QString err);
private:
    void run() override; // calls m_model->getValue(), emits incrementValue()
    Model* m_model;
};

Also assume that there is a Widget class with a QPushButton that when clicked calls the incrementValue() slot. Thread also occasionally emits the incrementValue signal and this is connected to the incrementValue() slot.

There is a potential data race:
incrementValue() may be called simultaneously from the main thread by the user clicking the QPushButton as getValue() from a non main thread by Thread::run().
However since the m_value variable is atomic this is safe?

I guess it comes down to what constitutes the "QObject subclass's internal data".
In my example m_value clearly is internal data.
What else?
Does the Q_OBJECT macro expand to variables that I need to mutex protect?

There is nothing in the above that is specific to QObject.
In other words I have the same potential problems with multiple threads as if Model did not inherit from QObject.
Qt does not fix my multithread problems in this case for me, but do not either introduce any new problems.
Is this correct?

To simplify the discussion:
both Model and Thread are as pure C++ as possible.
I do not use QTimer, QTcpSocket, event loop inside Thread or anything else Qt. Nor do I call moveToThread. The only thing I use Qt for in this context is its signal/slot mechanism (and QString).

One possible, but cumbersome, solution that I see is:
rewrite Model to NOT subclass QObject.
Introduce:

class Gui2Model : public QObject {
Q_OBJECT
public:
   Gui2Model(Model* model) : m_model(model) {}
signals:
   void error(QString err);
public slots:
   void incrementValue() {
      m_model->incrementValue();
   }
   void errorSlot(QString err) {
     emit error(err);
   }
private:
   Model* m_model;
};

Connect the increment QPushButton clicked signal to the Gui2Model::incrementValue() slot.

Signal errors from Thread by calling:

void Model::error(QString err) {
    QMetaObject::invokeMethod(m_gui2model, "errorSlot", Qt::QueuedConnection, Q_ARG(QString, err));
}

That way I take the full burden of synchronizing Model, but at least it happens according to rules which I (should) know from standard C++.


问:
SymPy: How can i output multiple LaTex equations in one cell in Google Colab?
I am using SymPy in Google Colab. Each cell outputs only 1 pretty LaTex output. Can i have multiple pretty outputs in one cell or do i have to create a new cell for each pretty output?</p>

答:
I was struggling with this as well, but I found some information here: https://www.roelpeters.be/jupyter-notebooks-how-to-print-multiple-outputs-in-a-cell/

With your import statements, put

```<code>from IPython.core.interactiveshell import InteractiveShell
InteractiveShell.ast_node_interactivity = 'all'
</code>```

Now you can print multiple outputs (LaTeX in this case) to the cell output. Technically this command concatenates the outputs but because we are using dataframes in this case (correct me if I'm wrong) then the output is actually placed on a new line in the cell output area.

Example

```<code>from sympy import *
from IPython.core.interactiveshell import InteractiveShell
InteractiveShell.ast_node_interactivity = 'all'

x = symbols('x')
f = exp(x**2);#f
df = diff(f,x);#df

f
df
</code>```

I cannot guarantee this is the correct or most efficient way to implement such behavior, but it works for my purposes.

Body:
I was struggling with this as well, but I found some information here: https://www.roelpeters.be/jupyter-notebooks-how-to-print-multiple-outputs-in-a-cell/

With your import statements, put

from IPython.core.interactiveshell import InteractiveShell
InteractiveShell.ast_node_interactivity = 'all'

Now you can print multiple outputs (LaTeX in this case) to the cell output. Technically this command concatenates the outputs but because we are using dataframes in this case (correct me if I'm wrong) then the output is actually placed on a new line in the cell output area.

Example

from sympy import *
from IPython.core.interactiveshell import InteractiveShell
InteractiveShell.ast_node_interactivity = 'all'

x = symbols('x')
f = exp(x**2);#f
df = diff(f,x);#df

f
df

I cannot guarantee this is the correct or most efficient way to implement such behavior, but it works for my purposes.


问:
Differentiate User and Owner Info in Apps Script Installable Trigger
When I call Session.getActiveUser() from a function called by an installable trigger (e.g. an OnOpen Event trigger in Google Sheets - but not the Simple Trigger) in Apps Script, what user information am I getting?

I understand that installable triggers run under the owner/creator of the trigger regardless of who has opened the sheet. So would this always return that person's info?

Either way, how do I get the information of the other person? (e.g. if it gives owner info, how do I get the info of the user actually opening it - and vice-versa)

Update:

I got another user to test my script. I watched the logs while they were in the file, and it definitely reported THEM as the user, even when the installable OnOpen trigger was triggered.

This is good from the perspective that it showed them the correct menu options - he and I saw different menus per my OnOpen script, which is what I want.

However, this raises two issues for me:

This seems to go against the Google Documentation, which states: "Installable triggers always run under the account of the person who created them. For example, if you create an installable open trigger, it runs when your colleague opens the document (if your colleague has edit access), but it runs as your account. This means that if you create a trigger to send an email when a document is opened, the email is always sent from your account, not necessarily the account that opened the document."

In a future function, I will be calling an API from another App. This API will need my credentials (API ID and Secret). I was hoping / expecting that I could "sandbox" my credentials in an installable trigger - invisible to other users - that will allow them to use my credentials just for the specific functions which I would script into the API. If the installable trigger is in fact, NOT using my credentials, then how can I do this? I don't want to have to make every user go to the other App and generate their own set of API credentials, that will be unsustainable in this organization, and not everyone should need to do that.

答:
It should return whomever triggered the script. But it depends if the security policy does allow you to access the user's identity. Seeing the documentation:

Gets information about the current user. If security policies do not allow access to the user's identity, User.getEmail() returns a blank string. The circumstances in which the email address is available vary: for example, the user's email address is not available in any context that allows a script to run without that user's authorization, like a simple onOpen(e) or onEdit(e) trigger, a custom function in Google Sheets, or a web app deployed to "execute as me" (that is, authorized by the developer instead of the user).

I have tested it and even an installable trigger won't return anything if it belongs to a different organization.

But you might be able to if other users belong to the same organization.

However, these restrictions generally do not apply if the developer runs the script themselves or belongs to the same Google Workspace domain as the user.

Workaround:

One thing I guess would be to assign the triggered function into a button and have the users click that upon opening the sheet. Via clicking the button, I have been able to show the User object using that method.

Or a webapp that will serve as a relay and will get the User details.