问:
Python Click: How to make an option available only when another option has a certain value?
I want to enhance an existing command-line application done with Python click to allow for certain options depending on what the --format option is set to.

In my special case, I would like to enable --delimiter option when the --format option equals csv and an --indent option when the --format option equals json. It should all fit into one command, so I do not want to introduce subcommands if not absolutely necessary.

I looked into the group mechanism of click and also the additional extension package click-option-group but I think this is only about grouping the commands, but does not fulfill the goal above.

This question is similar: python-click: dependent options on another option, but the difference is that it has predefined values for the "sub option", whereas in my case --indent is a user-specified value, e.g. 2, 4, 1, et cetera...
Furthermore, as all the answers that go into my direction are rather old, I would look for a more up-to-date answer, as to what is possible as of today. What also would be great if it were possible to use functionality of a Python library with preference on click instead of having to add additional code outside of the library.

Thanks for your help.

答:
You can use a callback function like this:

def fix_required(ctx, param, value):
    if value == 'csv':
        ctx.command.params[1].required = True
    else:
        ctx.command.params[2].required = True

@click.command()
@click.option('-f', '--format', required=True,
              type=click.Choice(['csv', 'json']), callback=fix_required)
@click.option('-i', '--delimiter', required=False, type=click.Choice(['\t', ', ']))
@click.option('-i', '--indent', required=False, type=int)
def formatter(format, delimiter, indent):
    pass
```

The params list is ordered after the order of the option annotations, so it is predictable and should be kept up to date if you add options to your command or edit their order.

Body:
You can use a callback function like this:

def fix_required(ctx, param, value):
    if value == 'csv':
        ctx.command.params[1].required = True
    else:
        ctx.command.params[2].required = True

@click.command()
@click.option('-f', '--format', required=True,
              type=click.Choice(['csv', 'json']), callback=fix_required)
@click.option('-i', '--delimiter', required=False, type=click.Choice(['\t', ', ']))
@click.option('-i', '--indent', required=False, type=int)
def formatter(format, delimiter, indent):
    pass

The params list is ordered after the order of the option annotations, so it is predictable and should be kept up to date if you add options to your command or edit their order.


来源: stackexchange

问:
MySQL synchronisation between 2 db
I am currently looking for a quick way to sync my production db and my dev-db.

I was thinking of doing it with something like this :

```<code>mysqladmin -u <user> -p<password> <dev-db_name> | mysqldump -u <user> -p<password> --databases <production-db-name> --add-drop-table
</code>```

but it seems that it just prints all of the drump on the screen instead of piping it to the mysqladmin util. Would there be any suggestion to improve this ?

答:
Right now you are piping the output of mysqladmin into mysqldump.

Flip them around, also instead of mysqladmin use regular mysql, to that the command like looks something like this:

```<code>mysqldump ... | mysql ...
</code>```

OwnerDisplayName: Erick

ContentLicense: CC BY-SA 2.5

Title: MySQL synchronisation between 2 db

Body:
I am currently looking for a quick way to sync my production db and my dev-db.

I was thinking of doing it with something like this :

mysqladmin -u <user> -p<password> <dev-db_name> | mysqldump -u <user> -p<password> --databases <production-db-name> --add-drop-table

but it seems that it just prints all of the drump on the screen instead of piping it to the mysqladmin util. Would there be any suggestion to improve this ?

Body:
Right now you are piping the output of mysqladmin into mysqldump.

Flip them around, also instead of mysqladmin use regular mysql, to that the command like looks something like this:

mysqldump ... | mysql ...

OwnerDisplayName: andri


问:
How can I guarantee all unit tests pass before committing?
We've had problems recently where developers commit code to SVN that doesn't pass unit tests, fails to compile on all platforms, or even fails to compile on their own platform. While this is all picked up by our CI server (Cruise Control), and we've instituted processes to try to stop it from happening, we'd really like to be able to stop the rogue commits from happening in the first place.

Based on a few other questions around here, it seems to be a Bad Idea™ to force this as a pre-commit hook on the server side mostly due to the length of time required to build + run the tests. I did some Googling and found this (all devs use TortoiseSVN):

http://cf-bill.blogspot.com/2010/03/pre-commit-force-unit-tests-without.html

Which would solve at least two of the problems (it wouldn't build on Unix), but it doesn't reject the commit if it fails. So my questions:

Is there a way to make a pre-commit hook in TortoiseSVN cause the commit to fail?

Is there a better way to do what I'm trying to do in general?

答:
There are two approaches:

Discipline

Tools

In my experience, #1 can only get you so far.

So the solution is probably tools. In your case, the obstacle is Subversion. Replace it with a DVCS like Mercurial or Git. That will allow every developer to work on their own branch without the merge nightmares of Subversion.

Every once in a while, a developer will mark a feature or branch as "complete". That is the time to merge the feature branch into the main branch. Push that into a "staging" repository which your CI server watches. The CI server can then pull the last commit(s), compile and test them and only if this passes, push them to the main repository.

So the loop is: main repo -> developer -> staging -> main.

There are many answers here which give you the details. Start here: Mercurial workflow for ~15 developers - Should we use named branches?

[EDIT] So you say you don't have the time to solve the major problems in your development process ... I'll let you guess how that sounds to anyone... ;-)

Anyway ... Use hg convert to get a Mercurial repo out of your Subversion tree. If you have a standard setup, that shouldn't take much of your time (it will just need a lot of time on your computer but it's automatic).

Clone that repo to get a work repo. The process works like this:

Develop in your second clone. Create feature branches for that.

If you need changes from someone, convert into the first clone. Pull from that into your second clone (that way, you always have a "clean" copy from subversion just in case you mess up).

Now merge the Subversion branch (default) and your feature branch. That should work much better than with Subversion.

When the merge is OK (all the tests run for you), create a patch from a diff between the two branches.

Apply the patch to a local checkout from Subversion. It should apply without problems. If it doesn't, you can clean your local checkout and repeat. No chance to lose work here.

Commit the changes in subversion, convert them back into repo #1 and pull into repo #2.

This sounds like a lot of work but within a week, you'll come up with a script or two to do most of the work.

When you notice someone broke the build (tests aren't running for you anymore), undo the merge (hg clean -C) and continue to work on your working feature branch.

When your colleagues complain that someone broke the build, tell them that you don't have a problem. When people start to notice that your productivity is much better despite all the hoops that you've got to jump, mention "it would be much more simple if we would scratch SVN".

ContentLicense: CC BY-SA 3.0


问:
How can I pass a function to the child component?
I have this component with a modal for confirmation when deleting an item. How can I pass the function to the child component so that once I click the button Agree, it will trigger this function for delete.

The function to delete an item:

```<code> const deleteProduct = async (id) => {
    const productDoc = doc(db, "products", id);
    await deleteDoc(productDoc);
  };
</code>```

The Dialog:

```<code> <Modal
        title="Confirmation"
        subtitle={sample}
        isOpen={isOpen}
        handleClose={handleClose}
      />
</code>```

The Reusable component:

```<code>import {
  Dialog,
  DialogContent,
  DialogContentText,
  DialogTitle,
  Divider,
  Button,
  DialogActions,
} from "@mui/material";

const Modal = ({ title, subtitle, children, isOpen, handleClose }) => {
  const handleConfirm = () => {
    alert("You Agreed!");
    handleClose();
  };
  return (
    <Dialog open={isOpen} onClose={handleClose}>
      <DialogTitle>{title}</DialogTitle>
      <DialogContent>
        <DialogContentText>{subtitle}</DialogContentText>
        <Divider />
        {children}
      </DialogContent>
      <DialogActions>
        <Button onClick={handleClose} color="error">
          Cancel
        </Button>
        <Button onClick={handleConfirm} color="primary">
          Agree
        </Button>
      </DialogActions>
    </Dialog>
  );
};

export default Modal;
</code>```

答:
Simply pass the function and productId as props to Modaland because the function is asynchronous, you have to make the handleConfirm asynchronous as well.

The Dialog:

```<code> <Modal
        productId={id}
        title="Confirmation"
        subtitle={sample}
        isOpen={isOpen}
        deleteProductCallback={deleteProduct}
        handleClose={handleClose}
      />
</code>```

The Reusable component:

```<code>import {
  Dialog,
  DialogContent,
  DialogContentText,
  DialogTitle,
  Divider,
  Button,
  DialogActions,
} from "@mui/material";

const Modal = ({ productId,title, subtitle, children, isOpen, handleClose ,deleteProductCallback}) => {
  const handleConfirm = async() => {
    alert("You Agreed!");
    await deleteProductCallback(productId);
    handleClose();
  };
  return (
    <Dialog open={isOpen} onClose={handleClose}>
      <DialogTitle>{title}</DialogTitle>
      <DialogContent>
        <DialogContentText>{subtitle}</DialogContentText>
        <Divider />
        {children}
      </DialogContent>
      <DialogActions>
        <Button onClick={handleClose} color="error">
          Cancel
        </Button>
        <Button onClick={handleConfirm} color="primary">
          Agree
        </Button>
      </DialogActions>
    </Dialog>
  );
};
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have this component with a modal for confirmation when deleting an item. How can I pass the function to the child component so that once I click the button Agree, it will trigger this function for delete.

The function to delete an item:

 const deleteProduct = async (id) => {
    const productDoc = doc(db, "products", id);
    await deleteDoc(productDoc);
  };

The Dialog:

 <Modal
        title="Confirmation"
        subtitle={sample}
        isOpen={isOpen}
        handleClose={handleClose}
      />

The Reusable component:

import {
  Dialog,
  DialogContent,
  DialogContentText,
  DialogTitle,
  Divider,
  Button,
  DialogActions,
} from "@mui/material";

const Modal = ({ title, subtitle, children, isOpen, handleClose }) => {
  const handleConfirm = () => {
    alert("You Agreed!");
    handleClose();
  };
  return (
    <Dialog open={isOpen} onClose={handleClose}>
      <DialogTitle>{title}</DialogTitle>
      <DialogContent>
        <DialogContentText>{subtitle}</DialogContentText>
        <Divider />
        {children}
      </DialogContent>
      <DialogActions>
        <Button onClick={handleClose} color="error">
          Cancel
        </Button>
        <Button onClick={handleConfirm} color="primary">
          Agree
        </Button>
      </DialogActions>
    </Dialog>
  );
};

export default Modal;

Body:
Simply pass the function and productId as props to Modaland because the function is asynchronous, you have to make the handleConfirm asynchronous as well.

The Dialog:

 <Modal
        productId={id}
        title="Confirmation"
        subtitle={sample}
        isOpen={isOpen}
        deleteProductCallback={deleteProduct}
        handleClose={handleClose}
      />

The Reusable component:

import {
  Dialog,
  DialogContent,
  DialogContentText,
  DialogTitle,
  Divider,
  Button,
  DialogActions,
} from "@mui/material";

const Modal = ({ productId,title, subtitle, children, isOpen, handleClose ,deleteProductCallback}) => {
  const handleConfirm = async() => {
    alert("You Agreed!");
    await deleteProductCallback(productId);
    handleClose();
  };
  return (
    <Dialog open={isOpen} onClose={handleClose}>
      <DialogTitle>{title}</DialogTitle>
      <DialogContent>
        <DialogContentText>{subtitle}</DialogContentText>
        <Divider />
        {children}
      </DialogContent>
      <DialogActions>
        <Button onClick={handleClose} color="error">
          Cancel
        </Button>
        <Button onClick={handleConfirm} color="primary">
          Agree
        </Button>
      </DialogActions>
    </Dialog>
  );
};


问:
Are type signatures now permitted in instance declarations without needing the InstanceSigs language extension?
I've noticed that when using VS Code with the current version of Haskell (GHC 9.2.1 and HLS 1.6.1.0), I no longer receive errors when I write type signatures in my instance declarations, even though I haven't included the {-# LANGUAGE InstanceSigs -#} extension.

Was there a change made to Haskell recently to allow instance signatures by default?

答:
GHC 9.2.1 enables GHC2021 by default.

The GHC2021 language is supported now. It builds on top of Haskell2010, adding several stable and conservative extensions, and removing deprecated ones. It is now also the “default” language set that is active when no other language set, such as Haskell98 or Haskell2010, is explicitly loaded (e.g via Cabal’s default-language).
https://downloads.haskell.org/~ghc/9.2.1/docs/html/users_guide/9.2.1-notes.html

GHC2021 language enables InstanceSigs.

https://github.com/ghc-proposals/ghc-proposals/blob/master/proposals/0380-ghc2021.rst


问:
Docker not starting on Windows 11 with WSL 2
I'm trying to setup docker with WSL 2 to run a Dockerfile. I downloaded Docker Desktop, and when I tried to follow the quick start guide, I got the following error:

```<code>docker: error during connect: This error may indicate that the docker daemon is not running.: Post "http://%2F%2F.%2Fpipe%d2Fdocker_engine/v1.24/containers/create?name=repo": open //./pipe/docker_enginer: The system cannot find the file specified.
</code>```

I set com.docker.service to run in the Task Manager, and have run:

```<code>“c:\Program Files\Docker\Docker\DockerCli.exe” -SwitchDaemon
</code>```

I have also quit Docker Desktop and reopened it in admin mode, and I still get the message that Docker Desktop has stopped.

Please let me know if there's any other options, thanks!

答:
Wow! I spent multiple days trying to get Docker for windows 11 to work. What finally did it was downgrading to version 4.4.4 as @GinglrBell recommended. Here's a link Docker version 4.4.4.

Make sure WSL is installed and virtualization is enabled. If you try to open WSL and you get an error telling you to enable virtualization in BIOS, run this command as Admin in powershell: bcdedit /set hypervisorlaunchtype auto (Docker src). Then restart your PC.

Body:
I'm trying to setup docker with WSL 2 to run a Dockerfile. I downloaded Docker Desktop, and when I tried to follow the quick start guide, I got the following error:

docker: error during connect: This error may indicate that the docker daemon is not running.: Post "http://%2F%2F.%2Fpipe%d2Fdocker_engine/v1.24/containers/create?name=repo": open //./pipe/docker_enginer: The system cannot find the file specified.

I set com.docker.service to run in the Task Manager, and have run:

“c:\Program Files\Docker\Docker\DockerCli.exe” -SwitchDaemon

I have also quit Docker Desktop and reopened it in admin mode, and I still get the message that Docker Desktop has stopped.

Please let me know if there's any other options, thanks!


问:
How to start inputting values on the next row after a submit
I would like for it to automatically start putting the values from the key down to the new row after the enter key is pressed, right now the values do display on the first row, but after the enter key is pressed it just focuses the next row and does not display the value</p>
```<code>import { useState, useEffect, useRef } from "react"

function LetterContainer({ textColor, bgColor }) {
    const [key, setKey] = useState("")
    const [guess, setGuess] = useState([])
    const [counter, setCounter] = useState(0)
    const searchInput1 = useRef(null)
    const searchInput2 = useRef(null)
    const displayLetter = guess < 5 ? key : guess
    let userGuess = []

    useEffect(() => {
        // Sets focus on first row for inital load
        searchInput1.current.focus()
        // Handles key up events on whole document
        function keyUp(e) {
            if (e.keyCode >= 65 && e.keyCode <= 90) {
                setKey(previous => `${previous}${e.key}`.toUpperCase().slice(0, 5))
            } else if (e.keyCode === 8) {
                setKey(previous => previous.slice(0, previous.length - 1))
            } else if (e.keyCode === 13 && key.length === 5) {
                setKey("")
                setGuess(key)
                setCounter(counter => counter + 1)
                searchInput2.current.focus()
            }
        }
        window.addEventListener("keyup", keyUp)
        return () => window.removeEventListener("keyup", keyUp)
    }, [key]);

    // Stores separated guess into array
    if (guess.length === 5) {
        userGuess = guess.split("")
    }

    return (
        <div className="container">
            <br></br>
            <br></br>
            <br></br>
            <div className="row">
                <input ref={searchInput1} className="letter-tile" style={{ color: textColor, backgroundColor: bgColor }} value={displayLetter.slice(0, 1)} readOnly={true} />
                <input className="letter-tile" style={{ color: textColor, backgroundColor: bgColor }} value={displayLetter.slice(1, 2)} readOnly={true} />
                <input className="letter-tile" style={{ color: textColor, backgroundColor: bgColor }} value={displayLetter.slice(2, 3)} readOnly={true} />
                <input className="letter-tile" style={{ color: textColor, backgroundColor: bgColor }} value={displayLetter.slice(3, 4)} readOnly={true} />
                <input className="letter-tile" style={{ color: textColor, backgroundColor: bgColor }} value={displayLetter.slice(4, 5)} readOnly={true} />
                <button type="submit" hidden={true}></button>
            </div>
            <div className="row">
                <input ref={searchInput2} className="letter-tile" style={{ color: textColor, backgroundColor: bgColor }} readOnly={true} />
                <input className="letter-tile" style={{ color: textColor, backgroundColor: bgColor }} readOnly={true} />
                <input className="letter-tile" style={{ color: textColor, backgroundColor: bgColor }} readOnly={true} />
                <input className="letter-tile" style={{ color: textColor, backgroundColor: bgColor }} readOnly={true} />
                <input className="letter-tile" style={{ color: textColor, backgroundColor: bgColor }} readOnly={true} />
            </div>
</code>```

答:
You won't see a value in the second row since there is no value property set for any of the <input> elements. So whatever values you would like to see in the second row should be included there.

If I may also leave at least one unsolicited suggestion for bug prevention and code readability, the guess state variable is initialized as an array, is set to a string once the first row is full, and is compared against an integer near the top of the functional component. I would suggest committing to using one data type for each of your variables to prevent issues in the future. Although you can implicitly compare and cast types in JS, it doesn't mean you should.

One fun example of where comparing different data types can go wrong:

```<code>[] < 0 // evaluates to false

[] >= 0 // evaluates to true
</code>```

Body:
I would like for it to automatically start putting the values from the key down to the new row after the enter key is pressed, right now the values do display on the first row, but after the enter key is pressed it just focuses the next row and does not display the value

import { useState, useEffect, useRef } from "react"

function LetterContainer({ textColor, bgColor }) {
    const [key, setKey] = useState("")
    const [guess, setGuess] = useState([])
    const [counter, setCounter] = useState(0)
    const searchInput1 = useRef(null)
    const searchInput2 = useRef(null)
    const displayLetter = guess < 5 ? key : guess
    let userGuess = []

    useEffect(() => {
        // Sets focus on first row for inital load
        searchInput1.current.focus()
        // Handles key up events on whole document
        function keyUp(e) {
            if (e.keyCode >= 65 && e.keyCode <= 90) {
                setKey(previous => `${previous}${e.key}`.toUpperCase().slice(0, 5))
            } else if (e.keyCode === 8) {
                setKey(previous => previous.slice(0, previous.length - 1))
            } else if (e.keyCode === 13 && key.length === 5) {
                setKey("")
                setGuess(key)
                setCounter(counter => counter + 1)
                searchInput2.current.focus()
            }
        }
        window.addEventListener("keyup", keyUp)
        return () => window.removeEventListener("keyup", keyUp)
    }, [key]);

    // Stores separated guess into array
    if (guess.length === 5) {
        userGuess = guess.split("")
    }

    return (

                <input ref={searchInput1} className="letter-tile" style={{ color: textColor, backgroundColor: bgColor }} value={displayLetter.slice(0, 1)} readOnly={true} />
                <input className="letter-tile" style={{ color: textColor, backgroundColor: bgColor }} value={displayLetter.slice(1, 2)} readOnly={true} />
                <input className="letter-tile" style={{ color: textColor, backgroundColor: bgColor }} value={displayLetter.slice(2, 3)} readOnly={true} />
                <input className="letter-tile" style={{ color: textColor, backgroundColor: bgColor }} value={displayLetter.slice(3, 4)} readOnly={true} />
                <input className="letter-tile" style={{ color: textColor, backgroundColor: bgColor }} value={displayLetter.slice(4, 5)} readOnly={true} />
                <button type="submit" hidden={true}></button>

                <input ref={searchInput2} className="letter-tile" style={{ color: textColor, backgroundColor: bgColor }} readOnly={true} />
                <input className="letter-tile" style={{ color: textColor, backgroundColor: bgColor }} readOnly={true} />
                <input className="letter-tile" style={{ color: textColor, backgroundColor: bgColor }} readOnly={true} />
                <input className="letter-tile" style={{ color: textColor, backgroundColor: bgColor }} readOnly={true} />
                <input className="letter-tile" style={{ color: textColor, backgroundColor: bgColor }} readOnly={true} />

Body:
You won't see a value in the second row since there is no value property set for any of the <input> elements. So whatever values you would like to see in the second row should be included there.

If I may also leave at least one unsolicited suggestion for bug prevention and code readability, the guess state variable is initialized as an array, is set to a string once the first row is full, and is compared against an integer near the top of the functional component. I would suggest committing to using one data type for each of your variables to prevent issues in the future. Although you can implicitly compare and cast types in JS, it doesn't mean you should.

One fun example of where comparing different data types can go wrong:

[] < 0 // evaluates to false

[] >= 0 // evaluates to true


问:
[JavaScript]Add elements to a global array in a function and keep them

window.onload = function(){
    func1();
};

var list = [];

function func1(){
  for(var i = 0; i < 9; i++){
    list.push(i);
  }
}

console.log(list);```

Which the output log is an empty array, then how do I add elements to a global array in a function, and access them globally?

答:
You need to wait for the window to load and call your function func1 before logging the value of the array to console...</p>
```<code>window.onload = function(){
    func1();
    console.log(list);
};

var list = [];

function func1(){
  for(var i = 0; i < 9; i++){
    list.push(i);
  }
}

</code>```

Body:
window.onload = function(){
    func1();
};

var list = [];

function func1(){
  for(var i = 0; i < 9; i++){
    list.push(i);
  }
}

console.log(list);

Which the output log is an empty array, then how do I add elements to a global array in a function, and access them globally?

Body:
You need to wait for the window to load and call your function func1 before logging the value of the array to console...

window.onload = function(){
    func1();
    console.log(list);
};

var list = [];

function func1(){
  for(var i = 0; i < 9; i++){
    list.push(i);
  }
}


问:
Angular | How to add condition to multiple elements by writing once
I have a div with multiple buttons in it... All buttons work similarly and I would like to disable all the buttons when a condition is true.

Currently the way I do it is..

```<code>  <button mat-button [disabled]="isLoading"> X </button>
  <button mat-button [disabled]="isLoading"> Y </button>
  <button mat-button [disabled]="isLoading"> Z </button>
</code>```

Is there a way where I would have to type [disabled]="isLoading" only once.

Something like this (Doesn't Work)

```<code><ng-container [disabled]="isLoading">
  <button mat-button>X</button>
  <button mat-button>Y</button>
  <button mat-button>Z</button>
</ng-container>
</code>```

答:
You can use fieldset HTML element to group several controls.

```<code><fieldset [disabled]="isLoading">
  <button mat-button>X</button>
  <button mat-button>Y</button>
  <button mat-button>Z</button>
</fieldset>
</code>```

Body:
I have a div with multiple buttons in it... All buttons work similarly and I would like to disable all the buttons when a condition is true.

Currently the way I do it is..

  <button mat-button [disabled]="isLoading"> X </button>
  <button mat-button [disabled]="isLoading"> Y </button>
  <button mat-button [disabled]="isLoading"> Z </button>

Is there a way where I would have to type [disabled]="isLoading" only once.

Something like this (Doesn't Work)

<ng-container [disabled]="isLoading">
  <button mat-button>X</button>
  <button mat-button>Y</button>
  <button mat-button>Z</button>
</ng-container>

Body:
You can use fieldset HTML element to group several controls.

<fieldset [disabled]="isLoading">
  <button mat-button>X</button>
  <button mat-button>Y</button>
  <button mat-button>Z</button>
</fieldset>


问:
favicon not working in IE
I have a site using a custom favicon.ico. The favicon displays as expected in all browsers except IE. When trying to display the favicon in IE, I get the big red x; when displaying the favicon in another browser, it displays just fine. The page source includes
 and it does work in other browsers. Thanks for your thoughts.

EDIT: SOLVED: The source of the issue was the file was a jpg renamed to ico. I created the file as an ico and it is working as expected. Thanks for your input.

答:
If you tried everything above and it still doesn’t work in IE, check your IIS settings if you are using a Windows Server.
Make sure that the  HTTP Headers > “Enable content expiration” setting, IS NOT SET to “Expire immediately” </p>

Title: favicon not working in IE


问:
React context state is not being updated
I have a next.js app where I am trying to use react context to export a state. However, the state is not updating and remains as the initial value set by the createContext hook which is undefined in this case. Am I doing something wrong?

This is the file where I create the context:

```<code>import { NextPage } from 'next';
import {
  useState,
  SyntheticEvent,
  createContext,
  useContext,
  ReactNode,
} from 'react';
import { TimeZoneType } from '../CompetitionList/types';

interface Props {
  children: ReactNode;
}

type ContextType = {
  timeZone: TimeZoneType;
  handleTimeZone: (_event: SyntheticEvent, _newZone: TimeZoneType) => void;
};

const TimeZone = createContext<ContextType>({} as ContextType);

const TimeZoneState: NextPage<Props> = ({ children }) => {
  const [timeZone, setTimeZone] = useState<TimeZoneType>('Local');
  const handleTimeZone = (_event: SyntheticEvent, newZone: TimeZoneType) => {
    if (newZone !== null) {
      setTimeZone(newZone);
    }
  };
  return (
    <TimeZone.Provider value={{ timeZone, handleTimeZone }}>
      {children}
    </TimeZone.Provider>
  );
};

export const useTimeZone = () => {
  return useContext(TimeZone);
};
</code>```

I call the context similar to this:

```<code>import { useTimeZone } from '../components/GlobalVariables/TimeZone';
...

const { timeZone, handleTimeZone } = useTimeZone();
console.log({timeZone})
//returns undefined
</code>```

Sorry if this is a bad question it is my first one.

答:
I think I found a workaround. I just needed to wrap my TimeZone.Provider around the components where I wanted to use my context. So, I exported the TimeZoneState function and wrapped it around my page components in _app.tsx like this:

```<code>const MyApp = ({ Component, pageProps }: AppProps) => {
  return (
    <TimeZoneState>
      <Component {...pageProps} />
    </TimeZoneState>
  );
};

export default MyApp
</code>```

This allowed me to use my context inside my pages how I wanted to.

```<code>import { useTimeZone } from '../components/GlobalVariables/TimeZone';
...

const { timeZone, handleTimeZone } = useTimeZone();
</code>```

Body:
I have a next.js app where I am trying to use react context to export a state. However, the state is not updating and remains as the initial value set by the createContext hook which is undefined in this case. Am I doing something wrong?

This is the file where I create the context:

import { NextPage } from 'next';
import {
  useState,
  SyntheticEvent,
  createContext,
  useContext,
  ReactNode,
} from 'react';
import { TimeZoneType } from '../CompetitionList/types';

interface Props {
  children: ReactNode;
}

type ContextType = {
  timeZone: TimeZoneType;
  handleTimeZone: (_event: SyntheticEvent, _newZone: TimeZoneType) => void;
};

const TimeZone = createContext<ContextType>({} as ContextType);

const TimeZoneState: NextPage<Props> = ({ children }) => {
  const [timeZone, setTimeZone] = useState<TimeZoneType>('Local');
  const handleTimeZone = (_event: SyntheticEvent, newZone: TimeZoneType) => {
    if (newZone !== null) {
      setTimeZone(newZone);
    }
  };
  return (
    <TimeZone.Provider value={{ timeZone, handleTimeZone }}>
      {children}
    </TimeZone.Provider>
  );
};

export const useTimeZone = () => {
  return useContext(TimeZone);
};

I call the context similar to this:

import { useTimeZone } from '../components/GlobalVariables/TimeZone';
...

const { timeZone, handleTimeZone } = useTimeZone();
console.log({timeZone})
//returns undefined

Sorry if this is a bad question it is my first one.

Body:
I think I found a workaround. I just needed to wrap my TimeZone.Provider around the components where I wanted to use my context. So, I exported the TimeZoneState function and wrapped it around my page components in _app.tsx like this:

const MyApp = ({ Component, pageProps }: AppProps) => {
  return (
    <TimeZoneState>
      <Component {...pageProps} />
    </TimeZoneState>
  );
};

export default MyApp

This allowed me to use my context inside my pages how I wanted to.

import { useTimeZone } from '../components/GlobalVariables/TimeZone';
...

const { timeZone, handleTimeZone } = useTimeZone();


问:
How can I fix the discrepancy between root directories when building an Electron.js project?
When running my Electron project normally, like electron ./artist-test-kit-main.js, everything works fine. When I build the project into an executable, attempts to load files start failing, like: Uncaught Error: ENOENT: no such file or directory, open 'asset-editor\data.json' So I ran a test to see if there's a difference in the root directory between the normal (electron ./artist-test-kit-main.js) execution and the .exe's.

Within index.js (launched by index.html, launched by artist-test-kit-main.js which is a standard electron.js initiator file):

```<code>console.log(fs.readdirSync('./'))
</code>```

In the .exe, this outputs:

In the normal dev execution (electron ./artist-test-kit-main.js), this outputs:

This usual root directory of the project is, after being packaged, stored in the resources directory seen in the .exe execution root directory. So now all my file reads seem to be broken because of this discrepancy in root directories.

How can I solve this?

My package.json shows the build arguments used:

```<code>{
  "name": "app",
  "version": "1.0.0",
  "description": "",
  "main": "artist-test-kit-main.js",
  "dependencies": {
    ...
  },
  "scripts": {
    "start": "electron .",
    "start-artist": "electron ./artist-test-kit-main.js",
    "build": "electron-packager ./ game --platform=win32 --arch=x64 --overwrite=true",
    "build-art": "electron-packager ./ asset-editor --platform=win32 --arch=x64 --overwrite=true"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "electron-packager": "^15.4.0"
  }
}
</code>```

答:
TLDR

Use __dirname instead of .

Explanation

. refers to the current working directory (cwd), which is the directory in which the node process was started.

For an unpackaged app, this is usually the root folder of your project, producing the expected results. For a packaged app, the cwd will likely be where the Electron executable is stored. The app's contents (what was previously the root folder) are put inside resources/app or resources/app.asar relative to the executable.

The way to unify the packaged and unpackaged scenarios is to use __dirname, which contains the directory of the currently running Node script. This way, it will be the same as using . in an unpackaged app, but will return the path with resources/app in the packaged scenario, as that is then the location of the currently running Node script.

This is why you'll often see people using something like `file://${__dirname}/assets/index.html` to address files in Electron.

Side note

If you use require('./file.js'), the path is evaluated relative to the location of the calling script and will work as if you had used __dirname.

Body:
When running my Electron project normally, like electron ./artist-test-kit-main.js, everything works fine. When I build the project into an executable, attempts to load files start failing, like: Uncaught Error: ENOENT: no such file or directory, open 'asset-editor\data.json' So I ran a test to see if there's a difference in the root directory between the normal (electron ./artist-test-kit-main.js) execution and the .exe's.

Within index.js (launched by index.html, launched by artist-test-kit-main.js which is a standard electron.js initiator file):

console.log(fs.readdirSync('./'))

In the .exe, this outputs:

In the normal dev execution (electron ./artist-test-kit-main.js), this outputs:

This usual root directory of the project is, after being packaged, stored in the resources directory seen in the .exe execution root directory. So now all my file reads seem to be broken because of this discrepancy in root directories.

How can I solve this?

My package.json shows the build arguments used:

{
  "name": "app",
  "version": "1.0.0",
  "description": "",
  "main": "artist-test-kit-main.js",
  "dependencies": {
    ...
  },
  "scripts": {
    "start": "electron .",
    "start-artist": "electron ./artist-test-kit-main.js",
    "build": "electron-packager ./ game --platform=win32 --arch=x64 --overwrite=true",
    "build-art": "electron-packager ./ asset-editor --platform=win32 --arch=x64 --overwrite=true"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "electron-packager": "^15.4.0"
  }
}


问:
Flutter Plugin 'permission_handler' causing errors during build
I'm trying to build my Flutter app and I keep running into an issue where the build fails and throws the following errors:

```<code>Task :permission_handler:compileDebugJavaWithJavac FAILED
/Users/ralph/Documents/flutter/.pub-cache/hosted/pub.dartlang.org/permission_handler-6.1.3/android/src/main/java/com/baseflow/permissionhandler/ServiceManager.java:152: warning: [deprecation] getDefaultAdapter() in BluetoothAdapter has been deprecated
        final BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
                                                                  ^
error: warnings found and -Werror specified
1 error
1 warning

warnings found and -Werror specified
</code>```

Below is my output from flutter doctor -v:

```<code>[✓] Flutter (Channel stable, 2.10.0, on macOS 12.0.1 21A559 darwin-arm, locale en-US)
    • Flutter version 2.10.0 at /Users/ralph/Documents/flutter
    • Upstream repository https://github.com/flutter/flutter.git
    • Framework revision 5f105a6ca7 (11 days ago), 2022-02-01 14:15:42 -0800
    • Engine revision 776efd2034
    • Dart version 2.16.0
    • DevTools version 2.9.2

[✓] Android toolchain - develop for Android devices (Android SDK version 32.1.0-rc1)
    • Android SDK at /Users/ralph/Library/Android/sdk
    • Platform android-32, build-tools 32.1.0-rc1
    • Java binary at: /Applications/Android Studio.app/Contents/jre/Contents/Home/bin/java
    • Java version OpenJDK Runtime Environment (build 11.0.11+0-b60-7772763)
    • All Android licenses accepted.

[✓] Xcode - develop for iOS and macOS (Xcode 13.2.1)
    • Xcode at /Applications/Xcode.app/Contents/Developer
    • CocoaPods version 1.11.2

[✓] Chrome - develop for the web
    • Chrome at /Applications/Google Chrome.app/Contents/MacOS/Google Chrome

[✓] Android Studio (version 2021.1)
    • Android Studio at /Applications/Android Studio.app/Contents
    • Flutter plugin can be installed from:
       https://plugins.jetbrains.com/plugin/9212-flutter
    • Dart plugin can be installed from:
       https://plugins.jetbrains.com/plugin/6351-dart
    • Java version OpenJDK Runtime Environment (build 11.0.11+0-b60-7772763)

[✓] VS Code (version 1.64.2)
    • VS Code at /Applications/Visual Studio Code.app/Contents
    • Flutter extension version 3.34.0

[✓] Connected device (1 available)
    • Chrome (web) • chrome • web-javascript • Google Chrome 98.0.4758.80

[✓] HTTP Host Availability
    • All required HTTP hosts are available

• No issues found!
</code>```

The thing is I am not even using permission_handler in my project dependencies.
Below are my project dependencies:

```<code>cupertino_icons: ^1.0.2
  get: 4.1.4
  image_picker: any
  image_cropper: any
  flutter_image_compress: any
  universal_html: any
  intl_phone_number_input: 0.7.0+2
  step_progress_indicator: 1.0.1
  intl: 0.17.0
  shared_preferences: any
  otp_text_field: 1.1.1
  connectivity: 3.0.6
  readmore: 2.1.0
  google_fonts: 2.1.0
  otp_count_down: 1.0.6
  firebase_messaging: any
  flutter_local_notifications: any
  firebase_core: any
  flutter_svg: 0.22.0
  table_calendar: 3.0.1
  flutter_time_picker_spinner: 2.0.0
  google_maps_flutter: any
  custom_info_window: any
  bubble: 1.2.1
  double_back_to_close_app: 2.0.1
  group_radio_button: 1.1.0
  graphql_flutter: 5.0.0
  hive: any
  hive_flutter: any
  path_provider: any
  google_maps_place_picker: any
  flutter_speed_dial: 4.2.0
  emoji_picker: any
  emoji_picker_flutter: 1.0.6
  flutter_slidable: 0.6.0
  firebase_auth: any
  amplify_auth_cognito: any
  amplify_flutter: any
  amplify_datastore: any
  amplify_api: any
  amplify_storage_s3: 0.2.2
  crypto: 3.0.1
  latlong: 0.6.1
  geolocator: 7.7.1
  flutter_native_splash: 1.2.2
  skeleton_loader: 2.0.0+4
  cached_network_image: 3.1.0
  emojis: 0.9.3
  autocomplete_textfield: 1.7.3
  mqtt_client: 9.6.0
  pull_to_refresh: 2.0.0
  flutter_cache_manager: 3.1.2
  wc_flutter_share: 0.4.0
  custom_refresh_indicator: 1.0.0
  flutter_contacts: 1.1.1+2
  grouped_list: 4.1.0
  full_screen_image: 1.0.2
  loadmore: 2.0.1
  flutter_dotenv: 5.0.2
  stamp_image: 0.0.2
  proste_bezier_curve: 2.0.2
  screenshot: 1.2.3
  flutter_autolink_text: 1.0.0+1
  url_launcher: any
  flutter_offline: 2.0.0
  internet_connection_checker: 0.0.1+3
  flutter_rating_bar: 4.0.0
  get_storage: 2.0.3
  twilio_flutter: 0.0.9
  upgrader: any
  google_ml_vision: 0.0.7
</code>```

How do I resolve this issue ??

答:
try one of the following

, run

flutter clean

then restart the emulator

, run

flutter pub get

then restart the emulator

hope its work

Body:
I'm trying to build my Flutter app and I keep running into an issue where the build fails and throws the following errors:

Task :permission_handler:compileDebugJavaWithJavac FAILED
/Users/ralph/Documents/flutter/.pub-cache/hosted/pub.dartlang.org/permission_handler-6.1.3/android/src/main/java/com/baseflow/permissionhandler/ServiceManager.java:152: warning: [deprecation] getDefaultAdapter() in BluetoothAdapter has been deprecated
        final BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
                                                                  ^
error: warnings found and -Werror specified
1 error
1 warning

warnings found and -Werror specified

Below is my output from flutter doctor -v:

[✓] Flutter (Channel stable, 2.10.0, on macOS 12.0.1 21A559 darwin-arm, locale en-US)
    • Flutter version 2.10.0 at /Users/ralph/Documents/flutter
    • Upstream repository https://github.com/flutter/flutter.git
    • Framework revision 5f105a6ca7 (11 days ago), 2022-02-01 14:15:42 -0800
    • Engine revision 776efd2034
    • Dart version 2.16.0
    • DevTools version 2.9.2

[✓] Android toolchain - develop for Android devices (Android SDK version 32.1.0-rc1)
    • Android SDK at /Users/ralph/Library/Android/sdk
    • Platform android-32, build-tools 32.1.0-rc1
    • Java binary at: /Applications/Android Studio.app/Contents/jre/Contents/Home/bin/java
    • Java version OpenJDK Runtime Environment (build 11.0.11+0-b60-7772763)
    • All Android licenses accepted.

[✓] Xcode - develop for iOS and macOS (Xcode 13.2.1)
    • Xcode at /Applications/Xcode.app/Contents/Developer
    • CocoaPods version 1.11.2

[✓] Chrome - develop for the web
    • Chrome at /Applications/Google Chrome.app/Contents/MacOS/Google Chrome

[✓] Android Studio (version 2021.1)
    • Android Studio at /Applications/Android Studio.app/Contents
    • Flutter plugin can be installed from:
       https://plugins.jetbrains.com/plugin/9212-flutter
    • Dart plugin can be installed from:
       https://plugins.jetbrains.com/plugin/6351-dart
    • Java version OpenJDK Runtime Environment (build 11.0.11+0-b60-7772763)

[✓] VS Code (version 1.64.2)
    • VS Code at /Applications/Visual Studio Code.app/Contents
    • Flutter extension version 3.34.0

[✓] Connected device (1 available)
    • Chrome (web) • chrome • web-javascript • Google Chrome 98.0.4758.80

[✓] HTTP Host Availability
    • All required HTTP hosts are available

• No issues found!

The thing is I am not even using permission_handler in my project dependencies.
Below are my project dependencies:

cupertino_icons: ^1.0.2
  get: 4.1.4
  image_picker: any
  image_cropper: any
  flutter_image_compress: any
  universal_html: any
  intl_phone_number_input: 0.7.0+2
  step_progress_indicator: 1.0.1
  intl: 0.17.0
  shared_preferences: any
  otp_text_field: 1.1.1
  connectivity: 3.0.6
  readmore: 2.1.0
  google_fonts: 2.1.0
  otp_count_down: 1.0.6
  firebase_messaging: any
  flutter_local_notifications: any
  firebase_core: any
  flutter_svg: 0.22.0
  table_calendar: 3.0.1
  flutter_time_picker_spinner: 2.0.0
  google_maps_flutter: any
  custom_info_window: any
  bubble: 1.2.1
  double_back_to_close_app: 2.0.1
  group_radio_button: 1.1.0
  graphql_flutter: 5.0.0
  hive: any
  hive_flutter: any
  path_provider: any
  google_maps_place_picker: any
  flutter_speed_dial: 4.2.0
  emoji_picker: any
  emoji_picker_flutter: 1.0.6
  flutter_slidable: 0.6.0
  firebase_auth: any
  amplify_auth_cognito: any
  amplify_flutter: any
  amplify_datastore: any
  amplify_api: any
  amplify_storage_s3: 0.2.2
  crypto: 3.0.1
  latlong: 0.6.1
  geolocator: 7.7.1
  flutter_native_splash: 1.2.2
  skeleton_loader: 2.0.0+4
  cached_network_image: 3.1.0
  emojis: 0.9.3
  autocomplete_textfield: 1.7.3
  mqtt_client: 9.6.0
  pull_to_refresh: 2.0.0
  flutter_cache_manager: 3.1.2
  wc_flutter_share: 0.4.0
  custom_refresh_indicator: 1.0.0
  flutter_contacts: 1.1.1+2
  grouped_list: 4.1.0
  full_screen_image: 1.0.2
  loadmore: 2.0.1
  flutter_dotenv: 5.0.2
  stamp_image: 0.0.2
  proste_bezier_curve: 2.0.2
  screenshot: 1.2.3
  flutter_autolink_text: 1.0.0+1
  url_launcher: any
  flutter_offline: 2.0.0
  internet_connection_checker: 0.0.1+3
  flutter_rating_bar: 4.0.0
  get_storage: 2.0.3
  twilio_flutter: 0.0.9
  upgrader: any
  google_ml_vision: 0.0.7

How do I resolve this issue ??


问:
Plesk Server DB query failed: SQLSTATE[HY000] [2002] No such file or directory
So I have just encountered a problem with my Plesk server and have been trying to figure it out. This is on a Plesk Obsidian 18.0.36 server with Ubuntu 20.04 running on MariaDB 10.3.29.

The error:

DB query failed: SQLSTATE[HY000] [2002] No such file or directory
```
<p>And I did what most people would:</p>
<pre class="lang-sh prettyprint-override"><code>plesk repair all -y
DB query failed: SQLSTATE[HY000] [2002] No such file or directory
</code>```

Same error again, so I went on to restart the server and hope that fixed what ever the problem is with the DB.

Didn't work but at least Plesk will show an error page the domains instead of browser saying connection problem.

Went to check DB status:

systemctl status mysql
● mariadb.service - MariaDB 10.3.29 database server
     Loaded: loaded (/lib/systemd/system/mariadb.service; enabled; vendor preset: enabled)
     Active: activating (start) since Sun 2021-07-25 01:37:23 PDT; 11min ago
       Docs: man:mysqld(8)
             https://mariadb.com/kb/en/library/systemd/
    Process: 1220 ExecStartPre=/usr/bin/install -m 755 -o mysql -g root -d /var/run/mysqld (code=exited, status=0/SUCCESS)
    Process: 1288 ExecStartPre=/bin/sh -c systemctl unset-environment _WSREP_START_POSITION (code=exited, status=0/SUCCESS)
    Process: 1291 ExecStartPre=/bin/sh -c [ ! -e /usr/bin/galera_recovery ] && VAR= ||   VAR=`cd /usr/bin/..; /usr/bin/galera_recovery`; [ $? -eq 0 ]   && systemctl set-environment _WSREP_START_POSITION=$VAR >
   Main PID: 1397 (mysqld)
     Status: "Waiting for page cleaner"
      Tasks: 3 (limit: 18993)
     Memory: 79.8M
     CGroup: /system.slice/mariadb.service
             └─1397 /usr/sbin/mysqld
```
<p>It says <code>Waiting for page cleaner</code> very interesting, no idea what that is but I believe it is a buffer cleaner triggered by the restart.</p>
<p>I then tried restarting and stopping the service:</p>
<pre class="lang-sh prettyprint-override"><code>$ systemctl restart mysql
^C
$ systemctl stop mysql
^C
</code>```

The command line just became unresponsive and I have to stop it after a while... So time to went into some deep thinking and googling mode.

I did find out the solution eventually by accident, it is right below this post.

答:
Another solution is:

```<code>sudo cat /var/log/mysql/error.log
</code>```

The last lines of the log will indicate the problem.

Body:
So I have just encountered a problem with my Plesk server and have been trying to figure it out. This is on a Plesk Obsidian 18.0.36 server with Ubuntu 20.04 running on MariaDB 10.3.29.

The error:

DB query failed: SQLSTATE[HY000] [2002] No such file or directory

And I did what most people would:

plesk repair all -y
DB query failed: SQLSTATE[HY000] [2002] No such file or directory

Same error again, so I went on to restart the server and hope that fixed what ever the problem is with the DB.

Didn't work but at least Plesk will show an error page the domains instead of browser saying connection problem.

Went to check DB status:

systemctl status mysql
● mariadb.service - MariaDB 10.3.29 database server
     Loaded: loaded (/lib/systemd/system/mariadb.service; enabled; vendor preset: enabled)
     Active: activating (start) since Sun 2021-07-25 01:37:23 PDT; 11min ago
       Docs: man:mysqld(8)
             https://mariadb.com/kb/en/library/systemd/
    Process: 1220 ExecStartPre=/usr/bin/install -m 755 -o mysql -g root -d /var/run/mysqld (code=exited, status=0/SUCCESS)
    Process: 1288 ExecStartPre=/bin/sh -c systemctl unset-environment _WSREP_START_POSITION (code=exited, status=0/SUCCESS)
    Process: 1291 ExecStartPre=/bin/sh -c [ ! -e /usr/bin/galera_recovery ] && VAR= ||   VAR=`cd /usr/bin/..; /usr/bin/galera_recovery`; [ $? -eq 0 ]   && systemctl set-environment _WSREP_START_POSITION=$VAR >
   Main PID: 1397 (mysqld)
     Status: "Waiting for page cleaner"
      Tasks: 3 (limit: 18993)
     Memory: 79.8M
     CGroup: /system.slice/mariadb.service
             └─1397 /usr/sbin/mysqld

It says Waiting for page cleaner very interesting, no idea what that is but I believe it is a buffer cleaner triggered by the restart.

I then tried restarting and stopping the service:

$ systemctl restart mysql
^C
$ systemctl stop mysql
^C

The command line just became unresponsive and I have to stop it after a while... So time to went into some deep thinking and googling mode.

I did find out the solution eventually by accident, it is right below this post.

Body:
Another solution is:

sudo cat /var/log/mysql/error.log

The last lines of the log will indicate the problem.


问:
How apply src from object when using video-js
I am having hard time using video-player for streaming m3u8 videos
Below works but I want to use src from object

<video
            id="my-video"
            class="video-js"
            autoplay
            preload="auto"
            data-setup="{}"
        >
            <source type="application/x-mpegURL"
            src=https://multiplatform-f.akamaihd.net/i/multi/will/bunny/big_buck_bunny_,640x360_400,640x360_700,640x360_1000,950x540_1500,.f4v.csmil/master.m3u8
            />
        </video>
```
<p>Instead of using hard coded src, I am trying to get src from an object that looks like this :</p>
<pre class="lang-js prettyprint-override"><code>    post: [{post_no:1,post_author:"Mercy", url:"http://demo.unified-streaming.com/video/tears-of-steel/tears-of-steel.ism/.m3u8",},],
</code>```

So I thought I could do something like this which none of them worked

idea 1

<video
            id="my-video"
            class="video-js"
            controls
            autoplay
            preload="auto"
            data-setup="{}"
        >
            <source type="application/x-mpegURL"
            :src="post.url"
            />
        </video>
```
<h3>idea 2</h3>
<pre class="lang-js prettyprint-override"><code>playerOptions: {
                    preload: "auto",
                    autoplay: true,
                    muted: true,
                    loop: true,
                    aspectRatio: "4:3",
                    sources: [
                        {
                            type: "application/x-mpegURL",
                            src: this.post.url,
                        },
                    ],
                },
</code>```

Sadly, none of them worked. Is there any way I can do?

答:
I managed to figure it out.
Instead of using method, using created() solved this problem.
So my source code is like this :

    created() {
            this.playerOptions = {
                preload: "auto",
                autoplay: true,
                muted: true,
                loop: true,
                aspectRatio: "4:3",
                sources: [
                    {
                        type: "application/x-mpegURL",
                        src: this.post.url,
                    },
                ],
            };
        },
```

Body:
I am having hard time using video-player for streaming m3u8 videos
Below works but I want to use src from object

<video
            id="my-video"
            class="video-js"
            autoplay
            preload="auto"
            data-setup="{}"
        >
            <source type="application/x-mpegURL"
            src=https://multiplatform-f.akamaihd.net/i/multi/will/bunny/big_buck_bunny_,640x360_400,640x360_700,640x360_1000,950x540_1500,.f4v.csmil/master.m3u8
            />
        </video>

Instead of using hard coded src, I am trying to get src from an object that looks like this :

    post: [{post_no:1,post_author:"Mercy", url:"http://demo.unified-streaming.com/video/tears-of-steel/tears-of-steel.ism/.m3u8",},],

So I thought I could do something like this which none of them worked

idea 1

<video
            id="my-video"
            class="video-js"
            controls
            autoplay
            preload="auto"
            data-setup="{}"
        >
            <source type="application/x-mpegURL"
            :src="post.url"
            />
        </video>

idea 2

playerOptions: {
                    preload: "auto",
                    autoplay: true,
                    muted: true,
                    loop: true,
                    aspectRatio: "4:3",
                    sources: [
                        {
                            type: "application/x-mpegURL",
                            src: this.post.url,
                        },
                    ],
                },

Sadly, none of them worked. Is there any way I can do?


问:
Return URL image in Laravel API
I need to return URL path and name image from database.

This my call method to get data from database:

```<code>public function index(){
    $rav=Rav::select('id','image','nameravs')->get('image');
    return $this->sendResponse($rav->toArray(),'rav show is succesfuly');
}
</code>```

Output data it look like this:

{
              "id": 88,
              "image": "1579781806.png",
              "nameravs": "asdad"
          },

But I want to return image with path URL like this:

"image": http://127.0.0.1:8000/images_ravs/1579781806.png

答:
In the Model you can create getAttribute:

```<code>   public function getImageAttribute()
    {
      return $this->attributes['image'] ? URL::to('/uploads/' . $this->attributes['image']) : null;
    }
</code>```

Or you can create custom casts file:

```<code>    protected $casts = [
        'image' => ImageCast::class,
        'created_at' => 'datetime',
        'updated_at' => 'datetime',
    ];
</code>```

Title: Return URL image in Laravel API

Body:
I need to return URL path and name image from database.

This my call method to get data from database:

public function index(){
    $rav=Rav::select('id','image','nameravs')->get('image');
    return $this->sendResponse($rav->toArray(),'rav show is succesfuly');
}

Output data it look like this:

{
              "id": 88,
              "image": "1579781806.png",
              "nameravs": "asdad"
          },

But I want to return image with path URL like this:

"image": http://127.0.0.1:8000/images_ravs/1579781806.png

Body:
In the Model you can create getAttribute:

   public function getImageAttribute()
    {
      return $this->attributes['image'] ? URL::to('/uploads/' . $this->attributes['image']) : null;
    }

Or you can create custom casts file:

    protected $casts = [
        'image' => ImageCast::class,
        'created_at' => 'datetime',
        'updated_at' => 'datetime',
    ];


问:
How to Access styles from React?
I am trying to access the width and height styles of a div in React but I have been running into one problem. This is what I got so far:

```<code>componentDidMount()  {
  console.log(this.refs.container.style);
}

render()  {
   return (
      <div ref={"container"} className={"container"}></div>  //set reff
   );
}
</code>```

This works but the output that I get is a CSSStyleDeclaration object and in the all property I can all the CSS selectors for that object but they none of them are set. They are all set to an empty string.

This is the output of the CSSStyleDecleration is: http://pastebin.com/wXRPxz5p

Any help on getting to see the actual styles (event inherrited ones) would be greatly appreciated!

Thanks!

答:
In case of function components use the useRef Hook:

```<code>const _optionsButton = useRef(null);
const _onSelectText = (event) => {
  if (true) {
    _optionsButton.current.style["display"] = "block";
  } else {
    _optionsButton.current.style["display"] = "none";
  }
  console.log(_optionsButton.current.style); //all styles applied to element
};
</code>```

add ref attribute to component

```<code><IconButton
  style={{
    color: "rgba(0, 0, 0, 0.54)",
    fill: "rgba(0, 0, 0, 0.54)",
    border: "1px solid rgba(0, 0, 0, 0.54)",
    position: "absolute",
    display: "none",
  }}
  color="primary"
  component="span"
  onClick={() => {}}
  ref={_optionsButton} //this
>
  Check
</IconButton>;
</code>```

Thank you

Title: How to Access styles from React?

Body:
I am trying to access the width and height styles of a div in React but I have been running into one problem. This is what I got so far:

componentDidMount()  {
  console.log(this.refs.container.style);
}

render()  {
   return (

  //set reff
   );
}

This works but the output that I get is a CSSStyleDeclaration object and in the all property I can all the CSS selectors for that object but they none of them are set. They are all set to an empty string.

This is the output of the CSSStyleDecleration is: http://pastebin.com/wXRPxz5p

Any help on getting to see the actual styles (event inherrited ones) would be greatly appreciated!

Thanks!

Body:
In case of function components use the useRef Hook:

const _optionsButton = useRef(null);
const _onSelectText = (event) => {
  if (true) {
    _optionsButton.current.style["display"] = "block";
  } else {
    _optionsButton.current.style["display"] = "none";
  }
  console.log(_optionsButton.current.style); //all styles applied to element
};

add ref attribute to component

<IconButton
  style={{
    color: "rgba(0, 0, 0, 0.54)",
    fill: "rgba(0, 0, 0, 0.54)",
    border: "1px solid rgba(0, 0, 0, 0.54)",
    position: "absolute",
    display: "none",
  }}
  color="primary"
  component="span"
  onClick={() => {}}
  ref={_optionsButton} //this
>
  Check
</IconButton>;

Thank you


问:
iOS Stop Audio Playback At Certain Time (AVAudioPlayer End Time)
I'm wanting to play just part of an audio file. This audio file contains 232 spoken words, I have a dictionary that contains the start time of each word. So I have the start and stop times I just can't find a way to stop at a given time or play the file for a certain duration. Any advice and/or sample code to help me would be much appreciated, thanks Jason.

So I've found a solution, there's a problem with how I get endTime but I sure I can fix it.

```<code>//Prepare to play
[audioPlayer prepareToPlay];

//Get current time from the array using selected word
audioPlayer.currentTime = [[wordsDict objectForKey:selectedWord] floatValue];

//Find end time  - this is a little messy for now
int currentIndex = 0;
int count = 0;

for (NSString* item in wordsKeys) {
    if ([item isEqualToString: selectedWord]) {
        currentIndex = count+1;
    }
    count++;
}

//Store found end time
endTime  = [[wordsDict objectForKey:[wordsKeys objectAtIndex:currentIndex]] floatValue];

//Start Timer
NSTimer * myAudioTimer = [NSTimer scheduledTimerWithTimeInterval:0.1
                                                             target:self
                                                           selector:@selector(checkCurrentTime)
                                                           userInfo:nil
                                                            repeats:YES]
//Now play audio
[audioPlayer play];

//Stop at endTime
- (void) checkCurrentTime {
if(audioPlayer.playing && audioPlayer.currentTime >= endTime)
    [audioPlayer stop];
}
</code>```

答:
The AVAudioPlayer gives you some neat properties to work with:

currentTime: during playback you can rely on this property.

playAtTime : starts playing from a pre-defined time.

But first of all I would write some helpers for that:

```<code>@interface Word {
    double startTime;
    double endTime;
}

@property double startTime;
@property double endTime;

@end
</code>```

This is just a class to simply working with the following method.

```<code>- (void)playWord:(Word *)aWord {

    self.avPlayer.playAtTime = aWord.startTime;
    [avPlayer prepareToPlay];
    [avPlayer play];

    while (avPlayer.playing) {
        /*
        This while loop could be dangerous as it could go on for a long time.
        But because we're just evaluating words, it won't be as much power draining
        */

        if(avPlayer.currentTime >= aWord.endTime;
        [avPlayer stop];
    }
}
</code>```

I would suggest you to use an array or any other mechanism to automatically switch to the next word. Maybe your could also add a Previous and Next button for handling user input.

Please let me know if that worked for you.

HTH

Body:
I'm wanting to play just part of an audio file. This audio file contains 232 spoken words, I have a dictionary that contains the start time of each word. So I have the start and stop times I just can't find a way to stop at a given time or play the file for a certain duration. Any advice and/or sample code to help me would be much appreciated, thanks Jason.

So I've found a solution, there's a problem with how I get endTime but I sure I can fix it.

//Prepare to play
[audioPlayer prepareToPlay];

//Get current time from the array using selected word
audioPlayer.currentTime = [[wordsDict objectForKey:selectedWord] floatValue];

//Find end time  - this is a little messy for now
int currentIndex = 0;
int count = 0;

for (NSString* item in wordsKeys) {
    if ([item isEqualToString: selectedWord]) {
        currentIndex = count+1;
    }
    count++;
}

//Store found end time
endTime  = [[wordsDict objectForKey:[wordsKeys objectAtIndex:currentIndex]] floatValue];

//Start Timer
NSTimer * myAudioTimer = [NSTimer scheduledTimerWithTimeInterval:0.1
                                                             target:self
                                                           selector:@selector(checkCurrentTime)
                                                           userInfo:nil
                                                            repeats:YES]
//Now play audio
[audioPlayer play];

//Stop at endTime
- (void) checkCurrentTime {
if(audioPlayer.playing && audioPlayer.currentTime >= endTime)
    [audioPlayer stop];
}

Body:
The AVAudioPlayer gives you some neat properties to work with:

currentTime: during playback you can rely on this property.

playAtTime : starts playing from a pre-defined time.

But first of all I would write some helpers for that:

@interface Word {
    double startTime;
    double endTime;
}

@property double startTime;
@property double endTime;

@end

This is just a class to simply working with the following method.

- (void)playWord:(Word *)aWord {

    self.avPlayer.playAtTime = aWord.startTime;
    [avPlayer prepareToPlay];
    [avPlayer play];

    while (avPlayer.playing) {
        /*
        This while loop could be dangerous as it could go on for a long time.
        But because we're just evaluating words, it won't be as much power draining
        */

        if(avPlayer.currentTime >= aWord.endTime;
        [avPlayer stop];
    }
}

I would suggest you to use an array or any other mechanism to automatically switch to the next word. Maybe your could also add a Previous and Next button for handling user input.

Please let me know if that worked for you.

HTH


问:
CSS to swap div from desktop to mobile
I have two divs for desktop and mobile, but the div for mobile doesn't show when I use the Inspect tool to pick different sizes for mobile.

.outdoor {
  display:block;
}

.outdoor-m {
  display:none;
}

@media screen and (max-width:600px) {
  .outdoor {
    display:none!important;
  }

  .outdoor-m {
    display:block!important;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="outdoor">
  <img src="outdoor.jpg">
</div>

<div class="outdoor-m">
  <img src="outdoor-600.jpg">
</div></code>```

Really appreciate your help

答:
The following example shows the
 element with the .outdoor class style applied on desktop and tablet devices; this
 element is not displayed on mobile devices. The
 element with the .outdoor-m class style is displayed on mobile devices; this
 element is not displayed on desktop and tablet devices. For mobile compatible devices, the maximum screen width should be 768px to write a media query. To test the application, you can enlarge or reduce the width of the page in the full-screen preview.

.outdoor{
  display: block;
}

.outdoor-m {
  display: none;
}

@media screen and (max-width:768px) {
  .outdoor {
    display: none !important;
  }

  .outdoor-m {
    display: block !important;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><h1 class="outdoor">Active: Desktop</h1>
<h1 class="outdoor-m">Active: Mobile</h1>

<!-- This <div> is displayed on desktop devices and tablets. -->
<div class="outdoor">
  <img src="https://via.placeholder.com/500">
</div>

<!-- On mobile devices this <div> is displayed. -->
<div class="outdoor-m">
  <img src="https://via.placeholder.com/250">
</div></code>```

Title: CSS to swap div from desktop to mobile

Body:
I have two divs for desktop and mobile, but the div for mobile doesn't show when I use the Inspect tool to pick different sizes for mobile.

.outdoor {
  display:block;
}

.outdoor-m {
  display:none;
}

@media screen and (max-width:600px) {
  .outdoor {
    display:none!important;
  }

  .outdoor-m {
    display:block!important;
  }
}

Really appreciate your help

Body:
The following example shows the <div> element with the .outdoor class style applied on desktop and tablet devices; this <div> element is not displayed on mobile devices. The <div> element with the .outdoor-m class style is displayed on mobile devices; this <div> element is not displayed on desktop and tablet devices. For mobile compatible devices, the maximum screen width should be 768px to write a media query. To test the application, you can enlarge or reduce the width of the page in the full-screen preview.

.outdoor{
  display: block;
}

.outdoor-m {
  display: none;
}

@media screen and (max-width:768px) {
  .outdoor {
    display: none !important;
  }

  .outdoor-m {
    display: block !important;
  }
}

<h1 class="outdoor">Active: Desktop</h1>
<h1 class="outdoor-m">Active: Mobile</h1>

<!-- This <div> is displayed on desktop devices and tablets. -->
<div class="outdoor">
  <img src="https://via.placeholder.com/500">
</div>

<!-- On mobile devices this <div> is displayed. -->
<div class="outdoor-m">
  <img src="https://via.placeholder.com/250">
</div>


问:
Running out of HTTP requests with a Ajax function on my server
I don't know so much about servers and HTTP requests limits, in my case I have a Linux Deluxe hosting on GoDaddy, which runs pretty smoothly, but now I would need to understand why my website goes unreachable (ERR_CONNECTION_CLOSED) after launching the following code 2-3 times (the first time it goes fine, the issue comes when I refresh the page 1-2 other times):

My ajax call:

```<code>function XSGetPointer(id, tableName) {
        var pointer;
        var ok = false;

        $.ajax({
            url : TABLES_PATH + 'm-query.php?',
            type: 'POST',
            data: 'tableName=' + tableName,
            async: false,
            success: function(data) {
                var results = JSON.parse(data);
                for(var i=0; i<results.length; i++) {
                    if (results[i]['ID_id'] == id ) {
                        pointer = results[i];
                        ok = true;
                    }
                    if (i == results.length-1 && !ok) {
                        pointer = null;
                    }
                }
            // error
            }, error: function(e) {
                console.log('XSCurrentUser -> Something went wrong: ' + e.message);
        }});
    return pointer;
    }
</code>```

PHP for loop where that JS script gets called:

```<code>for(var i=0; i<objectsArray.length; i++){
    var userPointer = XSGetPointer(objectsArray[i]['PO_userPointer_Users'], 'Users');
    $('#queryData').append(
         '<p>'
        +userPointer['ST_username']+
        '<br></p>'
    );
}// ./ For • Show results
</code>```

The for loop above iterates through 57 items (the objectsArray's length). The m-query.php script simply gets all data from a JSON file, like this:

```<code>// Get JSON data
$data = file_get_contents($tableName. '.json');
$data_array = json_decode($data, true);
echo json_encode(array_values($data_array), JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
</code>```

The support from GoDaddy told me to get a VPS server, but I couldn't understand the real cause of my issue, I suppose is something related to the many HTTP requests I send in the same page, as shown here:

As you can see, my ajax call stops after a few calls, it doesn't get to 57, and the Chrome Console shows:

```<code>jquery-3.4.1.min.js:2 POST https://example.com/m-query.php? net::ERR_CONNECTION_CLOSED
</code>```

I just wanted to know if switching to a VPS server may fix this issue, or if my ajax query is just totally wrong since it's also async: false (I cannot make it true, because it doesn't get JSON data then).

答: I’ve solved the issue by simply moving my php files into an AWS Lightsail instance</p>

Body:
I don't know so much about servers and HTTP requests limits, in my case I have a Linux Deluxe hosting on GoDaddy, which runs pretty smoothly, but now I would need to understand why my website goes unreachable (ERR_CONNECTION_CLOSED) after launching the following code 2-3 times (the first time it goes fine, the issue comes when I refresh the page 1-2 other times):

My ajax call:

function XSGetPointer(id, tableName) {
        var pointer;
        var ok = false;

        $.ajax({
            url : TABLES_PATH + 'm-query.php?',
            type: 'POST',
            data: 'tableName=' + tableName,
            async: false,
            success: function(data) {
                var results = JSON.parse(data);
                for(var i=0; i<results.length; i++) {
                    if (results[i]['ID_id'] == id ) {
                        pointer = results[i];
                        ok = true;
                    }
                    if (i == results.length-1 && !ok) {
                        pointer = null;
                    }
                }
            // error
            }, error: function(e) {
                console.log('XSCurrentUser -> Something went wrong: ' + e.message);
        }});
    return pointer;
    }

PHP for loop where that JS script gets called:

for(var i=0; i<objectsArray.length; i++){
    var userPointer = XSGetPointer(objectsArray[i]['PO_userPointer_Users'], 'Users');
    $('#queryData').append(
         '
'
        +userPointer['ST_username']+
        '

'
    );
}// ./ For • Show results

The for loop above iterates through 57 items (the objectsArray's length). The m-query.php script simply gets all data from a JSON file, like this:

// Get JSON data
$data = file_get_contents($tableName. '.json');
$data_array = json_decode($data, true);
echo json_encode(array_values($data_array), JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);

The support from GoDaddy told me to get a VPS server, but I couldn't understand the real cause of my issue, I suppose is something related to the many HTTP requests I send in the same page, as shown here:

As you can see, my ajax call stops after a few calls, it doesn't get to 57, and the Chrome Console shows:

jquery-3.4.1.min.js:2 POST https://example.com/m-query.php? net::ERR_CONNECTION_CLOSED

I just wanted to know if switching to a VPS server may fix this issue, or if my ajax query is just totally wrong since it's also async: false (I cannot make it true, because it doesn't get JSON data then).


问:
Asking for input again with do while loop in c
I am trying to have the user type in a number between 1 and 8 to print out stuff on screen (height), if the number is lower than 1 or higher than 8 I would like for the program to prompt again for an input instead of it quitting out and say "invalid". I know I have to set it up with do on top and when on the bottom in C, my question is how would I go about it when I have 2 possible outcomes, i.e. too low or too high?</p>
```<code>do {
    int height = get_int(Height: ");
    if (height < 1)
        ~ ~printf("invalid");
    else if (height > 8)
        ~ ~printf("invalid");
} when(???????)

printf("valid")
</code>```

答:
The key is Logical OR operator (||) in logical operator.

A logical operator would :

treats its operands as boolean values

treats a non-zero value operand as true

treats a zero value operand as false

operates the boolean algebra on its operands

returns the boolean algebra result

returns 1 for true boolean result

returns 0 for false boolean result

The Logical OR operator (||) :

```<code>lhs || rhs
</code>```

Here, lhs and rhs are the 2 operands of OR(||) operator

The OR operator returns 1 if any of the following conditions is true:

only lhs is true

only rhs is true

both lhs and rhs are true

In other words, the boolean algebra OR result is true if either lhs or rhs is true.

In your example, there are 2 conditions :

height is less than 1

height is larger than 8

if either of them is true, then the result is true (the loop will continue), so the expression in this example would be :

int height; /* move height outside the loop so it can be used in do-while condition */
do {
    height = get_int();

    if (height < 1)
        printf("invalid\n");
    else if (height > 8)
        printf("invalid\n");
} while(height < 1 || height > 8);

printf("valid\n");
```
<hr />
<p>Furthermore, since we have already done the logical condition in the loop, we can just add a flag variable instead:</p>
<pre class="lang-c prettyprint-override"><code>int flag; /* record the boolean result */
do {
    int height = get_int();

    if (height < 1) {
        printf("invalid\n");
        flag = 1;
    } else if (height > 8) {
        printf("invalid\n");
        flag = 1;
    } else {
        flag = 0; /* !(height < 1 || height > 8) */
    }
} while(flag);

printf("valid\n");
</code>```

Body:
I am trying to have the user type in a number between 1 and 8 to print out stuff on screen (height), if the number is lower than 1 or higher than 8 I would like for the program to prompt again for an input instead of it quitting out and say "invalid". I know I have to set it up with do on top and when on the bottom in C, my question is how would I go about it when I have 2 possible outcomes, i.e. too low or too high?

do {
    int height = get_int(Height: ");
    if (height < 1)
        ~ ~printf("invalid");
    else if (height > 8)
        ~ ~printf("invalid");
} when(???????)

printf("valid")

Body:
The key is Logical OR operator (||) in logical operator.

A logical operator would :

treats its operands as boolean values

treats a non-zero value operand as true

treats a zero value operand as false

operates the boolean algebra on its operands

returns the boolean algebra result

returns 1 for true boolean result

returns 0 for false boolean result

The Logical OR operator (||) :

lhs || rhs

Here, lhs and rhs are the 2 operands of OR(||) operator

The OR operator returns 1 if any of the following conditions is true:

only lhs is true

only rhs is true

both lhs and rhs are true

In other words, the boolean algebra OR result is true if either lhs or rhs is true.

In your example, there are 2 conditions :

height is less than 1

height is larger than 8

if either of them is true, then the result is true (the loop will continue), so the expression in this example would be :

int height; /* move height outside the loop so it can be used in do-while condition */
do {
    height = get_int();

    if (height < 1)
        printf("invalid\n");
    else if (height > 8)
        printf("invalid\n");
} while(height < 1 || height > 8);

printf("valid\n");

Furthermore, since we have already done the logical condition in the loop, we can just add a flag variable instead:

int flag; /* record the boolean result */
do {
    int height = get_int();

    if (height < 1) {
        printf("invalid\n");
        flag = 1;
    } else if (height > 8) {
        printf("invalid\n");
        flag = 1;
    } else {
        flag = 0; /* !(height < 1 || height > 8) */
    }
} while(flag);

printf("valid\n");


问:
Error connecting to server outside database in django
I use external postgreSQL server in django

Test on iPhone to check external connection

It is normally connected from the outside. external_connection_image

```<code>DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql',
        'NAME': 'project5',
        'USER': 'postgres',
        'PASSWORD': 'password',
        'HOST': '112.156.243.133',
        'PORT': '5432',
    }
}
</code>```

I set up the django database with the same dsn as I tested on iPhone.

but django web server can't connect to database.

error code

could not connect to server: Connection refused
Is the server running on host "112.156.243.133" and accepting
TCP/IP connections on port 5432?

Why doesn't it connect?

答:
Generally, when I get errors like this, it is usually due to a Firewall port that needs to be opened on inbound/outbound requests.

If you've tried everything, but it's still not working, then you'll need to ssh into the web server. Then run a packet tracert from the web server to the DB server. You'll be able to see where the packets are getting dropped, which should shed some light on the problem.

You could also try disabling the Firewall completely, to rule it out as a culprit.

Body:
I use external postgreSQL server in django

Test on iPhone to check external connection

It is normally connected from the outside. external_connection_image

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql',
        'NAME': 'project5',
        'USER': 'postgres',
        'PASSWORD': 'password',
        'HOST': '112.156.243.133',
        'PORT': '5432',
    }
}

I set up the django database with the same dsn as I tested on iPhone.

but django web server can't connect to database.

error code

could not connect to server: Connection refused
Is the server running on host "112.156.243.133" and accepting
TCP/IP connections on port 5432?

Why doesn't it connect?


问:
Getting this error: warning: too many arguments for format [-Wformat-extra-args]
```<code>  printf("\nEnter Matrix A\n", i + 1, j + 1);
  for (i = 0; i < r; ++i)
    for (j = 0; j < c; ++j) {
      scanf("%d", &a[i][j]);
    }

  printf("\nEnter Matrix B\n", i + 1, j + 1);
  for (i = 0; i < r; ++i)
    for (j = 0; j < c; ++j) {
      scanf("%d", &b[i][j]);
    }
</code>```

When I compile this, I get an error message saying main.c:9:10: warning: too many arguments for format [-Wformat-extra-args] on lines 10 and 16. I’m new to programming C so any tips would be helpful.

答:
Problem in the code: You are giving extra arguments in the printf() function without specifying format specifier. The syntax of printf() is int printf ( const char * format, ... );

You can check official or this websites to understand details of how to use printf() function.

Solution to your problem:
At line 10 and 16 you can use %d format specifier for two arguments. The code will be printf("\nEnter Matrix A: %d, %d\n", i + 1, j + 1);

However, you should not use those lines to imply matrix dimensions. You can write  something like printf("\nEnter Matrix A: which is (%d by %d) matrix\n", r, c); to denote matrix dimensions.

Body:
  printf("\nEnter Matrix A\n", i + 1, j + 1);
  for (i = 0; i < r; ++i)
    for (j = 0; j < c; ++j) {
      scanf("%d", &a[i][j]);
    }

  printf("\nEnter Matrix B\n", i + 1, j + 1);
  for (i = 0; i < r; ++i)
    for (j = 0; j < c; ++j) {
      scanf("%d", &b[i][j]);
    }

When I compile this, I get an error message saying main.c:9:10: warning: too many arguments for format [-Wformat-extra-args] on lines 10 and 16. I’m new to programming C so any tips would be helpful.


答:
Try this to see if it works for you.

If not, leave a comment to tell me what you really want.

```<code>#include <stdio.h>

int main()
{
    int height = 0;
    while (height < 1 || height > 8) {
        scanf("%d", &height);

        if (height >= 1 && height <= 8) {
            break;
        } else {
            printf("Invalid, please try again.\n");
        }
    }

    printf("Valid.\n");

    return 0;
}
</code>```

Title: Asking for input again with do while loop in c

Body:
Try this to see if it works for you.

If not, leave a comment to tell me what you really want.

#include <stdio.h>

int main()
{
    int height = 0;
    while (height < 1 || height > 8) {
        scanf("%d", &height);

        if (height >= 1 && height <= 8) {
            break;
        } else {
            printf("Invalid, please try again.\n");
        }
    }

    printf("Valid.\n");

    return 0;
}


问:
TS2740: Missing properties from type when using spread operator
I have an object mocking out an Angular ActivatedRouteSnapshot ( see definition ). All the props are mocked out. I am then creating another mock object by just spreading the first object's props into the second.

```<code>export class AddEditResolverMocks {

    static routeWithId: ActivatedRouteSnapshot = {
        params: { id: 123 },
        data: { entity: EntityTypes.PayBillCycle },
        url: [],
        queryParams: {},
        fragment: '',
        outlet: '',
        component: '',
        routeConfig: null,
        root: new ActivatedRouteSnapshot(),
        parent: new ActivatedRouteSnapshot(),
        firstChild: new ActivatedRouteSnapshot(),
        children: [],
        pathFromRoot: [],
        paramMap: null,
        queryParamMap: null,
    };
    static routeWithoutId: ActivatedRouteSnapshot = {
        ...this.routeWithId,
    };
}
</code>```

I thought it would bring over all the props, but VSCode seems to complain with:

```<code>Type '{
    url: UrlSegment[];
    params: Params;
    queryParams: Params;
    fragment: string;
    data: Data;
    outlet: string;
    component: string | Type<any>;
    routeConfig: Route;
}' is missing the following properties from type 'ActivatedRouteSnapshot':
 - root,
 - parent,
 - firstChild,
 - children,
 - and 3 more.ts(2740)
</code>```

When I let VSCode refactor it, the "missing" props are added and the error goes away. So why it not work without explicit initialization? ( feel I am missing something stupid )

I am also surprised that VSCode is allowing a this reference in a static initializer.

UPDATE:
Changing this to AddEditResolverMocks :

```<code> static routeWithoutId: ActivatedRouteSnapshot = {
        ...AddEditResolverMocks.routeWithId,
    };
</code>```

had no effect.

UPDATE 2:
Added definition of ActivatedRouteSnapshot in desc as per comment.

答:
The problem is that these missing properties are not present in the definition of the ActivatedRouteSnapshot class. They are actually getters, not attributes.

However, when there is a getter property without an equivalent setter, the "compiler" assumes this as readonly, which forces you to inform this attribute in the way you are creating the object instance.

But even though you have informed the attributes in this specific instance, the routeWithId variable definition is still ActivatedRouteSnapshot, which does not have these attributes.

For the error to disappear, just remove the definition of the variable:

export class AddEditResolverMocks {

    static routeWithId = {
        params: { id: 123 },
        data: { entity: EntityTypes.PayBillCycle },
        url: [],
        queryParams: {},
        fragment: '',
        outlet: '',
        component: '',
        routeConfig: null,
        root: new ActivatedRouteSnapshot(),
        parent: new ActivatedRouteSnapshot(),
        firstChild: new ActivatedRouteSnapshot(),
        children: [],
        pathFromRoot: [],
        paramMap: null,
        queryParamMap: null,
    };
    static routeWithoutId: ActivatedRouteSnapshot = {
        ...this.routeWithId,
    };
}
```

Still, I recommend that you don't instantiate these objects this way. The most appropriate is to use the new operator and pass the parameters via the constructor.

Also because the constructor performs some operations when receiving these parameters, something you are not doing when instantiating this way. And the extra attributes you are inserting shouldn't exist in this class.

Body:
I have an object mocking out an Angular ActivatedRouteSnapshot ( see definition ). All the props are mocked out. I am then creating another mock object by just spreading the first object's props into the second.

export class AddEditResolverMocks {

    static routeWithId: ActivatedRouteSnapshot = {
        params: { id: 123 },
        data: { entity: EntityTypes.PayBillCycle },
        url: [],
        queryParams: {},
        fragment: '',
        outlet: '',
        component: '',
        routeConfig: null,
        root: new ActivatedRouteSnapshot(),
        parent: new ActivatedRouteSnapshot(),
        firstChild: new ActivatedRouteSnapshot(),
        children: [],
        pathFromRoot: [],
        paramMap: null,
        queryParamMap: null,
    };
    static routeWithoutId: ActivatedRouteSnapshot = {
        ...this.routeWithId,
    };
}

I thought it would bring over all the props, but VSCode seems to complain with:

Type '{
    url: UrlSegment[];
    params: Params;
    queryParams: Params;
    fragment: string;
    data: Data;
    outlet: string;
    component: string | Type<any>;
    routeConfig: Route;
}' is missing the following properties from type 'ActivatedRouteSnapshot':
 - root,
 - parent,
 - firstChild,
 - children,
 - and 3 more.ts(2740)

When I let VSCode refactor it, the "missing" props are added and the error goes away. So why it not work without explicit initialization? ( feel I am missing something stupid )

I am also surprised that VSCode is allowing a this reference in a static initializer.

UPDATE:
Changing this to AddEditResolverMocks :

 static routeWithoutId: ActivatedRouteSnapshot = {
        ...AddEditResolverMocks.routeWithId,
    };

had no effect.

UPDATE 2:
Added definition of ActivatedRouteSnapshot in desc as per comment.

Body:
The problem is that these missing properties are not present in the definition of the ActivatedRouteSnapshot class. They are actually getters, not attributes.

However, when there is a getter property without an equivalent setter, the "compiler" assumes this as readonly, which forces you to inform this attribute in the way you are creating the object instance.

But even though you have informed the attributes in this specific instance, the routeWithId variable definition is still ActivatedRouteSnapshot, which does not have these attributes.

For the error to disappear, just remove the definition of the variable:

export class AddEditResolverMocks {

    static routeWithId = {
        params: { id: 123 },
        data: { entity: EntityTypes.PayBillCycle },
        url: [],
        queryParams: {},
        fragment: '',
        outlet: '',
        component: '',
        routeConfig: null,
        root: new ActivatedRouteSnapshot(),
        parent: new ActivatedRouteSnapshot(),
        firstChild: new ActivatedRouteSnapshot(),
        children: [],
        pathFromRoot: [],
        paramMap: null,
        queryParamMap: null,
    };
    static routeWithoutId: ActivatedRouteSnapshot = {
        ...this.routeWithId,
    };
}

Still, I recommend that you don't instantiate these objects this way. The most appropriate is to use the new operator and pass the parameters via the constructor.

Also because the constructor performs some operations when receiving these parameters, something you are not doing when instantiating this way. And the extra attributes you are inserting shouldn't exist in this class.


问:
JQuery doesnot support custom attribute in IE*?
In html I have on table like this:

then I user jquery to find the table

```<code>var table = $("table[for='availableTimeRanges']");
</code>```

In firefox and chrome, this works,can return the table, but in IE8, nothing return
Then i run below code in IE8, found the attribute value is empty:

```<code>$.each($("table"), function(i,n){
        alert($(n).attr("for")

});
</code>```

what's the reason

答:
In think you should try wrapping your code in $(function(){...});

```<code>$(function(){
   $.each($("table"), function(i,n){
        alert($(n).attr("for")
   });
});
</code>```

Body:
In html I have on table like this:

then I user jquery to find the table

var table = $("table[for='availableTimeRanges']");

In firefox and chrome, this works,can return the table, but in IE8, nothing return
Then i run below code in IE8, found the attribute value is empty:

$.each($("table"), function(i,n){
        alert($(n).attr("for")

});

what's the reason

Body:
In think you should try wrapping your code in $(function(){...});

$(function(){
   $.each($("table"), function(i,n){
        alert($(n).attr("for")
   });
});


问:
How do I add the name of the subjects rather than the index value?
```<code>public void getMarks(int numberOfSubject, String nameOfSubject) throws IOException{
    marks = new int[numberOfSubject];
    nameOfSubject = Arrays.toString(new String[numberOfSubject]);
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    for(int i = 0; i< numberOfSubject;i++){
        System.out.println("Enter the name of the subject "+i);
        numberOfSubject[i] = br.readLine();
        System.out.println("Enter "+ i +" Subject Marks:");
        marks[i] = Integer.parseInt(br.readLine());
        System.out.println(" ");
    }
}
</code>```

Hello Everyone!, hope you are doing fine.

So I was writing a problem statement for entering the grade of the students.

So I'm stuck at this part of the code, where when I print the Enter the subject marks it shows the index value

```<code>System.out.println("Enter "+ i +" Subject Marks:");
</code>```

Instead of the index value I want to actually add the subject name.

Can somebody please guide me?
Thank you In advance.

答:
Considering you want to read details for given number of subjects, and store it, the ideal way is to use a Map.
Please find solution below</p>
```<code>public void getMarks(int numberOfSubjects) throws IOException{ //Removed 2nd parameter as it is not reqd.

    Map<String, Integer> subjectMarksMap = new HashMap<>();

    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    for(int i = 0; i< numberOfSubjects;i++){
        System.out.println("Enter the name of the subject "+i);
        String subject = br.readLine()
        System.out.println("Enter "+ subject +" Subject Marks:"); //You need to use the above read subject name here, not i.
        Integer marks = Integer.parseInt(br.readLine());
        subjectMarksMap.put(subject, marks);
        System.out.println(" ");
    }

}
</code>```

Body:
public void getMarks(int numberOfSubject, String nameOfSubject) throws IOException{
    marks = new int[numberOfSubject];
    nameOfSubject = Arrays.toString(new String[numberOfSubject]);
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    for(int i = 0; i< numberOfSubject;i++){
        System.out.println("Enter the name of the subject "+i);
        numberOfSubject[i] = br.readLine();
        System.out.println("Enter "+ i +" Subject Marks:");
        marks[i] = Integer.parseInt(br.readLine());
        System.out.println(" ");
    }
}

Hello Everyone!, hope you are doing fine.

So I was writing a problem statement for entering the grade of the students.

So I'm stuck at this part of the code, where when I print the Enter the subject marks it shows the index value

System.out.println("Enter "+ i +" Subject Marks:");

Instead of the index value I want to actually add the subject name.

Can somebody please guide me?
Thank you In advance.

Body:
Considering you want to read details for given number of subjects, and store it, the ideal way is to use a Map.
Please find solution below

public void getMarks(int numberOfSubjects) throws IOException{ //Removed 2nd parameter as it is not reqd.

    Map<String, Integer> subjectMarksMap = new HashMap<>();

    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    for(int i = 0; i< numberOfSubjects;i++){
        System.out.println("Enter the name of the subject "+i);
        String subject = br.readLine()
        System.out.println("Enter "+ subject +" Subject Marks:"); //You need to use the above read subject name here, not i.
        Integer marks = Integer.parseInt(br.readLine());
        subjectMarksMap.put(subject, marks);
        System.out.println(" ");
    }

}


问:
MYSQL - How come when I made changes on my schema (I misspelled a word) it didn't update the local instance even after saving and restarting?
How do I show the changes made on my schema on the local instance? Thanks!</p>

答: You often need to actually refresh your schema. If you are building it from the code editor side and migrating and you don't have any data in it yet, it's never a bad idea to just dump it and start fresh though. Are you in a situation where you are making migrations and expecting to see the changes?sample schema right-click refresh option</p>


问:
'ForwardManyToOneDescriptor' object has no attribute 'pk'
Error in the line as below:
'ForwardManyToOneDescriptor' object has no attribute 'pk'

```<code> friend_user = User.objects.get(pk=Friend.to_user.id)
</code>```

Thanking you in advance,

models.py

```<code> class Friend(models.Model):
    status = models.CharField(max_length=10)
    from_user = models.ForeignKey(AUTH_USER_MODEL, on_delete=models.CASCADE, related_name = 'from_user')
    to_user = models.ForeignKey(AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="to_user")
    date_modified = models.DateTimeField(auto_now=True, blank=True)
    date_created = models.DateTimeField(auto_now_add=True, null=True)

   def __str__(self):
      return self.to_user.email
</code>```

答:
The related_name specifies the name of the relation at the target model, so your

to_user = models.ForeignKey(
   AUTH_USER_MODEL,
   on_delete=models.CASCADE,
   related_name="to_user"  # <-- confusing relation name
)
```
<p>adds a relation <code>User.to_user</code>. This is a confusing name because this <code>to_user</code> actually relates to a <code>Friend</code>. And because a foreign key technically allows multiple friends refer to the same user, it should be a plural.</p>
<p>So a better name would be <code>to_friends</code>, which adds <code>Friend.to_user</code> and  <code>User.to_friends</code>:</p>
<pre class="lang-py prettyprint-override"><code>to_user = models.ForeignKey(
    AUTH_USER_MODEL,
    on_delete=models.CASCADE,
    related_name="to_friends"  # <-- better relation name
)
</code>```

Provided you changed the name of the relation, you can find the friend for a given user using:

friend = User.to_friends.get(id=...)
```
<p>assuming the user actually has this friend. If not, you get a <code>Friend.DoesNotExist</code> exception. If you want to avoid that and get a <code>None</code> friend instead, use:</p>
<pre class="lang-py prettyprint-override"><code>friend = User.to_friends.filter(id=...).first()
if friend is not None:
   ... # Do something with friend.
</code>```

Body:
Error in the line as below:
'ForwardManyToOneDescriptor' object has no attribute 'pk'

 friend_user = User.objects.get(pk=Friend.to_user.id)

Thanking you in advance,

models.py

 class Friend(models.Model):
    status = models.CharField(max_length=10)
    from_user = models.ForeignKey(AUTH_USER_MODEL, on_delete=models.CASCADE, related_name = 'from_user')
    to_user = models.ForeignKey(AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="to_user")
    date_modified = models.DateTimeField(auto_now=True, blank=True)
    date_created = models.DateTimeField(auto_now_add=True, null=True)

   def __str__(self):
      return self.to_user.email

Body:
The related_name specifies the name of the relation at the target model, so your

to_user = models.ForeignKey(
   AUTH_USER_MODEL,
   on_delete=models.CASCADE,
   related_name="to_user"  # <-- confusing relation name
)

adds a relation User.to_user. This is a confusing name because this to_user actually relates to a Friend. And because a foreign key technically allows multiple friends refer to the same user, it should be a plural.

So a better name would be to_friends, which adds Friend.to_user and  User.to_friends:

to_user = models.ForeignKey(
    AUTH_USER_MODEL,
    on_delete=models.CASCADE,
    related_name="to_friends"  # <-- better relation name
)

Provided you changed the name of the relation, you can find the friend for a given user using:

friend = User.to_friends.get(id=...)

assuming the user actually has this friend. If not, you get a Friend.DoesNotExist exception. If you want to avoid that and get a None friend instead, use:

friend = User.to_friends.filter(id=...).first()
if friend is not None:
   ... # Do something with friend.


问:
Determining address memory of a library
I'd like to know if somebody would know some tools which can tell you the address memory for a static or dynamic library written in C++ (for windows, linux and macos).

Thanks

答: You can use readelf for Linux, which displays information about ELF files. You can use it to know the addresses of shared libraries (implicitly loaded dynamic libraries) as well as addresses of all the static symbols. You can't however use it for libraries which are explicitly loaded at runtime. You can turn off the Address space randomization in Linux as well.</p>

Title: Determining address memory of a library