问:
TypeScript Reset countdown timer when all questions have been answered or timer hits zero
I followed a tutorial online for a react quiz using typescript. I have the countdown/timer working (with help from a friend) but now I am looking to reset it back to the original countdown value when either the last question has been answered or when the countdown timer has reached zero seconds.

App.tsx

```<code>import React, { useEffect, useState } from 'react';
// Components
import QuestionCard from './components/QuestionCard';
// Types
import { QuestionState } from './API';
import Timer, { useTimer } from './components/Timer';

import StartButton from './components/StartButton';

export type AnswerObject = {
   question: string;
   answer: string;
   correct: boolean;
   correctAnswer: string;
};

const TOTAL_QUESTIONS = 10;
const TIME_ALLOWED = 20;

const App = () => {
   const [loading, setLoading] = useState(false);
   const [questions, setQuestions] = useState<QuestionState[]>([]);
   const [number, setNumber] = useState(0);
   const [userAnswers, setUserAnswers] = useState<AnswerObject[]>([]);
   const [score, setScore] = useState(0);
   const [gameOver, setGameOver] = useState(true);

   const { timeRemaining, toggle, reset, isActive } = useTimer(TIME_ALLOWED);

   const checkAnswer = (e: React.MouseEvent<HTMLButtonElement>) => {
      if (!gameOver) {
         //Users answer
         const answer = e.currentTarget.value;
         // Check answer against correct answer
         const correct = questions[number].correct_answer === answer;
         // Add score if answer is correct
         if (correct) setScore((prev) => prev + 1);
         // Save answer in the array for user answers
         const answerObject = {
            question: questions[number].question,
            answer,
            correct,
            correctAnswer: questions[number].correct_answer,
         };
         setUserAnswers((prev) => [...prev, answerObject]);
         console.log({ answerObject });
      }
   };

   const nextQuestion = () => {
      // Move on to the next question if not the last question
      const nextQuestion = number + 1;

      if (nextQuestion === TOTAL_QUESTIONS) {
         setGameOver(true);
      } else {
         setNumber(nextQuestion);
      }
   };

   useEffect(() => {
      // If the timer reaches 0, the game is over
      if (timeRemaining <= 0) {
         setGameOver(true);
      }
   }, [timeRemaining]);

   return (
      <div className="App">
         <h1>REACT QUIZ</h1>
         {(gameOver || userAnswers.length === TOTAL_QUESTIONS) && (
            <StartButton
               setLoading={setLoading}
               setQuestions={setQuestions}
               setUserAnswers={setUserAnswers}
               setNumber={setNumber}
               setScore={setScore}
               setGameOver={setGameOver}
               toggleTimer={toggle}
            />
         )}

         {!gameOver ? <p className="score">Score: {score}</p> : null}
         {loading && <p>Loading Questions...</p>}
         {!loading && !gameOver && (
            <QuestionCard
               questionNr={number + 1}
               totalQuestions={TOTAL_QUESTIONS}
               question={questions[number].question}
               answers={questions[number].answers}
               userAnswer={userAnswers ? userAnswers[number] : undefined}
               callback={checkAnswer}
            />
         )}
         {!gameOver &&
         !loading &&
         userAnswers.length === number + 1 &&
         number !== TOTAL_QUESTIONS - 1 ? (
            <button className="next" onClick={nextQuestion}>
               Next Question
            </button>
         ) : null}
         <Timer
            timeRemaining={timeRemaining}
            isActive={isActive}
            toggle={toggle}
            reset={reset}
         />
      </div>
   );
};

export default App;

</code>```

Timer.tsx

```<code>import React, { useMemo, useState, useEffect } from 'react';

export const useTimer = (timeAllowed: number) => {
   const [seconds, setSeconds] = useState(0);
   const [isActive, setIsActive] = useState(false);

   const timeRemaining = useMemo(
      () => timeAllowed - seconds,
      [timeAllowed, seconds]
   );
   function toggle() {
      setIsActive(!isActive);
   }

   function reset() {
      setSeconds(0);
      setIsActive(false);
   }

   useEffect(() => {
      let interval: any = null;
      if (isActive) {
         interval = setInterval(() => {
            setSeconds((seconds) => seconds + 1);
         }, 1000);
      } else if (!isActive && seconds !== 0) {
         clearInterval(interval);
      }
      return () => clearInterval(interval);
   }, [isActive, seconds]);

   return { timeRemaining, toggle, reset, isActive };
};

const Timer = ({ timeRemaining }: any) => {
   return <p className="time">{timeRemaining}s</p>;
};

export default Timer;
</code>```

Startbutton.tsx

```<code>import React, { useState } from 'react';
import { Difficulty, fetchQuizQuestions } from '../API';

export type AnswerObject = {
   question: string;
   answer: string;
   correct: boolean;
   correctAnswer: string;
};

const TOTAL_QUESTIONS = 10;

interface IStartButton {
   setLoading: React.Dispatch<React.SetStateAction<boolean>>;
   setQuestions: React.Dispatch<React.SetStateAction<any>>;
   setUserAnswers: React.Dispatch<React.SetStateAction<any>>;
   setNumber: React.Dispatch<React.SetStateAction<any>>;
   setScore: React.Dispatch<React.SetStateAction<any>>;
   setGameOver: React.Dispatch<React.SetStateAction<boolean>>;
   toggleTimer: () => void;
}
const StartButton = ({
   setLoading,
   setQuestions,
   setUserAnswers,
   setNumber,
   setScore,
   setGameOver,
   toggleTimer,
}: IStartButton) => {
   const startTrivia = async () => {
      setLoading(true);
      setGameOver(false);

      const newQuestions = await fetchQuizQuestions(
         TOTAL_QUESTIONS,
         Difficulty.EASY
      );
      toggleTimer();
      setQuestions(newQuestions);
      setScore(0);
      setUserAnswers([]);
      setNumber(0);
      setLoading(false);
   };

   return (
      <button className="start" onClick={startTrivia}>
         Start
      </button>
   );
};

export default StartButton;
</code>```

I thought about adding to the nextQuestion function in the if else statement that the Timer function would reset, but I wasn't too sure because of the useEffect in timer.tsx. So far when all the questions have been answered the timer keeps going until you hit the start button again. Thanks for the help in advance.

Body:
I followed a tutorial online for a react quiz using typescript. I have the countdown/timer working (with help from a friend) but now I am looking to reset it back to the original countdown value when either the last question has been answered or when the countdown timer has reached zero seconds.

App.tsx

import React, { useEffect, useState } from 'react';
// Components
import QuestionCard from './components/QuestionCard';
// Types
import { QuestionState } from './API';
import Timer, { useTimer } from './components/Timer';

import StartButton from './components/StartButton';

export type AnswerObject = {
   question: string;
   answer: string;
   correct: boolean;
   correctAnswer: string;
};

const TOTAL_QUESTIONS = 10;
const TIME_ALLOWED = 20;

const App = () => {
   const [loading, setLoading] = useState(false);
   const [questions, setQuestions] = useState<QuestionState[]>([]);
   const [number, setNumber] = useState(0);
   const [userAnswers, setUserAnswers] = useState<AnswerObject[]>([]);
   const [score, setScore] = useState(0);
   const [gameOver, setGameOver] = useState(true);

   const { timeRemaining, toggle, reset, isActive } = useTimer(TIME_ALLOWED);

   const checkAnswer = (e: React.MouseEvent<HTMLButtonElement>) => {
      if (!gameOver) {
         //Users answer
         const answer = e.currentTarget.value;
         // Check answer against correct answer
         const correct = questions[number].correct_answer === answer;
         // Add score if answer is correct
         if (correct) setScore((prev) => prev + 1);
         // Save answer in the array for user answers
         const answerObject = {
            question: questions[number].question,
            answer,
            correct,
            correctAnswer: questions[number].correct_answer,
         };
         setUserAnswers((prev) => [...prev, answerObject]);
         console.log({ answerObject });
      }
   };

   const nextQuestion = () => {
      // Move on to the next question if not the last question
      const nextQuestion = number + 1;

      if (nextQuestion === TOTAL_QUESTIONS) {
         setGameOver(true);
      } else {
         setNumber(nextQuestion);
      }
   };

   useEffect(() => {
      // If the timer reaches 0, the game is over
      if (timeRemaining <= 0) {
         setGameOver(true);
      }
   }, [timeRemaining]);

   return (

REACT QUIZ

         {(gameOver || userAnswers.length === TOTAL_QUESTIONS) && (
            <StartButton
               setLoading={setLoading}
               setQuestions={setQuestions}
               setUserAnswers={setUserAnswers}
               setNumber={setNumber}
               setScore={setScore}
               setGameOver={setGameOver}
               toggleTimer={toggle}
            />
         )}

         {!gameOver ?
Score: {score}
 : null}
         {loading &&
Loading Questions...
}
         {!loading && !gameOver && (
            <QuestionCard
               questionNr={number + 1}
               totalQuestions={TOTAL_QUESTIONS}
               question={questions[number].question}
               answers={questions[number].answers}
               userAnswer={userAnswers ? userAnswers[number] : undefined}
               callback={checkAnswer}
            />
         )}
         {!gameOver &&
         !loading &&
         userAnswers.length === number + 1 &&
         number !== TOTAL_QUESTIONS - 1 ? (
            <button className="next" onClick={nextQuestion}>
               Next Question
            </button>
         ) : null}
         <Timer
            timeRemaining={timeRemaining}
            isActive={isActive}
            toggle={toggle}
            reset={reset}
         />

   );
};

export default App;

Timer.tsx

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

export const useTimer = (timeAllowed: number) => {
   const [seconds, setSeconds] = useState(0);
   const [isActive, setIsActive] = useState(false);

   const timeRemaining = useMemo(
      () => timeAllowed - seconds,
      [timeAllowed, seconds]
   );
   function toggle() {
      setIsActive(!isActive);
   }

   function reset() {
      setSeconds(0);
      setIsActive(false);
   }

   useEffect(() => {
      let interval: any = null;
      if (isActive) {
         interval = setInterval(() => {
            setSeconds((seconds) => seconds + 1);
         }, 1000);
      } else if (!isActive && seconds !== 0) {
         clearInterval(interval);
      }
      return () => clearInterval(interval);
   }, [isActive, seconds]);

   return { timeRemaining, toggle, reset, isActive };
};

const Timer = ({ timeRemaining }: any) => {
   return
{timeRemaining}s
;
};

export default Timer;

Startbutton.tsx

import React, { useState } from 'react';
import { Difficulty, fetchQuizQuestions } from '../API';

export type AnswerObject = {
   question: string;
   answer: string;
   correct: boolean;
   correctAnswer: string;
};

const TOTAL_QUESTIONS = 10;

interface IStartButton {
   setLoading: React.Dispatch<React.SetStateAction<boolean>>;
   setQuestions: React.Dispatch<React.SetStateAction<any>>;
   setUserAnswers: React.Dispatch<React.SetStateAction<any>>;
   setNumber: React.Dispatch<React.SetStateAction<any>>;
   setScore: React.Dispatch<React.SetStateAction<any>>;
   setGameOver: React.Dispatch<React.SetStateAction<boolean>>;
   toggleTimer: () => void;
}
const StartButton = ({
   setLoading,
   setQuestions,
   setUserAnswers,
   setNumber,
   setScore,
   setGameOver,
   toggleTimer,
}: IStartButton) => {
   const startTrivia = async () => {
      setLoading(true);
      setGameOver(false);

      const newQuestions = await fetchQuizQuestions(
         TOTAL_QUESTIONS,
         Difficulty.EASY
      );
      toggleTimer();
      setQuestions(newQuestions);
      setScore(0);
      setUserAnswers([]);
      setNumber(0);
      setLoading(false);
   };

   return (
      <button className="start" onClick={startTrivia}>
         Start
      </button>
   );
};

export default StartButton;

I thought about adding to the nextQuestion function in the if else statement that the Timer function would reset, but I wasn't too sure because of the useEffect in timer.tsx. So far when all the questions have been answered the timer keeps going until you hit the start button again. Thanks for the help in advance.


来源: stackexchange

问:
Is there a list of platform native libraries that are already available in Kotlin?
The following documentation states that there are many native libraries already wrapped up for Kotlin usage.

There are many more platform libraries available for host and cross-compilation targets. Kotlin/Native distribution provides access to OpenGL, zlib and other popular native libraries on applicable platforms. - https://kotlinlang.org/docs/native-platform-libs.html#popular-native-libraries

Question comes up: is there a list of native libraries that are available for this usage?

And if not how to check if a library already has such a wrapper?

ContentLicense: CC BY-SA 4.0


问:
how to check Java is running inside a container enviroment by Java
I need to check is my springboot is running in a docker container or not. I am doing it as following. I don't know if .dockerenv is always on root or not. If it is not correct. How to do it by java?

```<code>public static boolean isRunningInsideDocker() {
    if(Files.exists(Path.of("/.dockerenv"))){
        return true;
    }else{
        return false;
    }
}
</code>```

Body:
I need to check is my springboot is running in a docker container or not. I am doing it as following. I don't know if .dockerenv is always on root or not. If it is not correct. How to do it by java?

public static boolean isRunningInsideDocker() {
    if(Files.exists(Path.of("/.dockerenv"))){
        return true;
    }else{
        return false;
    }
}


问:
How to configure mail.php and service.php in laravel 9 project when i use Sendinblue smtp service
In development it works perfectly, the emails reach the recipient, but when I display the project in cpanel I get a 500 error when my client presses the send button.

Currently my configuration is like this:

.ENV:

```<code>MAIL_MAILER=smtp
MAIL_HOST=smtp-relay.sendinblue.com
MAIL_PORT=587
MAIL_USERNAME=myEmailUserSendinblue
MAIL_PASSWORD=passwordMySendiblueService
MAIL_ENCRYPTION=tls
MAIL_FROM_ADDRESS="EmailClient"
MAIL_FROM_NAME="${APP_NAME}"
SENDINBLUE_API_KEY=xxxxxxxxxxxxxxxxxxxxxxx
</code>```

mail.php:

```<code>'mailers' => [
        'sendinblue' => [
            'transport' => 'sendinblue',
            'host' => env('MAIL_HOST', 'smtp-relay.sendinblue.com'),
            'port' => env('MAIL_PORT', 587),
            'encryption' => env('MAIL_ENCRYPTION', 'tls'),
            'username' => env('MAIL_USERNAME'),
            'password' => env('MAIL_PASSWORD'),

        ],
</code>```

services.php:

```<code>return [
    'sendinblue' => [
    'api_key' => env('SENDINBLUE_API_KEY'),
    ],
    'mailgun' => [
        'domain' => env('MAILGUN_DOMAIN'),
        'secret' => env('MAILGUN_SECRET'),
        'endpoint' => env('MAILGUN_ENDPOINT', 'api.mailgun.net'),
        'scheme' => 'https',
    ],

    'postmark' => [
        'token' => env('POSTMARK_TOKEN'),
    ],

    'ses' => [
        'key' => env('AWS_ACCESS_KEY_ID'),
        'secret' => env('AWS_SECRET_ACCESS_KEY'),
        'region' => env('AWS_DEFAULT_REGION', 'us-east-1'),
    ],

];
</code>```

Thank you very much in advance, I remain attentive to your comments.

EDIT 1:
I got an error through the laravel logs, it is as follows:
production.ERROR: Unsupported mail transport [sendinblue]. {"exception":"[object] (InvalidArgumentException(code: 0): Unsupported mail transport [sendinblue]. at /home/-------/public_html/vendor/laravel/framework/src/Illuminate/Mail/MailManager.php:157)
[stacktrace]

Body:
In development it works perfectly, the emails reach the recipient, but when I display the project in cpanel I get a 500 error when my client presses the send button.

Currently my configuration is like this:

.ENV:

MAIL_MAILER=smtp
MAIL_HOST=smtp-relay.sendinblue.com
MAIL_PORT=587
MAIL_USERNAME=myEmailUserSendinblue
MAIL_PASSWORD=passwordMySendiblueService
MAIL_ENCRYPTION=tls
MAIL_FROM_ADDRESS="EmailClient"
MAIL_FROM_NAME="${APP_NAME}"
SENDINBLUE_API_KEY=xxxxxxxxxxxxxxxxxxxxxxx

mail.php:

'mailers' => [
        'sendinblue' => [
            'transport' => 'sendinblue',
            'host' => env('MAIL_HOST', 'smtp-relay.sendinblue.com'),
            'port' => env('MAIL_PORT', 587),
            'encryption' => env('MAIL_ENCRYPTION', 'tls'),
            'username' => env('MAIL_USERNAME'),
            'password' => env('MAIL_PASSWORD'),

        ],

services.php:

return [
    'sendinblue' => [
    'api_key' => env('SENDINBLUE_API_KEY'),
    ],
    'mailgun' => [
        'domain' => env('MAILGUN_DOMAIN'),
        'secret' => env('MAILGUN_SECRET'),
        'endpoint' => env('MAILGUN_ENDPOINT', 'api.mailgun.net'),
        'scheme' => 'https',
    ],

    'postmark' => [
        'token' => env('POSTMARK_TOKEN'),
    ],

    'ses' => [
        'key' => env('AWS_ACCESS_KEY_ID'),
        'secret' => env('AWS_SECRET_ACCESS_KEY'),
        'region' => env('AWS_DEFAULT_REGION', 'us-east-1'),
    ],

];

Thank you very much in advance, I remain attentive to your comments.

EDIT 1:
I got an error through the laravel logs, it is as follows:
production.ERROR: Unsupported mail transport [sendinblue]. {"exception":"[object] (InvalidArgumentException(code: 0): Unsupported mail transport [sendinblue]. at /home/-------/public_html/vendor/laravel/framework/src/Illuminate/Mail/MailManager.php:157)
[stacktrace]


问:
Calling a class objects name within the class
I have a class that I want to print it's name within a method

In the class file

```<code>class Example():
   def __init__(self,x):
      self.x = x
      if self.x == True:
         print(#Name of class object)
</code>```

In main

```<code>from class_file.py import Example

abc = Example(True)
</code>```

And when run I would like it to print "abc".

I have tried __name__ but that only returns "Example" (the class name) instead of the objects name.

Body:
I have a class that I want to print it's name within a method

In the class file

class Example():
   def __init__(self,x):
      self.x = x
      if self.x == True:
         print(#Name of class object)

In main

from class_file.py import Example

abc = Example(True)

And when run I would like it to print "abc".

I have tried __name__ but that only returns "Example" (the class name) instead of the objects name.


问:
How to write in XML an associative array that is in an indexed array?
I made these functions:

```<code>function arrayToXml(string $rootTagName, array $data) {
    $xml = new \XMLWriter();
    $xml->openMemory();
    $xml->startDocument('1.0', 'UTF-8');
    $xml->startElement($rootTagName);

    _arrayToXml($data, $xml);

    $xml->endElement();
    $xml->endDocument();
    return $xml->outputMemory(true);
}
function _arrayToXml(array $data, \XMLWriter &$xml) {
    foreach ($data as $key => $value) {
        if (is_numeric($key)) {
            throw new \Exception("Numeric key found: '$key'");
        }
        if (is_array($value)) {
            $xml->startElement($key);
            _arrayToXml($value, $xml);
            $xml->endElement();
        } else {
            $xml->writeElement($key, $value);
        }
    }
}
</code>```

if I pass this array

```<code>$test = [
    'tag1' => 'value1',
    'tag2' => [
        'child_tag1' => 'child value 1',
        'child_tag2' => 'child value 2'
    ]
];
arrayToXml("ROOT_TAG", $test);
</code>```

it works, and it gives this XML

```<code><?xml version="1.0" encoding="UTF-8"?>
<ROOT_TAG>
   <tag1>value1</tag1>
   <tag2>
     <child_tag1>child value 1</child_tag1>
     <child_tag2>child value 2</child_tag2>
   </tag2>
</ROOT_TAG>
</code>```

the problems is that now I found that I have to pass this array:

```<code>$test = [
    'tag1' => 'value1',
    'tag2' => [
        'child_tag1' => 'child value 1',
        'child_tag2' => 'child value 2'
    ],
    'car' => [
        [
            'name' => 'Car 1 name',
            'year' => 2013
        ],
        [
            'name' => 'Car 2 name',
            'year' => 2014
        ]
    ]
];
arrayToXml("ROOT_TAG", $test);
</code>```

obivoulsy it does not works, when it have to put "cars" in the XML, because the method try to put the index number as key. I would like to get this XML:

```<code><?xml version="1.0" encoding="UTF-8"?>
<ROOT_TAG>
   <tag1>value1</tag1>
   <tag2>
     <child_tag1>child value 1</child_tag1>
     <child_tag2>child value 2</child_tag2>
   </tag2>
   <car>
     <name>Car 1 name</name>
     <year>2013</year>
   </car>
   <car>
     <name>Car 2 name</name>
     <year>2014</year>
   </car>
</ROOT_TAG>
</code>```

How can I do that?

Body:
I made these functions:

function arrayToXml(string $rootTagName, array $data) {
    $xml = new \XMLWriter();
    $xml->openMemory();
    $xml->startDocument('1.0', 'UTF-8');
    $xml->startElement($rootTagName);

    _arrayToXml($data, $xml);

    $xml->endElement();
    $xml->endDocument();
    return $xml->outputMemory(true);
}
function _arrayToXml(array $data, \XMLWriter &$xml) {
    foreach ($data as $key => $value) {
        if (is_numeric($key)) {
            throw new \Exception("Numeric key found: '$key'");
        }
        if (is_array($value)) {
            $xml->startElement($key);
            _arrayToXml($value, $xml);
            $xml->endElement();
        } else {
            $xml->writeElement($key, $value);
        }
    }
}

if I pass this array

$test = [
    'tag1' => 'value1',
    'tag2' => [
        'child_tag1' => 'child value 1',
        'child_tag2' => 'child value 2'
    ]
];
arrayToXml("ROOT_TAG", $test);

it works, and it gives this XML

<?xml version="1.0" encoding="UTF-8"?>
<ROOT_TAG>
   <tag1>value1</tag1>
   <tag2>
     <child_tag1>child value 1</child_tag1>
     <child_tag2>child value 2</child_tag2>
   </tag2>
</ROOT_TAG>

the problems is that now I found that I have to pass this array:

$test = [
    'tag1' => 'value1',
    'tag2' => [
        'child_tag1' => 'child value 1',
        'child_tag2' => 'child value 2'
    ],
    'car' => [
        [
            'name' => 'Car 1 name',
            'year' => 2013
        ],
        [
            'name' => 'Car 2 name',
            'year' => 2014
        ]
    ]
];
arrayToXml("ROOT_TAG", $test);

obivoulsy it does not works, when it have to put "cars" in the XML, because the method try to put the index number as key. I would like to get this XML:

<?xml version="1.0" encoding="UTF-8"?>
<ROOT_TAG>
   <tag1>value1</tag1>
   <tag2>
     <child_tag1>child value 1</child_tag1>
     <child_tag2>child value 2</child_tag2>
   </tag2>
   <car>
     <name>Car 1 name</name>
     <year>2013</year>
   </car>
   <car>
     <name>Car 2 name</name>
     <year>2014</year>
   </car>
</ROOT_TAG>

How can I do that?


问:
install sublipse using linux cli or ansible
I have an ansible playbook to install eclipse. This works fine but I would like to add some plugins to it, like subclipse for instance. Does anyone know how to do it? It might also be a shell script which allow me to install subclipse. This I can run via ansible. I've already tried many things but most often end up with an error:

The org.eclipse.m2e.logback.configuration bundle was activated before the state location was initialized


问:
SwiftUI NavigationSplitView column visibility on iPhone?
I'm trying to create a 3-column layout in SwiftUI.

The first column is a LazyVGrid of selectable items. The selection then impacts a list of items in a content view (second column) which also isn't a SwiftUI list but a VStack + other views in a scrollview. Selecting items on that column impacts the detail view.

I got it all to work on the iPad, but this is because the iPad displays multiple columns at a time and NavigationSplitView supports gestures on the iPad as well as column visibility settings in code.

The problem is that I can't find a way to programmatically navigate from one column to another on the iPhone as it doesn't seem to respond to column visibility bindings.

I initially had it working with navigation links for each item on my grid where the destination was set to a view, but the code smelled pretty bad.

Eventually, I came up with the code below. In the first column I have my grid view which has a custom onSelect modifier that I trigger whenever an item is selected. That's where I'm trying to change column visibility. I tried setting vm.navigationColumnVisibility = .detailOnly, but the iPhone seems to ignore it.

I was able to get it to work exactly as expected by changing the grid to a List. The selection property/Binding in the List view seemed to trigger navigation on the iPhone. However, that's not the desired UI/UX.

Any advice on how to trigger navigation between columns programatically on the iPhone or a better way to adapt this code to achieve the described UI/UX?

```<code>struct JNavSplitView: View {
    @EnvironmentObject var vm: JNavSplitViewModel
    @State private var book: Book? = nil
    @State private var entry: Entry? = nil

    var sheet: some View {
        #if os(macOS)
        JEntryCreateFormMacOS(book: book)
        #else
        JEntryCreateForm(book: book)
            .onCreate { entry in
                self.entry = entry
            }
        #endif
    }

    var body: some View {
        NavigationSplitView(columnVisibility: $vm.navigationColumnVisibility) {
            BooksGridView(selected: $book)
                .onSelect { book in
                    self.entry = book.getEntries(forDate: Date()).first
                }
        } content: {
            BookEntriesView(book: book, selected: $entry)
        } detail: {
            PageCollectionView(entry: $entry)
        }
        .navigationViewStyle(DoubleColumnNavigationViewStyle())
        #if os(macOS)
        .toolbarBackground(Color("Purple 1000"), for: .windowToolbar)
        #endif
        .environmentObject(vm)
        .sheet(isPresented: $vm.presentNewEntryForm, content: {
            sheet
        })
    }

}
</code>```

Body:
I'm trying to create a 3-column layout in SwiftUI.

The first column is a LazyVGrid of selectable items. The selection then impacts a list of items in a content view (second column) which also isn't a SwiftUI list but a VStack + other views in a scrollview. Selecting items on that column impacts the detail view.

I got it all to work on the iPad, but this is because the iPad displays multiple columns at a time and NavigationSplitView supports gestures on the iPad as well as column visibility settings in code.

The problem is that I can't find a way to programmatically navigate from one column to another on the iPhone as it doesn't seem to respond to column visibility bindings.

I initially had it working with navigation links for each item on my grid where the destination was set to a view, but the code smelled pretty bad.

Eventually, I came up with the code below. In the first column I have my grid view which has a custom onSelect modifier that I trigger whenever an item is selected. That's where I'm trying to change column visibility. I tried setting vm.navigationColumnVisibility = .detailOnly, but the iPhone seems to ignore it.

I was able to get it to work exactly as expected by changing the grid to a List. The selection property/Binding in the List view seemed to trigger navigation on the iPhone. However, that's not the desired UI/UX.

Any advice on how to trigger navigation between columns programatically on the iPhone or a better way to adapt this code to achieve the described UI/UX?

struct JNavSplitView: View {
    @EnvironmentObject var vm: JNavSplitViewModel
    @State private var book: Book? = nil
    @State private var entry: Entry? = nil

    var sheet: some View {
        #if os(macOS)
        JEntryCreateFormMacOS(book: book)
        #else
        JEntryCreateForm(book: book)
            .onCreate { entry in
                self.entry = entry
            }
        #endif
    }

    var body: some View {
        NavigationSplitView(columnVisibility: $vm.navigationColumnVisibility) {
            BooksGridView(selected: $book)
                .onSelect { book in
                    self.entry = book.getEntries(forDate: Date()).first
                }
        } content: {
            BookEntriesView(book: book, selected: $entry)
        } detail: {
            PageCollectionView(entry: $entry)
        }
        .navigationViewStyle(DoubleColumnNavigationViewStyle())
        #if os(macOS)
        .toolbarBackground(Color("Purple 1000"), for: .windowToolbar)
        #endif
        .environmentObject(vm)
        .sheet(isPresented: $vm.presentNewEntryForm, content: {
            sheet
        })
    }

}


问:
C# XPS Document, GetFixedDocumentSequence() generate an error
I'm trying to fix this error on C# but I'm really not getting it.
Here the screen of the error and where I call the function

```<code>public ReportMagazzino(XpsDocument document)
{
       InitializeComponent();
       this.WindowState = WindowState.Maximized;
       documentViewer.Document = document.GetFixedDocumentSequence(); // Exception is generated here
       document.Close();
}

Unable to create an object of type 'System.Windows.ResourceDictionary'. Error on object 'System.Windows.Documents.FixedPage', line 1, position 200
</code>```

Stack Trace here:
Stack Trace

I tried to follow other threads and install a fix through power shell but nothing worked.

Body:
I'm trying to fix this error on C# but I'm really not getting it.
Here the screen of the error and where I call the function

public ReportMagazzino(XpsDocument document)
{
       InitializeComponent();
       this.WindowState = WindowState.Maximized;
       documentViewer.Document = document.GetFixedDocumentSequence(); // Exception is generated here
       document.Close();
}

Unable to create an object of type 'System.Windows.ResourceDictionary'. Error on object 'System.Windows.Documents.FixedPage', line 1, position 200

Stack Trace here:
Stack Trace

I tried to follow other threads and install a fix through power shell but nothing worked.


问:
Historically, why asterisk for a pointer/indirection in C?
One of my students asked why C would use * for pointers since it's already the multiplication operator. I didn't have a good response. I looked into some of the history, but couldn't find a "why". Hoping some of you might have been around a bit longer than me and know why * for pointer/dereferencing/indirection.

I understand this is not necessarily a coding-question per say, so some might get upset it is posted on Stack Overflow, but I know of no better place to ask this question.


问:
Is ASP.NET templating with autoescaping equivalent to just templating?
In ASP.NET application (not MVC) i sometimes embed server side values using <%=serverSideValue%> way to template a variable. So that it's simpler to understand which variables goes where in html.

Even if i do my best to keep my data source clean (the variables), i am start to be a bit afraid that encoding the value (before put it into the page) may be a better option.

So i am start thinking to adopt <%:serverSideValue%> instead of the previous example.

Considering that the project should work in multiple languages, is this (the use of <%:) a conservative and safe enought approach or may introduce unexpected behaviour?


问:
Storing complex items in postgresql
I'm trying to implement a password manager and am having trouble structuring the data. I basically want to store a "Passwords" struct in the DB for each user. I was thinking about implementing composite types for "PasswordComponent" and doing it that way but it got messy. These are the basic structs:

struct PasswordComponent {

name: String,

email: String,

password: String, // before someone says something, passwords aren't stored in plaintext

websites: Vec<String>

}

struct Passwords {

id: i32,

passwords: Vec<PasswordComponent>

}

```

I feel like this is the wrong way to go about this and shouldn't be trying to use this like "object oriented" style in postgresql though

Title: Storing complex items in postgresql

Body:
I'm trying to implement a password manager and am having trouble structuring the data. I basically want to store a "Passwords" struct in the DB for each user. I was thinking about implementing composite types for "PasswordComponent" and doing it that way but it got messy. These are the basic structs:

struct PasswordComponent {

name: String,

email: String,

password: String, // before someone says something, passwords aren't stored in plaintext

websites: Vec<String>

}

struct Passwords {

id: i32,

passwords: Vec<PasswordComponent>

}

I feel like this is the wrong way to go about this and shouldn't be trying to use this like "object oriented" style in postgresql though


问:
How to retrieve struct with nested structs with sqlx and Rust?
I'm trying to use Rust and sqlx (v0.6.2) to retrieve from DB structs with nested structs.

I tried using the below code but I found out that there is a limit of 9 fields in tuple that I can use with FromRow.

Note:
As you can see I'm using a Box<T> for struct fields.

use sqlx::{postgres::PgRow, FromRow, QueryBuilder, Row};

#[derive(Debug, Default, sqlx::FromRow)]
pub struct PgCoach { //PgCoach has ONLY scalar values
    pub team_id: String,
    pub id: String,
    pub created_at: Time::OffsetDateTime,
    pub updated_at: Option<Time::OffsetDateTime>,
    pub firstname: Option<String>,
    pub lastname: Option<String>,
    pub motto: Option<String>,
    pub first_case: Option<String>,
    pub second_case: Option<String>,
    pub third_case: Option<String>,
    pub birth_date: Option<Time::OffsetDateTime>,
    pub sex: Option<i64>,
    pub phone: Option<String>,
    pub email_address: Option<String>,
    pub address: Option<String>,
    pub picture: Option<String>,
    pub notes: Option<String>,
}

#[derive(Debug, Default)]
pub struct PgPlayer {
    pub team_id: String,
    pub id: String,
    pub created_at: Time::OffsetDateTime,
    pub updated_at: Option<Time::OffsetDateTime>,
    pub score: i64,
    pub birth_date: Time::OffsetDateTime,
    pub code: String,
    pub payed: bool,
    pub coach_id: String,
    pub coach: Option<Box<PgCoach>>,
    pub skills: Option<Vec<PgSkill>>,
}

impl FromRow<'_, PgRow> for PgPlayer {
    fn from_row(row: &PgRow) -> sqlx::Result<Self> {
        let mut res = Self {
            team_id: row.get("team_id"),
            id: row.get("id"),
            created_at: row.get("created_at"),
            updated_at: row.get("updated_at"),
            score: row.get("score"),
            birth_date: row.get("birth_date"),
            code: row.get("code"),
            payed: row.get("payed"),
            coach_id: row.get("coach_id"),
            ..Default::default()
        };

        if row.try_get_raw("coach").is_ok() {
            res.coach = Some(Box::new(PgCoach {
                id: row.try_get::<PgCoach, &str>("coach")?.1,
                firstname: row.try_get::<PgCoach, &str>("coach")?.4,
                lastname: row.try_get::<PgCoach, &str>("coach")?.5,
                ..Default::default()
            }));
        }

        Ok(res)
    }
}
```
<p>The error is:</p>
<pre class="lang-bash prettyprint-override"><code>error[E0277]: the trait bound `pg::PgCoach: sqlx::Decode<'_, sqlx::Postgres>` is not satisfied
   --> src\crates\project\pg.rs:656:21
    |
656 |                 id: row.try_get::<PgCoach, &str>("coach")?.id,
    |                     ^^^ ------- required by a bound introduced by this call
    |                     |
    |                     the trait `sqlx::Decode<'_, sqlx::Postgres>` is not implemented for `pg::PgCoach`
    |
    = help: the following other types implement trait `sqlx::Decode<'r, DB>`:
              <&'r [u8] as sqlx::Decode<'r, sqlx::Postgres>>
              <&'r [u8] as sqlx::Decode<'r, sqlx_core::any::database::Any>>
              <&'r sqlx::types::JsonRawValue as sqlx::Decode<'r, DB>>
              <&'r str as sqlx::Decode<'r, sqlx::Postgres>>
              <&'r str as sqlx::Decode<'r, sqlx_core::any::database::Any>>
              <() as sqlx::Decode<'r, sqlx::Postgres>>
              <(T1, T2) as sqlx::Decode<'r, sqlx::Postgres>>
              <(T1, T2, T3) as sqlx::Decode<'r, sqlx::Postgres>>
            and 43 others
note: required by a bound in `sqlx::Row::try_get`
   --> C:\Users\Fred\.cargo\registry\src\github.com-1ecc6299db9ec823\sqlx-core-0.6.2\src\row.rs:114:12
    |
114 |         T: Decode<'r, Self::Database> + Type<Self::Database>,
    |            ^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `sqlx::Row::try_get`
</code>```

I can use whatever SQL query the method needs.

I can return tuple from DB or single columns, I don't care. I only need a way to query with sqlx structs with nested Box<Struct> and I cannot understand how.

How can I retrieve these structs?

Body:
I'm trying to use Rust and sqlx (v0.6.2) to retrieve from DB structs with nested structs.

I tried using the below code but I found out that there is a limit of 9 fields in tuple that I can use with FromRow.

Note:
As you can see I'm using a Box<T> for struct fields.

use sqlx::{postgres::PgRow, FromRow, QueryBuilder, Row};

#[derive(Debug, Default, sqlx::FromRow)]
pub struct PgCoach { //PgCoach has ONLY scalar values
    pub team_id: String,
    pub id: String,
    pub created_at: Time::OffsetDateTime,
    pub updated_at: Option<Time::OffsetDateTime>,
    pub firstname: Option<String>,
    pub lastname: Option<String>,
    pub motto: Option<String>,
    pub first_case: Option<String>,
    pub second_case: Option<String>,
    pub third_case: Option<String>,
    pub birth_date: Option<Time::OffsetDateTime>,
    pub sex: Option<i64>,
    pub phone: Option<String>,
    pub email_address: Option<String>,
    pub address: Option<String>,
    pub picture: Option<String>,
    pub notes: Option<String>,
}

#[derive(Debug, Default)]
pub struct PgPlayer {
    pub team_id: String,
    pub id: String,
    pub created_at: Time::OffsetDateTime,
    pub updated_at: Option<Time::OffsetDateTime>,
    pub score: i64,
    pub birth_date: Time::OffsetDateTime,
    pub code: String,
    pub payed: bool,
    pub coach_id: String,
    pub coach: Option<Box<PgCoach>>,
    pub skills: Option<Vec<PgSkill>>,
}

impl FromRow<'_, PgRow> for PgPlayer {
    fn from_row(row: &PgRow) -> sqlx::Result<Self> {
        let mut res = Self {
            team_id: row.get("team_id"),
            id: row.get("id"),
            created_at: row.get("created_at"),
            updated_at: row.get("updated_at"),
            score: row.get("score"),
            birth_date: row.get("birth_date"),
            code: row.get("code"),
            payed: row.get("payed"),
            coach_id: row.get("coach_id"),
            ..Default::default()
        };

        if row.try_get_raw("coach").is_ok() {
            res.coach = Some(Box::new(PgCoach {
                id: row.try_get::<PgCoach, &str>("coach")?.1,
                firstname: row.try_get::<PgCoach, &str>("coach")?.4,
                lastname: row.try_get::<PgCoach, &str>("coach")?.5,
                ..Default::default()
            }));
        }

        Ok(res)
    }
}

The error is:

error[E0277]: the trait bound `pg::PgCoach: sqlx::Decode<'_, sqlx::Postgres>` is not satisfied
   --> src\crates\project\pg.rs:656:21
    |
656 |                 id: row.try_get::<PgCoach, &str>("coach")?.id,
    |                     ^^^ ------- required by a bound introduced by this call
    |                     |
    |                     the trait `sqlx::Decode<'_, sqlx::Postgres>` is not implemented for `pg::PgCoach`
    |
    = help: the following other types implement trait `sqlx::Decode<'r, DB>`:
              <&'r [u8] as sqlx::Decode<'r, sqlx::Postgres>>
              <&'r [u8] as sqlx::Decode<'r, sqlx_core::any::database::Any>>
              <&'r sqlx::types::JsonRawValue as sqlx::Decode<'r, DB>>
              <&'r str as sqlx::Decode<'r, sqlx::Postgres>>
              <&'r str as sqlx::Decode<'r, sqlx_core::any::database::Any>>
              <() as sqlx::Decode<'r, sqlx::Postgres>>
              <(T1, T2) as sqlx::Decode<'r, sqlx::Postgres>>
              <(T1, T2, T3) as sqlx::Decode<'r, sqlx::Postgres>>
            and 43 others
note: required by a bound in `sqlx::Row::try_get`
   --> C:\Users\Fred\.cargo\registry\src\github.com-1ecc6299db9ec823\sqlx-core-0.6.2\src\row.rs:114:12
    |
114 |         T: Decode<'r, Self::Database> + Type<Self::Database>,
    |            ^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `sqlx::Row::try_get`

I can use whatever SQL query the method needs.

I can return tuple from DB or single columns, I don't care. I only need a way to query with sqlx structs with nested Box<Struct> and I cannot understand how.

How can I retrieve these structs?


问:
What is the advantage of making logic to manage the network by injecting dependency using context API in react?
```<code>export class HttpClientService {
  private baseURL: string;
  tokenRepository: LocalTokenRepository;
  instance: AxiosInstance;

  constructor(baseURL: string, tokenRepository: LocalTokenRepository) {
    this.tokenRepository = tokenRepository;
    this.baseURL = baseURL;
    this.instance = axios.create({
      baseURL: this.baseURL,
      headers: { Authorization: this.tokenRepository.get() }
    });

    this.handleInterceptor();
  }
  private handleInterceptor = () => {
    this.instance.interceptors.response.use(
      this.handleResponse,
      this.handleError
    );
  };

  private handleResponse = ({ data }: AxiosResponse) => data;

  protected handleError = (error: any) => Promise.reject(error);
}
</code>```
```<code>export class AuthService {
  private httpClient: HttpClientService;
  private tokenRepository: LocalTokenRepository;
  constructor(
    httpClient: HttpClientService
    // tokenRepository: LocalTokenRepository
  ) {
    this.httpClient = httpClient;
    this.tokenRepository = this.httpClient.tokenRepository;
  }

  async signup(email: string, password: string) {
    const accessTOKEN = (await this.httpClient.instance.post(
      'data',
      { email, password },
      { params: '' }
    )) as string;
    this.tokenRepository.save(accessTOKEN);
  }

  async singin(email: string, password: string): Promise<any> {
    console.log(email, password, 'signIn?');
    // return await this.httpClient.instance.get('products', { params: '' });
  }

  signout() {
    this.tokenRepository.remove();
  }
}
</code>```
```<code>export const apiContext = createContext<APIType | null>(null);

const tokenRepository = new LocalTokenRepository();
const httpClient = new HttpClientService('baseurl', tokenRepository);
const productService = new ProductService(httpClient);
const authService = new AuthService(httpClient);

export const ApiProvider = ({ children }: { children: React.ReactNode }) => {
  return (
    <apiContext.Provider value={{ productService, authService }}>
      {children}
    </apiContext.Provider>
  );
};

</code>```

I made network logic like this. Make the network logic by class and inject dependency by context API. Is there any advantages of making network logic by class?
I don't recognize between network class logic and use axios right away.

What is the best way to handle api logic in react? and What kind of method people use the most?

Body:
export class HttpClientService {
  private baseURL: string;
  tokenRepository: LocalTokenRepository;
  instance: AxiosInstance;

  constructor(baseURL: string, tokenRepository: LocalTokenRepository) {
    this.tokenRepository = tokenRepository;
    this.baseURL = baseURL;
    this.instance = axios.create({
      baseURL: this.baseURL,
      headers: { Authorization: this.tokenRepository.get() }
    });

    this.handleInterceptor();
  }
  private handleInterceptor = () => {
    this.instance.interceptors.response.use(
      this.handleResponse,
      this.handleError
    );
  };

  private handleResponse = ({ data }: AxiosResponse) => data;

  protected handleError = (error: any) => Promise.reject(error);
}

export class AuthService {
  private httpClient: HttpClientService;
  private tokenRepository: LocalTokenRepository;
  constructor(
    httpClient: HttpClientService
    // tokenRepository: LocalTokenRepository
  ) {
    this.httpClient = httpClient;
    this.tokenRepository = this.httpClient.tokenRepository;
  }

  async signup(email: string, password: string) {
    const accessTOKEN = (await this.httpClient.instance.post(
      'data',
      { email, password },
      { params: '' }
    )) as string;
    this.tokenRepository.save(accessTOKEN);
  }

  async singin(email: string, password: string): Promise<any> {
    console.log(email, password, 'signIn?');
    // return await this.httpClient.instance.get('products', { params: '' });
  }

  signout() {
    this.tokenRepository.remove();
  }
}

export const apiContext = createContext<APIType | null>(null);

const tokenRepository = new LocalTokenRepository();
const httpClient = new HttpClientService('baseurl', tokenRepository);
const productService = new ProductService(httpClient);
const authService = new AuthService(httpClient);

export const ApiProvider = ({ children }: { children: React.ReactNode }) => {
  return (
    <apiContext.Provider value={{ productService, authService }}>
      {children}
    </apiContext.Provider>
  );
};

I made network logic like this. Make the network logic by class and inject dependency by context API. Is there any advantages of making network logic by class?
I don't recognize between network class logic and use axios right away.

What is the best way to handle api logic in react? and What kind of method people use the most?


问:
getting object by parameter from nested object mongodb spring data jpa
I have mongodb collection for following documents:

```<code>@Builder
@Data
@AllArgsConstructor
@NoArgsConstructor
@Document
public class Account {
    @Id
    private String id;

    @Indexed(unique=true)
    private String username;

    @Indexed(unique=true)
    private String email;

    @Indexed(unique=true)
    private String contact;

    private ConfirmationTokenDetails confirmationTokenDetails;
}

@Builder
@Data
@AllArgsConstructor
@NoArgsConstructor
@Document
public class ConfirmationTokenDetails {
    @Indexed(unique=true)
    private String confirmationToken;

    private LocalDateTime createdAt;

    private LocalDateTime expiredAt;
}
</code>```

Basically all what I want is just get Account entity by confirmationToken attribut which stores in nested ConfirmationTokenDetails object. I tried do that by using following method

```<code>public interface AccountRepository extends MongoRepository<Account, String> {

    Optional<Account> findByConfirmationTokenDetails_ConfirmationToken(String token);
}
</code>```

but it wasn't working for me.

Body:
I have mongodb collection for following documents:

@Builder
@Data
@AllArgsConstructor
@NoArgsConstructor
@Document
public class Account {
    @Id
    private String id;

    @Indexed(unique=true)
    private String username;

    @Indexed(unique=true)
    private String email;

    @Indexed(unique=true)
    private String contact;

    private ConfirmationTokenDetails confirmationTokenDetails;
}

@Builder
@Data
@AllArgsConstructor
@NoArgsConstructor
@Document
public class ConfirmationTokenDetails {
    @Indexed(unique=true)
    private String confirmationToken;

    private LocalDateTime createdAt;

    private LocalDateTime expiredAt;
}

Basically all what I want is just get Account entity by confirmationToken attribut which stores in nested ConfirmationTokenDetails object. I tried do that by using following method

public interface AccountRepository extends MongoRepository<Account, String> {

    Optional<Account> findByConfirmationTokenDetails_ConfirmationToken(String token);
}

but it wasn't working for me.


问:
How stop spawned block from rotating inside the background blocks?
I followed a tutorial about making a tetris game in NetBeans using Java, and one of the guy's assignment is to stop the block from rotating into another block. Can someone please help me fix this issue?

the problem: https://youtu.be/_jnccg1q65M?list=PL8wKnrrMApCoP9xTwOmQRHsZ8_Kr9c_DY&t=1142

```<code>  public void rotateBlock(){
        int[][] shape = block.getShape();
        int w= block.getWidth();
        int h = block.getHeight();
        if(block == null)return;
        if(!block.getCanMove()) return;
        block.rotate();

        if(block.getLeftEdge()<0)block.setX(0);
        if(block.getRightEdge()>= gridColumns)block.setX(gridColumns-block.getWidth());
        if(block.getBottomEdge() >= gridRows)block.setY(gridRows-block.getHeight());

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

Body:
I followed a tutorial about making a tetris game in NetBeans using Java, and one of the guy's assignment is to stop the block from rotating into another block. Can someone please help me fix this issue?

the problem: https://youtu.be/_jnccg1q65M?list=PL8wKnrrMApCoP9xTwOmQRHsZ8_Kr9c_DY&t=1142

  public void rotateBlock(){
        int[][] shape = block.getShape();
        int w= block.getWidth();
        int h = block.getHeight();
        if(block == null)return;
        if(!block.getCanMove()) return;
        block.rotate();

        if(block.getLeftEdge()<0)block.setX(0);
        if(block.getRightEdge()>= gridColumns)block.setX(gridColumns-block.getWidth());
        if(block.getBottomEdge() >= gridRows)block.setY(gridRows-block.getHeight());

        repaint();
    }


问:
to_html() formatters, float and string together
I'm trying to to_html(formatters={column: function}) in order to make visual changes.

```<code>df = pd.DataFrame({'name':['Here',4.45454,5]}, index=['A', 'B', 'C'])
def _form(val):
    value = 'STRING' if isinstance(val, str) else '{:0.0f}'.format(val)
    return value

df.to_html(formatters={'name':_form})
</code>```

I get

name

A
STRING

B
4.45454

C
5

instead of
|          | name           |
| -------- | -------------- |
| A        | STRING         |
| B        | 4              |
| C        | 5              |

Problem here is float value doesn't change.

On the other hand when I have all values float or integers, it gives desired result:

```<code>df = pd.DataFrame({'name':[323.322,4.45454,5]}, index=['A', 'B', 'C'])
def _form(val):
    value = 'STRING' if isinstance(val, str) else '{:0.0f}'.format(val)
    return value

df.to_html(formatters={'name':_form})
</code>```

How can it be fixed?
Thank you.

Body:
I'm trying to to_html(formatters={column: function}) in order to make visual changes.

df = pd.DataFrame({'name':['Here',4.45454,5]}, index=['A', 'B', 'C'])
def _form(val):
    value = 'STRING' if isinstance(val, str) else '{:0.0f}'.format(val)
    return value

df.to_html(formatters={'name':_form})

I get

name

A
STRING

B
4.45454

C
5

instead of
|          | name           |
| -------- | -------------- |
| A        | STRING         |
| B        | 4              |
| C        | 5              |

Problem here is float value doesn't change.

On the other hand when I have all values float or integers, it gives desired result:

df = pd.DataFrame({'name':[323.322,4.45454,5]}, index=['A', 'B', 'C'])
def _form(val):
    value = 'STRING' if isinstance(val, str) else '{:0.0f}'.format(val)
    return value

df.to_html(formatters={'name':_form})

How can it be fixed?
Thank you.


问:
Android notification how to create play /pause button?
I am not able to create bigger play/pause button in Decorated notification.
How can I do it?
Here is what I have:

```<code>if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {

        if (statusPlay){
            notification = new NotificationCompat.Builder(this,FOREGROUND_CHANNEL_ID)
                    .setSmallIcon(R.drawable.ic_books_mini2)
                    .setContentTitle(tmpTitle)
                    .setContentText(""+notificationPercentage + "%  " + tmpAuthor)
                    .setLargeIcon(artwork)
                    .setCategory(NotificationCompat.CATEGORY_TRANSPORT) //CATEGORY_SERVICE
                    .addAction(R.drawable.prev10w,"prev10",lPendingSeekPrevIntent)
                    .addAction(R.drawable.ic_pause_white,"pause",lPendingPauseIntent)
                    .addAction(R.drawable.next10w,"next10",lPendingSeekNextIntent)
                    .setStyle(new androidx.media.app.NotificationCompat.DecoratedMediaCustomViewStyle()
                            .setShowActionsInCompactView(0,1,2)
                            .setMediaSession(mediaSession.getSessionToken())
                    )
                    .setPriority(NotificationCompat.PRIORITY_LOW)
                    .setColorized(true)
                    .setContentIntent(pendingIntent)
                    .setAutoCancel(true)
                    .setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
                    .setOngoing(true);

        }else {
            notification = new NotificationCompat.Builder(this, FOREGROUND_CHANNEL_ID)
                    .setSmallIcon(R.drawable.ic_books_mini2)
                    .setContentTitle(tmpTitle)
                    .setContentText("" + notificationPercentage + "%  " + tmpAuthor)
                    .setLargeIcon(artwork)
                    .setCategory(NotificationCompat.CATEGORY_TRANSPORT)
                    .addAction(R.drawable.prev10w,"prev10",lPendingSeekPrevIntent)
                    .addAction(R.drawable.ic_play_arrow_white,"play",lPendingPlayIntent)
                    .addAction(R.drawable.next10w,"next10",lPendingSeekNextIntent)
                    .setStyle(new androidx.media.app.NotificationCompat.DecoratedMediaCustomViewStyle()
                            .setShowActionsInCompactView(0,1,2)
                            .setMediaSession(mediaSession.getSessionToken())
                    )
                    .setPriority(NotificationCompat.PRIORITY_LOW)
                    .setColorized(true)
                    .setContentIntent(pendingIntent)
                    .setAutoCancel(true)
                    .setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
                    .setOngoing(true)
                    ;

            ;
        }

    }
</code>```

This looks like this with small buttons on bottom:

But required is this bigger button:

In official poages of android development ,they recommend to use this Decorated Media Custom View in notifications due to restricted space and colors to be visible with texts. Many thanks for help.

Body:
I am not able to create bigger play/pause button in Decorated notification.
How can I do it?
Here is what I have:

if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {

        if (statusPlay){
            notification = new NotificationCompat.Builder(this,FOREGROUND_CHANNEL_ID)
                    .setSmallIcon(R.drawable.ic_books_mini2)
                    .setContentTitle(tmpTitle)
                    .setContentText(""+notificationPercentage + "%  " + tmpAuthor)
                    .setLargeIcon(artwork)
                    .setCategory(NotificationCompat.CATEGORY_TRANSPORT) //CATEGORY_SERVICE
                    .addAction(R.drawable.prev10w,"prev10",lPendingSeekPrevIntent)
                    .addAction(R.drawable.ic_pause_white,"pause",lPendingPauseIntent)
                    .addAction(R.drawable.next10w,"next10",lPendingSeekNextIntent)
                    .setStyle(new androidx.media.app.NotificationCompat.DecoratedMediaCustomViewStyle()
                            .setShowActionsInCompactView(0,1,2)
                            .setMediaSession(mediaSession.getSessionToken())
                    )
                    .setPriority(NotificationCompat.PRIORITY_LOW)
                    .setColorized(true)
                    .setContentIntent(pendingIntent)
                    .setAutoCancel(true)
                    .setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
                    .setOngoing(true);

        }else {
            notification = new NotificationCompat.Builder(this, FOREGROUND_CHANNEL_ID)
                    .setSmallIcon(R.drawable.ic_books_mini2)
                    .setContentTitle(tmpTitle)
                    .setContentText("" + notificationPercentage + "%  " + tmpAuthor)
                    .setLargeIcon(artwork)
                    .setCategory(NotificationCompat.CATEGORY_TRANSPORT)
                    .addAction(R.drawable.prev10w,"prev10",lPendingSeekPrevIntent)
                    .addAction(R.drawable.ic_play_arrow_white,"play",lPendingPlayIntent)
                    .addAction(R.drawable.next10w,"next10",lPendingSeekNextIntent)
                    .setStyle(new androidx.media.app.NotificationCompat.DecoratedMediaCustomViewStyle()
                            .setShowActionsInCompactView(0,1,2)
                            .setMediaSession(mediaSession.getSessionToken())
                    )
                    .setPriority(NotificationCompat.PRIORITY_LOW)
                    .setColorized(true)
                    .setContentIntent(pendingIntent)
                    .setAutoCancel(true)
                    .setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
                    .setOngoing(true)
                    ;

            ;
        }

    }

This looks like this with small buttons on bottom:

But required is this bigger button:

In official poages of android development ,they recommend to use this Decorated Media Custom View in notifications due to restricted space and colors to be visible with texts. Many thanks for help.


问:
How to add a proxy with SOAPConnection
I have an application that sends SOAP messages using the SOAP API.
It worked from office perfectly, but when on remote from home using VPN, SOAP calls don't work anymore.

Error message is :

```<code>[Fatal Error] :1:1: Content is not allowed in prolog.
Content is not allowed in prolog.
</code>```

The code I use for soap calls :

```<code>SOAPConnection con;
SOAPConnectionFactory conFactory = SOAPConnectionFactory.newInstance();
con = conFactory.createConnection();
URL endpoint = new URL(this.getURI());
SOAPMessage retval = con.call(message, endpoint);
</code>```

How to add a proxy to make those calls work when using a VPN?

Title: How to add a proxy with SOAPConnection

Body:
I have an application that sends SOAP messages using the SOAP API.
It worked from office perfectly, but when on remote from home using VPN, SOAP calls don't work anymore.

Error message is :

[Fatal Error] :1:1: Content is not allowed in prolog.
Content is not allowed in prolog.

The code I use for soap calls :

SOAPConnection con;
SOAPConnectionFactory conFactory = SOAPConnectionFactory.newInstance();
con = conFactory.createConnection();
URL endpoint = new URL(this.getURI());
SOAPMessage retval = con.call(message, endpoint);

How to add a proxy to make those calls work when using a VPN?


问:
Solr search not giving proper result when search for special character
I am trying to search field which has "\r\n" both together in the field.

I tried this query but it did not work:

```<code>fq
Field:"*\r\n*"
</code>```

But this gives result along with field has "\" only. I just want result for which field contains whole "\r\n".

Body:
I am trying to search field which has "\r\n" both together in the field.

I tried this query but it did not work:

fq
Field:"*\r\n*"

But this gives result along with field has "\" only. I just want result for which field contains whole "\r\n".


问:
JLabel not Moving or Appearing
I am trying to make a fade out transition my moving a JLabel with a transparent gradient so it starts fading out from the bottom up. This will be activated by a button that when pressed, will begin the transition by creating a label with the transparent gradient image and changing its position using a for loop. However, whenever I click the button, it appears to do nothing and it does not load the image nor the animation.
This is the image I am trying to load https://imgur.com/a/WhSCVna</p>
```<code> setSize(800, 600);
 setLayout(null);
 setResizable(false);
 setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

 // Start Menu Background
 ImageIcon start_menu_img = new ImageIcon("src/img/menu_background.png");
 JLabel start_menu = new JLabel("", start_menu_img, JLabel.CENTER);
 start_menu.setBounds(0,0,800,600);

 // Start Button
 start = new JButton(new ImageIcon("src/img/start.png"));
 start.setBounds(240,327,320,100);
 start.setBorder(BorderFactory.createEmptyBorder());

 // Sets main menu label and adds it to the frame
 start.addActionListener(this);

 JLabel main_menu = new JLabel();
 main_menu.setBounds(getBounds());
 main_menu.add(start);
 main_menu.add(start_menu);
 add(main_menu);

@Override
  public void actionPerformed(ActionEvent e) {
    if(e.getSource() == start) {

      try {
        AudioInputStream select = getAudioFile("select.wav");
        Clip clip = AudioSystem.getClip();
        clip.open(select);
        clip.start();

        Thread.sleep(500);

        ImageIcon transition_ImageIcon = new ImageIcon("src/img/transition.png");
        JLabel transition = new JLabel();
        transition.setIcon(transition_ImageIcon);
        transition.setBounds(0,600,800,1800);
        add(transition);

        for(int i = 600; i > -1200; i--) {
          transition.setBounds(0, i, 800, 1800);
          Thread.sleep(1);
        }

      } catch (Exception e1) {}
    }
  }
</code>```

Title: JLabel not Moving or Appearing

Body:
I am trying to make a fade out transition my moving a JLabel with a transparent gradient so it starts fading out from the bottom up. This will be activated by a button that when pressed, will begin the transition by creating a label with the transparent gradient image and changing its position using a for loop. However, whenever I click the button, it appears to do nothing and it does not load the image nor the animation.
This is the image I am trying to load https://imgur.com/a/WhSCVna

 setSize(800, 600);
 setLayout(null);
 setResizable(false);
 setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

 // Start Menu Background
 ImageIcon start_menu_img = new ImageIcon("src/img/menu_background.png");
 JLabel start_menu = new JLabel("", start_menu_img, JLabel.CENTER);
 start_menu.setBounds(0,0,800,600);

 // Start Button
 start = new JButton(new ImageIcon("src/img/start.png"));
 start.setBounds(240,327,320,100);
 start.setBorder(BorderFactory.createEmptyBorder());

 // Sets main menu label and adds it to the frame
 start.addActionListener(this);

 JLabel main_menu = new JLabel();
 main_menu.setBounds(getBounds());
 main_menu.add(start);
 main_menu.add(start_menu);
 add(main_menu);

@Override
  public void actionPerformed(ActionEvent e) {
    if(e.getSource() == start) {

      try {
        AudioInputStream select = getAudioFile("select.wav");
        Clip clip = AudioSystem.getClip();
        clip.open(select);
        clip.start();

        Thread.sleep(500);

        ImageIcon transition_ImageIcon = new ImageIcon("src/img/transition.png");
        JLabel transition = new JLabel();
        transition.setIcon(transition_ImageIcon);
        transition.setBounds(0,600,800,1800);
        add(transition);

        for(int i = 600; i > -1200; i--) {
          transition.setBounds(0, i, 800, 1800);
          Thread.sleep(1);
        }

      } catch (Exception e1) {}
    }
  }


问:
In linear regression, is the coefficient of un-transformed (0,1) categorical data is the same scale as other coefficient of transformed features?
I want to perform a linear regression on house price dataset to rank the features that most impacting the price. I handled categorical data by one hot encoding. Then, I transformed (log) all the features except the categorical data (0,1). After I run the regression, is the coefficient of the categorical data is the same scale as other feature's coefficient?

I have a problem to understand why 0,1 data cannot be transformed and is the coefficient of untransformed one hot encoded data is the same scale with other transformed coefficient.


问:
Trigger plotly autoscale from a function, without altering the axis style - in r
I'm trying to autoscale a plotly graph from a function in a R shiny app - which essentially works, but also resets the entire x and y axis layout (size, font, color, ...). Is it possible to preserve those settings and to only modify the axis scaling?

That's the code:

```<code>observeEvent(input$selBg_dz1,{

backgroundSignal$dz1_delta <- calcSignalBackground("DZ1_delta")

plotlyProxy("myGraph", session = session) %>%
 plotlyProxyInvoke("relayout", list(xaxis=list(autorange=T), yaxis=list(autorange=T)))

 })
</code>```

Body:
I'm trying to autoscale a plotly graph from a function in a R shiny app - which essentially works, but also resets the entire x and y axis layout (size, font, color, ...). Is it possible to preserve those settings and to only modify the axis scaling?

That's the code:

observeEvent(input$selBg_dz1,{

backgroundSignal$dz1_delta <- calcSignalBackground("DZ1_delta")

plotlyProxy("myGraph", session = session) %>%
 plotlyProxyInvoke("relayout", list(xaxis=list(autorange=T), yaxis=list(autorange=T)))

 })


问:
Filling form fields in Word automatically with pywin32
I want to automatically fill FormFields in Word with entries of dictionaries.

The pywin32 command that I use in a loop is marks(i).Result = keyValue. Here marks is, as far as I understand, a formfields object, which I get by marks = doc.FormFields.

This works to some extent, but as soon as I update the document in Word, all entries disappear again.

How could I make it that the entry is permanent?

I do not understand the documentation of pywin32.

The whole function.

```<code>def wordExport(window, excDict, docPath):

    wordApp = win32com.client.Dispatch('Word.Application') #Word App Object
    wordApp.Visible = False
    doc = wordApp.Documents.Open(docPath) #Open .docx
    marks = doc.FormFields # FormFields object
    cMarks = marks.Count # FormField count
    cMatches = 0 #Match counter
    cOverwrt = 0 #Fields overwritten

    for i in range(1, cMarks + 1):
        fieldName = str(marks(i).Name) #String object of FormField

        #Default Cases --------------------------------------------------------------------
        if fieldName in excDict:
            keyValue = excDict.get(fieldName) #Get value to key(FormField)
            resultIsEmpty = not marks(i).Result #No text has been entered before

            # No prior entry present
            if keyValue != "None"
                marks(i).Result = keyValue + " "
                cMatches += 1
                if not resultIsEmpty:
                    cOverwrt += 1

    doc.Close()
    wordApp.Visible = False
</code>```

Body:
I want to automatically fill FormFields in Word with entries of dictionaries.

The pywin32 command that I use in a loop is marks(i).Result = keyValue. Here marks is, as far as I understand, a formfields object, which I get by marks = doc.FormFields.

This works to some extent, but as soon as I update the document in Word, all entries disappear again.

How could I make it that the entry is permanent?

I do not understand the documentation of pywin32.

The whole function.

def wordExport(window, excDict, docPath):

    wordApp = win32com.client.Dispatch('Word.Application') #Word App Object
    wordApp.Visible = False
    doc = wordApp.Documents.Open(docPath) #Open .docx
    marks = doc.FormFields # FormFields object
    cMarks = marks.Count # FormField count
    cMatches = 0 #Match counter
    cOverwrt = 0 #Fields overwritten

    for i in range(1, cMarks + 1):
        fieldName = str(marks(i).Name) #String object of FormField

        #Default Cases --------------------------------------------------------------------
        if fieldName in excDict:
            keyValue = excDict.get(fieldName) #Get value to key(FormField)
            resultIsEmpty = not marks(i).Result #No text has been entered before

            # No prior entry present
            if keyValue != "None"
                marks(i).Result = keyValue + " "
                cMatches += 1
                if not resultIsEmpty:
                    cOverwrt += 1

    doc.Close()
    wordApp.Visible = False


问:
Working curl command to send SMS via Twilio API but need in JSON format
I am not a coder, but did stay at a Holiday Inn Express once.  Working on a solution to automatically send SMS messages to customers giving them updates.

I have a working Curl command, but the system that will trigger the webhook must be setup as follows (The tool is Freshdesk) :

Image of Input for API trigger (Freshdesk)

This is the curl command that I have made work with no problems:

```<code>`curl 'https://api.twilio.com/2010-04-  01/Accounts/AccountSID/Messages.json' -X POST \
--data-urlencode 'To=+19155402805' \
--data-urlencode 'From=+15104055319' \
--data-urlencode 'Body=This is the update you were asking for' \
-u Account_SID:[AuthToken]`
</code>```

I was able to import this into Postman and again it works great.  When I try to use the format provided it gives me the Response Text = {"code": 21604, "message": "A 'To' phone number is required.", "more_info": "https://www.twilio.com/docs/errors/21604", "status": 400} error.

This is what I have tried so far and it is not working:

```<code>`{
"To": "+19155409999",
"From": "+15109999999",
"Body": "Its Me, Its Me"
}`
</code>```

I know this is something easy and stupid, but haven't been able to solve it yet.  Any help would be appreciated.

Thank you for the time.

Body:
I am not a coder, but did stay at a Holiday Inn Express once.  Working on a solution to automatically send SMS messages to customers giving them updates.

I have a working Curl command, but the system that will trigger the webhook must be setup as follows (The tool is Freshdesk) :

Image of Input for API trigger (Freshdesk)

This is the curl command that I have made work with no problems:

`curl 'https://api.twilio.com/2010-04-  01/Accounts/AccountSID/Messages.json' -X POST \
--data-urlencode 'To=+19155402805' \
--data-urlencode 'From=+15104055319' \
--data-urlencode 'Body=This is the update you were asking for' \
-u Account_SID:[AuthToken]`

I was able to import this into Postman and again it works great.  When I try to use the format provided it gives me the Response Text = {"code": 21604, "message": "A 'To' phone number is required.", "more_info": "https://www.twilio.com/docs/errors/21604", "status": 400} error.

This is what I have tried so far and it is not working:

`{
"To": "+19155409999",
"From": "+15109999999",
"Body": "Its Me, Its Me"
}`

I know this is something easy and stupid, but haven't been able to solve it yet.  Any help would be appreciated.

Thank you for the time.