Popular New Releases in Command Line Interface
terminal
Windows Terminal Preview v1.13.1098
thefuck
fzf
0.30.0
hyper
3.2.3
alacritty
Alacritty Version 0.10.1
Popular Libraries in Command Line Interface
by ohmyzsh shell
141698 MIT
π A delightful community-driven (with 2,000+ contributors) framework for managing your zsh configuration. Includes 300+ optional plugins (rails, git, macOS, hub, docker, homebrew, node, php, python, etc), 140+ themes to spice up your morning, and an auto-update tool so that makes it easy to keep up with the latest updates from the community.
by microsoft c++
82454 MIT
The new Windows Terminal and the original Windows console host, all in the same place!
by nvbn python
65678 MIT
Magnificent app which corrects your previous console command.
by junegunn go
43649 MIT
:cherry_blossom: A command-line fuzzy finder
by vercel typescript
38268 MIT
A terminal built on web technologies
by alacritty rust
37538 Apache-2.0
A cross-platform, OpenGL terminal emulator.
by sharkdp rust
33294 NOASSERTION
A cat(1) clone with wings.
by GitSquared javascript
33065 GPL-3.0
A cross-platform, customizable science fiction terminal emulator with advanced monitoring & touchscreen support.
by PowerShell csharp
32939 MIT
PowerShell for every system!
Trending New libraries in Command Line Interface
by qier222 javascript
14385 MIT
ι«ι’εΌη第δΈζΉη½ζδΊζζΎε¨οΌζ―ζ Windows / macOS / Linux :electron:
by charmbracelet go
9726 MIT
A powerful little TUI framework π
by aristocratos shell
9013 Apache-2.0
Linux/OSX/FreeBSD resource monitor
by JetBrains kotlin
8605 Apache-2.0
Compose Multiplatform, a modern UI framework for Kotlin that makes building performant and beautiful user interfaces easy and enjoyable.
by muesli go
8271 NOASSERTION
Disk Usage/Free Utility - a better 'df' alternative
by extrawurst rust
7791 MIT
Blazing π₯ fast terminal-ui for git written in rust π¦
by willmcgugan python
6803 MIT
Textual is a TUI (Text User Interface) framework for Python inspired by modern web development.
by Miodec typescript
6320 GPL-3.0
The most customizable typing website with a minimalistic design and a ton of features. Test yourself in various modes, track your progress and improve your speed.
by zellij-org rust
6038 MIT
A terminal workspace with batteries included
Top Authors in Command Line Interface
1
78 Libraries
94730
2
71 Libraries
37244
3
56 Libraries
2964
4
48 Libraries
1321
5
46 Libraries
42095
6
39 Libraries
3783
7
26 Libraries
6580
8
24 Libraries
3024
9
23 Libraries
860
10
23 Libraries
6634
1
78 Libraries
94730
2
71 Libraries
37244
3
56 Libraries
2964
4
48 Libraries
1321
5
46 Libraries
42095
6
39 Libraries
3783
7
26 Libraries
6580
8
24 Libraries
3024
9
23 Libraries
860
10
23 Libraries
6634
Trending Kits in Command Line Interface
A Python package called "colorama" enables you to print colourful text on the terminal. Both Windows and Linux/Unix systems are compatible with it, and it has the ability to recognise whether it is operating on Windows or not and adapt its behaviour accordingly.β―
There are several applications for colourful text printing on terminals, some of which are as follows:β―
- Debugging: You may rapidly find and discover mistakes in your code by printing coloured text, which makes debugging simpler.β―
- Status updates: Updates on the state of your code can be made using coloured text, such as if a task has been successfully completed or if an error has occurred.β―
- User interaction: Using coloured text to make your code output more aesthetically pleasing and approachable can increase user satisfaction and engagement.β―
- Logging: To make log files for debugging, monitoring, and troubleshooting your code simpler to see and analyse, you can use coloured text.β―
- Data visualization: Colored text can be used to visualise data by using color coding, making it easier to comprehend and analyse the information.β―
- CLI tools: Colored text can be used to enhance a command-line tool's user interface.β―
Here is how you can print coloured text in Terminal:β―
Preview of the output that you will get on running this code in your IDE
Code
In this solution we have used Colorama Library.
- Copy this code using "Copy "button above and paste it in your python file IDE
- Add Colorama Library to run this code
- Run the code to get the texts coloured.
I hope you found this useful i have added the Dependent libraries , versions in the following sections
I have searched using "Print Coloured Text in Terminal" in Kandi. you can try any use case
Environment Tested
I have tested this solution with following versions. Be mindful of changes when working with other versions
- This solution is created and executed in Python 3.7.15 version.
- This solution is tested on Colorama 0.4.6 version.
Using this solution we able to change the style , color, Brightness of the Text in Terminal using Colorama Library in python with simple steps. This process also facilities an easy to use, hassle free method to create a hands-on working version of code which would help us edit the text in Python.
Dependent Library
If you don't have this Colorama Library that required to run this code. You can install by clicking the above link and copying the pip install command from the Colorama page in Kandi. You can search any Library Like colorama in kandi
Support
- For any support on kandi solution kits, please use the chat
- For further learning resources, visit the Open Weaver Community learning page.
We can use ANSI escape codes to print specific words in color to the output terminal in Linux or macOS. ANSI escape codes are special sequences of characters that can be used to change the formatting of text in the terminal, including the color. Some commonly used ANSI escape codes for changing the color of text:
- \033[0;30m to \033[0;37m changes the text color to a color from black to white.
- \033[1;30m to \033[1;37m changes the text color to a color from black to white with bright effect.
- \033[4;30m to \033[4;37m changes the text color to a color from black to white with underline effect.
ANSI escape codes are special sequences of characters that can be used to change the formatting of text in the terminal, including the color, font style, cursor position, and more. They are known as ANSI escape codes because they were originally defined by the American National Standards Institute (ANSI). You can also change font style to bold and underlining using ANSI codes.
- \033[1m sets text in bold
- \033[4m sets text in underline
After applying the formatting, you can reset it back to default by sending \033[0m.
To learn more about printing specific words in color to the output terminal, you may have a look at the code below.
Preview of the output that you will get on running this code in your IDE
Code
- Copy this code using "Copy "button above and paste it in your python file IDE
- Run the code to get the texts coloured.
I have searched using "Print specific words in color to output terminal" in Kandi. you can try any use case
Environment Tested
I have tested this solution with following versions. Be mindful of changes when working with other versions
- This solution is created and executed in Python 3.7.15 version
Using this solution we able to color the text using if case, printing the output depending on Output of the code . This process also facilities an easy to use, hassle free method to create a hands-on working version of code which would help us color the text in Python.
Support
- For any support on kandi solution kits, please use the chat
- For further learning resources, visit the Open Weaver Community learning page.
Trending Discussions on Command Line Interface
Argparse outputting help text twice
Solving conda environment stuck
Mysql Error while piping database to different server
Shell script to pull row counts from all Hive tables in multiple Hive databases
See workspace in MATLAB command line terminal
How can I fix "Failed to compile src/index.js 'firebase' is not defined no-undef"?
Array of structs only takes last value in C
How to detect if Python is running in Git Bash terminal, or Windows cmd?
Connecting to MySQL server in a script returns error, but it works fine in a terminal
Python 3 + Click: CLI arguments get butchered when calling one command from another
QUESTION
Argparse outputting help text twice
Asked 2022-Feb-25 at 21:44After an hour googling, I can't find anybody who has had anything resembling this issue besides myself. I created a command line interface with argparse. Originally I had tried to leverage argparse's built in help text behavior. But my boss isn't satisfied with the default help text, so he is having me write up the full usage/help text in a text file and just display the entire file.
For some reason, in a certain case, its outputting the text twice.
Here is the basics of how my program is broken down:
I have a top level parser. I read in my help text file, set it to a string help_text, and then set "usage=help_text" on the parser. Then I create subparsers (4 of them and then a base case) to create subcommands. Only one of those subparsers has any additional arguments (one positional, one optional). Before I reworked the help text, I had help text for each individual subcommand by using "help=" but now those are all blank. Lastly, I have set up a base case to display the help text whenever no subcommands are given.
Here is the behavior I'm getting:
When I call the main function with no subcommands and no arguments, my help_text from the text file outputs, and then like 2-3 additional lines of boiler plate I can't seem to get rid of. Also because the word usage appears in my text file, it says "usage: usage"
When I call the main command and then type --help, the exact same thing happens as above.
When I call the one subcommand that has a required positional argument and I don't include that argument... it spits out the entire help text twice. Right above the second time it prints, it prints the default usage line for that subcommand.
Lastly, when I use a different subcommand that has no arguments and give it an argument (one too many) it spits out everything completely correctly without even the extra couple lines at the end.
I don't know how to make heads or tales about this. Here is the main function of the script (I can verify that this problem occurs only in the main function where argparse is used, not the other functions that the main function calls):
1def main():
2 # Import help text from file
3 p = Path(__file__).with_name("help_text.txt")
4 with p.open() as file:
5 help_text = file.read()
6
7 # Configure the top level Parser
8 parser = argparse.ArgumentParser(prog='hubmap-clt', description='Name of cli', usage=help_text)
9 subparsers = parser.add_subparsers()
10
11 # Create Subparsers to give subcommands
12 parser_transfer = subparsers.add_parser('subcommandone')
13 parser_transfer.add_argument('argument1', type=str)
14 parser_transfer.add_argument('--optionalargument', default='mydefault')
15 parser_login = subparsers.add_parser('subcommandtwo')
16 parser_whoami = subparsers.add_parser('subcommandthree')
17 parser_logout = subparsers.add_parser('subcommandfour')
18
19 # Assign subparsers to their respective functions
20 parser_subcommandone.set_defaults(func=subcommandone)
21 parser_subcommandtwo.set_defaults(func=subcommandtwo)
22 parser_subcommandthree.set_defaults(func=subcommandthree)
23 parser_subcommandfour.set_defaults(func=subcommandfour)
24 parser.set_defaults(func=base_case)
25
26 # Parse the arguments and call appropriate functions
27 args = parser.parse_args()
28 if len(sys.argv) == 1:
29 args.func(args, parser)
30 else:
31 args.func(args)
32
So to clarify:
Why does the extra couple lines of boiler-plat help text appear sometimes which looks like this:
1def main():
2 # Import help text from file
3 p = Path(__file__).with_name("help_text.txt")
4 with p.open() as file:
5 help_text = file.read()
6
7 # Configure the top level Parser
8 parser = argparse.ArgumentParser(prog='hubmap-clt', description='Name of cli', usage=help_text)
9 subparsers = parser.add_subparsers()
10
11 # Create Subparsers to give subcommands
12 parser_transfer = subparsers.add_parser('subcommandone')
13 parser_transfer.add_argument('argument1', type=str)
14 parser_transfer.add_argument('--optionalargument', default='mydefault')
15 parser_login = subparsers.add_parser('subcommandtwo')
16 parser_whoami = subparsers.add_parser('subcommandthree')
17 parser_logout = subparsers.add_parser('subcommandfour')
18
19 # Assign subparsers to their respective functions
20 parser_subcommandone.set_defaults(func=subcommandone)
21 parser_subcommandtwo.set_defaults(func=subcommandtwo)
22 parser_subcommandthree.set_defaults(func=subcommandthree)
23 parser_subcommandfour.set_defaults(func=subcommandfour)
24 parser.set_defaults(func=base_case)
25
26 # Parse the arguments and call appropriate functions
27 args = parser.parse_args()
28 if len(sys.argv) == 1:
29 args.func(args, parser)
30 else:
31 args.func(args)
32 name of cli
33
34 positional arguments:
35 {subcommandone,subcommandtwo,subcommandthree,subcommandfour}
36
37 optional arguments:
38 -h, --help show this help message and exit
39
Why does using subcommandone with too few arguments print out the help text twice (but NOT the extra lines of boiler-plate help text.
why does using subcommandtwo with one too MANY arguments print everything perfectly without any extra lines?
ANSWER
Answered 2022-Feb-25 at 21:44With a modification of your main
:
1def main():
2 # Import help text from file
3 p = Path(__file__).with_name("help_text.txt")
4 with p.open() as file:
5 help_text = file.read()
6
7 # Configure the top level Parser
8 parser = argparse.ArgumentParser(prog='hubmap-clt', description='Name of cli', usage=help_text)
9 subparsers = parser.add_subparsers()
10
11 # Create Subparsers to give subcommands
12 parser_transfer = subparsers.add_parser('subcommandone')
13 parser_transfer.add_argument('argument1', type=str)
14 parser_transfer.add_argument('--optionalargument', default='mydefault')
15 parser_login = subparsers.add_parser('subcommandtwo')
16 parser_whoami = subparsers.add_parser('subcommandthree')
17 parser_logout = subparsers.add_parser('subcommandfour')
18
19 # Assign subparsers to their respective functions
20 parser_subcommandone.set_defaults(func=subcommandone)
21 parser_subcommandtwo.set_defaults(func=subcommandtwo)
22 parser_subcommandthree.set_defaults(func=subcommandthree)
23 parser_subcommandfour.set_defaults(func=subcommandfour)
24 parser.set_defaults(func=base_case)
25
26 # Parse the arguments and call appropriate functions
27 args = parser.parse_args()
28 if len(sys.argv) == 1:
29 args.func(args, parser)
30 else:
31 args.func(args)
32 name of cli
33
34 positional arguments:
35 {subcommandone,subcommandtwo,subcommandthree,subcommandfour}
36
37 optional arguments:
38 -h, --help show this help message and exit
39def foo():
40 # Import help text from file
41 # p = Path(__file__).with_name("help_text.txt")
42 # with p.open() as file:
43 # help_text = file.read()
44 help_text = "cli usage: foobar\n morebar"
45
46 # Configure the top level Parser
47 parser = argparse.ArgumentParser(
48 prog="hubmap-clt", description="Name of cli", usage=help_text
49 )
50 subparsers = parser.add_subparsers()
51
52 # Create Subparsers to give subcommands
53 parser_transfer = subparsers.add_parser("subcommandone")
54 parser_transfer.add_argument("argument1", type=str)
55 parser_transfer.add_argument("--optionalargument", default="mydefault")
56 parser_login = subparsers.add_parser("subcommandtwo")
57 # parser_whoami = subparsers.add_parser("subcommandthree")
58 # parser_logout = subparsers.add_parser("subcommandfour")
59
60 # Assign subparsers to their respective functions
61 parser_transfer.set_defaults(func="subcommandone")
62 parser_login.set_defaults(func="subcommandtwo")
63 # parser_subcommandthree.set_defaults(func="subcommandthree")
64 # parser_subcommandfour.set_defaults(func="subcommandfour")
65 parser.set_defaults(func="base_case")
66
67 return parser
68
in an iteractive ipython session:
1def main():
2 # Import help text from file
3 p = Path(__file__).with_name("help_text.txt")
4 with p.open() as file:
5 help_text = file.read()
6
7 # Configure the top level Parser
8 parser = argparse.ArgumentParser(prog='hubmap-clt', description='Name of cli', usage=help_text)
9 subparsers = parser.add_subparsers()
10
11 # Create Subparsers to give subcommands
12 parser_transfer = subparsers.add_parser('subcommandone')
13 parser_transfer.add_argument('argument1', type=str)
14 parser_transfer.add_argument('--optionalargument', default='mydefault')
15 parser_login = subparsers.add_parser('subcommandtwo')
16 parser_whoami = subparsers.add_parser('subcommandthree')
17 parser_logout = subparsers.add_parser('subcommandfour')
18
19 # Assign subparsers to their respective functions
20 parser_subcommandone.set_defaults(func=subcommandone)
21 parser_subcommandtwo.set_defaults(func=subcommandtwo)
22 parser_subcommandthree.set_defaults(func=subcommandthree)
23 parser_subcommandfour.set_defaults(func=subcommandfour)
24 parser.set_defaults(func=base_case)
25
26 # Parse the arguments and call appropriate functions
27 args = parser.parse_args()
28 if len(sys.argv) == 1:
29 args.func(args, parser)
30 else:
31 args.func(args)
32 name of cli
33
34 positional arguments:
35 {subcommandone,subcommandtwo,subcommandthree,subcommandfour}
36
37 optional arguments:
38 -h, --help show this help message and exit
39def foo():
40 # Import help text from file
41 # p = Path(__file__).with_name("help_text.txt")
42 # with p.open() as file:
43 # help_text = file.read()
44 help_text = "cli usage: foobar\n morebar"
45
46 # Configure the top level Parser
47 parser = argparse.ArgumentParser(
48 prog="hubmap-clt", description="Name of cli", usage=help_text
49 )
50 subparsers = parser.add_subparsers()
51
52 # Create Subparsers to give subcommands
53 parser_transfer = subparsers.add_parser("subcommandone")
54 parser_transfer.add_argument("argument1", type=str)
55 parser_transfer.add_argument("--optionalargument", default="mydefault")
56 parser_login = subparsers.add_parser("subcommandtwo")
57 # parser_whoami = subparsers.add_parser("subcommandthree")
58 # parser_logout = subparsers.add_parser("subcommandfour")
59
60 # Assign subparsers to their respective functions
61 parser_transfer.set_defaults(func="subcommandone")
62 parser_login.set_defaults(func="subcommandtwo")
63 # parser_subcommandthree.set_defaults(func="subcommandthree")
64 # parser_subcommandfour.set_defaults(func="subcommandfour")
65 parser.set_defaults(func="base_case")
66
67 return parser
68In [8]: p = foo()
69
70In [9]: p.print_usage()
71usage: cli usage: foobar
72 morebar
73
Usage is exactly as I specified. And the help for the main parser:
1def main():
2 # Import help text from file
3 p = Path(__file__).with_name("help_text.txt")
4 with p.open() as file:
5 help_text = file.read()
6
7 # Configure the top level Parser
8 parser = argparse.ArgumentParser(prog='hubmap-clt', description='Name of cli', usage=help_text)
9 subparsers = parser.add_subparsers()
10
11 # Create Subparsers to give subcommands
12 parser_transfer = subparsers.add_parser('subcommandone')
13 parser_transfer.add_argument('argument1', type=str)
14 parser_transfer.add_argument('--optionalargument', default='mydefault')
15 parser_login = subparsers.add_parser('subcommandtwo')
16 parser_whoami = subparsers.add_parser('subcommandthree')
17 parser_logout = subparsers.add_parser('subcommandfour')
18
19 # Assign subparsers to their respective functions
20 parser_subcommandone.set_defaults(func=subcommandone)
21 parser_subcommandtwo.set_defaults(func=subcommandtwo)
22 parser_subcommandthree.set_defaults(func=subcommandthree)
23 parser_subcommandfour.set_defaults(func=subcommandfour)
24 parser.set_defaults(func=base_case)
25
26 # Parse the arguments and call appropriate functions
27 args = parser.parse_args()
28 if len(sys.argv) == 1:
29 args.func(args, parser)
30 else:
31 args.func(args)
32 name of cli
33
34 positional arguments:
35 {subcommandone,subcommandtwo,subcommandthree,subcommandfour}
36
37 optional arguments:
38 -h, --help show this help message and exit
39def foo():
40 # Import help text from file
41 # p = Path(__file__).with_name("help_text.txt")
42 # with p.open() as file:
43 # help_text = file.read()
44 help_text = "cli usage: foobar\n morebar"
45
46 # Configure the top level Parser
47 parser = argparse.ArgumentParser(
48 prog="hubmap-clt", description="Name of cli", usage=help_text
49 )
50 subparsers = parser.add_subparsers()
51
52 # Create Subparsers to give subcommands
53 parser_transfer = subparsers.add_parser("subcommandone")
54 parser_transfer.add_argument("argument1", type=str)
55 parser_transfer.add_argument("--optionalargument", default="mydefault")
56 parser_login = subparsers.add_parser("subcommandtwo")
57 # parser_whoami = subparsers.add_parser("subcommandthree")
58 # parser_logout = subparsers.add_parser("subcommandfour")
59
60 # Assign subparsers to their respective functions
61 parser_transfer.set_defaults(func="subcommandone")
62 parser_login.set_defaults(func="subcommandtwo")
63 # parser_subcommandthree.set_defaults(func="subcommandthree")
64 # parser_subcommandfour.set_defaults(func="subcommandfour")
65 parser.set_defaults(func="base_case")
66
67 return parser
68In [8]: p = foo()
69
70In [9]: p.print_usage()
71usage: cli usage: foobar
72 morebar
73In [10]: p.print_help()
74usage: cli usage: foobar
75 morebar
76
77Name of cli
78
79positional arguments:
80 {subcommandone,subcommandtwo}
81
82optional arguments:
83 -h, --help show this help message and exit
84
That's what I expect given the arguments.
Help for a subparser:
1def main():
2 # Import help text from file
3 p = Path(__file__).with_name("help_text.txt")
4 with p.open() as file:
5 help_text = file.read()
6
7 # Configure the top level Parser
8 parser = argparse.ArgumentParser(prog='hubmap-clt', description='Name of cli', usage=help_text)
9 subparsers = parser.add_subparsers()
10
11 # Create Subparsers to give subcommands
12 parser_transfer = subparsers.add_parser('subcommandone')
13 parser_transfer.add_argument('argument1', type=str)
14 parser_transfer.add_argument('--optionalargument', default='mydefault')
15 parser_login = subparsers.add_parser('subcommandtwo')
16 parser_whoami = subparsers.add_parser('subcommandthree')
17 parser_logout = subparsers.add_parser('subcommandfour')
18
19 # Assign subparsers to their respective functions
20 parser_subcommandone.set_defaults(func=subcommandone)
21 parser_subcommandtwo.set_defaults(func=subcommandtwo)
22 parser_subcommandthree.set_defaults(func=subcommandthree)
23 parser_subcommandfour.set_defaults(func=subcommandfour)
24 parser.set_defaults(func=base_case)
25
26 # Parse the arguments and call appropriate functions
27 args = parser.parse_args()
28 if len(sys.argv) == 1:
29 args.func(args, parser)
30 else:
31 args.func(args)
32 name of cli
33
34 positional arguments:
35 {subcommandone,subcommandtwo,subcommandthree,subcommandfour}
36
37 optional arguments:
38 -h, --help show this help message and exit
39def foo():
40 # Import help text from file
41 # p = Path(__file__).with_name("help_text.txt")
42 # with p.open() as file:
43 # help_text = file.read()
44 help_text = "cli usage: foobar\n morebar"
45
46 # Configure the top level Parser
47 parser = argparse.ArgumentParser(
48 prog="hubmap-clt", description="Name of cli", usage=help_text
49 )
50 subparsers = parser.add_subparsers()
51
52 # Create Subparsers to give subcommands
53 parser_transfer = subparsers.add_parser("subcommandone")
54 parser_transfer.add_argument("argument1", type=str)
55 parser_transfer.add_argument("--optionalargument", default="mydefault")
56 parser_login = subparsers.add_parser("subcommandtwo")
57 # parser_whoami = subparsers.add_parser("subcommandthree")
58 # parser_logout = subparsers.add_parser("subcommandfour")
59
60 # Assign subparsers to their respective functions
61 parser_transfer.set_defaults(func="subcommandone")
62 parser_login.set_defaults(func="subcommandtwo")
63 # parser_subcommandthree.set_defaults(func="subcommandthree")
64 # parser_subcommandfour.set_defaults(func="subcommandfour")
65 parser.set_defaults(func="base_case")
66
67 return parser
68In [8]: p = foo()
69
70In [9]: p.print_usage()
71usage: cli usage: foobar
72 morebar
73In [10]: p.print_help()
74usage: cli usage: foobar
75 morebar
76
77Name of cli
78
79positional arguments:
80 {subcommandone,subcommandtwo}
81
82optional arguments:
83 -h, --help show this help message and exit
84In [11]: p.parse_args(["subcommandone", "-h"])
85usage: cli usage: foobar
86 morebar subcommandone [-h] [--optionalargument OPTIONALARGUMENT] argument1
87
88positional arguments:
89 argument1
90
91optional arguments:
92 -h, --help show this help message and exit
93 --optionalargument OPTIONALARGUMENT
94
Usage is like the main's but with some added info on how to call this subparser and its arguments.
Error when calling the subparsers without enough values:
1def main():
2 # Import help text from file
3 p = Path(__file__).with_name("help_text.txt")
4 with p.open() as file:
5 help_text = file.read()
6
7 # Configure the top level Parser
8 parser = argparse.ArgumentParser(prog='hubmap-clt', description='Name of cli', usage=help_text)
9 subparsers = parser.add_subparsers()
10
11 # Create Subparsers to give subcommands
12 parser_transfer = subparsers.add_parser('subcommandone')
13 parser_transfer.add_argument('argument1', type=str)
14 parser_transfer.add_argument('--optionalargument', default='mydefault')
15 parser_login = subparsers.add_parser('subcommandtwo')
16 parser_whoami = subparsers.add_parser('subcommandthree')
17 parser_logout = subparsers.add_parser('subcommandfour')
18
19 # Assign subparsers to their respective functions
20 parser_subcommandone.set_defaults(func=subcommandone)
21 parser_subcommandtwo.set_defaults(func=subcommandtwo)
22 parser_subcommandthree.set_defaults(func=subcommandthree)
23 parser_subcommandfour.set_defaults(func=subcommandfour)
24 parser.set_defaults(func=base_case)
25
26 # Parse the arguments and call appropriate functions
27 args = parser.parse_args()
28 if len(sys.argv) == 1:
29 args.func(args, parser)
30 else:
31 args.func(args)
32 name of cli
33
34 positional arguments:
35 {subcommandone,subcommandtwo,subcommandthree,subcommandfour}
36
37 optional arguments:
38 -h, --help show this help message and exit
39def foo():
40 # Import help text from file
41 # p = Path(__file__).with_name("help_text.txt")
42 # with p.open() as file:
43 # help_text = file.read()
44 help_text = "cli usage: foobar\n morebar"
45
46 # Configure the top level Parser
47 parser = argparse.ArgumentParser(
48 prog="hubmap-clt", description="Name of cli", usage=help_text
49 )
50 subparsers = parser.add_subparsers()
51
52 # Create Subparsers to give subcommands
53 parser_transfer = subparsers.add_parser("subcommandone")
54 parser_transfer.add_argument("argument1", type=str)
55 parser_transfer.add_argument("--optionalargument", default="mydefault")
56 parser_login = subparsers.add_parser("subcommandtwo")
57 # parser_whoami = subparsers.add_parser("subcommandthree")
58 # parser_logout = subparsers.add_parser("subcommandfour")
59
60 # Assign subparsers to their respective functions
61 parser_transfer.set_defaults(func="subcommandone")
62 parser_login.set_defaults(func="subcommandtwo")
63 # parser_subcommandthree.set_defaults(func="subcommandthree")
64 # parser_subcommandfour.set_defaults(func="subcommandfour")
65 parser.set_defaults(func="base_case")
66
67 return parser
68In [8]: p = foo()
69
70In [9]: p.print_usage()
71usage: cli usage: foobar
72 morebar
73In [10]: p.print_help()
74usage: cli usage: foobar
75 morebar
76
77Name of cli
78
79positional arguments:
80 {subcommandone,subcommandtwo}
81
82optional arguments:
83 -h, --help show this help message and exit
84In [11]: p.parse_args(["subcommandone", "-h"])
85usage: cli usage: foobar
86 morebar subcommandone [-h] [--optionalargument OPTIONALARGUMENT] argument1
87
88positional arguments:
89 argument1
90
91optional arguments:
92 -h, --help show this help message and exit
93 --optionalargument OPTIONALARGUMENT
94In [15]: p.parse_args(["subcommandone"])
95usage: cli usage: foobar
96 morebar subcommandone [-h] [--optionalargument OPTIONALARGUMENT] argument1
97cli usage: foobar
98 morebar subcommandone: error: the following arguments are required: argument1
99
Is this repeat of cli usage
that bothering you? This error is raised by the subparser, and I suspect the extra comes from the prog
of that subparser. I think I saw something like this on the Python bug/issues for argparse
.
error with too much:
1def main():
2 # Import help text from file
3 p = Path(__file__).with_name("help_text.txt")
4 with p.open() as file:
5 help_text = file.read()
6
7 # Configure the top level Parser
8 parser = argparse.ArgumentParser(prog='hubmap-clt', description='Name of cli', usage=help_text)
9 subparsers = parser.add_subparsers()
10
11 # Create Subparsers to give subcommands
12 parser_transfer = subparsers.add_parser('subcommandone')
13 parser_transfer.add_argument('argument1', type=str)
14 parser_transfer.add_argument('--optionalargument', default='mydefault')
15 parser_login = subparsers.add_parser('subcommandtwo')
16 parser_whoami = subparsers.add_parser('subcommandthree')
17 parser_logout = subparsers.add_parser('subcommandfour')
18
19 # Assign subparsers to their respective functions
20 parser_subcommandone.set_defaults(func=subcommandone)
21 parser_subcommandtwo.set_defaults(func=subcommandtwo)
22 parser_subcommandthree.set_defaults(func=subcommandthree)
23 parser_subcommandfour.set_defaults(func=subcommandfour)
24 parser.set_defaults(func=base_case)
25
26 # Parse the arguments and call appropriate functions
27 args = parser.parse_args()
28 if len(sys.argv) == 1:
29 args.func(args, parser)
30 else:
31 args.func(args)
32 name of cli
33
34 positional arguments:
35 {subcommandone,subcommandtwo,subcommandthree,subcommandfour}
36
37 optional arguments:
38 -h, --help show this help message and exit
39def foo():
40 # Import help text from file
41 # p = Path(__file__).with_name("help_text.txt")
42 # with p.open() as file:
43 # help_text = file.read()
44 help_text = "cli usage: foobar\n morebar"
45
46 # Configure the top level Parser
47 parser = argparse.ArgumentParser(
48 prog="hubmap-clt", description="Name of cli", usage=help_text
49 )
50 subparsers = parser.add_subparsers()
51
52 # Create Subparsers to give subcommands
53 parser_transfer = subparsers.add_parser("subcommandone")
54 parser_transfer.add_argument("argument1", type=str)
55 parser_transfer.add_argument("--optionalargument", default="mydefault")
56 parser_login = subparsers.add_parser("subcommandtwo")
57 # parser_whoami = subparsers.add_parser("subcommandthree")
58 # parser_logout = subparsers.add_parser("subcommandfour")
59
60 # Assign subparsers to their respective functions
61 parser_transfer.set_defaults(func="subcommandone")
62 parser_login.set_defaults(func="subcommandtwo")
63 # parser_subcommandthree.set_defaults(func="subcommandthree")
64 # parser_subcommandfour.set_defaults(func="subcommandfour")
65 parser.set_defaults(func="base_case")
66
67 return parser
68In [8]: p = foo()
69
70In [9]: p.print_usage()
71usage: cli usage: foobar
72 morebar
73In [10]: p.print_help()
74usage: cli usage: foobar
75 morebar
76
77Name of cli
78
79positional arguments:
80 {subcommandone,subcommandtwo}
81
82optional arguments:
83 -h, --help show this help message and exit
84In [11]: p.parse_args(["subcommandone", "-h"])
85usage: cli usage: foobar
86 morebar subcommandone [-h] [--optionalargument OPTIONALARGUMENT] argument1
87
88positional arguments:
89 argument1
90
91optional arguments:
92 -h, --help show this help message and exit
93 --optionalargument OPTIONALARGUMENT
94In [15]: p.parse_args(["subcommandone"])
95usage: cli usage: foobar
96 morebar subcommandone [-h] [--optionalargument OPTIONALARGUMENT] argument1
97cli usage: foobar
98 morebar subcommandone: error: the following arguments are required: argument1
99In [17]: p.parse_args(["subcommandone", "test", "extra"])
100usage: cli usage: foobar
101 morebar
102hubmap-clt: error: unrecognized arguments: extra
103
In this case error is produced by the main parser, hence the "hubmat-clt" prog
.
change prog
:
...: parser_transfer = subparsers.add_parser( ...: "subcommandone", prog="hubmap-clt sobcommandone" ...: )
1def main():
2 # Import help text from file
3 p = Path(__file__).with_name("help_text.txt")
4 with p.open() as file:
5 help_text = file.read()
6
7 # Configure the top level Parser
8 parser = argparse.ArgumentParser(prog='hubmap-clt', description='Name of cli', usage=help_text)
9 subparsers = parser.add_subparsers()
10
11 # Create Subparsers to give subcommands
12 parser_transfer = subparsers.add_parser('subcommandone')
13 parser_transfer.add_argument('argument1', type=str)
14 parser_transfer.add_argument('--optionalargument', default='mydefault')
15 parser_login = subparsers.add_parser('subcommandtwo')
16 parser_whoami = subparsers.add_parser('subcommandthree')
17 parser_logout = subparsers.add_parser('subcommandfour')
18
19 # Assign subparsers to their respective functions
20 parser_subcommandone.set_defaults(func=subcommandone)
21 parser_subcommandtwo.set_defaults(func=subcommandtwo)
22 parser_subcommandthree.set_defaults(func=subcommandthree)
23 parser_subcommandfour.set_defaults(func=subcommandfour)
24 parser.set_defaults(func=base_case)
25
26 # Parse the arguments and call appropriate functions
27 args = parser.parse_args()
28 if len(sys.argv) == 1:
29 args.func(args, parser)
30 else:
31 args.func(args)
32 name of cli
33
34 positional arguments:
35 {subcommandone,subcommandtwo,subcommandthree,subcommandfour}
36
37 optional arguments:
38 -h, --help show this help message and exit
39def foo():
40 # Import help text from file
41 # p = Path(__file__).with_name("help_text.txt")
42 # with p.open() as file:
43 # help_text = file.read()
44 help_text = "cli usage: foobar\n morebar"
45
46 # Configure the top level Parser
47 parser = argparse.ArgumentParser(
48 prog="hubmap-clt", description="Name of cli", usage=help_text
49 )
50 subparsers = parser.add_subparsers()
51
52 # Create Subparsers to give subcommands
53 parser_transfer = subparsers.add_parser("subcommandone")
54 parser_transfer.add_argument("argument1", type=str)
55 parser_transfer.add_argument("--optionalargument", default="mydefault")
56 parser_login = subparsers.add_parser("subcommandtwo")
57 # parser_whoami = subparsers.add_parser("subcommandthree")
58 # parser_logout = subparsers.add_parser("subcommandfour")
59
60 # Assign subparsers to their respective functions
61 parser_transfer.set_defaults(func="subcommandone")
62 parser_login.set_defaults(func="subcommandtwo")
63 # parser_subcommandthree.set_defaults(func="subcommandthree")
64 # parser_subcommandfour.set_defaults(func="subcommandfour")
65 parser.set_defaults(func="base_case")
66
67 return parser
68In [8]: p = foo()
69
70In [9]: p.print_usage()
71usage: cli usage: foobar
72 morebar
73In [10]: p.print_help()
74usage: cli usage: foobar
75 morebar
76
77Name of cli
78
79positional arguments:
80 {subcommandone,subcommandtwo}
81
82optional arguments:
83 -h, --help show this help message and exit
84In [11]: p.parse_args(["subcommandone", "-h"])
85usage: cli usage: foobar
86 morebar subcommandone [-h] [--optionalargument OPTIONALARGUMENT] argument1
87
88positional arguments:
89 argument1
90
91optional arguments:
92 -h, --help show this help message and exit
93 --optionalargument OPTIONALARGUMENT
94In [15]: p.parse_args(["subcommandone"])
95usage: cli usage: foobar
96 morebar subcommandone [-h] [--optionalargument OPTIONALARGUMENT] argument1
97cli usage: foobar
98 morebar subcommandone: error: the following arguments are required: argument1
99In [17]: p.parse_args(["subcommandone", "test", "extra"])
100usage: cli usage: foobar
101 morebar
102hubmap-clt: error: unrecognized arguments: extra
103In [21]: p.parse_args(["subcommandone", "test", "extra"])
104usage: cli usage: foobar
105 morebar
106hubmap-clt: error: unrecognized arguments: extra
107
108In [22]: p.parse_args(["subcommandone"])
109usage: hubmap-clt sobcommandone [-h] [--optionalargument OPTIONALARGUMENT] argument1
110hubmap-clt sobcommandone: error: the following arguments are required: argument1
111
[21] is as before [17]. But [22] is now showing the prog
that I set. I could also have specified a custom usage
for the subparser.
If I modify the function to use default usage and prog, but also display the subparser's prog. And I gave the main an "main_foo" positional argument:
1def main():
2 # Import help text from file
3 p = Path(__file__).with_name("help_text.txt")
4 with p.open() as file:
5 help_text = file.read()
6
7 # Configure the top level Parser
8 parser = argparse.ArgumentParser(prog='hubmap-clt', description='Name of cli', usage=help_text)
9 subparsers = parser.add_subparsers()
10
11 # Create Subparsers to give subcommands
12 parser_transfer = subparsers.add_parser('subcommandone')
13 parser_transfer.add_argument('argument1', type=str)
14 parser_transfer.add_argument('--optionalargument', default='mydefault')
15 parser_login = subparsers.add_parser('subcommandtwo')
16 parser_whoami = subparsers.add_parser('subcommandthree')
17 parser_logout = subparsers.add_parser('subcommandfour')
18
19 # Assign subparsers to their respective functions
20 parser_subcommandone.set_defaults(func=subcommandone)
21 parser_subcommandtwo.set_defaults(func=subcommandtwo)
22 parser_subcommandthree.set_defaults(func=subcommandthree)
23 parser_subcommandfour.set_defaults(func=subcommandfour)
24 parser.set_defaults(func=base_case)
25
26 # Parse the arguments and call appropriate functions
27 args = parser.parse_args()
28 if len(sys.argv) == 1:
29 args.func(args, parser)
30 else:
31 args.func(args)
32 name of cli
33
34 positional arguments:
35 {subcommandone,subcommandtwo,subcommandthree,subcommandfour}
36
37 optional arguments:
38 -h, --help show this help message and exit
39def foo():
40 # Import help text from file
41 # p = Path(__file__).with_name("help_text.txt")
42 # with p.open() as file:
43 # help_text = file.read()
44 help_text = "cli usage: foobar\n morebar"
45
46 # Configure the top level Parser
47 parser = argparse.ArgumentParser(
48 prog="hubmap-clt", description="Name of cli", usage=help_text
49 )
50 subparsers = parser.add_subparsers()
51
52 # Create Subparsers to give subcommands
53 parser_transfer = subparsers.add_parser("subcommandone")
54 parser_transfer.add_argument("argument1", type=str)
55 parser_transfer.add_argument("--optionalargument", default="mydefault")
56 parser_login = subparsers.add_parser("subcommandtwo")
57 # parser_whoami = subparsers.add_parser("subcommandthree")
58 # parser_logout = subparsers.add_parser("subcommandfour")
59
60 # Assign subparsers to their respective functions
61 parser_transfer.set_defaults(func="subcommandone")
62 parser_login.set_defaults(func="subcommandtwo")
63 # parser_subcommandthree.set_defaults(func="subcommandthree")
64 # parser_subcommandfour.set_defaults(func="subcommandfour")
65 parser.set_defaults(func="base_case")
66
67 return parser
68In [8]: p = foo()
69
70In [9]: p.print_usage()
71usage: cli usage: foobar
72 morebar
73In [10]: p.print_help()
74usage: cli usage: foobar
75 morebar
76
77Name of cli
78
79positional arguments:
80 {subcommandone,subcommandtwo}
81
82optional arguments:
83 -h, --help show this help message and exit
84In [11]: p.parse_args(["subcommandone", "-h"])
85usage: cli usage: foobar
86 morebar subcommandone [-h] [--optionalargument OPTIONALARGUMENT] argument1
87
88positional arguments:
89 argument1
90
91optional arguments:
92 -h, --help show this help message and exit
93 --optionalargument OPTIONALARGUMENT
94In [15]: p.parse_args(["subcommandone"])
95usage: cli usage: foobar
96 morebar subcommandone [-h] [--optionalargument OPTIONALARGUMENT] argument1
97cli usage: foobar
98 morebar subcommandone: error: the following arguments are required: argument1
99In [17]: p.parse_args(["subcommandone", "test", "extra"])
100usage: cli usage: foobar
101 morebar
102hubmap-clt: error: unrecognized arguments: extra
103In [21]: p.parse_args(["subcommandone", "test", "extra"])
104usage: cli usage: foobar
105 morebar
106hubmap-clt: error: unrecognized arguments: extra
107
108In [22]: p.parse_args(["subcommandone"])
109usage: hubmap-clt sobcommandone [-h] [--optionalargument OPTIONALARGUMENT] argument1
110hubmap-clt sobcommandone: error: the following arguments are required: argument1
111In [30]: p = foo()
112hubmap-clt main_foo subcommandone
113In [31]: p.parse_args(["subcommandone"])
114Out[31]: Namespace(main_foo='subcommandone')
115In [32]: p.parse_args(["foo", "subcommandone"])
116usage: hubmap-clt main_foo subcommandone [-h] [--optionalargument OPTIONALARGUMENT] argument1
117hubmap-clt main_foo subcommandone: error: the following arguments are required: argument1
118
Notice how the main's usage has been incorporated into the 'prog' for the subparser.
In the bug/issue I found the main parser's usage
gets incorporated into the prog
of the subparser. That's why you see the duplicate.
https://bugs.python.org/issue42297 [argparse] Bad error message formatting when using custom usage text
The relatively recent date of this bug issue indicates that custom usage is not that common, and even less so when used with subparsers. As my post on this issue indicates, the relation between the main parser, the "subparsers" command, and individual subparsers gets complicated.
QUESTION
Solving conda environment stuck
Asked 2021-Dec-22 at 18:02I'm trying to install conda environment using the command:
1conda env create -f devenv.yaml
2
My .yaml file is
1conda env create -f devenv.yaml
2name: myname
3channels:
4 - conda-forge
5 - bioconda
6dependencies:
7 # Package creation and environment management
8 - conda-build
9 # Automation control (command line interface, workflow and multi-process management)
10 - python-dotenv
11 - click
12 - snakemake-minimal
13 - joblib
14 - numba
15 # Workspace
16 - notebook
17 # Visualization
18 - plotly
19 - plotly-orca
20 - matplotlib
21 - seaborn
22 - shap
23 - openpyxl
24 - ipywidgets
25 - tensorboard
26 # Data manipulation
27 - numpy
28 - pandas
29 - pyarrow
30 # Functional style tools
31 - more-itertools
32 - toolz
33 # Machine learning
34 - scikit-learn
35 - imbalanced-learn
36 - scikit-image
37 - statsmodels
38 - catboost
39 - hyperopt
40 - tsfresh
41 # Deep learning
42 - pytorch
43 # code checking and formatting
44 - pylint
45 - black
46 - flake8
47 - mypy
48 # Python base
49 - python
50 - pip
51 - pip:
52
I've tried to update conda but it doesn't help. It just stuck on solving the environment.
conda version: 4.11.0 c OS: Ubuntu 18.04.5 LTS
The exact same environment works fine on my mac, but not on that server. What could be the issue? I appreciate any suggestions. Thx.
ANSWER
Answered 2021-Dec-22 at 18:02This solves fine (), but is indeed a complex solve mainly due to:
- underspecification
- lack of modularization
This particular environment specification ends up installing well over 300 packages. And there isn't a single one of those that are constrained by the specification. That is a huge SAT problem to solve and Conda will struggle with this. Mamba will help solve faster, but providing additional constraints can vastly reduce the solution space.
At minimum, specify a Python version (major.minor), such as python=3.9
. This is the single most effective constraint.
Beyond that, putting minimum requirements on central packages (those that are dependencies of others) can help, such as minimum NumPy.
Lack of ModularizationI assume the name "devenv" means this is a development environment. So, I get that one wants all these tools immediately at hand. However, Conda environment activation is so simple, and most IDE tooling these days (Spyder, VSCode, Jupyter) encourages separation of infrastructure and the execution kernel. Being more thoughtful about how environments (emphasis on the plural) are organized and work together, can go a long way in having a sustainable and painless data science workflow.
The environment at hand has multiple red flags in my book:
conda-build
should be in base and only in basesnakemake
should be in a dedicated environmentnotebook
(i.e., Jupyter) should be in a dedicated environment, co-installed withnb_conda_kernels
; all kernel environments need areipykernel
I'd probably also have the linting/formatting packages separated, but that's less an issue. The real killer though is snakemake
- it's just a massive piece of infrastructure and I'd strongly encourage keeping that separated.
QUESTION
Mysql Error while piping database to different server
Asked 2021-Nov-28 at 19:48I have a strange error here. The command I am executing is this:
1mysqldump -u root -ppass kodi_video119 | mysql -h192.168.178.73 -u kodi -ppass kodi_video119
2
When I execute it over SSH it all works fine, but when I save it to a file and execute this file I get the following error:
1mysqldump -u root -ppass kodi_video119 | mysql -h192.168.178.73 -u kodi -ppass kodi_video119
2mysqldump: [Warning] Using a password on the command line interface can be insecure.
3mysql: [Warning] Using a password on the command line interface can be insecure.
4'RROR 1102 (42000): Incorrect database name 'kodi_video119
5mysqldump: Got errno 11 on write
6
I can't find any results using google on that error number. The user is allowed to write and it all works fine when I execute it direcly from SSH. But using the same SSH session (as root user) just executing the command embedded in the file it does not work.
Whats going wrong here? I created the file using nano and saved it using nano. Then chmod +x and execute ./test
ANSWER
Answered 2021-Nov-28 at 19:48By default, when you use mysqldump DB
, the output includes table-creation statements, but no CREATE DATABASE
statement. It just assumes you have created an empty schema first.
So you could do this to create the schema first:
1mysqldump -u root -ppass kodi_video119 | mysql -h192.168.178.73 -u kodi -ppass kodi_video119
2mysqldump: [Warning] Using a password on the command line interface can be insecure.
3mysql: [Warning] Using a password on the command line interface can be insecure.
4'RROR 1102 (42000): Incorrect database name 'kodi_video119
5mysqldump: Got errno 11 on write
6mysqladmin -h192.168.178.73 create kodi_video119
7mysqldump kodi_video119 | mysql -h192.168.178.73 kodi_video119
8
(I left out the -u and -p options for brevity)
Alternatively, you can use the -B
option, aka --databases
. This option allows you to specify one or more databases, and the output includes CREATE DATABASE
statements for each one before it then creates and populates tables. You can use it with a single database argument:
1mysqldump -u root -ppass kodi_video119 | mysql -h192.168.178.73 -u kodi -ppass kodi_video119
2mysqldump: [Warning] Using a password on the command line interface can be insecure.
3mysql: [Warning] Using a password on the command line interface can be insecure.
4'RROR 1102 (42000): Incorrect database name 'kodi_video119
5mysqldump: Got errno 11 on write
6mysqladmin -h192.168.178.73 create kodi_video119
7mysqldump kodi_video119 | mysql -h192.168.178.73 kodi_video119
8mysqldump -B kodi_video119 | mysql -h192.168.178.73 kodi_video119
9
QUESTION
Shell script to pull row counts from all Hive tables in multiple Hive databases
Asked 2021-Nov-22 at 07:57I am trying to create a shell script that will pull row counts in all tables from multiple databases. All of the databases follow the same naming convention "the_same_databasename_<%>" except the final layer in the name, which varies. I am trying to run the following:
use <database_name>;
show tables;
select count(*) from <table_name>;
Since I have 40 different databases, I would need to run the first two queries for each database 40 different times, plus the select count query even more depending on how many table in the database (very time consuming). I have my PuTTy configuration settings set to save my PuTTy sessions into a .txt on my local directory, so I can have the row count results displayed right in my command line interface. So far this is what I have but not sure how to include the final commands to get the actual row counts from the tables in each database.
1#!/bin/bash
2for db in $(hive -e "show databases like 'the_same_databasename_*;")
3do
4 tbl_count=$(hive -S -e "use $db; show tables;" | wc -l)
5 echo "Database $db contains $tbl_count tables."
6
7done
8
I'm not very experienced in shell scripting so any guidance/help is greatly appreciated. Thanks in advance.
ANSWER
Answered 2021-Nov-22 at 07:57You can use nested for-loop:
1#!/bin/bash
2for db in $(hive -e "show databases like 'the_same_databasename_*;")
3do
4 tbl_count=$(hive -S -e "use $db; show tables;" | wc -l)
5 echo "Database $db contains $tbl_count tables."
6
7done
8#!/bin/bash
9for db in $(hive -e "show databases like 'the_same_databasename_*;")
10do
11 tbl_count=$(hive -S -e "use $db; show tables;" | wc -l)
12 echo "Database $db contains $tbl_count tables."
13
14 for table in $(hive -S -e "use $db; show tables;")
15 do
16 count=$(hive -S -e "use $db; select count(*) from $table;")
17 echo "Table $db.$table contains $count rows."
18 done
19
20done
21
Or you can use variable to increment count of tables
1#!/bin/bash
2for db in $(hive -e "show databases like 'the_same_databasename_*;")
3do
4 tbl_count=$(hive -S -e "use $db; show tables;" | wc -l)
5 echo "Database $db contains $tbl_count tables."
6
7done
8#!/bin/bash
9for db in $(hive -e "show databases like 'the_same_databasename_*;")
10do
11 tbl_count=$(hive -S -e "use $db; show tables;" | wc -l)
12 echo "Database $db contains $tbl_count tables."
13
14 for table in $(hive -S -e "use $db; show tables;")
15 do
16 count=$(hive -S -e "use $db; select count(*) from $table;")
17 echo "Table $db.$table contains $count rows."
18 done
19
20done
21#!/bin/bash
22for db in $(hive -e "show databases like 'the_same_databasename_*;")
23do
24
25 tbl_count=0
26 for table in $(hive -S -e "use $db; show tables;")
27 do
28 (( tbl_count++ ))
29 count=$(hive -S -e "use $db; select count(*) from $table;")
30 echo "Table $db.$table contains $count rows."
31 done
32 echo "Database $db contains $tbl_count tables."
33
34done
35
QUESTION
See workspace in MATLAB command line terminal
Asked 2021-Nov-20 at 09:18Is there any command to see all variable names, types and values in command line interface? Similar to Matlab's Workspace? I already know about command whos
but it doesn't show the values, It just shows names and types.
Thanks :)
ANSWER
Answered 2021-Nov-20 at 09:18try this:
1vals = who;
2for val = vals
3 eval(val.name)
4end
5
QUESTION
How can I fix "Failed to compile src/index.js 'firebase' is not defined no-undef"?
Asked 2021-Nov-12 at 21:59I am trying to use a React web app to read and write stuff in a Firebase realtime database. Every time I run "npm run start", I get this error message.
1Failed to compile
2src/index.js
3 Line 25:1: 'firebase' is not defined no-undef
4 Line 28:16: 'firebase' is not defined no-undef
5
6Search for the keywords to learn more about each error.
7This error occurred during the build time and cannot be dismissed.
8
This is what package.json, src/index.js, build/index.html, and public/index.html looked like when I first got this error. (is it bad to have 2 index.html files?)
1Failed to compile
2src/index.js
3 Line 25:1: 'firebase' is not defined no-undef
4 Line 28:16: 'firebase' is not defined no-undef
5
6Search for the keywords to learn more about each error.
7This error occurred during the build time and cannot be dismissed.
8{
9 "name": "my-app",
10 "version": "0.1.0",
11 "private": true,
12 "dependencies": {
13 "@material-ui/core": "^4.12.2",
14 "@testing-library/jest-dom": "^5.14.1",
15 "@testing-library/react": "^11.2.7",
16 "@testing-library/user-event": "^12.8.3",
17 "firebase": "^9.0.0",
18 "react": "^17.0.2",
19 "react-dom": "^17.0.2",
20 "react-router-config": "^5.1.1",
21 "react-router-dom": "^5.2.0",
22 "react-scripts": "4.0.3",
23 "web-vitals": "^1.1.2"
24 },
25 "scripts": {
26 "start": "react-scripts start",
27 "build": "react-scripts build",
28 "test": "react-scripts test",
29 "eject": "react-scripts eject"
30 },
31 "eslintConfig": {
32 "extends": [
33 "react-app",
34 "react-app/jest"
35 ]
36 },
37 "browserslist": {
38 "production": [
39 ">0.2%",
40 "not dead",
41 "not op_mini all"
42 ],
43 "development": [
44 "last 1 chrome version",
45 "last 1 firefox version",
46 "last 1 safari version"
47 ]
48 }
49}
1Failed to compile
2src/index.js
3 Line 25:1: 'firebase' is not defined no-undef
4 Line 28:16: 'firebase' is not defined no-undef
5
6Search for the keywords to learn more about each error.
7This error occurred during the build time and cannot be dismissed.
8{
9 "name": "my-app",
10 "version": "0.1.0",
11 "private": true,
12 "dependencies": {
13 "@material-ui/core": "^4.12.2",
14 "@testing-library/jest-dom": "^5.14.1",
15 "@testing-library/react": "^11.2.7",
16 "@testing-library/user-event": "^12.8.3",
17 "firebase": "^9.0.0",
18 "react": "^17.0.2",
19 "react-dom": "^17.0.2",
20 "react-router-config": "^5.1.1",
21 "react-router-dom": "^5.2.0",
22 "react-scripts": "4.0.3",
23 "web-vitals": "^1.1.2"
24 },
25 "scripts": {
26 "start": "react-scripts start",
27 "build": "react-scripts build",
28 "test": "react-scripts test",
29 "eject": "react-scripts eject"
30 },
31 "eslintConfig": {
32 "extends": [
33 "react-app",
34 "react-app/jest"
35 ]
36 },
37 "browserslist": {
38 "production": [
39 ">0.2%",
40 "not dead",
41 "not op_mini all"
42 ],
43 "development": [
44 "last 1 chrome version",
45 "last 1 firefox version",
46 "last 1 safari version"
47 ]
48 }
49}import React from 'react';
50import ReactDOM from 'react-dom';
51//import './index.css';
52//import App from './App';
53//import reportWebVitals from './reportWebVitals';
54// Import the functions you need from the SDKs you need
55import { initializeApp } from "firebase/app";
56import { getAnalytics } from "firebase/analytics";
57// TODO: Add SDKs for Firebase products that you want to use
58// https://firebase.google.com/docs/web/setup#available-libraries
59
60// Your web app's Firebase configuration
61// For Firebase JS SDK v7.20.0 and later, measurementId is optional
62const config = {
63 apiKey: "AIzaSyBk5lf0WtiZPs1ZQkA48OfXpzW7P_RCrZk",
64 authDomain: "test-c2ec9.firebaseapp.com",
65 projectId: "test-c2ec9",
66 storageBucket: "test-c2ec9.appspot.com",
67 messagingSenderId: "11138018851",
68 appId: "1:11138018851:web:ecfb63337ca11f62028b96",
69 measurementId: "G-3S1M3601YR"
70};
71
72// Initialize Firebase
73firebase.initializeApp(config);
74
75// Get a reference to the database service
76var database = firebase.database();
77const app = initializeApp(config);
78const analytics = getAnalytics(app);
79
80ReactDOM.render(
81 <React.StrictMode>
82 </React.StrictMode>,
83 document.getElementById('root')
84);
85
86// If you want to start measuring performance in your app, pass a function
87// to log results (for example: reportWebVitals(console.log))
88// or send to an analytics endpoint.
89//reportWebVitals();
1Failed to compile
2src/index.js
3 Line 25:1: 'firebase' is not defined no-undef
4 Line 28:16: 'firebase' is not defined no-undef
5
6Search for the keywords to learn more about each error.
7This error occurred during the build time and cannot be dismissed.
8{
9 "name": "my-app",
10 "version": "0.1.0",
11 "private": true,
12 "dependencies": {
13 "@material-ui/core": "^4.12.2",
14 "@testing-library/jest-dom": "^5.14.1",
15 "@testing-library/react": "^11.2.7",
16 "@testing-library/user-event": "^12.8.3",
17 "firebase": "^9.0.0",
18 "react": "^17.0.2",
19 "react-dom": "^17.0.2",
20 "react-router-config": "^5.1.1",
21 "react-router-dom": "^5.2.0",
22 "react-scripts": "4.0.3",
23 "web-vitals": "^1.1.2"
24 },
25 "scripts": {
26 "start": "react-scripts start",
27 "build": "react-scripts build",
28 "test": "react-scripts test",
29 "eject": "react-scripts eject"
30 },
31 "eslintConfig": {
32 "extends": [
33 "react-app",
34 "react-app/jest"
35 ]
36 },
37 "browserslist": {
38 "production": [
39 ">0.2%",
40 "not dead",
41 "not op_mini all"
42 ],
43 "development": [
44 "last 1 chrome version",
45 "last 1 firefox version",
46 "last 1 safari version"
47 ]
48 }
49}import React from 'react';
50import ReactDOM from 'react-dom';
51//import './index.css';
52//import App from './App';
53//import reportWebVitals from './reportWebVitals';
54// Import the functions you need from the SDKs you need
55import { initializeApp } from "firebase/app";
56import { getAnalytics } from "firebase/analytics";
57// TODO: Add SDKs for Firebase products that you want to use
58// https://firebase.google.com/docs/web/setup#available-libraries
59
60// Your web app's Firebase configuration
61// For Firebase JS SDK v7.20.0 and later, measurementId is optional
62const config = {
63 apiKey: "AIzaSyBk5lf0WtiZPs1ZQkA48OfXpzW7P_RCrZk",
64 authDomain: "test-c2ec9.firebaseapp.com",
65 projectId: "test-c2ec9",
66 storageBucket: "test-c2ec9.appspot.com",
67 messagingSenderId: "11138018851",
68 appId: "1:11138018851:web:ecfb63337ca11f62028b96",
69 measurementId: "G-3S1M3601YR"
70};
71
72// Initialize Firebase
73firebase.initializeApp(config);
74
75// Get a reference to the database service
76var database = firebase.database();
77const app = initializeApp(config);
78const analytics = getAnalytics(app);
79
80ReactDOM.render(
81 <React.StrictMode>
82 </React.StrictMode>,
83 document.getElementById('root')
84);
85
86// If you want to start measuring performance in your app, pass a function
87// to log results (for example: reportWebVitals(console.log))
88// or send to an analytics endpoint.
89//reportWebVitals();<!DOCTYPE html>
90<html>
91 <head>
92 <meta charset="utf-8">
93 <meta name="viewport" content="width=device-width, initial-scale=1">
94 <title>Welcome to Firebase Hosting</title>
95
96 <!-- update the version number as needed -->
97 <script defer src="/__/firebase/8.10.0/firebase-app.js"></script>
98 <!-- include only the Firebase features as you need -->
99 <script defer src="/__/firebase/8.10.0/firebase-auth.js"></script>
100 <script defer src="/__/firebase/8.10.0/firebase-database.js"></script>
101 <script defer src="/__/firebase/8.10.0/firebase-firestore.js"></script>
102 <script defer src="/__/firebase/8.10.0/firebase-functions.js"></script>
103 <script defer src="/__/firebase/8.10.0/firebase-messaging.js"></script>
104 <script defer src="/__/firebase/8.10.0/firebase-storage.js"></script>
105 <script defer src="/__/firebase/8.10.0/firebase-analytics.js"></script>
106 <script defer src="/__/firebase/8.10.0/firebase-remote-config.js"></script>
107 <script defer src="/__/firebase/8.10.0/firebase-performance.js"></script>
108 <!--
109 initialize the SDK after all desired features are loaded, set useEmulator to false
110 to avoid connecting the SDK to running emulators.
111 -->
112 <script defer src="/__/firebase/init.js?useEmulator=true"></script>
113
114 <style media="screen">
115 body { background: #ECEFF1; color: rgba(0,0,0,0.87); font-family: Roboto, Helvetica, Arial, sans-serif; margin: 0; padding: 0; }
116 #message { background: white; max-width: 360px; margin: 100px auto 16px; padding: 32px 24px; border-radius: 3px; }
117 #message h2 { color: #ffa100; font-weight: bold; font-size: 16px; margin: 0 0 8px; }
118 #message h1 { font-size: 22px; font-weight: 300; color: rgba(0,0,0,0.6); margin: 0 0 16px;}
119 #message p { line-height: 140%; margin: 16px 0 24px; font-size: 14px; }
120 #message a { display: block; text-align: center; background: #039be5; text-transform: uppercase; text-decoration: none; color: white; padding: 16px; border-radius: 4px; }
121 #message, #message a { box-shadow: 0 1px 3px rgba(0,0,0,0.12), 0 1px 2px rgba(0,0,0,0.24); }
122 #load { color: rgba(0,0,0,0.4); text-align: center; font-size: 13px; }
123 @media (max-width: 600px) {
124 body, #message { margin-top: 0; background: white; box-shadow: none; }
125 body { border-top: 16px solid #ffa100; }
126 }
127 </style>
128 </head>
129 <body>
130 <div id="message">
131 <h2>Welcome</h2>
132 <h1>Firebase Hosting Setup Complete</h1>
133 <p>You're seeing this because you've successfully setup Firebase Hosting. Now it's time to go build something extraordinary!</p>
134 <a target="_blank" href="https://firebase.google.com/docs/hosting/">Open Hosting Documentation</a>
135 </div>
136 <p id="load">Firebase SDK Loading&hellip;</p>
137
138 <script>
139 document.addEventListener('DOMContentLoaded', function() {
140 const loadEl = document.querySelector('#load');
141 // // π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯
142 // // The Firebase SDK is initialized and available here!
143 //
144 // firebase.auth().onAuthStateChanged(user => { });
145 // firebase.database().ref('/path/to/ref').on('value', snapshot => { });
146 // firebase.firestore().doc('/foo/bar').get().then(() => { });
147 // firebase.functions().httpsCallable('yourFunction')().then(() => { });
148 // firebase.messaging().requestPermission().then(() => { });
149 // firebase.storage().ref('/path/to/ref').getDownloadURL().then(() => { });
150 // firebase.analytics(); // call to activate
151 // firebase.analytics().logEvent('tutorial_completed');
152 // firebase.performance(); // call to activate
153 //
154 // // π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯
155
156 try {
157 let app = firebase.app();
158 let features = [
159 'auth',
160 'database',
161 'firestore',
162 'functions',
163 'messaging',
164 'storage',
165 'analytics',
166 'remoteConfig',
167 'performance',
168 ].filter(feature => typeof app[feature] === 'function');
169 loadEl.textContent = `Firebase SDK loaded with ${features.join(', ')}`;
170 } catch (e) {
171 console.error(e);
172 loadEl.textContent = 'Error loading the Firebase SDK, check the console.';
173 }
174 });
175 </script>
176 <!-- The core Firebase JS SDK is always required and must be listed first -->
177 <script src="/__/firebase/8.10.0/firebase-app.js"></script>
178
179 <!-- TODO: Add SDKs for Firebase products that you want to use
180 https://firebase.google.com/docs/web/setup#available-libraries -->
181 <script src="/__/firebase/8.10.0/firebase-analytics.js"></script>
182 <!-- Initialize Firebase -->
183 <script src="/__/firebase/init.js"></script>
184 </body>
185</html>
1Failed to compile
2src/index.js
3 Line 25:1: 'firebase' is not defined no-undef
4 Line 28:16: 'firebase' is not defined no-undef
5
6Search for the keywords to learn more about each error.
7This error occurred during the build time and cannot be dismissed.
8{
9 "name": "my-app",
10 "version": "0.1.0",
11 "private": true,
12 "dependencies": {
13 "@material-ui/core": "^4.12.2",
14 "@testing-library/jest-dom": "^5.14.1",
15 "@testing-library/react": "^11.2.7",
16 "@testing-library/user-event": "^12.8.3",
17 "firebase": "^9.0.0",
18 "react": "^17.0.2",
19 "react-dom": "^17.0.2",
20 "react-router-config": "^5.1.1",
21 "react-router-dom": "^5.2.0",
22 "react-scripts": "4.0.3",
23 "web-vitals": "^1.1.2"
24 },
25 "scripts": {
26 "start": "react-scripts start",
27 "build": "react-scripts build",
28 "test": "react-scripts test",
29 "eject": "react-scripts eject"
30 },
31 "eslintConfig": {
32 "extends": [
33 "react-app",
34 "react-app/jest"
35 ]
36 },
37 "browserslist": {
38 "production": [
39 ">0.2%",
40 "not dead",
41 "not op_mini all"
42 ],
43 "development": [
44 "last 1 chrome version",
45 "last 1 firefox version",
46 "last 1 safari version"
47 ]
48 }
49}import React from 'react';
50import ReactDOM from 'react-dom';
51//import './index.css';
52//import App from './App';
53//import reportWebVitals from './reportWebVitals';
54// Import the functions you need from the SDKs you need
55import { initializeApp } from "firebase/app";
56import { getAnalytics } from "firebase/analytics";
57// TODO: Add SDKs for Firebase products that you want to use
58// https://firebase.google.com/docs/web/setup#available-libraries
59
60// Your web app's Firebase configuration
61// For Firebase JS SDK v7.20.0 and later, measurementId is optional
62const config = {
63 apiKey: "AIzaSyBk5lf0WtiZPs1ZQkA48OfXpzW7P_RCrZk",
64 authDomain: "test-c2ec9.firebaseapp.com",
65 projectId: "test-c2ec9",
66 storageBucket: "test-c2ec9.appspot.com",
67 messagingSenderId: "11138018851",
68 appId: "1:11138018851:web:ecfb63337ca11f62028b96",
69 measurementId: "G-3S1M3601YR"
70};
71
72// Initialize Firebase
73firebase.initializeApp(config);
74
75// Get a reference to the database service
76var database = firebase.database();
77const app = initializeApp(config);
78const analytics = getAnalytics(app);
79
80ReactDOM.render(
81 <React.StrictMode>
82 </React.StrictMode>,
83 document.getElementById('root')
84);
85
86// If you want to start measuring performance in your app, pass a function
87// to log results (for example: reportWebVitals(console.log))
88// or send to an analytics endpoint.
89//reportWebVitals();<!DOCTYPE html>
90<html>
91 <head>
92 <meta charset="utf-8">
93 <meta name="viewport" content="width=device-width, initial-scale=1">
94 <title>Welcome to Firebase Hosting</title>
95
96 <!-- update the version number as needed -->
97 <script defer src="/__/firebase/8.10.0/firebase-app.js"></script>
98 <!-- include only the Firebase features as you need -->
99 <script defer src="/__/firebase/8.10.0/firebase-auth.js"></script>
100 <script defer src="/__/firebase/8.10.0/firebase-database.js"></script>
101 <script defer src="/__/firebase/8.10.0/firebase-firestore.js"></script>
102 <script defer src="/__/firebase/8.10.0/firebase-functions.js"></script>
103 <script defer src="/__/firebase/8.10.0/firebase-messaging.js"></script>
104 <script defer src="/__/firebase/8.10.0/firebase-storage.js"></script>
105 <script defer src="/__/firebase/8.10.0/firebase-analytics.js"></script>
106 <script defer src="/__/firebase/8.10.0/firebase-remote-config.js"></script>
107 <script defer src="/__/firebase/8.10.0/firebase-performance.js"></script>
108 <!--
109 initialize the SDK after all desired features are loaded, set useEmulator to false
110 to avoid connecting the SDK to running emulators.
111 -->
112 <script defer src="/__/firebase/init.js?useEmulator=true"></script>
113
114 <style media="screen">
115 body { background: #ECEFF1; color: rgba(0,0,0,0.87); font-family: Roboto, Helvetica, Arial, sans-serif; margin: 0; padding: 0; }
116 #message { background: white; max-width: 360px; margin: 100px auto 16px; padding: 32px 24px; border-radius: 3px; }
117 #message h2 { color: #ffa100; font-weight: bold; font-size: 16px; margin: 0 0 8px; }
118 #message h1 { font-size: 22px; font-weight: 300; color: rgba(0,0,0,0.6); margin: 0 0 16px;}
119 #message p { line-height: 140%; margin: 16px 0 24px; font-size: 14px; }
120 #message a { display: block; text-align: center; background: #039be5; text-transform: uppercase; text-decoration: none; color: white; padding: 16px; border-radius: 4px; }
121 #message, #message a { box-shadow: 0 1px 3px rgba(0,0,0,0.12), 0 1px 2px rgba(0,0,0,0.24); }
122 #load { color: rgba(0,0,0,0.4); text-align: center; font-size: 13px; }
123 @media (max-width: 600px) {
124 body, #message { margin-top: 0; background: white; box-shadow: none; }
125 body { border-top: 16px solid #ffa100; }
126 }
127 </style>
128 </head>
129 <body>
130 <div id="message">
131 <h2>Welcome</h2>
132 <h1>Firebase Hosting Setup Complete</h1>
133 <p>You're seeing this because you've successfully setup Firebase Hosting. Now it's time to go build something extraordinary!</p>
134 <a target="_blank" href="https://firebase.google.com/docs/hosting/">Open Hosting Documentation</a>
135 </div>
136 <p id="load">Firebase SDK Loading&hellip;</p>
137
138 <script>
139 document.addEventListener('DOMContentLoaded', function() {
140 const loadEl = document.querySelector('#load');
141 // // π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯
142 // // The Firebase SDK is initialized and available here!
143 //
144 // firebase.auth().onAuthStateChanged(user => { });
145 // firebase.database().ref('/path/to/ref').on('value', snapshot => { });
146 // firebase.firestore().doc('/foo/bar').get().then(() => { });
147 // firebase.functions().httpsCallable('yourFunction')().then(() => { });
148 // firebase.messaging().requestPermission().then(() => { });
149 // firebase.storage().ref('/path/to/ref').getDownloadURL().then(() => { });
150 // firebase.analytics(); // call to activate
151 // firebase.analytics().logEvent('tutorial_completed');
152 // firebase.performance(); // call to activate
153 //
154 // // π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯
155
156 try {
157 let app = firebase.app();
158 let features = [
159 'auth',
160 'database',
161 'firestore',
162 'functions',
163 'messaging',
164 'storage',
165 'analytics',
166 'remoteConfig',
167 'performance',
168 ].filter(feature => typeof app[feature] === 'function');
169 loadEl.textContent = `Firebase SDK loaded with ${features.join(', ')}`;
170 } catch (e) {
171 console.error(e);
172 loadEl.textContent = 'Error loading the Firebase SDK, check the console.';
173 }
174 });
175 </script>
176 <!-- The core Firebase JS SDK is always required and must be listed first -->
177 <script src="/__/firebase/8.10.0/firebase-app.js"></script>
178
179 <!-- TODO: Add SDKs for Firebase products that you want to use
180 https://firebase.google.com/docs/web/setup#available-libraries -->
181 <script src="/__/firebase/8.10.0/firebase-analytics.js"></script>
182 <!-- Initialize Firebase -->
183 <script src="/__/firebase/init.js"></script>
184 </body>
185</html><!DOCTYPE html>
186<html lang="en">
187 <head>
188 <meta charset="utf-8" />
189 <link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
190 <meta name="viewport" content="width=device-width, initial-scale=1" />
191 <meta name="theme-color" content="#000000" />
192 <meta
193 name="description"
194 content="Web site created using create-react-app"
195 />
196 <link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" />
197 <!--
198 manifest.json provides metadata used when your web app is installed on a
199 user's mobile device or desktop. See https://developers.google.com/web/fundamentals/web-app-manifest/
200 -->
201 <link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
202 <!--
203 Notice the use of %PUBLIC_URL% in the tags above.
204 It will be replaced with the URL of the `public` folder during the build.
205 Only files inside the `public` folder can be referenced from the HTML.
206
207 Unlike "/favicon.ico" or "favicon.ico", "%PUBLIC_URL%/favicon.ico" will
208 work correctly both with client-side routing and a non-root public URL.
209 Learn how to configure a non-root public URL by running `npm run build`.
210 -->
211 <title>React App</title>
212 </head>
213 <body>
214 <noscript>You need to enable JavaScript to run this app.</noscript>
215 <div id="root"></div>
216 <!--
217 This HTML file is a template.
218 If you open it directly in the browser, you will see an empty page.
219
220 You can add webfonts, meta tags, or analytics to this file.
221 The build step will place the bundled scripts into the <body> tag.
222
223 To begin the development, run `npm start` or `yarn start`.
224 To create a production bundle, use `npm run build` or `yarn build`.
225 -->
226 <!-- The core Firebase JS SDK is always required and must be listed first -->
227 <script src="/__/firebase/8.10.0/firebase-app.js"></script>
228
229 <!-- TODO: Add SDKs for Firebase products that you want to use
230 https://firebase.google.com/docs/web/setup#available-libraries -->
231 <script src="/__/firebase/8.10.0/firebase-analytics.js"></script>
232 <!-- Initialize Firebase -->
233 <script src="/__/firebase/init.js"></script>
234 </body>
235</html>
Lines 25 and 28 in src/index.js are "firebase.initializeApp(config);" and "var database = firebase.database();", respectively. You should be able to reproduce this error by following these steps:
create test/package.json, test/src/index.js, test/build/index.html, and test/public/index.html
copy and paste the above 4 snippets into their respective files
save the 4 files
open a command line interface
use cd to navigate to the test folder
run "npm install"
run "npm run start"
Commenting out lines 25 and 28 causes a much longer error message that starts with "Firebase: No Firebase App '[DEFAULT]' has been created - call Firebase App.initializeApp() (app/no-app)." When I searched that error message, I got results telling me to add those lines back into index.js, which leads me back to this "'firebase' is not defined" error. Additionally, I tried each of these things, and I still got the same error message.
restarting my computer
following this tutorial
changing line 28 to "var rootref = firebase.database().ref();"
running "npm start" instead of "npm run start"
pasting this snippet in the head part of build/index.html and public/index.html
1Failed to compile
2src/index.js
3 Line 25:1: 'firebase' is not defined no-undef
4 Line 28:16: 'firebase' is not defined no-undef
5
6Search for the keywords to learn more about each error.
7This error occurred during the build time and cannot be dismissed.
8{
9 "name": "my-app",
10 "version": "0.1.0",
11 "private": true,
12 "dependencies": {
13 "@material-ui/core": "^4.12.2",
14 "@testing-library/jest-dom": "^5.14.1",
15 "@testing-library/react": "^11.2.7",
16 "@testing-library/user-event": "^12.8.3",
17 "firebase": "^9.0.0",
18 "react": "^17.0.2",
19 "react-dom": "^17.0.2",
20 "react-router-config": "^5.1.1",
21 "react-router-dom": "^5.2.0",
22 "react-scripts": "4.0.3",
23 "web-vitals": "^1.1.2"
24 },
25 "scripts": {
26 "start": "react-scripts start",
27 "build": "react-scripts build",
28 "test": "react-scripts test",
29 "eject": "react-scripts eject"
30 },
31 "eslintConfig": {
32 "extends": [
33 "react-app",
34 "react-app/jest"
35 ]
36 },
37 "browserslist": {
38 "production": [
39 ">0.2%",
40 "not dead",
41 "not op_mini all"
42 ],
43 "development": [
44 "last 1 chrome version",
45 "last 1 firefox version",
46 "last 1 safari version"
47 ]
48 }
49}import React from 'react';
50import ReactDOM from 'react-dom';
51//import './index.css';
52//import App from './App';
53//import reportWebVitals from './reportWebVitals';
54// Import the functions you need from the SDKs you need
55import { initializeApp } from "firebase/app";
56import { getAnalytics } from "firebase/analytics";
57// TODO: Add SDKs for Firebase products that you want to use
58// https://firebase.google.com/docs/web/setup#available-libraries
59
60// Your web app's Firebase configuration
61// For Firebase JS SDK v7.20.0 and later, measurementId is optional
62const config = {
63 apiKey: "AIzaSyBk5lf0WtiZPs1ZQkA48OfXpzW7P_RCrZk",
64 authDomain: "test-c2ec9.firebaseapp.com",
65 projectId: "test-c2ec9",
66 storageBucket: "test-c2ec9.appspot.com",
67 messagingSenderId: "11138018851",
68 appId: "1:11138018851:web:ecfb63337ca11f62028b96",
69 measurementId: "G-3S1M3601YR"
70};
71
72// Initialize Firebase
73firebase.initializeApp(config);
74
75// Get a reference to the database service
76var database = firebase.database();
77const app = initializeApp(config);
78const analytics = getAnalytics(app);
79
80ReactDOM.render(
81 <React.StrictMode>
82 </React.StrictMode>,
83 document.getElementById('root')
84);
85
86// If you want to start measuring performance in your app, pass a function
87// to log results (for example: reportWebVitals(console.log))
88// or send to an analytics endpoint.
89//reportWebVitals();<!DOCTYPE html>
90<html>
91 <head>
92 <meta charset="utf-8">
93 <meta name="viewport" content="width=device-width, initial-scale=1">
94 <title>Welcome to Firebase Hosting</title>
95
96 <!-- update the version number as needed -->
97 <script defer src="/__/firebase/8.10.0/firebase-app.js"></script>
98 <!-- include only the Firebase features as you need -->
99 <script defer src="/__/firebase/8.10.0/firebase-auth.js"></script>
100 <script defer src="/__/firebase/8.10.0/firebase-database.js"></script>
101 <script defer src="/__/firebase/8.10.0/firebase-firestore.js"></script>
102 <script defer src="/__/firebase/8.10.0/firebase-functions.js"></script>
103 <script defer src="/__/firebase/8.10.0/firebase-messaging.js"></script>
104 <script defer src="/__/firebase/8.10.0/firebase-storage.js"></script>
105 <script defer src="/__/firebase/8.10.0/firebase-analytics.js"></script>
106 <script defer src="/__/firebase/8.10.0/firebase-remote-config.js"></script>
107 <script defer src="/__/firebase/8.10.0/firebase-performance.js"></script>
108 <!--
109 initialize the SDK after all desired features are loaded, set useEmulator to false
110 to avoid connecting the SDK to running emulators.
111 -->
112 <script defer src="/__/firebase/init.js?useEmulator=true"></script>
113
114 <style media="screen">
115 body { background: #ECEFF1; color: rgba(0,0,0,0.87); font-family: Roboto, Helvetica, Arial, sans-serif; margin: 0; padding: 0; }
116 #message { background: white; max-width: 360px; margin: 100px auto 16px; padding: 32px 24px; border-radius: 3px; }
117 #message h2 { color: #ffa100; font-weight: bold; font-size: 16px; margin: 0 0 8px; }
118 #message h1 { font-size: 22px; font-weight: 300; color: rgba(0,0,0,0.6); margin: 0 0 16px;}
119 #message p { line-height: 140%; margin: 16px 0 24px; font-size: 14px; }
120 #message a { display: block; text-align: center; background: #039be5; text-transform: uppercase; text-decoration: none; color: white; padding: 16px; border-radius: 4px; }
121 #message, #message a { box-shadow: 0 1px 3px rgba(0,0,0,0.12), 0 1px 2px rgba(0,0,0,0.24); }
122 #load { color: rgba(0,0,0,0.4); text-align: center; font-size: 13px; }
123 @media (max-width: 600px) {
124 body, #message { margin-top: 0; background: white; box-shadow: none; }
125 body { border-top: 16px solid #ffa100; }
126 }
127 </style>
128 </head>
129 <body>
130 <div id="message">
131 <h2>Welcome</h2>
132 <h1>Firebase Hosting Setup Complete</h1>
133 <p>You're seeing this because you've successfully setup Firebase Hosting. Now it's time to go build something extraordinary!</p>
134 <a target="_blank" href="https://firebase.google.com/docs/hosting/">Open Hosting Documentation</a>
135 </div>
136 <p id="load">Firebase SDK Loading&hellip;</p>
137
138 <script>
139 document.addEventListener('DOMContentLoaded', function() {
140 const loadEl = document.querySelector('#load');
141 // // π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯
142 // // The Firebase SDK is initialized and available here!
143 //
144 // firebase.auth().onAuthStateChanged(user => { });
145 // firebase.database().ref('/path/to/ref').on('value', snapshot => { });
146 // firebase.firestore().doc('/foo/bar').get().then(() => { });
147 // firebase.functions().httpsCallable('yourFunction')().then(() => { });
148 // firebase.messaging().requestPermission().then(() => { });
149 // firebase.storage().ref('/path/to/ref').getDownloadURL().then(() => { });
150 // firebase.analytics(); // call to activate
151 // firebase.analytics().logEvent('tutorial_completed');
152 // firebase.performance(); // call to activate
153 //
154 // // π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯
155
156 try {
157 let app = firebase.app();
158 let features = [
159 'auth',
160 'database',
161 'firestore',
162 'functions',
163 'messaging',
164 'storage',
165 'analytics',
166 'remoteConfig',
167 'performance',
168 ].filter(feature => typeof app[feature] === 'function');
169 loadEl.textContent = `Firebase SDK loaded with ${features.join(', ')}`;
170 } catch (e) {
171 console.error(e);
172 loadEl.textContent = 'Error loading the Firebase SDK, check the console.';
173 }
174 });
175 </script>
176 <!-- The core Firebase JS SDK is always required and must be listed first -->
177 <script src="/__/firebase/8.10.0/firebase-app.js"></script>
178
179 <!-- TODO: Add SDKs for Firebase products that you want to use
180 https://firebase.google.com/docs/web/setup#available-libraries -->
181 <script src="/__/firebase/8.10.0/firebase-analytics.js"></script>
182 <!-- Initialize Firebase -->
183 <script src="/__/firebase/init.js"></script>
184 </body>
185</html><!DOCTYPE html>
186<html lang="en">
187 <head>
188 <meta charset="utf-8" />
189 <link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
190 <meta name="viewport" content="width=device-width, initial-scale=1" />
191 <meta name="theme-color" content="#000000" />
192 <meta
193 name="description"
194 content="Web site created using create-react-app"
195 />
196 <link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" />
197 <!--
198 manifest.json provides metadata used when your web app is installed on a
199 user's mobile device or desktop. See https://developers.google.com/web/fundamentals/web-app-manifest/
200 -->
201 <link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
202 <!--
203 Notice the use of %PUBLIC_URL% in the tags above.
204 It will be replaced with the URL of the `public` folder during the build.
205 Only files inside the `public` folder can be referenced from the HTML.
206
207 Unlike "/favicon.ico" or "favicon.ico", "%PUBLIC_URL%/favicon.ico" will
208 work correctly both with client-side routing and a non-root public URL.
209 Learn how to configure a non-root public URL by running `npm run build`.
210 -->
211 <title>React App</title>
212 </head>
213 <body>
214 <noscript>You need to enable JavaScript to run this app.</noscript>
215 <div id="root"></div>
216 <!--
217 This HTML file is a template.
218 If you open it directly in the browser, you will see an empty page.
219
220 You can add webfonts, meta tags, or analytics to this file.
221 The build step will place the bundled scripts into the <body> tag.
222
223 To begin the development, run `npm start` or `yarn start`.
224 To create a production bundle, use `npm run build` or `yarn build`.
225 -->
226 <!-- The core Firebase JS SDK is always required and must be listed first -->
227 <script src="/__/firebase/8.10.0/firebase-app.js"></script>
228
229 <!-- TODO: Add SDKs for Firebase products that you want to use
230 https://firebase.google.com/docs/web/setup#available-libraries -->
231 <script src="/__/firebase/8.10.0/firebase-analytics.js"></script>
232 <!-- Initialize Firebase -->
233 <script src="/__/firebase/init.js"></script>
234 </body>
235</html><script src='https://cdn.firebase.com/js/client/8.10.0/firebase.js'></script>
236<script src='https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js'></script>
237<link rel='stylesheet' type='text/css' href='/resources/tutorial/css/example.css'>
238
pasting this snippet in the head part of build/index.html and public/index.html
1Failed to compile
2src/index.js
3 Line 25:1: 'firebase' is not defined no-undef
4 Line 28:16: 'firebase' is not defined no-undef
5
6Search for the keywords to learn more about each error.
7This error occurred during the build time and cannot be dismissed.
8{
9 "name": "my-app",
10 "version": "0.1.0",
11 "private": true,
12 "dependencies": {
13 "@material-ui/core": "^4.12.2",
14 "@testing-library/jest-dom": "^5.14.1",
15 "@testing-library/react": "^11.2.7",
16 "@testing-library/user-event": "^12.8.3",
17 "firebase": "^9.0.0",
18 "react": "^17.0.2",
19 "react-dom": "^17.0.2",
20 "react-router-config": "^5.1.1",
21 "react-router-dom": "^5.2.0",
22 "react-scripts": "4.0.3",
23 "web-vitals": "^1.1.2"
24 },
25 "scripts": {
26 "start": "react-scripts start",
27 "build": "react-scripts build",
28 "test": "react-scripts test",
29 "eject": "react-scripts eject"
30 },
31 "eslintConfig": {
32 "extends": [
33 "react-app",
34 "react-app/jest"
35 ]
36 },
37 "browserslist": {
38 "production": [
39 ">0.2%",
40 "not dead",
41 "not op_mini all"
42 ],
43 "development": [
44 "last 1 chrome version",
45 "last 1 firefox version",
46 "last 1 safari version"
47 ]
48 }
49}import React from 'react';
50import ReactDOM from 'react-dom';
51//import './index.css';
52//import App from './App';
53//import reportWebVitals from './reportWebVitals';
54// Import the functions you need from the SDKs you need
55import { initializeApp } from "firebase/app";
56import { getAnalytics } from "firebase/analytics";
57// TODO: Add SDKs for Firebase products that you want to use
58// https://firebase.google.com/docs/web/setup#available-libraries
59
60// Your web app's Firebase configuration
61// For Firebase JS SDK v7.20.0 and later, measurementId is optional
62const config = {
63 apiKey: "AIzaSyBk5lf0WtiZPs1ZQkA48OfXpzW7P_RCrZk",
64 authDomain: "test-c2ec9.firebaseapp.com",
65 projectId: "test-c2ec9",
66 storageBucket: "test-c2ec9.appspot.com",
67 messagingSenderId: "11138018851",
68 appId: "1:11138018851:web:ecfb63337ca11f62028b96",
69 measurementId: "G-3S1M3601YR"
70};
71
72// Initialize Firebase
73firebase.initializeApp(config);
74
75// Get a reference to the database service
76var database = firebase.database();
77const app = initializeApp(config);
78const analytics = getAnalytics(app);
79
80ReactDOM.render(
81 <React.StrictMode>
82 </React.StrictMode>,
83 document.getElementById('root')
84);
85
86// If you want to start measuring performance in your app, pass a function
87// to log results (for example: reportWebVitals(console.log))
88// or send to an analytics endpoint.
89//reportWebVitals();<!DOCTYPE html>
90<html>
91 <head>
92 <meta charset="utf-8">
93 <meta name="viewport" content="width=device-width, initial-scale=1">
94 <title>Welcome to Firebase Hosting</title>
95
96 <!-- update the version number as needed -->
97 <script defer src="/__/firebase/8.10.0/firebase-app.js"></script>
98 <!-- include only the Firebase features as you need -->
99 <script defer src="/__/firebase/8.10.0/firebase-auth.js"></script>
100 <script defer src="/__/firebase/8.10.0/firebase-database.js"></script>
101 <script defer src="/__/firebase/8.10.0/firebase-firestore.js"></script>
102 <script defer src="/__/firebase/8.10.0/firebase-functions.js"></script>
103 <script defer src="/__/firebase/8.10.0/firebase-messaging.js"></script>
104 <script defer src="/__/firebase/8.10.0/firebase-storage.js"></script>
105 <script defer src="/__/firebase/8.10.0/firebase-analytics.js"></script>
106 <script defer src="/__/firebase/8.10.0/firebase-remote-config.js"></script>
107 <script defer src="/__/firebase/8.10.0/firebase-performance.js"></script>
108 <!--
109 initialize the SDK after all desired features are loaded, set useEmulator to false
110 to avoid connecting the SDK to running emulators.
111 -->
112 <script defer src="/__/firebase/init.js?useEmulator=true"></script>
113
114 <style media="screen">
115 body { background: #ECEFF1; color: rgba(0,0,0,0.87); font-family: Roboto, Helvetica, Arial, sans-serif; margin: 0; padding: 0; }
116 #message { background: white; max-width: 360px; margin: 100px auto 16px; padding: 32px 24px; border-radius: 3px; }
117 #message h2 { color: #ffa100; font-weight: bold; font-size: 16px; margin: 0 0 8px; }
118 #message h1 { font-size: 22px; font-weight: 300; color: rgba(0,0,0,0.6); margin: 0 0 16px;}
119 #message p { line-height: 140%; margin: 16px 0 24px; font-size: 14px; }
120 #message a { display: block; text-align: center; background: #039be5; text-transform: uppercase; text-decoration: none; color: white; padding: 16px; border-radius: 4px; }
121 #message, #message a { box-shadow: 0 1px 3px rgba(0,0,0,0.12), 0 1px 2px rgba(0,0,0,0.24); }
122 #load { color: rgba(0,0,0,0.4); text-align: center; font-size: 13px; }
123 @media (max-width: 600px) {
124 body, #message { margin-top: 0; background: white; box-shadow: none; }
125 body { border-top: 16px solid #ffa100; }
126 }
127 </style>
128 </head>
129 <body>
130 <div id="message">
131 <h2>Welcome</h2>
132 <h1>Firebase Hosting Setup Complete</h1>
133 <p>You're seeing this because you've successfully setup Firebase Hosting. Now it's time to go build something extraordinary!</p>
134 <a target="_blank" href="https://firebase.google.com/docs/hosting/">Open Hosting Documentation</a>
135 </div>
136 <p id="load">Firebase SDK Loading&hellip;</p>
137
138 <script>
139 document.addEventListener('DOMContentLoaded', function() {
140 const loadEl = document.querySelector('#load');
141 // // π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯
142 // // The Firebase SDK is initialized and available here!
143 //
144 // firebase.auth().onAuthStateChanged(user => { });
145 // firebase.database().ref('/path/to/ref').on('value', snapshot => { });
146 // firebase.firestore().doc('/foo/bar').get().then(() => { });
147 // firebase.functions().httpsCallable('yourFunction')().then(() => { });
148 // firebase.messaging().requestPermission().then(() => { });
149 // firebase.storage().ref('/path/to/ref').getDownloadURL().then(() => { });
150 // firebase.analytics(); // call to activate
151 // firebase.analytics().logEvent('tutorial_completed');
152 // firebase.performance(); // call to activate
153 //
154 // // π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯
155
156 try {
157 let app = firebase.app();
158 let features = [
159 'auth',
160 'database',
161 'firestore',
162 'functions',
163 'messaging',
164 'storage',
165 'analytics',
166 'remoteConfig',
167 'performance',
168 ].filter(feature => typeof app[feature] === 'function');
169 loadEl.textContent = `Firebase SDK loaded with ${features.join(', ')}`;
170 } catch (e) {
171 console.error(e);
172 loadEl.textContent = 'Error loading the Firebase SDK, check the console.';
173 }
174 });
175 </script>
176 <!-- The core Firebase JS SDK is always required and must be listed first -->
177 <script src="/__/firebase/8.10.0/firebase-app.js"></script>
178
179 <!-- TODO: Add SDKs for Firebase products that you want to use
180 https://firebase.google.com/docs/web/setup#available-libraries -->
181 <script src="/__/firebase/8.10.0/firebase-analytics.js"></script>
182 <!-- Initialize Firebase -->
183 <script src="/__/firebase/init.js"></script>
184 </body>
185</html><!DOCTYPE html>
186<html lang="en">
187 <head>
188 <meta charset="utf-8" />
189 <link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
190 <meta name="viewport" content="width=device-width, initial-scale=1" />
191 <meta name="theme-color" content="#000000" />
192 <meta
193 name="description"
194 content="Web site created using create-react-app"
195 />
196 <link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" />
197 <!--
198 manifest.json provides metadata used when your web app is installed on a
199 user's mobile device or desktop. See https://developers.google.com/web/fundamentals/web-app-manifest/
200 -->
201 <link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
202 <!--
203 Notice the use of %PUBLIC_URL% in the tags above.
204 It will be replaced with the URL of the `public` folder during the build.
205 Only files inside the `public` folder can be referenced from the HTML.
206
207 Unlike "/favicon.ico" or "favicon.ico", "%PUBLIC_URL%/favicon.ico" will
208 work correctly both with client-side routing and a non-root public URL.
209 Learn how to configure a non-root public URL by running `npm run build`.
210 -->
211 <title>React App</title>
212 </head>
213 <body>
214 <noscript>You need to enable JavaScript to run this app.</noscript>
215 <div id="root"></div>
216 <!--
217 This HTML file is a template.
218 If you open it directly in the browser, you will see an empty page.
219
220 You can add webfonts, meta tags, or analytics to this file.
221 The build step will place the bundled scripts into the <body> tag.
222
223 To begin the development, run `npm start` or `yarn start`.
224 To create a production bundle, use `npm run build` or `yarn build`.
225 -->
226 <!-- The core Firebase JS SDK is always required and must be listed first -->
227 <script src="/__/firebase/8.10.0/firebase-app.js"></script>
228
229 <!-- TODO: Add SDKs for Firebase products that you want to use
230 https://firebase.google.com/docs/web/setup#available-libraries -->
231 <script src="/__/firebase/8.10.0/firebase-analytics.js"></script>
232 <!-- Initialize Firebase -->
233 <script src="/__/firebase/init.js"></script>
234 </body>
235</html><script src='https://cdn.firebase.com/js/client/8.10.0/firebase.js'></script>
236<script src='https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js'></script>
237<link rel='stylesheet' type='text/css' href='/resources/tutorial/css/example.css'>
238<script src="https://www.gstatic.com/firebasejs/8.10.0/firebase.js"></script>
239<link rel='stylesheet' type='text/css' href='/resources/tutorial/css/example.css'>
240
pasting this snippet in the head part of build/index.html and public/index.html
1Failed to compile
2src/index.js
3 Line 25:1: 'firebase' is not defined no-undef
4 Line 28:16: 'firebase' is not defined no-undef
5
6Search for the keywords to learn more about each error.
7This error occurred during the build time and cannot be dismissed.
8{
9 "name": "my-app",
10 "version": "0.1.0",
11 "private": true,
12 "dependencies": {
13 "@material-ui/core": "^4.12.2",
14 "@testing-library/jest-dom": "^5.14.1",
15 "@testing-library/react": "^11.2.7",
16 "@testing-library/user-event": "^12.8.3",
17 "firebase": "^9.0.0",
18 "react": "^17.0.2",
19 "react-dom": "^17.0.2",
20 "react-router-config": "^5.1.1",
21 "react-router-dom": "^5.2.0",
22 "react-scripts": "4.0.3",
23 "web-vitals": "^1.1.2"
24 },
25 "scripts": {
26 "start": "react-scripts start",
27 "build": "react-scripts build",
28 "test": "react-scripts test",
29 "eject": "react-scripts eject"
30 },
31 "eslintConfig": {
32 "extends": [
33 "react-app",
34 "react-app/jest"
35 ]
36 },
37 "browserslist": {
38 "production": [
39 ">0.2%",
40 "not dead",
41 "not op_mini all"
42 ],
43 "development": [
44 "last 1 chrome version",
45 "last 1 firefox version",
46 "last 1 safari version"
47 ]
48 }
49}import React from 'react';
50import ReactDOM from 'react-dom';
51//import './index.css';
52//import App from './App';
53//import reportWebVitals from './reportWebVitals';
54// Import the functions you need from the SDKs you need
55import { initializeApp } from "firebase/app";
56import { getAnalytics } from "firebase/analytics";
57// TODO: Add SDKs for Firebase products that you want to use
58// https://firebase.google.com/docs/web/setup#available-libraries
59
60// Your web app's Firebase configuration
61// For Firebase JS SDK v7.20.0 and later, measurementId is optional
62const config = {
63 apiKey: "AIzaSyBk5lf0WtiZPs1ZQkA48OfXpzW7P_RCrZk",
64 authDomain: "test-c2ec9.firebaseapp.com",
65 projectId: "test-c2ec9",
66 storageBucket: "test-c2ec9.appspot.com",
67 messagingSenderId: "11138018851",
68 appId: "1:11138018851:web:ecfb63337ca11f62028b96",
69 measurementId: "G-3S1M3601YR"
70};
71
72// Initialize Firebase
73firebase.initializeApp(config);
74
75// Get a reference to the database service
76var database = firebase.database();
77const app = initializeApp(config);
78const analytics = getAnalytics(app);
79
80ReactDOM.render(
81 <React.StrictMode>
82 </React.StrictMode>,
83 document.getElementById('root')
84);
85
86// If you want to start measuring performance in your app, pass a function
87// to log results (for example: reportWebVitals(console.log))
88// or send to an analytics endpoint.
89//reportWebVitals();<!DOCTYPE html>
90<html>
91 <head>
92 <meta charset="utf-8">
93 <meta name="viewport" content="width=device-width, initial-scale=1">
94 <title>Welcome to Firebase Hosting</title>
95
96 <!-- update the version number as needed -->
97 <script defer src="/__/firebase/8.10.0/firebase-app.js"></script>
98 <!-- include only the Firebase features as you need -->
99 <script defer src="/__/firebase/8.10.0/firebase-auth.js"></script>
100 <script defer src="/__/firebase/8.10.0/firebase-database.js"></script>
101 <script defer src="/__/firebase/8.10.0/firebase-firestore.js"></script>
102 <script defer src="/__/firebase/8.10.0/firebase-functions.js"></script>
103 <script defer src="/__/firebase/8.10.0/firebase-messaging.js"></script>
104 <script defer src="/__/firebase/8.10.0/firebase-storage.js"></script>
105 <script defer src="/__/firebase/8.10.0/firebase-analytics.js"></script>
106 <script defer src="/__/firebase/8.10.0/firebase-remote-config.js"></script>
107 <script defer src="/__/firebase/8.10.0/firebase-performance.js"></script>
108 <!--
109 initialize the SDK after all desired features are loaded, set useEmulator to false
110 to avoid connecting the SDK to running emulators.
111 -->
112 <script defer src="/__/firebase/init.js?useEmulator=true"></script>
113
114 <style media="screen">
115 body { background: #ECEFF1; color: rgba(0,0,0,0.87); font-family: Roboto, Helvetica, Arial, sans-serif; margin: 0; padding: 0; }
116 #message { background: white; max-width: 360px; margin: 100px auto 16px; padding: 32px 24px; border-radius: 3px; }
117 #message h2 { color: #ffa100; font-weight: bold; font-size: 16px; margin: 0 0 8px; }
118 #message h1 { font-size: 22px; font-weight: 300; color: rgba(0,0,0,0.6); margin: 0 0 16px;}
119 #message p { line-height: 140%; margin: 16px 0 24px; font-size: 14px; }
120 #message a { display: block; text-align: center; background: #039be5; text-transform: uppercase; text-decoration: none; color: white; padding: 16px; border-radius: 4px; }
121 #message, #message a { box-shadow: 0 1px 3px rgba(0,0,0,0.12), 0 1px 2px rgba(0,0,0,0.24); }
122 #load { color: rgba(0,0,0,0.4); text-align: center; font-size: 13px; }
123 @media (max-width: 600px) {
124 body, #message { margin-top: 0; background: white; box-shadow: none; }
125 body { border-top: 16px solid #ffa100; }
126 }
127 </style>
128 </head>
129 <body>
130 <div id="message">
131 <h2>Welcome</h2>
132 <h1>Firebase Hosting Setup Complete</h1>
133 <p>You're seeing this because you've successfully setup Firebase Hosting. Now it's time to go build something extraordinary!</p>
134 <a target="_blank" href="https://firebase.google.com/docs/hosting/">Open Hosting Documentation</a>
135 </div>
136 <p id="load">Firebase SDK Loading&hellip;</p>
137
138 <script>
139 document.addEventListener('DOMContentLoaded', function() {
140 const loadEl = document.querySelector('#load');
141 // // π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯
142 // // The Firebase SDK is initialized and available here!
143 //
144 // firebase.auth().onAuthStateChanged(user => { });
145 // firebase.database().ref('/path/to/ref').on('value', snapshot => { });
146 // firebase.firestore().doc('/foo/bar').get().then(() => { });
147 // firebase.functions().httpsCallable('yourFunction')().then(() => { });
148 // firebase.messaging().requestPermission().then(() => { });
149 // firebase.storage().ref('/path/to/ref').getDownloadURL().then(() => { });
150 // firebase.analytics(); // call to activate
151 // firebase.analytics().logEvent('tutorial_completed');
152 // firebase.performance(); // call to activate
153 //
154 // // π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯
155
156 try {
157 let app = firebase.app();
158 let features = [
159 'auth',
160 'database',
161 'firestore',
162 'functions',
163 'messaging',
164 'storage',
165 'analytics',
166 'remoteConfig',
167 'performance',
168 ].filter(feature => typeof app[feature] === 'function');
169 loadEl.textContent = `Firebase SDK loaded with ${features.join(', ')}`;
170 } catch (e) {
171 console.error(e);
172 loadEl.textContent = 'Error loading the Firebase SDK, check the console.';
173 }
174 });
175 </script>
176 <!-- The core Firebase JS SDK is always required and must be listed first -->
177 <script src="/__/firebase/8.10.0/firebase-app.js"></script>
178
179 <!-- TODO: Add SDKs for Firebase products that you want to use
180 https://firebase.google.com/docs/web/setup#available-libraries -->
181 <script src="/__/firebase/8.10.0/firebase-analytics.js"></script>
182 <!-- Initialize Firebase -->
183 <script src="/__/firebase/init.js"></script>
184 </body>
185</html><!DOCTYPE html>
186<html lang="en">
187 <head>
188 <meta charset="utf-8" />
189 <link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
190 <meta name="viewport" content="width=device-width, initial-scale=1" />
191 <meta name="theme-color" content="#000000" />
192 <meta
193 name="description"
194 content="Web site created using create-react-app"
195 />
196 <link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" />
197 <!--
198 manifest.json provides metadata used when your web app is installed on a
199 user's mobile device or desktop. See https://developers.google.com/web/fundamentals/web-app-manifest/
200 -->
201 <link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
202 <!--
203 Notice the use of %PUBLIC_URL% in the tags above.
204 It will be replaced with the URL of the `public` folder during the build.
205 Only files inside the `public` folder can be referenced from the HTML.
206
207 Unlike "/favicon.ico" or "favicon.ico", "%PUBLIC_URL%/favicon.ico" will
208 work correctly both with client-side routing and a non-root public URL.
209 Learn how to configure a non-root public URL by running `npm run build`.
210 -->
211 <title>React App</title>
212 </head>
213 <body>
214 <noscript>You need to enable JavaScript to run this app.</noscript>
215 <div id="root"></div>
216 <!--
217 This HTML file is a template.
218 If you open it directly in the browser, you will see an empty page.
219
220 You can add webfonts, meta tags, or analytics to this file.
221 The build step will place the bundled scripts into the <body> tag.
222
223 To begin the development, run `npm start` or `yarn start`.
224 To create a production bundle, use `npm run build` or `yarn build`.
225 -->
226 <!-- The core Firebase JS SDK is always required and must be listed first -->
227 <script src="/__/firebase/8.10.0/firebase-app.js"></script>
228
229 <!-- TODO: Add SDKs for Firebase products that you want to use
230 https://firebase.google.com/docs/web/setup#available-libraries -->
231 <script src="/__/firebase/8.10.0/firebase-analytics.js"></script>
232 <!-- Initialize Firebase -->
233 <script src="/__/firebase/init.js"></script>
234 </body>
235</html><script src='https://cdn.firebase.com/js/client/8.10.0/firebase.js'></script>
236<script src='https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js'></script>
237<link rel='stylesheet' type='text/css' href='/resources/tutorial/css/example.css'>
238<script src="https://www.gstatic.com/firebasejs/8.10.0/firebase.js"></script>
239<link rel='stylesheet' type='text/css' href='/resources/tutorial/css/example.css'>
240<script src="https://www.gstatic.com/firebasejs/ui/8.10.0/firebase-ui-auth.js"></script>
241<link type="text/css" rel="stylesheet" href="https://www.gstatic.com/firebasejs/ui/5.0.0/firebase-ui-auth.css" />
242
pasting this snippet in the head part of build/index.html and public/index.html
1Failed to compile
2src/index.js
3 Line 25:1: 'firebase' is not defined no-undef
4 Line 28:16: 'firebase' is not defined no-undef
5
6Search for the keywords to learn more about each error.
7This error occurred during the build time and cannot be dismissed.
8{
9 "name": "my-app",
10 "version": "0.1.0",
11 "private": true,
12 "dependencies": {
13 "@material-ui/core": "^4.12.2",
14 "@testing-library/jest-dom": "^5.14.1",
15 "@testing-library/react": "^11.2.7",
16 "@testing-library/user-event": "^12.8.3",
17 "firebase": "^9.0.0",
18 "react": "^17.0.2",
19 "react-dom": "^17.0.2",
20 "react-router-config": "^5.1.1",
21 "react-router-dom": "^5.2.0",
22 "react-scripts": "4.0.3",
23 "web-vitals": "^1.1.2"
24 },
25 "scripts": {
26 "start": "react-scripts start",
27 "build": "react-scripts build",
28 "test": "react-scripts test",
29 "eject": "react-scripts eject"
30 },
31 "eslintConfig": {
32 "extends": [
33 "react-app",
34 "react-app/jest"
35 ]
36 },
37 "browserslist": {
38 "production": [
39 ">0.2%",
40 "not dead",
41 "not op_mini all"
42 ],
43 "development": [
44 "last 1 chrome version",
45 "last 1 firefox version",
46 "last 1 safari version"
47 ]
48 }
49}import React from 'react';
50import ReactDOM from 'react-dom';
51//import './index.css';
52//import App from './App';
53//import reportWebVitals from './reportWebVitals';
54// Import the functions you need from the SDKs you need
55import { initializeApp } from "firebase/app";
56import { getAnalytics } from "firebase/analytics";
57// TODO: Add SDKs for Firebase products that you want to use
58// https://firebase.google.com/docs/web/setup#available-libraries
59
60// Your web app's Firebase configuration
61// For Firebase JS SDK v7.20.0 and later, measurementId is optional
62const config = {
63 apiKey: "AIzaSyBk5lf0WtiZPs1ZQkA48OfXpzW7P_RCrZk",
64 authDomain: "test-c2ec9.firebaseapp.com",
65 projectId: "test-c2ec9",
66 storageBucket: "test-c2ec9.appspot.com",
67 messagingSenderId: "11138018851",
68 appId: "1:11138018851:web:ecfb63337ca11f62028b96",
69 measurementId: "G-3S1M3601YR"
70};
71
72// Initialize Firebase
73firebase.initializeApp(config);
74
75// Get a reference to the database service
76var database = firebase.database();
77const app = initializeApp(config);
78const analytics = getAnalytics(app);
79
80ReactDOM.render(
81 <React.StrictMode>
82 </React.StrictMode>,
83 document.getElementById('root')
84);
85
86// If you want to start measuring performance in your app, pass a function
87// to log results (for example: reportWebVitals(console.log))
88// or send to an analytics endpoint.
89//reportWebVitals();<!DOCTYPE html>
90<html>
91 <head>
92 <meta charset="utf-8">
93 <meta name="viewport" content="width=device-width, initial-scale=1">
94 <title>Welcome to Firebase Hosting</title>
95
96 <!-- update the version number as needed -->
97 <script defer src="/__/firebase/8.10.0/firebase-app.js"></script>
98 <!-- include only the Firebase features as you need -->
99 <script defer src="/__/firebase/8.10.0/firebase-auth.js"></script>
100 <script defer src="/__/firebase/8.10.0/firebase-database.js"></script>
101 <script defer src="/__/firebase/8.10.0/firebase-firestore.js"></script>
102 <script defer src="/__/firebase/8.10.0/firebase-functions.js"></script>
103 <script defer src="/__/firebase/8.10.0/firebase-messaging.js"></script>
104 <script defer src="/__/firebase/8.10.0/firebase-storage.js"></script>
105 <script defer src="/__/firebase/8.10.0/firebase-analytics.js"></script>
106 <script defer src="/__/firebase/8.10.0/firebase-remote-config.js"></script>
107 <script defer src="/__/firebase/8.10.0/firebase-performance.js"></script>
108 <!--
109 initialize the SDK after all desired features are loaded, set useEmulator to false
110 to avoid connecting the SDK to running emulators.
111 -->
112 <script defer src="/__/firebase/init.js?useEmulator=true"></script>
113
114 <style media="screen">
115 body { background: #ECEFF1; color: rgba(0,0,0,0.87); font-family: Roboto, Helvetica, Arial, sans-serif; margin: 0; padding: 0; }
116 #message { background: white; max-width: 360px; margin: 100px auto 16px; padding: 32px 24px; border-radius: 3px; }
117 #message h2 { color: #ffa100; font-weight: bold; font-size: 16px; margin: 0 0 8px; }
118 #message h1 { font-size: 22px; font-weight: 300; color: rgba(0,0,0,0.6); margin: 0 0 16px;}
119 #message p { line-height: 140%; margin: 16px 0 24px; font-size: 14px; }
120 #message a { display: block; text-align: center; background: #039be5; text-transform: uppercase; text-decoration: none; color: white; padding: 16px; border-radius: 4px; }
121 #message, #message a { box-shadow: 0 1px 3px rgba(0,0,0,0.12), 0 1px 2px rgba(0,0,0,0.24); }
122 #load { color: rgba(0,0,0,0.4); text-align: center; font-size: 13px; }
123 @media (max-width: 600px) {
124 body, #message { margin-top: 0; background: white; box-shadow: none; }
125 body { border-top: 16px solid #ffa100; }
126 }
127 </style>
128 </head>
129 <body>
130 <div id="message">
131 <h2>Welcome</h2>
132 <h1>Firebase Hosting Setup Complete</h1>
133 <p>You're seeing this because you've successfully setup Firebase Hosting. Now it's time to go build something extraordinary!</p>
134 <a target="_blank" href="https://firebase.google.com/docs/hosting/">Open Hosting Documentation</a>
135 </div>
136 <p id="load">Firebase SDK Loading&hellip;</p>
137
138 <script>
139 document.addEventListener('DOMContentLoaded', function() {
140 const loadEl = document.querySelector('#load');
141 // // π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯
142 // // The Firebase SDK is initialized and available here!
143 //
144 // firebase.auth().onAuthStateChanged(user => { });
145 // firebase.database().ref('/path/to/ref').on('value', snapshot => { });
146 // firebase.firestore().doc('/foo/bar').get().then(() => { });
147 // firebase.functions().httpsCallable('yourFunction')().then(() => { });
148 // firebase.messaging().requestPermission().then(() => { });
149 // firebase.storage().ref('/path/to/ref').getDownloadURL().then(() => { });
150 // firebase.analytics(); // call to activate
151 // firebase.analytics().logEvent('tutorial_completed');
152 // firebase.performance(); // call to activate
153 //
154 // // π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯
155
156 try {
157 let app = firebase.app();
158 let features = [
159 'auth',
160 'database',
161 'firestore',
162 'functions',
163 'messaging',
164 'storage',
165 'analytics',
166 'remoteConfig',
167 'performance',
168 ].filter(feature => typeof app[feature] === 'function');
169 loadEl.textContent = `Firebase SDK loaded with ${features.join(', ')}`;
170 } catch (e) {
171 console.error(e);
172 loadEl.textContent = 'Error loading the Firebase SDK, check the console.';
173 }
174 });
175 </script>
176 <!-- The core Firebase JS SDK is always required and must be listed first -->
177 <script src="/__/firebase/8.10.0/firebase-app.js"></script>
178
179 <!-- TODO: Add SDKs for Firebase products that you want to use
180 https://firebase.google.com/docs/web/setup#available-libraries -->
181 <script src="/__/firebase/8.10.0/firebase-analytics.js"></script>
182 <!-- Initialize Firebase -->
183 <script src="/__/firebase/init.js"></script>
184 </body>
185</html><!DOCTYPE html>
186<html lang="en">
187 <head>
188 <meta charset="utf-8" />
189 <link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
190 <meta name="viewport" content="width=device-width, initial-scale=1" />
191 <meta name="theme-color" content="#000000" />
192 <meta
193 name="description"
194 content="Web site created using create-react-app"
195 />
196 <link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" />
197 <!--
198 manifest.json provides metadata used when your web app is installed on a
199 user's mobile device or desktop. See https://developers.google.com/web/fundamentals/web-app-manifest/
200 -->
201 <link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
202 <!--
203 Notice the use of %PUBLIC_URL% in the tags above.
204 It will be replaced with the URL of the `public` folder during the build.
205 Only files inside the `public` folder can be referenced from the HTML.
206
207 Unlike "/favicon.ico" or "favicon.ico", "%PUBLIC_URL%/favicon.ico" will
208 work correctly both with client-side routing and a non-root public URL.
209 Learn how to configure a non-root public URL by running `npm run build`.
210 -->
211 <title>React App</title>
212 </head>
213 <body>
214 <noscript>You need to enable JavaScript to run this app.</noscript>
215 <div id="root"></div>
216 <!--
217 This HTML file is a template.
218 If you open it directly in the browser, you will see an empty page.
219
220 You can add webfonts, meta tags, or analytics to this file.
221 The build step will place the bundled scripts into the <body> tag.
222
223 To begin the development, run `npm start` or `yarn start`.
224 To create a production bundle, use `npm run build` or `yarn build`.
225 -->
226 <!-- The core Firebase JS SDK is always required and must be listed first -->
227 <script src="/__/firebase/8.10.0/firebase-app.js"></script>
228
229 <!-- TODO: Add SDKs for Firebase products that you want to use
230 https://firebase.google.com/docs/web/setup#available-libraries -->
231 <script src="/__/firebase/8.10.0/firebase-analytics.js"></script>
232 <!-- Initialize Firebase -->
233 <script src="/__/firebase/init.js"></script>
234 </body>
235</html><script src='https://cdn.firebase.com/js/client/8.10.0/firebase.js'></script>
236<script src='https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js'></script>
237<link rel='stylesheet' type='text/css' href='/resources/tutorial/css/example.css'>
238<script src="https://www.gstatic.com/firebasejs/8.10.0/firebase.js"></script>
239<link rel='stylesheet' type='text/css' href='/resources/tutorial/css/example.css'>
240<script src="https://www.gstatic.com/firebasejs/ui/8.10.0/firebase-ui-auth.js"></script>
241<link type="text/css" rel="stylesheet" href="https://www.gstatic.com/firebasejs/ui/5.0.0/firebase-ui-auth.css" />
242<script src="cdn.firebase.com/js/client/8.10.0/firebase.js"></script>
243<script src="cdn.firebase.com/libs/angularfire/0.8.2/ang.."></script>
244
copying this snippet from the head part of build/index.html and pasting it in public/index.html
1Failed to compile
2src/index.js
3 Line 25:1: 'firebase' is not defined no-undef
4 Line 28:16: 'firebase' is not defined no-undef
5
6Search for the keywords to learn more about each error.
7This error occurred during the build time and cannot be dismissed.
8{
9 "name": "my-app",
10 "version": "0.1.0",
11 "private": true,
12 "dependencies": {
13 "@material-ui/core": "^4.12.2",
14 "@testing-library/jest-dom": "^5.14.1",
15 "@testing-library/react": "^11.2.7",
16 "@testing-library/user-event": "^12.8.3",
17 "firebase": "^9.0.0",
18 "react": "^17.0.2",
19 "react-dom": "^17.0.2",
20 "react-router-config": "^5.1.1",
21 "react-router-dom": "^5.2.0",
22 "react-scripts": "4.0.3",
23 "web-vitals": "^1.1.2"
24 },
25 "scripts": {
26 "start": "react-scripts start",
27 "build": "react-scripts build",
28 "test": "react-scripts test",
29 "eject": "react-scripts eject"
30 },
31 "eslintConfig": {
32 "extends": [
33 "react-app",
34 "react-app/jest"
35 ]
36 },
37 "browserslist": {
38 "production": [
39 ">0.2%",
40 "not dead",
41 "not op_mini all"
42 ],
43 "development": [
44 "last 1 chrome version",
45 "last 1 firefox version",
46 "last 1 safari version"
47 ]
48 }
49}import React from 'react';
50import ReactDOM from 'react-dom';
51//import './index.css';
52//import App from './App';
53//import reportWebVitals from './reportWebVitals';
54// Import the functions you need from the SDKs you need
55import { initializeApp } from "firebase/app";
56import { getAnalytics } from "firebase/analytics";
57// TODO: Add SDKs for Firebase products that you want to use
58// https://firebase.google.com/docs/web/setup#available-libraries
59
60// Your web app's Firebase configuration
61// For Firebase JS SDK v7.20.0 and later, measurementId is optional
62const config = {
63 apiKey: "AIzaSyBk5lf0WtiZPs1ZQkA48OfXpzW7P_RCrZk",
64 authDomain: "test-c2ec9.firebaseapp.com",
65 projectId: "test-c2ec9",
66 storageBucket: "test-c2ec9.appspot.com",
67 messagingSenderId: "11138018851",
68 appId: "1:11138018851:web:ecfb63337ca11f62028b96",
69 measurementId: "G-3S1M3601YR"
70};
71
72// Initialize Firebase
73firebase.initializeApp(config);
74
75// Get a reference to the database service
76var database = firebase.database();
77const app = initializeApp(config);
78const analytics = getAnalytics(app);
79
80ReactDOM.render(
81 <React.StrictMode>
82 </React.StrictMode>,
83 document.getElementById('root')
84);
85
86// If you want to start measuring performance in your app, pass a function
87// to log results (for example: reportWebVitals(console.log))
88// or send to an analytics endpoint.
89//reportWebVitals();<!DOCTYPE html>
90<html>
91 <head>
92 <meta charset="utf-8">
93 <meta name="viewport" content="width=device-width, initial-scale=1">
94 <title>Welcome to Firebase Hosting</title>
95
96 <!-- update the version number as needed -->
97 <script defer src="/__/firebase/8.10.0/firebase-app.js"></script>
98 <!-- include only the Firebase features as you need -->
99 <script defer src="/__/firebase/8.10.0/firebase-auth.js"></script>
100 <script defer src="/__/firebase/8.10.0/firebase-database.js"></script>
101 <script defer src="/__/firebase/8.10.0/firebase-firestore.js"></script>
102 <script defer src="/__/firebase/8.10.0/firebase-functions.js"></script>
103 <script defer src="/__/firebase/8.10.0/firebase-messaging.js"></script>
104 <script defer src="/__/firebase/8.10.0/firebase-storage.js"></script>
105 <script defer src="/__/firebase/8.10.0/firebase-analytics.js"></script>
106 <script defer src="/__/firebase/8.10.0/firebase-remote-config.js"></script>
107 <script defer src="/__/firebase/8.10.0/firebase-performance.js"></script>
108 <!--
109 initialize the SDK after all desired features are loaded, set useEmulator to false
110 to avoid connecting the SDK to running emulators.
111 -->
112 <script defer src="/__/firebase/init.js?useEmulator=true"></script>
113
114 <style media="screen">
115 body { background: #ECEFF1; color: rgba(0,0,0,0.87); font-family: Roboto, Helvetica, Arial, sans-serif; margin: 0; padding: 0; }
116 #message { background: white; max-width: 360px; margin: 100px auto 16px; padding: 32px 24px; border-radius: 3px; }
117 #message h2 { color: #ffa100; font-weight: bold; font-size: 16px; margin: 0 0 8px; }
118 #message h1 { font-size: 22px; font-weight: 300; color: rgba(0,0,0,0.6); margin: 0 0 16px;}
119 #message p { line-height: 140%; margin: 16px 0 24px; font-size: 14px; }
120 #message a { display: block; text-align: center; background: #039be5; text-transform: uppercase; text-decoration: none; color: white; padding: 16px; border-radius: 4px; }
121 #message, #message a { box-shadow: 0 1px 3px rgba(0,0,0,0.12), 0 1px 2px rgba(0,0,0,0.24); }
122 #load { color: rgba(0,0,0,0.4); text-align: center; font-size: 13px; }
123 @media (max-width: 600px) {
124 body, #message { margin-top: 0; background: white; box-shadow: none; }
125 body { border-top: 16px solid #ffa100; }
126 }
127 </style>
128 </head>
129 <body>
130 <div id="message">
131 <h2>Welcome</h2>
132 <h1>Firebase Hosting Setup Complete</h1>
133 <p>You're seeing this because you've successfully setup Firebase Hosting. Now it's time to go build something extraordinary!</p>
134 <a target="_blank" href="https://firebase.google.com/docs/hosting/">Open Hosting Documentation</a>
135 </div>
136 <p id="load">Firebase SDK Loading&hellip;</p>
137
138 <script>
139 document.addEventListener('DOMContentLoaded', function() {
140 const loadEl = document.querySelector('#load');
141 // // π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯
142 // // The Firebase SDK is initialized and available here!
143 //
144 // firebase.auth().onAuthStateChanged(user => { });
145 // firebase.database().ref('/path/to/ref').on('value', snapshot => { });
146 // firebase.firestore().doc('/foo/bar').get().then(() => { });
147 // firebase.functions().httpsCallable('yourFunction')().then(() => { });
148 // firebase.messaging().requestPermission().then(() => { });
149 // firebase.storage().ref('/path/to/ref').getDownloadURL().then(() => { });
150 // firebase.analytics(); // call to activate
151 // firebase.analytics().logEvent('tutorial_completed');
152 // firebase.performance(); // call to activate
153 //
154 // // π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯
155
156 try {
157 let app = firebase.app();
158 let features = [
159 'auth',
160 'database',
161 'firestore',
162 'functions',
163 'messaging',
164 'storage',
165 'analytics',
166 'remoteConfig',
167 'performance',
168 ].filter(feature => typeof app[feature] === 'function');
169 loadEl.textContent = `Firebase SDK loaded with ${features.join(', ')}`;
170 } catch (e) {
171 console.error(e);
172 loadEl.textContent = 'Error loading the Firebase SDK, check the console.';
173 }
174 });
175 </script>
176 <!-- The core Firebase JS SDK is always required and must be listed first -->
177 <script src="/__/firebase/8.10.0/firebase-app.js"></script>
178
179 <!-- TODO: Add SDKs for Firebase products that you want to use
180 https://firebase.google.com/docs/web/setup#available-libraries -->
181 <script src="/__/firebase/8.10.0/firebase-analytics.js"></script>
182 <!-- Initialize Firebase -->
183 <script src="/__/firebase/init.js"></script>
184 </body>
185</html><!DOCTYPE html>
186<html lang="en">
187 <head>
188 <meta charset="utf-8" />
189 <link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
190 <meta name="viewport" content="width=device-width, initial-scale=1" />
191 <meta name="theme-color" content="#000000" />
192 <meta
193 name="description"
194 content="Web site created using create-react-app"
195 />
196 <link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" />
197 <!--
198 manifest.json provides metadata used when your web app is installed on a
199 user's mobile device or desktop. See https://developers.google.com/web/fundamentals/web-app-manifest/
200 -->
201 <link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
202 <!--
203 Notice the use of %PUBLIC_URL% in the tags above.
204 It will be replaced with the URL of the `public` folder during the build.
205 Only files inside the `public` folder can be referenced from the HTML.
206
207 Unlike "/favicon.ico" or "favicon.ico", "%PUBLIC_URL%/favicon.ico" will
208 work correctly both with client-side routing and a non-root public URL.
209 Learn how to configure a non-root public URL by running `npm run build`.
210 -->
211 <title>React App</title>
212 </head>
213 <body>
214 <noscript>You need to enable JavaScript to run this app.</noscript>
215 <div id="root"></div>
216 <!--
217 This HTML file is a template.
218 If you open it directly in the browser, you will see an empty page.
219
220 You can add webfonts, meta tags, or analytics to this file.
221 The build step will place the bundled scripts into the <body> tag.
222
223 To begin the development, run `npm start` or `yarn start`.
224 To create a production bundle, use `npm run build` or `yarn build`.
225 -->
226 <!-- The core Firebase JS SDK is always required and must be listed first -->
227 <script src="/__/firebase/8.10.0/firebase-app.js"></script>
228
229 <!-- TODO: Add SDKs for Firebase products that you want to use
230 https://firebase.google.com/docs/web/setup#available-libraries -->
231 <script src="/__/firebase/8.10.0/firebase-analytics.js"></script>
232 <!-- Initialize Firebase -->
233 <script src="/__/firebase/init.js"></script>
234 </body>
235</html><script src='https://cdn.firebase.com/js/client/8.10.0/firebase.js'></script>
236<script src='https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js'></script>
237<link rel='stylesheet' type='text/css' href='/resources/tutorial/css/example.css'>
238<script src="https://www.gstatic.com/firebasejs/8.10.0/firebase.js"></script>
239<link rel='stylesheet' type='text/css' href='/resources/tutorial/css/example.css'>
240<script src="https://www.gstatic.com/firebasejs/ui/8.10.0/firebase-ui-auth.js"></script>
241<link type="text/css" rel="stylesheet" href="https://www.gstatic.com/firebasejs/ui/5.0.0/firebase-ui-auth.css" />
242<script src="cdn.firebase.com/js/client/8.10.0/firebase.js"></script>
243<script src="cdn.firebase.com/libs/angularfire/0.8.2/ang.."></script>
244<!-- update the version number as needed -->
245<script defer src="/__/firebase/8.10.0/firebase-app.js"></script>
246<!-- include only the Firebase features as you need -->
247<script defer src="/__/firebase/8.10.0/firebase-auth.js"></script>
248<script defer src="/__/firebase/8.10.0/firebase-database.js"></script>
249<script defer src="/__/firebase/8.10.0/firebase-firestore.js"></script>
250<script defer src="/__/firebase/8.10.0/firebase-functions.js"></script>
251<script defer src="/__/firebase/8.10.0/firebase-messaging.js"></script>
252<script defer src="/__/firebase/8.10.0/firebase-storage.js"></script>
253<script defer src="/__/firebase/8.10.0/firebase-analytics.js"></script>
254<script defer src="/__/firebase/8.10.0/firebase-remote-config.js"></script>
255<script defer src="/__/firebase/8.10.0/firebase-performance.js"></script>
256<!--
257 initialize the SDK after all desired features are loaded, set useEmulator to false
258 to avoid connecting the SDK to running emulators.
259-->
260<script defer src="/__/firebase/init.js?useEmulator=true"></script>
261
Is there anything else that I can try?
ANSWER
Answered 2021-Nov-12 at 21:59Recently, Firebase announced that version 9 of Firebase SDK JS is generally available. This was done to do some optimisations. Try using:
1Failed to compile
2src/index.js
3 Line 25:1: 'firebase' is not defined no-undef
4 Line 28:16: 'firebase' is not defined no-undef
5
6Search for the keywords to learn more about each error.
7This error occurred during the build time and cannot be dismissed.
8{
9 "name": "my-app",
10 "version": "0.1.0",
11 "private": true,
12 "dependencies": {
13 "@material-ui/core": "^4.12.2",
14 "@testing-library/jest-dom": "^5.14.1",
15 "@testing-library/react": "^11.2.7",
16 "@testing-library/user-event": "^12.8.3",
17 "firebase": "^9.0.0",
18 "react": "^17.0.2",
19 "react-dom": "^17.0.2",
20 "react-router-config": "^5.1.1",
21 "react-router-dom": "^5.2.0",
22 "react-scripts": "4.0.3",
23 "web-vitals": "^1.1.2"
24 },
25 "scripts": {
26 "start": "react-scripts start",
27 "build": "react-scripts build",
28 "test": "react-scripts test",
29 "eject": "react-scripts eject"
30 },
31 "eslintConfig": {
32 "extends": [
33 "react-app",
34 "react-app/jest"
35 ]
36 },
37 "browserslist": {
38 "production": [
39 ">0.2%",
40 "not dead",
41 "not op_mini all"
42 ],
43 "development": [
44 "last 1 chrome version",
45 "last 1 firefox version",
46 "last 1 safari version"
47 ]
48 }
49}import React from 'react';
50import ReactDOM from 'react-dom';
51//import './index.css';
52//import App from './App';
53//import reportWebVitals from './reportWebVitals';
54// Import the functions you need from the SDKs you need
55import { initializeApp } from "firebase/app";
56import { getAnalytics } from "firebase/analytics";
57// TODO: Add SDKs for Firebase products that you want to use
58// https://firebase.google.com/docs/web/setup#available-libraries
59
60// Your web app's Firebase configuration
61// For Firebase JS SDK v7.20.0 and later, measurementId is optional
62const config = {
63 apiKey: "AIzaSyBk5lf0WtiZPs1ZQkA48OfXpzW7P_RCrZk",
64 authDomain: "test-c2ec9.firebaseapp.com",
65 projectId: "test-c2ec9",
66 storageBucket: "test-c2ec9.appspot.com",
67 messagingSenderId: "11138018851",
68 appId: "1:11138018851:web:ecfb63337ca11f62028b96",
69 measurementId: "G-3S1M3601YR"
70};
71
72// Initialize Firebase
73firebase.initializeApp(config);
74
75// Get a reference to the database service
76var database = firebase.database();
77const app = initializeApp(config);
78const analytics = getAnalytics(app);
79
80ReactDOM.render(
81 <React.StrictMode>
82 </React.StrictMode>,
83 document.getElementById('root')
84);
85
86// If you want to start measuring performance in your app, pass a function
87// to log results (for example: reportWebVitals(console.log))
88// or send to an analytics endpoint.
89//reportWebVitals();<!DOCTYPE html>
90<html>
91 <head>
92 <meta charset="utf-8">
93 <meta name="viewport" content="width=device-width, initial-scale=1">
94 <title>Welcome to Firebase Hosting</title>
95
96 <!-- update the version number as needed -->
97 <script defer src="/__/firebase/8.10.0/firebase-app.js"></script>
98 <!-- include only the Firebase features as you need -->
99 <script defer src="/__/firebase/8.10.0/firebase-auth.js"></script>
100 <script defer src="/__/firebase/8.10.0/firebase-database.js"></script>
101 <script defer src="/__/firebase/8.10.0/firebase-firestore.js"></script>
102 <script defer src="/__/firebase/8.10.0/firebase-functions.js"></script>
103 <script defer src="/__/firebase/8.10.0/firebase-messaging.js"></script>
104 <script defer src="/__/firebase/8.10.0/firebase-storage.js"></script>
105 <script defer src="/__/firebase/8.10.0/firebase-analytics.js"></script>
106 <script defer src="/__/firebase/8.10.0/firebase-remote-config.js"></script>
107 <script defer src="/__/firebase/8.10.0/firebase-performance.js"></script>
108 <!--
109 initialize the SDK after all desired features are loaded, set useEmulator to false
110 to avoid connecting the SDK to running emulators.
111 -->
112 <script defer src="/__/firebase/init.js?useEmulator=true"></script>
113
114 <style media="screen">
115 body { background: #ECEFF1; color: rgba(0,0,0,0.87); font-family: Roboto, Helvetica, Arial, sans-serif; margin: 0; padding: 0; }
116 #message { background: white; max-width: 360px; margin: 100px auto 16px; padding: 32px 24px; border-radius: 3px; }
117 #message h2 { color: #ffa100; font-weight: bold; font-size: 16px; margin: 0 0 8px; }
118 #message h1 { font-size: 22px; font-weight: 300; color: rgba(0,0,0,0.6); margin: 0 0 16px;}
119 #message p { line-height: 140%; margin: 16px 0 24px; font-size: 14px; }
120 #message a { display: block; text-align: center; background: #039be5; text-transform: uppercase; text-decoration: none; color: white; padding: 16px; border-radius: 4px; }
121 #message, #message a { box-shadow: 0 1px 3px rgba(0,0,0,0.12), 0 1px 2px rgba(0,0,0,0.24); }
122 #load { color: rgba(0,0,0,0.4); text-align: center; font-size: 13px; }
123 @media (max-width: 600px) {
124 body, #message { margin-top: 0; background: white; box-shadow: none; }
125 body { border-top: 16px solid #ffa100; }
126 }
127 </style>
128 </head>
129 <body>
130 <div id="message">
131 <h2>Welcome</h2>
132 <h1>Firebase Hosting Setup Complete</h1>
133 <p>You're seeing this because you've successfully setup Firebase Hosting. Now it's time to go build something extraordinary!</p>
134 <a target="_blank" href="https://firebase.google.com/docs/hosting/">Open Hosting Documentation</a>
135 </div>
136 <p id="load">Firebase SDK Loading&hellip;</p>
137
138 <script>
139 document.addEventListener('DOMContentLoaded', function() {
140 const loadEl = document.querySelector('#load');
141 // // π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯
142 // // The Firebase SDK is initialized and available here!
143 //
144 // firebase.auth().onAuthStateChanged(user => { });
145 // firebase.database().ref('/path/to/ref').on('value', snapshot => { });
146 // firebase.firestore().doc('/foo/bar').get().then(() => { });
147 // firebase.functions().httpsCallable('yourFunction')().then(() => { });
148 // firebase.messaging().requestPermission().then(() => { });
149 // firebase.storage().ref('/path/to/ref').getDownloadURL().then(() => { });
150 // firebase.analytics(); // call to activate
151 // firebase.analytics().logEvent('tutorial_completed');
152 // firebase.performance(); // call to activate
153 //
154 // // π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯
155
156 try {
157 let app = firebase.app();
158 let features = [
159 'auth',
160 'database',
161 'firestore',
162 'functions',
163 'messaging',
164 'storage',
165 'analytics',
166 'remoteConfig',
167 'performance',
168 ].filter(feature => typeof app[feature] === 'function');
169 loadEl.textContent = `Firebase SDK loaded with ${features.join(', ')}`;
170 } catch (e) {
171 console.error(e);
172 loadEl.textContent = 'Error loading the Firebase SDK, check the console.';
173 }
174 });
175 </script>
176 <!-- The core Firebase JS SDK is always required and must be listed first -->
177 <script src="/__/firebase/8.10.0/firebase-app.js"></script>
178
179 <!-- TODO: Add SDKs for Firebase products that you want to use
180 https://firebase.google.com/docs/web/setup#available-libraries -->
181 <script src="/__/firebase/8.10.0/firebase-analytics.js"></script>
182 <!-- Initialize Firebase -->
183 <script src="/__/firebase/init.js"></script>
184 </body>
185</html><!DOCTYPE html>
186<html lang="en">
187 <head>
188 <meta charset="utf-8" />
189 <link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
190 <meta name="viewport" content="width=device-width, initial-scale=1" />
191 <meta name="theme-color" content="#000000" />
192 <meta
193 name="description"
194 content="Web site created using create-react-app"
195 />
196 <link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" />
197 <!--
198 manifest.json provides metadata used when your web app is installed on a
199 user's mobile device or desktop. See https://developers.google.com/web/fundamentals/web-app-manifest/
200 -->
201 <link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
202 <!--
203 Notice the use of %PUBLIC_URL% in the tags above.
204 It will be replaced with the URL of the `public` folder during the build.
205 Only files inside the `public` folder can be referenced from the HTML.
206
207 Unlike "/favicon.ico" or "favicon.ico", "%PUBLIC_URL%/favicon.ico" will
208 work correctly both with client-side routing and a non-root public URL.
209 Learn how to configure a non-root public URL by running `npm run build`.
210 -->
211 <title>React App</title>
212 </head>
213 <body>
214 <noscript>You need to enable JavaScript to run this app.</noscript>
215 <div id="root"></div>
216 <!--
217 This HTML file is a template.
218 If you open it directly in the browser, you will see an empty page.
219
220 You can add webfonts, meta tags, or analytics to this file.
221 The build step will place the bundled scripts into the <body> tag.
222
223 To begin the development, run `npm start` or `yarn start`.
224 To create a production bundle, use `npm run build` or `yarn build`.
225 -->
226 <!-- The core Firebase JS SDK is always required and must be listed first -->
227 <script src="/__/firebase/8.10.0/firebase-app.js"></script>
228
229 <!-- TODO: Add SDKs for Firebase products that you want to use
230 https://firebase.google.com/docs/web/setup#available-libraries -->
231 <script src="/__/firebase/8.10.0/firebase-analytics.js"></script>
232 <!-- Initialize Firebase -->
233 <script src="/__/firebase/init.js"></script>
234 </body>
235</html><script src='https://cdn.firebase.com/js/client/8.10.0/firebase.js'></script>
236<script src='https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js'></script>
237<link rel='stylesheet' type='text/css' href='/resources/tutorial/css/example.css'>
238<script src="https://www.gstatic.com/firebasejs/8.10.0/firebase.js"></script>
239<link rel='stylesheet' type='text/css' href='/resources/tutorial/css/example.css'>
240<script src="https://www.gstatic.com/firebasejs/ui/8.10.0/firebase-ui-auth.js"></script>
241<link type="text/css" rel="stylesheet" href="https://www.gstatic.com/firebasejs/ui/5.0.0/firebase-ui-auth.css" />
242<script src="cdn.firebase.com/js/client/8.10.0/firebase.js"></script>
243<script src="cdn.firebase.com/libs/angularfire/0.8.2/ang.."></script>
244<!-- update the version number as needed -->
245<script defer src="/__/firebase/8.10.0/firebase-app.js"></script>
246<!-- include only the Firebase features as you need -->
247<script defer src="/__/firebase/8.10.0/firebase-auth.js"></script>
248<script defer src="/__/firebase/8.10.0/firebase-database.js"></script>
249<script defer src="/__/firebase/8.10.0/firebase-firestore.js"></script>
250<script defer src="/__/firebase/8.10.0/firebase-functions.js"></script>
251<script defer src="/__/firebase/8.10.0/firebase-messaging.js"></script>
252<script defer src="/__/firebase/8.10.0/firebase-storage.js"></script>
253<script defer src="/__/firebase/8.10.0/firebase-analytics.js"></script>
254<script defer src="/__/firebase/8.10.0/firebase-remote-config.js"></script>
255<script defer src="/__/firebase/8.10.0/firebase-performance.js"></script>
256<!--
257 initialize the SDK after all desired features are loaded, set useEmulator to false
258 to avoid connecting the SDK to running emulators.
259-->
260<script defer src="/__/firebase/init.js?useEmulator=true"></script>
261import { initializeApp } from 'firebase/app';
262import { getAuth, onAuthStateChanged } from 'firebase/auth';
263
and
1Failed to compile
2src/index.js
3 Line 25:1: 'firebase' is not defined no-undef
4 Line 28:16: 'firebase' is not defined no-undef
5
6Search for the keywords to learn more about each error.
7This error occurred during the build time and cannot be dismissed.
8{
9 "name": "my-app",
10 "version": "0.1.0",
11 "private": true,
12 "dependencies": {
13 "@material-ui/core": "^4.12.2",
14 "@testing-library/jest-dom": "^5.14.1",
15 "@testing-library/react": "^11.2.7",
16 "@testing-library/user-event": "^12.8.3",
17 "firebase": "^9.0.0",
18 "react": "^17.0.2",
19 "react-dom": "^17.0.2",
20 "react-router-config": "^5.1.1",
21 "react-router-dom": "^5.2.0",
22 "react-scripts": "4.0.3",
23 "web-vitals": "^1.1.2"
24 },
25 "scripts": {
26 "start": "react-scripts start",
27 "build": "react-scripts build",
28 "test": "react-scripts test",
29 "eject": "react-scripts eject"
30 },
31 "eslintConfig": {
32 "extends": [
33 "react-app",
34 "react-app/jest"
35 ]
36 },
37 "browserslist": {
38 "production": [
39 ">0.2%",
40 "not dead",
41 "not op_mini all"
42 ],
43 "development": [
44 "last 1 chrome version",
45 "last 1 firefox version",
46 "last 1 safari version"
47 ]
48 }
49}import React from 'react';
50import ReactDOM from 'react-dom';
51//import './index.css';
52//import App from './App';
53//import reportWebVitals from './reportWebVitals';
54// Import the functions you need from the SDKs you need
55import { initializeApp } from "firebase/app";
56import { getAnalytics } from "firebase/analytics";
57// TODO: Add SDKs for Firebase products that you want to use
58// https://firebase.google.com/docs/web/setup#available-libraries
59
60// Your web app's Firebase configuration
61// For Firebase JS SDK v7.20.0 and later, measurementId is optional
62const config = {
63 apiKey: "AIzaSyBk5lf0WtiZPs1ZQkA48OfXpzW7P_RCrZk",
64 authDomain: "test-c2ec9.firebaseapp.com",
65 projectId: "test-c2ec9",
66 storageBucket: "test-c2ec9.appspot.com",
67 messagingSenderId: "11138018851",
68 appId: "1:11138018851:web:ecfb63337ca11f62028b96",
69 measurementId: "G-3S1M3601YR"
70};
71
72// Initialize Firebase
73firebase.initializeApp(config);
74
75// Get a reference to the database service
76var database = firebase.database();
77const app = initializeApp(config);
78const analytics = getAnalytics(app);
79
80ReactDOM.render(
81 <React.StrictMode>
82 </React.StrictMode>,
83 document.getElementById('root')
84);
85
86// If you want to start measuring performance in your app, pass a function
87// to log results (for example: reportWebVitals(console.log))
88// or send to an analytics endpoint.
89//reportWebVitals();<!DOCTYPE html>
90<html>
91 <head>
92 <meta charset="utf-8">
93 <meta name="viewport" content="width=device-width, initial-scale=1">
94 <title>Welcome to Firebase Hosting</title>
95
96 <!-- update the version number as needed -->
97 <script defer src="/__/firebase/8.10.0/firebase-app.js"></script>
98 <!-- include only the Firebase features as you need -->
99 <script defer src="/__/firebase/8.10.0/firebase-auth.js"></script>
100 <script defer src="/__/firebase/8.10.0/firebase-database.js"></script>
101 <script defer src="/__/firebase/8.10.0/firebase-firestore.js"></script>
102 <script defer src="/__/firebase/8.10.0/firebase-functions.js"></script>
103 <script defer src="/__/firebase/8.10.0/firebase-messaging.js"></script>
104 <script defer src="/__/firebase/8.10.0/firebase-storage.js"></script>
105 <script defer src="/__/firebase/8.10.0/firebase-analytics.js"></script>
106 <script defer src="/__/firebase/8.10.0/firebase-remote-config.js"></script>
107 <script defer src="/__/firebase/8.10.0/firebase-performance.js"></script>
108 <!--
109 initialize the SDK after all desired features are loaded, set useEmulator to false
110 to avoid connecting the SDK to running emulators.
111 -->
112 <script defer src="/__/firebase/init.js?useEmulator=true"></script>
113
114 <style media="screen">
115 body { background: #ECEFF1; color: rgba(0,0,0,0.87); font-family: Roboto, Helvetica, Arial, sans-serif; margin: 0; padding: 0; }
116 #message { background: white; max-width: 360px; margin: 100px auto 16px; padding: 32px 24px; border-radius: 3px; }
117 #message h2 { color: #ffa100; font-weight: bold; font-size: 16px; margin: 0 0 8px; }
118 #message h1 { font-size: 22px; font-weight: 300; color: rgba(0,0,0,0.6); margin: 0 0 16px;}
119 #message p { line-height: 140%; margin: 16px 0 24px; font-size: 14px; }
120 #message a { display: block; text-align: center; background: #039be5; text-transform: uppercase; text-decoration: none; color: white; padding: 16px; border-radius: 4px; }
121 #message, #message a { box-shadow: 0 1px 3px rgba(0,0,0,0.12), 0 1px 2px rgba(0,0,0,0.24); }
122 #load { color: rgba(0,0,0,0.4); text-align: center; font-size: 13px; }
123 @media (max-width: 600px) {
124 body, #message { margin-top: 0; background: white; box-shadow: none; }
125 body { border-top: 16px solid #ffa100; }
126 }
127 </style>
128 </head>
129 <body>
130 <div id="message">
131 <h2>Welcome</h2>
132 <h1>Firebase Hosting Setup Complete</h1>
133 <p>You're seeing this because you've successfully setup Firebase Hosting. Now it's time to go build something extraordinary!</p>
134 <a target="_blank" href="https://firebase.google.com/docs/hosting/">Open Hosting Documentation</a>
135 </div>
136 <p id="load">Firebase SDK Loading&hellip;</p>
137
138 <script>
139 document.addEventListener('DOMContentLoaded', function() {
140 const loadEl = document.querySelector('#load');
141 // // π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯
142 // // The Firebase SDK is initialized and available here!
143 //
144 // firebase.auth().onAuthStateChanged(user => { });
145 // firebase.database().ref('/path/to/ref').on('value', snapshot => { });
146 // firebase.firestore().doc('/foo/bar').get().then(() => { });
147 // firebase.functions().httpsCallable('yourFunction')().then(() => { });
148 // firebase.messaging().requestPermission().then(() => { });
149 // firebase.storage().ref('/path/to/ref').getDownloadURL().then(() => { });
150 // firebase.analytics(); // call to activate
151 // firebase.analytics().logEvent('tutorial_completed');
152 // firebase.performance(); // call to activate
153 //
154 // // π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯
155
156 try {
157 let app = firebase.app();
158 let features = [
159 'auth',
160 'database',
161 'firestore',
162 'functions',
163 'messaging',
164 'storage',
165 'analytics',
166 'remoteConfig',
167 'performance',
168 ].filter(feature => typeof app[feature] === 'function');
169 loadEl.textContent = `Firebase SDK loaded with ${features.join(', ')}`;
170 } catch (e) {
171 console.error(e);
172 loadEl.textContent = 'Error loading the Firebase SDK, check the console.';
173 }
174 });
175 </script>
176 <!-- The core Firebase JS SDK is always required and must be listed first -->
177 <script src="/__/firebase/8.10.0/firebase-app.js"></script>
178
179 <!-- TODO: Add SDKs for Firebase products that you want to use
180 https://firebase.google.com/docs/web/setup#available-libraries -->
181 <script src="/__/firebase/8.10.0/firebase-analytics.js"></script>
182 <!-- Initialize Firebase -->
183 <script src="/__/firebase/init.js"></script>
184 </body>
185</html><!DOCTYPE html>
186<html lang="en">
187 <head>
188 <meta charset="utf-8" />
189 <link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
190 <meta name="viewport" content="width=device-width, initial-scale=1" />
191 <meta name="theme-color" content="#000000" />
192 <meta
193 name="description"
194 content="Web site created using create-react-app"
195 />
196 <link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" />
197 <!--
198 manifest.json provides metadata used when your web app is installed on a
199 user's mobile device or desktop. See https://developers.google.com/web/fundamentals/web-app-manifest/
200 -->
201 <link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
202 <!--
203 Notice the use of %PUBLIC_URL% in the tags above.
204 It will be replaced with the URL of the `public` folder during the build.
205 Only files inside the `public` folder can be referenced from the HTML.
206
207 Unlike "/favicon.ico" or "favicon.ico", "%PUBLIC_URL%/favicon.ico" will
208 work correctly both with client-side routing and a non-root public URL.
209 Learn how to configure a non-root public URL by running `npm run build`.
210 -->
211 <title>React App</title>
212 </head>
213 <body>
214 <noscript>You need to enable JavaScript to run this app.</noscript>
215 <div id="root"></div>
216 <!--
217 This HTML file is a template.
218 If you open it directly in the browser, you will see an empty page.
219
220 You can add webfonts, meta tags, or analytics to this file.
221 The build step will place the bundled scripts into the <body> tag.
222
223 To begin the development, run `npm start` or `yarn start`.
224 To create a production bundle, use `npm run build` or `yarn build`.
225 -->
226 <!-- The core Firebase JS SDK is always required and must be listed first -->
227 <script src="/__/firebase/8.10.0/firebase-app.js"></script>
228
229 <!-- TODO: Add SDKs for Firebase products that you want to use
230 https://firebase.google.com/docs/web/setup#available-libraries -->
231 <script src="/__/firebase/8.10.0/firebase-analytics.js"></script>
232 <!-- Initialize Firebase -->
233 <script src="/__/firebase/init.js"></script>
234 </body>
235</html><script src='https://cdn.firebase.com/js/client/8.10.0/firebase.js'></script>
236<script src='https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js'></script>
237<link rel='stylesheet' type='text/css' href='/resources/tutorial/css/example.css'>
238<script src="https://www.gstatic.com/firebasejs/8.10.0/firebase.js"></script>
239<link rel='stylesheet' type='text/css' href='/resources/tutorial/css/example.css'>
240<script src="https://www.gstatic.com/firebasejs/ui/8.10.0/firebase-ui-auth.js"></script>
241<link type="text/css" rel="stylesheet" href="https://www.gstatic.com/firebasejs/ui/5.0.0/firebase-ui-auth.css" />
242<script src="cdn.firebase.com/js/client/8.10.0/firebase.js"></script>
243<script src="cdn.firebase.com/libs/angularfire/0.8.2/ang.."></script>
244<!-- update the version number as needed -->
245<script defer src="/__/firebase/8.10.0/firebase-app.js"></script>
246<!-- include only the Firebase features as you need -->
247<script defer src="/__/firebase/8.10.0/firebase-auth.js"></script>
248<script defer src="/__/firebase/8.10.0/firebase-database.js"></script>
249<script defer src="/__/firebase/8.10.0/firebase-firestore.js"></script>
250<script defer src="/__/firebase/8.10.0/firebase-functions.js"></script>
251<script defer src="/__/firebase/8.10.0/firebase-messaging.js"></script>
252<script defer src="/__/firebase/8.10.0/firebase-storage.js"></script>
253<script defer src="/__/firebase/8.10.0/firebase-analytics.js"></script>
254<script defer src="/__/firebase/8.10.0/firebase-remote-config.js"></script>
255<script defer src="/__/firebase/8.10.0/firebase-performance.js"></script>
256<!--
257 initialize the SDK after all desired features are loaded, set useEmulator to false
258 to avoid connecting the SDK to running emulators.
259-->
260<script defer src="/__/firebase/init.js?useEmulator=true"></script>
261import { initializeApp } from 'firebase/app';
262import { getAuth, onAuthStateChanged } from 'firebase/auth';
263const firebaseApp = initializeApp({ /* config */ });
264const auth = getAuth();
265onAuthStateChanged(auth, user => { console.log(user); });
266
instead of
1Failed to compile
2src/index.js
3 Line 25:1: 'firebase' is not defined no-undef
4 Line 28:16: 'firebase' is not defined no-undef
5
6Search for the keywords to learn more about each error.
7This error occurred during the build time and cannot be dismissed.
8{
9 "name": "my-app",
10 "version": "0.1.0",
11 "private": true,
12 "dependencies": {
13 "@material-ui/core": "^4.12.2",
14 "@testing-library/jest-dom": "^5.14.1",
15 "@testing-library/react": "^11.2.7",
16 "@testing-library/user-event": "^12.8.3",
17 "firebase": "^9.0.0",
18 "react": "^17.0.2",
19 "react-dom": "^17.0.2",
20 "react-router-config": "^5.1.1",
21 "react-router-dom": "^5.2.0",
22 "react-scripts": "4.0.3",
23 "web-vitals": "^1.1.2"
24 },
25 "scripts": {
26 "start": "react-scripts start",
27 "build": "react-scripts build",
28 "test": "react-scripts test",
29 "eject": "react-scripts eject"
30 },
31 "eslintConfig": {
32 "extends": [
33 "react-app",
34 "react-app/jest"
35 ]
36 },
37 "browserslist": {
38 "production": [
39 ">0.2%",
40 "not dead",
41 "not op_mini all"
42 ],
43 "development": [
44 "last 1 chrome version",
45 "last 1 firefox version",
46 "last 1 safari version"
47 ]
48 }
49}import React from 'react';
50import ReactDOM from 'react-dom';
51//import './index.css';
52//import App from './App';
53//import reportWebVitals from './reportWebVitals';
54// Import the functions you need from the SDKs you need
55import { initializeApp } from "firebase/app";
56import { getAnalytics } from "firebase/analytics";
57// TODO: Add SDKs for Firebase products that you want to use
58// https://firebase.google.com/docs/web/setup#available-libraries
59
60// Your web app's Firebase configuration
61// For Firebase JS SDK v7.20.0 and later, measurementId is optional
62const config = {
63 apiKey: "AIzaSyBk5lf0WtiZPs1ZQkA48OfXpzW7P_RCrZk",
64 authDomain: "test-c2ec9.firebaseapp.com",
65 projectId: "test-c2ec9",
66 storageBucket: "test-c2ec9.appspot.com",
67 messagingSenderId: "11138018851",
68 appId: "1:11138018851:web:ecfb63337ca11f62028b96",
69 measurementId: "G-3S1M3601YR"
70};
71
72// Initialize Firebase
73firebase.initializeApp(config);
74
75// Get a reference to the database service
76var database = firebase.database();
77const app = initializeApp(config);
78const analytics = getAnalytics(app);
79
80ReactDOM.render(
81 <React.StrictMode>
82 </React.StrictMode>,
83 document.getElementById('root')
84);
85
86// If you want to start measuring performance in your app, pass a function
87// to log results (for example: reportWebVitals(console.log))
88// or send to an analytics endpoint.
89//reportWebVitals();<!DOCTYPE html>
90<html>
91 <head>
92 <meta charset="utf-8">
93 <meta name="viewport" content="width=device-width, initial-scale=1">
94 <title>Welcome to Firebase Hosting</title>
95
96 <!-- update the version number as needed -->
97 <script defer src="/__/firebase/8.10.0/firebase-app.js"></script>
98 <!-- include only the Firebase features as you need -->
99 <script defer src="/__/firebase/8.10.0/firebase-auth.js"></script>
100 <script defer src="/__/firebase/8.10.0/firebase-database.js"></script>
101 <script defer src="/__/firebase/8.10.0/firebase-firestore.js"></script>
102 <script defer src="/__/firebase/8.10.0/firebase-functions.js"></script>
103 <script defer src="/__/firebase/8.10.0/firebase-messaging.js"></script>
104 <script defer src="/__/firebase/8.10.0/firebase-storage.js"></script>
105 <script defer src="/__/firebase/8.10.0/firebase-analytics.js"></script>
106 <script defer src="/__/firebase/8.10.0/firebase-remote-config.js"></script>
107 <script defer src="/__/firebase/8.10.0/firebase-performance.js"></script>
108 <!--
109 initialize the SDK after all desired features are loaded, set useEmulator to false
110 to avoid connecting the SDK to running emulators.
111 -->
112 <script defer src="/__/firebase/init.js?useEmulator=true"></script>
113
114 <style media="screen">
115 body { background: #ECEFF1; color: rgba(0,0,0,0.87); font-family: Roboto, Helvetica, Arial, sans-serif; margin: 0; padding: 0; }
116 #message { background: white; max-width: 360px; margin: 100px auto 16px; padding: 32px 24px; border-radius: 3px; }
117 #message h2 { color: #ffa100; font-weight: bold; font-size: 16px; margin: 0 0 8px; }
118 #message h1 { font-size: 22px; font-weight: 300; color: rgba(0,0,0,0.6); margin: 0 0 16px;}
119 #message p { line-height: 140%; margin: 16px 0 24px; font-size: 14px; }
120 #message a { display: block; text-align: center; background: #039be5; text-transform: uppercase; text-decoration: none; color: white; padding: 16px; border-radius: 4px; }
121 #message, #message a { box-shadow: 0 1px 3px rgba(0,0,0,0.12), 0 1px 2px rgba(0,0,0,0.24); }
122 #load { color: rgba(0,0,0,0.4); text-align: center; font-size: 13px; }
123 @media (max-width: 600px) {
124 body, #message { margin-top: 0; background: white; box-shadow: none; }
125 body { border-top: 16px solid #ffa100; }
126 }
127 </style>
128 </head>
129 <body>
130 <div id="message">
131 <h2>Welcome</h2>
132 <h1>Firebase Hosting Setup Complete</h1>
133 <p>You're seeing this because you've successfully setup Firebase Hosting. Now it's time to go build something extraordinary!</p>
134 <a target="_blank" href="https://firebase.google.com/docs/hosting/">Open Hosting Documentation</a>
135 </div>
136 <p id="load">Firebase SDK Loading&hellip;</p>
137
138 <script>
139 document.addEventListener('DOMContentLoaded', function() {
140 const loadEl = document.querySelector('#load');
141 // // π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯
142 // // The Firebase SDK is initialized and available here!
143 //
144 // firebase.auth().onAuthStateChanged(user => { });
145 // firebase.database().ref('/path/to/ref').on('value', snapshot => { });
146 // firebase.firestore().doc('/foo/bar').get().then(() => { });
147 // firebase.functions().httpsCallable('yourFunction')().then(() => { });
148 // firebase.messaging().requestPermission().then(() => { });
149 // firebase.storage().ref('/path/to/ref').getDownloadURL().then(() => { });
150 // firebase.analytics(); // call to activate
151 // firebase.analytics().logEvent('tutorial_completed');
152 // firebase.performance(); // call to activate
153 //
154 // // π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯
155
156 try {
157 let app = firebase.app();
158 let features = [
159 'auth',
160 'database',
161 'firestore',
162 'functions',
163 'messaging',
164 'storage',
165 'analytics',
166 'remoteConfig',
167 'performance',
168 ].filter(feature => typeof app[feature] === 'function');
169 loadEl.textContent = `Firebase SDK loaded with ${features.join(', ')}`;
170 } catch (e) {
171 console.error(e);
172 loadEl.textContent = 'Error loading the Firebase SDK, check the console.';
173 }
174 });
175 </script>
176 <!-- The core Firebase JS SDK is always required and must be listed first -->
177 <script src="/__/firebase/8.10.0/firebase-app.js"></script>
178
179 <!-- TODO: Add SDKs for Firebase products that you want to use
180 https://firebase.google.com/docs/web/setup#available-libraries -->
181 <script src="/__/firebase/8.10.0/firebase-analytics.js"></script>
182 <!-- Initialize Firebase -->
183 <script src="/__/firebase/init.js"></script>
184 </body>
185</html><!DOCTYPE html>
186<html lang="en">
187 <head>
188 <meta charset="utf-8" />
189 <link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
190 <meta name="viewport" content="width=device-width, initial-scale=1" />
191 <meta name="theme-color" content="#000000" />
192 <meta
193 name="description"
194 content="Web site created using create-react-app"
195 />
196 <link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" />
197 <!--
198 manifest.json provides metadata used when your web app is installed on a
199 user's mobile device or desktop. See https://developers.google.com/web/fundamentals/web-app-manifest/
200 -->
201 <link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
202 <!--
203 Notice the use of %PUBLIC_URL% in the tags above.
204 It will be replaced with the URL of the `public` folder during the build.
205 Only files inside the `public` folder can be referenced from the HTML.
206
207 Unlike "/favicon.ico" or "favicon.ico", "%PUBLIC_URL%/favicon.ico" will
208 work correctly both with client-side routing and a non-root public URL.
209 Learn how to configure a non-root public URL by running `npm run build`.
210 -->
211 <title>React App</title>
212 </head>
213 <body>
214 <noscript>You need to enable JavaScript to run this app.</noscript>
215 <div id="root"></div>
216 <!--
217 This HTML file is a template.
218 If you open it directly in the browser, you will see an empty page.
219
220 You can add webfonts, meta tags, or analytics to this file.
221 The build step will place the bundled scripts into the <body> tag.
222
223 To begin the development, run `npm start` or `yarn start`.
224 To create a production bundle, use `npm run build` or `yarn build`.
225 -->
226 <!-- The core Firebase JS SDK is always required and must be listed first -->
227 <script src="/__/firebase/8.10.0/firebase-app.js"></script>
228
229 <!-- TODO: Add SDKs for Firebase products that you want to use
230 https://firebase.google.com/docs/web/setup#available-libraries -->
231 <script src="/__/firebase/8.10.0/firebase-analytics.js"></script>
232 <!-- Initialize Firebase -->
233 <script src="/__/firebase/init.js"></script>
234 </body>
235</html><script src='https://cdn.firebase.com/js/client/8.10.0/firebase.js'></script>
236<script src='https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js'></script>
237<link rel='stylesheet' type='text/css' href='/resources/tutorial/css/example.css'>
238<script src="https://www.gstatic.com/firebasejs/8.10.0/firebase.js"></script>
239<link rel='stylesheet' type='text/css' href='/resources/tutorial/css/example.css'>
240<script src="https://www.gstatic.com/firebasejs/ui/8.10.0/firebase-ui-auth.js"></script>
241<link type="text/css" rel="stylesheet" href="https://www.gstatic.com/firebasejs/ui/5.0.0/firebase-ui-auth.css" />
242<script src="cdn.firebase.com/js/client/8.10.0/firebase.js"></script>
243<script src="cdn.firebase.com/libs/angularfire/0.8.2/ang.."></script>
244<!-- update the version number as needed -->
245<script defer src="/__/firebase/8.10.0/firebase-app.js"></script>
246<!-- include only the Firebase features as you need -->
247<script defer src="/__/firebase/8.10.0/firebase-auth.js"></script>
248<script defer src="/__/firebase/8.10.0/firebase-database.js"></script>
249<script defer src="/__/firebase/8.10.0/firebase-firestore.js"></script>
250<script defer src="/__/firebase/8.10.0/firebase-functions.js"></script>
251<script defer src="/__/firebase/8.10.0/firebase-messaging.js"></script>
252<script defer src="/__/firebase/8.10.0/firebase-storage.js"></script>
253<script defer src="/__/firebase/8.10.0/firebase-analytics.js"></script>
254<script defer src="/__/firebase/8.10.0/firebase-remote-config.js"></script>
255<script defer src="/__/firebase/8.10.0/firebase-performance.js"></script>
256<!--
257 initialize the SDK after all desired features are loaded, set useEmulator to false
258 to avoid connecting the SDK to running emulators.
259-->
260<script defer src="/__/firebase/init.js?useEmulator=true"></script>
261import { initializeApp } from 'firebase/app';
262import { getAuth, onAuthStateChanged } from 'firebase/auth';
263const firebaseApp = initializeApp({ /* config */ });
264const auth = getAuth();
265onAuthStateChanged(auth, user => { console.log(user); });
266import firebase from 'firebase/app';
267import 'firebase/auth';
268
and
1Failed to compile
2src/index.js
3 Line 25:1: 'firebase' is not defined no-undef
4 Line 28:16: 'firebase' is not defined no-undef
5
6Search for the keywords to learn more about each error.
7This error occurred during the build time and cannot be dismissed.
8{
9 "name": "my-app",
10 "version": "0.1.0",
11 "private": true,
12 "dependencies": {
13 "@material-ui/core": "^4.12.2",
14 "@testing-library/jest-dom": "^5.14.1",
15 "@testing-library/react": "^11.2.7",
16 "@testing-library/user-event": "^12.8.3",
17 "firebase": "^9.0.0",
18 "react": "^17.0.2",
19 "react-dom": "^17.0.2",
20 "react-router-config": "^5.1.1",
21 "react-router-dom": "^5.2.0",
22 "react-scripts": "4.0.3",
23 "web-vitals": "^1.1.2"
24 },
25 "scripts": {
26 "start": "react-scripts start",
27 "build": "react-scripts build",
28 "test": "react-scripts test",
29 "eject": "react-scripts eject"
30 },
31 "eslintConfig": {
32 "extends": [
33 "react-app",
34 "react-app/jest"
35 ]
36 },
37 "browserslist": {
38 "production": [
39 ">0.2%",
40 "not dead",
41 "not op_mini all"
42 ],
43 "development": [
44 "last 1 chrome version",
45 "last 1 firefox version",
46 "last 1 safari version"
47 ]
48 }
49}import React from 'react';
50import ReactDOM from 'react-dom';
51//import './index.css';
52//import App from './App';
53//import reportWebVitals from './reportWebVitals';
54// Import the functions you need from the SDKs you need
55import { initializeApp } from "firebase/app";
56import { getAnalytics } from "firebase/analytics";
57// TODO: Add SDKs for Firebase products that you want to use
58// https://firebase.google.com/docs/web/setup#available-libraries
59
60// Your web app's Firebase configuration
61// For Firebase JS SDK v7.20.0 and later, measurementId is optional
62const config = {
63 apiKey: "AIzaSyBk5lf0WtiZPs1ZQkA48OfXpzW7P_RCrZk",
64 authDomain: "test-c2ec9.firebaseapp.com",
65 projectId: "test-c2ec9",
66 storageBucket: "test-c2ec9.appspot.com",
67 messagingSenderId: "11138018851",
68 appId: "1:11138018851:web:ecfb63337ca11f62028b96",
69 measurementId: "G-3S1M3601YR"
70};
71
72// Initialize Firebase
73firebase.initializeApp(config);
74
75// Get a reference to the database service
76var database = firebase.database();
77const app = initializeApp(config);
78const analytics = getAnalytics(app);
79
80ReactDOM.render(
81 <React.StrictMode>
82 </React.StrictMode>,
83 document.getElementById('root')
84);
85
86// If you want to start measuring performance in your app, pass a function
87// to log results (for example: reportWebVitals(console.log))
88// or send to an analytics endpoint.
89//reportWebVitals();<!DOCTYPE html>
90<html>
91 <head>
92 <meta charset="utf-8">
93 <meta name="viewport" content="width=device-width, initial-scale=1">
94 <title>Welcome to Firebase Hosting</title>
95
96 <!-- update the version number as needed -->
97 <script defer src="/__/firebase/8.10.0/firebase-app.js"></script>
98 <!-- include only the Firebase features as you need -->
99 <script defer src="/__/firebase/8.10.0/firebase-auth.js"></script>
100 <script defer src="/__/firebase/8.10.0/firebase-database.js"></script>
101 <script defer src="/__/firebase/8.10.0/firebase-firestore.js"></script>
102 <script defer src="/__/firebase/8.10.0/firebase-functions.js"></script>
103 <script defer src="/__/firebase/8.10.0/firebase-messaging.js"></script>
104 <script defer src="/__/firebase/8.10.0/firebase-storage.js"></script>
105 <script defer src="/__/firebase/8.10.0/firebase-analytics.js"></script>
106 <script defer src="/__/firebase/8.10.0/firebase-remote-config.js"></script>
107 <script defer src="/__/firebase/8.10.0/firebase-performance.js"></script>
108 <!--
109 initialize the SDK after all desired features are loaded, set useEmulator to false
110 to avoid connecting the SDK to running emulators.
111 -->
112 <script defer src="/__/firebase/init.js?useEmulator=true"></script>
113
114 <style media="screen">
115 body { background: #ECEFF1; color: rgba(0,0,0,0.87); font-family: Roboto, Helvetica, Arial, sans-serif; margin: 0; padding: 0; }
116 #message { background: white; max-width: 360px; margin: 100px auto 16px; padding: 32px 24px; border-radius: 3px; }
117 #message h2 { color: #ffa100; font-weight: bold; font-size: 16px; margin: 0 0 8px; }
118 #message h1 { font-size: 22px; font-weight: 300; color: rgba(0,0,0,0.6); margin: 0 0 16px;}
119 #message p { line-height: 140%; margin: 16px 0 24px; font-size: 14px; }
120 #message a { display: block; text-align: center; background: #039be5; text-transform: uppercase; text-decoration: none; color: white; padding: 16px; border-radius: 4px; }
121 #message, #message a { box-shadow: 0 1px 3px rgba(0,0,0,0.12), 0 1px 2px rgba(0,0,0,0.24); }
122 #load { color: rgba(0,0,0,0.4); text-align: center; font-size: 13px; }
123 @media (max-width: 600px) {
124 body, #message { margin-top: 0; background: white; box-shadow: none; }
125 body { border-top: 16px solid #ffa100; }
126 }
127 </style>
128 </head>
129 <body>
130 <div id="message">
131 <h2>Welcome</h2>
132 <h1>Firebase Hosting Setup Complete</h1>
133 <p>You're seeing this because you've successfully setup Firebase Hosting. Now it's time to go build something extraordinary!</p>
134 <a target="_blank" href="https://firebase.google.com/docs/hosting/">Open Hosting Documentation</a>
135 </div>
136 <p id="load">Firebase SDK Loading&hellip;</p>
137
138 <script>
139 document.addEventListener('DOMContentLoaded', function() {
140 const loadEl = document.querySelector('#load');
141 // // π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯
142 // // The Firebase SDK is initialized and available here!
143 //
144 // firebase.auth().onAuthStateChanged(user => { });
145 // firebase.database().ref('/path/to/ref').on('value', snapshot => { });
146 // firebase.firestore().doc('/foo/bar').get().then(() => { });
147 // firebase.functions().httpsCallable('yourFunction')().then(() => { });
148 // firebase.messaging().requestPermission().then(() => { });
149 // firebase.storage().ref('/path/to/ref').getDownloadURL().then(() => { });
150 // firebase.analytics(); // call to activate
151 // firebase.analytics().logEvent('tutorial_completed');
152 // firebase.performance(); // call to activate
153 //
154 // // π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯
155
156 try {
157 let app = firebase.app();
158 let features = [
159 'auth',
160 'database',
161 'firestore',
162 'functions',
163 'messaging',
164 'storage',
165 'analytics',
166 'remoteConfig',
167 'performance',
168 ].filter(feature => typeof app[feature] === 'function');
169 loadEl.textContent = `Firebase SDK loaded with ${features.join(', ')}`;
170 } catch (e) {
171 console.error(e);
172 loadEl.textContent = 'Error loading the Firebase SDK, check the console.';
173 }
174 });
175 </script>
176 <!-- The core Firebase JS SDK is always required and must be listed first -->
177 <script src="/__/firebase/8.10.0/firebase-app.js"></script>
178
179 <!-- TODO: Add SDKs for Firebase products that you want to use
180 https://firebase.google.com/docs/web/setup#available-libraries -->
181 <script src="/__/firebase/8.10.0/firebase-analytics.js"></script>
182 <!-- Initialize Firebase -->
183 <script src="/__/firebase/init.js"></script>
184 </body>
185</html><!DOCTYPE html>
186<html lang="en">
187 <head>
188 <meta charset="utf-8" />
189 <link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
190 <meta name="viewport" content="width=device-width, initial-scale=1" />
191 <meta name="theme-color" content="#000000" />
192 <meta
193 name="description"
194 content="Web site created using create-react-app"
195 />
196 <link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" />
197 <!--
198 manifest.json provides metadata used when your web app is installed on a
199 user's mobile device or desktop. See https://developers.google.com/web/fundamentals/web-app-manifest/
200 -->
201 <link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
202 <!--
203 Notice the use of %PUBLIC_URL% in the tags above.
204 It will be replaced with the URL of the `public` folder during the build.
205 Only files inside the `public` folder can be referenced from the HTML.
206
207 Unlike "/favicon.ico" or "favicon.ico", "%PUBLIC_URL%/favicon.ico" will
208 work correctly both with client-side routing and a non-root public URL.
209 Learn how to configure a non-root public URL by running `npm run build`.
210 -->
211 <title>React App</title>
212 </head>
213 <body>
214 <noscript>You need to enable JavaScript to run this app.</noscript>
215 <div id="root"></div>
216 <!--
217 This HTML file is a template.
218 If you open it directly in the browser, you will see an empty page.
219
220 You can add webfonts, meta tags, or analytics to this file.
221 The build step will place the bundled scripts into the <body> tag.
222
223 To begin the development, run `npm start` or `yarn start`.
224 To create a production bundle, use `npm run build` or `yarn build`.
225 -->
226 <!-- The core Firebase JS SDK is always required and must be listed first -->
227 <script src="/__/firebase/8.10.0/firebase-app.js"></script>
228
229 <!-- TODO: Add SDKs for Firebase products that you want to use
230 https://firebase.google.com/docs/web/setup#available-libraries -->
231 <script src="/__/firebase/8.10.0/firebase-analytics.js"></script>
232 <!-- Initialize Firebase -->
233 <script src="/__/firebase/init.js"></script>
234 </body>
235</html><script src='https://cdn.firebase.com/js/client/8.10.0/firebase.js'></script>
236<script src='https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js'></script>
237<link rel='stylesheet' type='text/css' href='/resources/tutorial/css/example.css'>
238<script src="https://www.gstatic.com/firebasejs/8.10.0/firebase.js"></script>
239<link rel='stylesheet' type='text/css' href='/resources/tutorial/css/example.css'>
240<script src="https://www.gstatic.com/firebasejs/ui/8.10.0/firebase-ui-auth.js"></script>
241<link type="text/css" rel="stylesheet" href="https://www.gstatic.com/firebasejs/ui/5.0.0/firebase-ui-auth.css" />
242<script src="cdn.firebase.com/js/client/8.10.0/firebase.js"></script>
243<script src="cdn.firebase.com/libs/angularfire/0.8.2/ang.."></script>
244<!-- update the version number as needed -->
245<script defer src="/__/firebase/8.10.0/firebase-app.js"></script>
246<!-- include only the Firebase features as you need -->
247<script defer src="/__/firebase/8.10.0/firebase-auth.js"></script>
248<script defer src="/__/firebase/8.10.0/firebase-database.js"></script>
249<script defer src="/__/firebase/8.10.0/firebase-firestore.js"></script>
250<script defer src="/__/firebase/8.10.0/firebase-functions.js"></script>
251<script defer src="/__/firebase/8.10.0/firebase-messaging.js"></script>
252<script defer src="/__/firebase/8.10.0/firebase-storage.js"></script>
253<script defer src="/__/firebase/8.10.0/firebase-analytics.js"></script>
254<script defer src="/__/firebase/8.10.0/firebase-remote-config.js"></script>
255<script defer src="/__/firebase/8.10.0/firebase-performance.js"></script>
256<!--
257 initialize the SDK after all desired features are loaded, set useEmulator to false
258 to avoid connecting the SDK to running emulators.
259-->
260<script defer src="/__/firebase/init.js?useEmulator=true"></script>
261import { initializeApp } from 'firebase/app';
262import { getAuth, onAuthStateChanged } from 'firebase/auth';
263const firebaseApp = initializeApp({ /* config */ });
264const auth = getAuth();
265onAuthStateChanged(auth, user => { console.log(user); });
266import firebase from 'firebase/app';
267import 'firebase/auth';
268const firebaseApp = firebase.initializeApp({ /* config */ });
269const auth = firebaseApp.auth();
270auth.onAuthStateChanged(user => { console.log(user); });
271
Refer to this link for further reference: https://firebase.google.com/docs/web/modular-upgrade
QUESTION
Array of structs only takes last value in C
Asked 2021-Nov-05 at 19:41I'm trying to make a simple command line interface, but i'm having a probleme for parsing commands :
process_t is a structure contient the path of the command with arguments to be stored in the variable argv.
1int parse_cmd(char* tokens[], process_t* commands) {
2 assert(tokens!=NULL);
3 assert(commands!=NULL);
4
5 int position = 0;
6 int commandNumber = 0;
7
8 for(int i=0; tokens[i] != NULL; i++){
9 if(is_reserved(tokens[i]) == 0 && tokens[i+1] != NULL) continue;
10 int end = is_reserved(tokens[i]) == 0 ? i+1 : i;
11 int argc = position;
12 int count = 0;
13
14 process_t newProcess;
15
16 char* argv[MAX_CMD_SIZE] = {NULL};
17 for(argc; argc < end; argc++) {
18 argv[count] = tokens[argc];
19 count = count + 1;
20 }
21 newProcess.path = tokens[position];
22 newProcess.argv = argv;
23 position = i + 1;
24 commands[commandNumber] = newProcess;
25 commandNumber = commandNumber + 1;
26 }
27}
28
29int main(int argc, char* argv[]) {
30
31 char path[MAX_LINE_SIZE];
32 char line[MAX_LINE_SIZE];
33 char* cmdline[MAX_CMD_SIZE];
34 process_t cmds[MAX_CMD_SIZE];
35
36 getcwd(path, MAX_LINE_SIZE);
37 while (1) {
38
39 printf("mini@shell:%s$ ", path);
40 scanf("%[^\n]%*c", line);
41
42 trim(line);
43 clean(line);
44 tokenize(line, cmdline);
45
46 parse_cmd(cmdline, cmds);
47 toString(cmds);
48
49 break;.
50 }
51 return -1;
52}
53
Input: ls -l ; grep ^a
Why the array contain only the value of argv of the last iteration ?
Output :
path : ls => argv = {grep, ^a, (null)} path : grep => argv = {grep, ^a, (null)}
ANSWER
Answered 2021-Nov-05 at 11:12You're trying to use the block-local array argv
, which is recreated for every command and, what's worse, doesn't even exist any longer after parse_cmd
has returned. An array object with sufficient lifetime has to be used; you can do this by changing
1int parse_cmd(char* tokens[], process_t* commands) {
2 assert(tokens!=NULL);
3 assert(commands!=NULL);
4
5 int position = 0;
6 int commandNumber = 0;
7
8 for(int i=0; tokens[i] != NULL; i++){
9 if(is_reserved(tokens[i]) == 0 && tokens[i+1] != NULL) continue;
10 int end = is_reserved(tokens[i]) == 0 ? i+1 : i;
11 int argc = position;
12 int count = 0;
13
14 process_t newProcess;
15
16 char* argv[MAX_CMD_SIZE] = {NULL};
17 for(argc; argc < end; argc++) {
18 argv[count] = tokens[argc];
19 count = count + 1;
20 }
21 newProcess.path = tokens[position];
22 newProcess.argv = argv;
23 position = i + 1;
24 commands[commandNumber] = newProcess;
25 commandNumber = commandNumber + 1;
26 }
27}
28
29int main(int argc, char* argv[]) {
30
31 char path[MAX_LINE_SIZE];
32 char line[MAX_LINE_SIZE];
33 char* cmdline[MAX_CMD_SIZE];
34 process_t cmds[MAX_CMD_SIZE];
35
36 getcwd(path, MAX_LINE_SIZE);
37 while (1) {
38
39 printf("mini@shell:%s$ ", path);
40 scanf("%[^\n]%*c", line);
41
42 trim(line);
43 clean(line);
44 tokenize(line, cmdline);
45
46 parse_cmd(cmdline, cmds);
47 toString(cmds);
48
49 break;.
50 }
51 return -1;
52}
53 char* argv[MAX_CMD_SIZE] = {NULL};
54
to
1int parse_cmd(char* tokens[], process_t* commands) {
2 assert(tokens!=NULL);
3 assert(commands!=NULL);
4
5 int position = 0;
6 int commandNumber = 0;
7
8 for(int i=0; tokens[i] != NULL; i++){
9 if(is_reserved(tokens[i]) == 0 && tokens[i+1] != NULL) continue;
10 int end = is_reserved(tokens[i]) == 0 ? i+1 : i;
11 int argc = position;
12 int count = 0;
13
14 process_t newProcess;
15
16 char* argv[MAX_CMD_SIZE] = {NULL};
17 for(argc; argc < end; argc++) {
18 argv[count] = tokens[argc];
19 count = count + 1;
20 }
21 newProcess.path = tokens[position];
22 newProcess.argv = argv;
23 position = i + 1;
24 commands[commandNumber] = newProcess;
25 commandNumber = commandNumber + 1;
26 }
27}
28
29int main(int argc, char* argv[]) {
30
31 char path[MAX_LINE_SIZE];
32 char line[MAX_LINE_SIZE];
33 char* cmdline[MAX_CMD_SIZE];
34 process_t cmds[MAX_CMD_SIZE];
35
36 getcwd(path, MAX_LINE_SIZE);
37 while (1) {
38
39 printf("mini@shell:%s$ ", path);
40 scanf("%[^\n]%*c", line);
41
42 trim(line);
43 clean(line);
44 tokenize(line, cmdline);
45
46 parse_cmd(cmdline, cmds);
47 toString(cmds);
48
49 break;.
50 }
51 return -1;
52}
53 char* argv[MAX_CMD_SIZE] = {NULL};
54 char **argv = calloc(end-position+1, sizeof *argv);
55
Note that you'd have to free
this object when no longer needed.
Also note that you forgot to return commandNumber;
from parse_cmd
; without that, you have no way of knowing how many commands were found.
QUESTION
How to detect if Python is running in Git Bash terminal, or Windows cmd?
Asked 2021-Oct-17 at 16:37I'd like to give my Python scripts the ability to detect whether it was executed in a Git Bash terminal, or the Windows cmd command line interface. For example, I'm trying to write a function to clear the terminal (regardless of which terminal it is), e.g. echoes the clear
command if in Git Bash, or cls
if in cmd.
I've tried using sys.platform to detect this, but it returns win32
regardless of which type of terminal it was ran in.
ANSWER
Answered 2021-Oct-17 at 05:23I don't believe what you're asking for is possible, but there are several answers here that show all the detections you can do to use the correct type of clear. Usually, it's just best to either make your own window or not clear the screen, sadly.
QUESTION
Connecting to MySQL server in a script returns error, but it works fine in a terminal
Asked 2021-Oct-12 at 15:28I'm trying to write a bash script which will install and set up a MySQL server automatically. The problem is that when my script executes the following command:
1mysql --socket=<path-to-mysql-dir>/mysql/socket -u root -p"$pass"
2
I get the following error:
1mysql --socket=<path-to-mysql-dir>/mysql/socket -u root -p"$pass"
2mysql: [Warning] Using a password on the command line interface can be insecure.
3ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/<path-to-mysql-dir>/mysql/socket' (2)
4
Yet when I run the same command in my bash terminal, it works fine:
1mysql --socket=<path-to-mysql-dir>/mysql/socket -u root -p"$pass"
2mysql: [Warning] Using a password on the command line interface can be insecure.
3ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/<path-to-mysql-dir>/mysql/socket' (2)
4$ mysql --socket=socket -u root -p'random-init-pass'
5mysql: [Warning] Using a password on the command line interface can be insecure.
6Welcome to the MySQL monitor. Commands end with ; or \g.
7Your MySQL connection id is 3
8Server version: 5.7.18
9
10Copyright (c) 2000, 2017, Oracle and/or its affiliates. All rights reserved.
11
12Oracle is a registered trademark of Oracle Corporation and/or its
13affiliates. Other names may be trademarks of their respective
14owners.
15
16Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
17
18mysql>
19
Here's the set-up:
I have a script called sourceme.bash
. I source sourceme.bash
in order to set up the server. Here's what it looks like (everything in <>
is unimportant):
mysql/sourceme.bash
:
1mysql --socket=<path-to-mysql-dir>/mysql/socket -u root -p"$pass"
2mysql: [Warning] Using a password on the command line interface can be insecure.
3ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/<path-to-mysql-dir>/mysql/socket' (2)
4$ mysql --socket=socket -u root -p'random-init-pass'
5mysql: [Warning] Using a password on the command line interface can be insecure.
6Welcome to the MySQL monitor. Commands end with ; or \g.
7Your MySQL connection id is 3
8Server version: 5.7.18
9
10Copyright (c) 2000, 2017, Oracle and/or its affiliates. All rights reserved.
11
12Oracle is a registered trademark of Oracle Corporation and/or its
13affiliates. Other names may be trademarks of their respective
14owners.
15
16Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
17
18mysql>
19source /<path-to-bash-init>/bash
20module load <modules>
21
22SQLDIR="/<path-to-mysql-dir>"
23cd $SQLDIR
24
25# Kill the existing MySQL server (for testing purposes as I'm re-running this script multiple times)
26# Do so by locating its process ID and terminating that ID, waiting until it's killed before proceeding.
27ps -aux | grep mysql | grep -v grep
28mysqlps=`ps -aux | grep mysql | grep -v grep | sed -e 's/ \{2,\}/ /g' | cut -f2 -d' '`
29
30if [[ -n $mysqlps ]]; then
31 kill $mysqlps
32 while kill -0 $mysqlps; do
33 sleep 0.5
34 done
35 echo "MySQL process successfully killed. Status $?"
36else
37 echo "No MySQL process to kill. Status $?"
38fi
39rm -rf $SQLDIR/mysql
40
41# Set up MySQL server directory
42mkdir -p $SQLDIR/mysql
43pushd $SQLDIR/mysql
44
45# Copy setup files stored in $SQLDIR in order to install MySQL
46# The my.cnf config file contains the string "$USER" which should be replaced with a Unix username.
47cat $SQLDIR/setup_files/my.cnf | awk -v user=`whoami` '{ sub(/\$USER/, user); print }' > my.cnf
48cp -t . $SQLDIR/setup_files/loadmodules.bash $SQLDIR/setup_files/mysql_*
49chmod +x mysql_*
50
51# Load modules necessary to run the server
52source loadmodules.bash
53
54# Initialise MySQL server, kill the script if this step fails.
55# NB thanks to Raman Sailopal for helping me with this bit: https://stackoverflow.com/questions/69406526/start-a-mysql-server-pipe-the-output-to-a-file
56./mysql_init.sh 2>&1 | tee mysql_init.log
57init_status=${PIPESTATUS[0]}
58if [[ $init_status -ne 0 ]]; then
59 echo "Init script failed - kill script"
60 return 1
61fi
62
63# Grab the setup password from the log produced by mysql_init.sh. Copy into variable.
64line=`tail -n1 mysql_init.log`
65pass="${line##* }"
66
67# Launch MySQL server now that it's been initialised
68./mysql_start.sh
69
70# Create a .my.cnf config file in the user's home area, set to user-access only
71user=`whoami`
72cat << EOT > ~/.my.cnf
73[mysqld]
74
75user=$user
76password=$pass
77socket=$SQLDIR/mysql/socket
78EOT
79
80chmod 700 ~/.my.cnf
81
82# Fire up the MySQL server command line
83# THIS IS THE BIT THAT DOESN'T WORK
84mysql --socket=$SQLDIR/mysql/socket -u root -p"$pass"
85
If I comment out the last line and copy the exact same thing into my terminal, it will start the MySQL server without complaint. I've also tried using the -e option to feed a command into the CLI and then quit, but that doesn't work either.
For completeness, here are the setup files that will be in the location $SQLDIR/mysql - which the script runs in order to start the MySQL server.
mysql/my.cnf
:
1mysql --socket=<path-to-mysql-dir>/mysql/socket -u root -p"$pass"
2mysql: [Warning] Using a password on the command line interface can be insecure.
3ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/<path-to-mysql-dir>/mysql/socket' (2)
4$ mysql --socket=socket -u root -p'random-init-pass'
5mysql: [Warning] Using a password on the command line interface can be insecure.
6Welcome to the MySQL monitor. Commands end with ; or \g.
7Your MySQL connection id is 3
8Server version: 5.7.18
9
10Copyright (c) 2000, 2017, Oracle and/or its affiliates. All rights reserved.
11
12Oracle is a registered trademark of Oracle Corporation and/or its
13affiliates. Other names may be trademarks of their respective
14owners.
15
16Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
17
18mysql>
19source /<path-to-bash-init>/bash
20module load <modules>
21
22SQLDIR="/<path-to-mysql-dir>"
23cd $SQLDIR
24
25# Kill the existing MySQL server (for testing purposes as I'm re-running this script multiple times)
26# Do so by locating its process ID and terminating that ID, waiting until it's killed before proceeding.
27ps -aux | grep mysql | grep -v grep
28mysqlps=`ps -aux | grep mysql | grep -v grep | sed -e 's/ \{2,\}/ /g' | cut -f2 -d' '`
29
30if [[ -n $mysqlps ]]; then
31 kill $mysqlps
32 while kill -0 $mysqlps; do
33 sleep 0.5
34 done
35 echo "MySQL process successfully killed. Status $?"
36else
37 echo "No MySQL process to kill. Status $?"
38fi
39rm -rf $SQLDIR/mysql
40
41# Set up MySQL server directory
42mkdir -p $SQLDIR/mysql
43pushd $SQLDIR/mysql
44
45# Copy setup files stored in $SQLDIR in order to install MySQL
46# The my.cnf config file contains the string "$USER" which should be replaced with a Unix username.
47cat $SQLDIR/setup_files/my.cnf | awk -v user=`whoami` '{ sub(/\$USER/, user); print }' > my.cnf
48cp -t . $SQLDIR/setup_files/loadmodules.bash $SQLDIR/setup_files/mysql_*
49chmod +x mysql_*
50
51# Load modules necessary to run the server
52source loadmodules.bash
53
54# Initialise MySQL server, kill the script if this step fails.
55# NB thanks to Raman Sailopal for helping me with this bit: https://stackoverflow.com/questions/69406526/start-a-mysql-server-pipe-the-output-to-a-file
56./mysql_init.sh 2>&1 | tee mysql_init.log
57init_status=${PIPESTATUS[0]}
58if [[ $init_status -ne 0 ]]; then
59 echo "Init script failed - kill script"
60 return 1
61fi
62
63# Grab the setup password from the log produced by mysql_init.sh. Copy into variable.
64line=`tail -n1 mysql_init.log`
65pass="${line##* }"
66
67# Launch MySQL server now that it's been initialised
68./mysql_start.sh
69
70# Create a .my.cnf config file in the user's home area, set to user-access only
71user=`whoami`
72cat << EOT > ~/.my.cnf
73[mysqld]
74
75user=$user
76password=$pass
77socket=$SQLDIR/mysql/socket
78EOT
79
80chmod 700 ~/.my.cnf
81
82# Fire up the MySQL server command line
83# THIS IS THE BIT THAT DOESN'T WORK
84mysql --socket=$SQLDIR/mysql/socket -u root -p"$pass"
85[mysqld]
86
87user=lou-unix-username
88socket=socket
89
mysql/mysql_init.sh
:
1mysql --socket=<path-to-mysql-dir>/mysql/socket -u root -p"$pass"
2mysql: [Warning] Using a password on the command line interface can be insecure.
3ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/<path-to-mysql-dir>/mysql/socket' (2)
4$ mysql --socket=socket -u root -p'random-init-pass'
5mysql: [Warning] Using a password on the command line interface can be insecure.
6Welcome to the MySQL monitor. Commands end with ; or \g.
7Your MySQL connection id is 3
8Server version: 5.7.18
9
10Copyright (c) 2000, 2017, Oracle and/or its affiliates. All rights reserved.
11
12Oracle is a registered trademark of Oracle Corporation and/or its
13affiliates. Other names may be trademarks of their respective
14owners.
15
16Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
17
18mysql>
19source /<path-to-bash-init>/bash
20module load <modules>
21
22SQLDIR="/<path-to-mysql-dir>"
23cd $SQLDIR
24
25# Kill the existing MySQL server (for testing purposes as I'm re-running this script multiple times)
26# Do so by locating its process ID and terminating that ID, waiting until it's killed before proceeding.
27ps -aux | grep mysql | grep -v grep
28mysqlps=`ps -aux | grep mysql | grep -v grep | sed -e 's/ \{2,\}/ /g' | cut -f2 -d' '`
29
30if [[ -n $mysqlps ]]; then
31 kill $mysqlps
32 while kill -0 $mysqlps; do
33 sleep 0.5
34 done
35 echo "MySQL process successfully killed. Status $?"
36else
37 echo "No MySQL process to kill. Status $?"
38fi
39rm -rf $SQLDIR/mysql
40
41# Set up MySQL server directory
42mkdir -p $SQLDIR/mysql
43pushd $SQLDIR/mysql
44
45# Copy setup files stored in $SQLDIR in order to install MySQL
46# The my.cnf config file contains the string "$USER" which should be replaced with a Unix username.
47cat $SQLDIR/setup_files/my.cnf | awk -v user=`whoami` '{ sub(/\$USER/, user); print }' > my.cnf
48cp -t . $SQLDIR/setup_files/loadmodules.bash $SQLDIR/setup_files/mysql_*
49chmod +x mysql_*
50
51# Load modules necessary to run the server
52source loadmodules.bash
53
54# Initialise MySQL server, kill the script if this step fails.
55# NB thanks to Raman Sailopal for helping me with this bit: https://stackoverflow.com/questions/69406526/start-a-mysql-server-pipe-the-output-to-a-file
56./mysql_init.sh 2>&1 | tee mysql_init.log
57init_status=${PIPESTATUS[0]}
58if [[ $init_status -ne 0 ]]; then
59 echo "Init script failed - kill script"
60 return 1
61fi
62
63# Grab the setup password from the log produced by mysql_init.sh. Copy into variable.
64line=`tail -n1 mysql_init.log`
65pass="${line##* }"
66
67# Launch MySQL server now that it's been initialised
68./mysql_start.sh
69
70# Create a .my.cnf config file in the user's home area, set to user-access only
71user=`whoami`
72cat << EOT > ~/.my.cnf
73[mysqld]
74
75user=$user
76password=$pass
77socket=$SQLDIR/mysql/socket
78EOT
79
80chmod 700 ~/.my.cnf
81
82# Fire up the MySQL server command line
83# THIS IS THE BIT THAT DOESN'T WORK
84mysql --socket=$SQLDIR/mysql/socket -u root -p"$pass"
85[mysqld]
86
87user=lou-unix-username
88socket=socket
89#! /bin/sh
90
91export MYSQL_HOME=$PWD
92
93# Change lc-messages-dir if running on RHE6 host
94
95mysqld \
96--defaults-file=$MYSQL_HOME/my.cnf \
97--lc-messages-dir="/<path-to-mysql>/mysql/5.7.18/rhe7-x86_64/share/english/" \
98--datadir=$MYSQL_HOME/data \
99--basedir=$MYSQL_HOME \
100--pid-file=$MYSQL_HOME/mysql.pid \
101--socket=$MYSQL_HOME/socket \
102--port=3307 \
103--initialize
104
mysql/mysql_start.sh
:
1mysql --socket=<path-to-mysql-dir>/mysql/socket -u root -p"$pass"
2mysql: [Warning] Using a password on the command line interface can be insecure.
3ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/<path-to-mysql-dir>/mysql/socket' (2)
4$ mysql --socket=socket -u root -p'random-init-pass'
5mysql: [Warning] Using a password on the command line interface can be insecure.
6Welcome to the MySQL monitor. Commands end with ; or \g.
7Your MySQL connection id is 3
8Server version: 5.7.18
9
10Copyright (c) 2000, 2017, Oracle and/or its affiliates. All rights reserved.
11
12Oracle is a registered trademark of Oracle Corporation and/or its
13affiliates. Other names may be trademarks of their respective
14owners.
15
16Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
17
18mysql>
19source /<path-to-bash-init>/bash
20module load <modules>
21
22SQLDIR="/<path-to-mysql-dir>"
23cd $SQLDIR
24
25# Kill the existing MySQL server (for testing purposes as I'm re-running this script multiple times)
26# Do so by locating its process ID and terminating that ID, waiting until it's killed before proceeding.
27ps -aux | grep mysql | grep -v grep
28mysqlps=`ps -aux | grep mysql | grep -v grep | sed -e 's/ \{2,\}/ /g' | cut -f2 -d' '`
29
30if [[ -n $mysqlps ]]; then
31 kill $mysqlps
32 while kill -0 $mysqlps; do
33 sleep 0.5
34 done
35 echo "MySQL process successfully killed. Status $?"
36else
37 echo "No MySQL process to kill. Status $?"
38fi
39rm -rf $SQLDIR/mysql
40
41# Set up MySQL server directory
42mkdir -p $SQLDIR/mysql
43pushd $SQLDIR/mysql
44
45# Copy setup files stored in $SQLDIR in order to install MySQL
46# The my.cnf config file contains the string "$USER" which should be replaced with a Unix username.
47cat $SQLDIR/setup_files/my.cnf | awk -v user=`whoami` '{ sub(/\$USER/, user); print }' > my.cnf
48cp -t . $SQLDIR/setup_files/loadmodules.bash $SQLDIR/setup_files/mysql_*
49chmod +x mysql_*
50
51# Load modules necessary to run the server
52source loadmodules.bash
53
54# Initialise MySQL server, kill the script if this step fails.
55# NB thanks to Raman Sailopal for helping me with this bit: https://stackoverflow.com/questions/69406526/start-a-mysql-server-pipe-the-output-to-a-file
56./mysql_init.sh 2>&1 | tee mysql_init.log
57init_status=${PIPESTATUS[0]}
58if [[ $init_status -ne 0 ]]; then
59 echo "Init script failed - kill script"
60 return 1
61fi
62
63# Grab the setup password from the log produced by mysql_init.sh. Copy into variable.
64line=`tail -n1 mysql_init.log`
65pass="${line##* }"
66
67# Launch MySQL server now that it's been initialised
68./mysql_start.sh
69
70# Create a .my.cnf config file in the user's home area, set to user-access only
71user=`whoami`
72cat << EOT > ~/.my.cnf
73[mysqld]
74
75user=$user
76password=$pass
77socket=$SQLDIR/mysql/socket
78EOT
79
80chmod 700 ~/.my.cnf
81
82# Fire up the MySQL server command line
83# THIS IS THE BIT THAT DOESN'T WORK
84mysql --socket=$SQLDIR/mysql/socket -u root -p"$pass"
85[mysqld]
86
87user=lou-unix-username
88socket=socket
89#! /bin/sh
90
91export MYSQL_HOME=$PWD
92
93# Change lc-messages-dir if running on RHE6 host
94
95mysqld \
96--defaults-file=$MYSQL_HOME/my.cnf \
97--lc-messages-dir="/<path-to-mysql>/mysql/5.7.18/rhe7-x86_64/share/english/" \
98--datadir=$MYSQL_HOME/data \
99--basedir=$MYSQL_HOME \
100--pid-file=$MYSQL_HOME/mysql.pid \
101--socket=$MYSQL_HOME/socket \
102--port=3307 \
103--initialize
104#! /bin/sh
105echo $DATADIR
106export MYSQL_HOME=$PWD
107
108mysqld \
109--defaults-file=$MYSQL_HOME/my.cnf \
110--log-error \
111--lc-messages-dir="/<path-to-mysql>/mysql/5.7.18/rhe7-x86_64/share/english/" \
112--datadir=$MYSQL_HOME/data \
113--basedir=$MYSQL_HOME \
114--pid-file=$MYSQL_HOME/mysql.pid \
115--socket=$MYSQL_HOME/socket \
116--port=3307 &
117
~/.my.cnf
:
1mysql --socket=<path-to-mysql-dir>/mysql/socket -u root -p"$pass"
2mysql: [Warning] Using a password on the command line interface can be insecure.
3ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/<path-to-mysql-dir>/mysql/socket' (2)
4$ mysql --socket=socket -u root -p'random-init-pass'
5mysql: [Warning] Using a password on the command line interface can be insecure.
6Welcome to the MySQL monitor. Commands end with ; or \g.
7Your MySQL connection id is 3
8Server version: 5.7.18
9
10Copyright (c) 2000, 2017, Oracle and/or its affiliates. All rights reserved.
11
12Oracle is a registered trademark of Oracle Corporation and/or its
13affiliates. Other names may be trademarks of their respective
14owners.
15
16Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
17
18mysql>
19source /<path-to-bash-init>/bash
20module load <modules>
21
22SQLDIR="/<path-to-mysql-dir>"
23cd $SQLDIR
24
25# Kill the existing MySQL server (for testing purposes as I'm re-running this script multiple times)
26# Do so by locating its process ID and terminating that ID, waiting until it's killed before proceeding.
27ps -aux | grep mysql | grep -v grep
28mysqlps=`ps -aux | grep mysql | grep -v grep | sed -e 's/ \{2,\}/ /g' | cut -f2 -d' '`
29
30if [[ -n $mysqlps ]]; then
31 kill $mysqlps
32 while kill -0 $mysqlps; do
33 sleep 0.5
34 done
35 echo "MySQL process successfully killed. Status $?"
36else
37 echo "No MySQL process to kill. Status $?"
38fi
39rm -rf $SQLDIR/mysql
40
41# Set up MySQL server directory
42mkdir -p $SQLDIR/mysql
43pushd $SQLDIR/mysql
44
45# Copy setup files stored in $SQLDIR in order to install MySQL
46# The my.cnf config file contains the string "$USER" which should be replaced with a Unix username.
47cat $SQLDIR/setup_files/my.cnf | awk -v user=`whoami` '{ sub(/\$USER/, user); print }' > my.cnf
48cp -t . $SQLDIR/setup_files/loadmodules.bash $SQLDIR/setup_files/mysql_*
49chmod +x mysql_*
50
51# Load modules necessary to run the server
52source loadmodules.bash
53
54# Initialise MySQL server, kill the script if this step fails.
55# NB thanks to Raman Sailopal for helping me with this bit: https://stackoverflow.com/questions/69406526/start-a-mysql-server-pipe-the-output-to-a-file
56./mysql_init.sh 2>&1 | tee mysql_init.log
57init_status=${PIPESTATUS[0]}
58if [[ $init_status -ne 0 ]]; then
59 echo "Init script failed - kill script"
60 return 1
61fi
62
63# Grab the setup password from the log produced by mysql_init.sh. Copy into variable.
64line=`tail -n1 mysql_init.log`
65pass="${line##* }"
66
67# Launch MySQL server now that it's been initialised
68./mysql_start.sh
69
70# Create a .my.cnf config file in the user's home area, set to user-access only
71user=`whoami`
72cat << EOT > ~/.my.cnf
73[mysqld]
74
75user=$user
76password=$pass
77socket=$SQLDIR/mysql/socket
78EOT
79
80chmod 700 ~/.my.cnf
81
82# Fire up the MySQL server command line
83# THIS IS THE BIT THAT DOESN'T WORK
84mysql --socket=$SQLDIR/mysql/socket -u root -p"$pass"
85[mysqld]
86
87user=lou-unix-username
88socket=socket
89#! /bin/sh
90
91export MYSQL_HOME=$PWD
92
93# Change lc-messages-dir if running on RHE6 host
94
95mysqld \
96--defaults-file=$MYSQL_HOME/my.cnf \
97--lc-messages-dir="/<path-to-mysql>/mysql/5.7.18/rhe7-x86_64/share/english/" \
98--datadir=$MYSQL_HOME/data \
99--basedir=$MYSQL_HOME \
100--pid-file=$MYSQL_HOME/mysql.pid \
101--socket=$MYSQL_HOME/socket \
102--port=3307 \
103--initialize
104#! /bin/sh
105echo $DATADIR
106export MYSQL_HOME=$PWD
107
108mysqld \
109--defaults-file=$MYSQL_HOME/my.cnf \
110--log-error \
111--lc-messages-dir="/<path-to-mysql>/mysql/5.7.18/rhe7-x86_64/share/english/" \
112--datadir=$MYSQL_HOME/data \
113--basedir=$MYSQL_HOME \
114--pid-file=$MYSQL_HOME/mysql.pid \
115--socket=$MYSQL_HOME/socket \
116--port=3307 &
117[mysqld]
118
119user=lou-unix-username
120password=random-init-password
121socket=/<path-to-mysql-dir>/mysql/socket
122
Is anyone able to suggest why I can launch the CLI on the terminal but not in a script? I know that I need to reset the randomly initialised password after starting up the MySQL CLI, but it won't even let me do that using the script. What could I be doing wrong?
ANSWER
Answered 2021-Oct-12 at 15:28Well, I'm not entirely sure what was wrong, but I think it came down to one process not finishing before another process started. I inserted a sleep 5
in the script - just before the last line where I'm trying to connect to the server, and that worked. I also wrapped the line in a while loop, giving it up to 5 attempts to connect to the server, and if it fails, it will wait a further 5 seconds. Currently this seems to work fairly reliably and I am able to connect to the MySQL server.
So either way the problem appears to be solved.
QUESTION
Python 3 + Click: CLI arguments get butchered when calling one command from another
Asked 2021-Sep-10 at 16:18I am using Python 3.9 and Click to build a small command line interface utility, but I am getting strange errors, specifically when I attempt to call one function decorated as a @click.command()
from another function that is also decorated the same way.
I have distilled my program down to the bare minimum to explain what I mean.
This is my program
1import click
2
3@click.group()
4def cli():
5 pass
6
7@click.command()
8@click.argument('id')
9def outer(id):
10 print('outer id',id,type(id))
11 inner(id) # run inner() from within outer(), pass argument unchanged
12
13@click.command() # *
14@click.argument('id') # *
15def inner(id):
16 print('inner id',id,type(id))
17
18cli.add_command(outer)
19cli.add_command(inner) # *
20
21if __name__ == '__main__':
22 cli()
23
This is the CLI result when I run my script using both the inner
and outer
commands:
1import click
2
3@click.group()
4def cli():
5 pass
6
7@click.command()
8@click.argument('id')
9def outer(id):
10 print('outer id',id,type(id))
11 inner(id) # run inner() from within outer(), pass argument unchanged
12
13@click.command() # *
14@click.argument('id') # *
15def inner(id):
16 print('inner id',id,type(id))
17
18cli.add_command(outer)
19cli.add_command(inner) # *
20
21if __name__ == '__main__':
22 cli()
23% python3 test.py inner 123
24inner id 123 <class 'str'>
25% python3 test.py outer 123
26outer id 123 <class 'str'>
27Usage: test.py [OPTIONS] ID
28Try 'test.py --help' for help.
29
30Error: Got unexpected extra arguments (2 3)
31%
32
Interestingly, it works when I use a single character argument:
1import click
2
3@click.group()
4def cli():
5 pass
6
7@click.command()
8@click.argument('id')
9def outer(id):
10 print('outer id',id,type(id))
11 inner(id) # run inner() from within outer(), pass argument unchanged
12
13@click.command() # *
14@click.argument('id') # *
15def inner(id):
16 print('inner id',id,type(id))
17
18cli.add_command(outer)
19cli.add_command(inner) # *
20
21if __name__ == '__main__':
22 cli()
23% python3 test.py inner 123
24inner id 123 <class 'str'>
25% python3 test.py outer 123
26outer id 123 <class 'str'>
27Usage: test.py [OPTIONS] ID
28Try 'test.py --help' for help.
29
30Error: Got unexpected extra arguments (2 3)
31%
32% python3 test.py outer 1
33outer id 1 <class 'str'>
34inner id 1 <class 'str'>
35%
36
If I comment out the three lines marked with # *
, running the outer
command behaves as expected, passing on the id
argument to inner()
without changes or issues, no matter the length of the argument:
1import click
2
3@click.group()
4def cli():
5 pass
6
7@click.command()
8@click.argument('id')
9def outer(id):
10 print('outer id',id,type(id))
11 inner(id) # run inner() from within outer(), pass argument unchanged
12
13@click.command() # *
14@click.argument('id') # *
15def inner(id):
16 print('inner id',id,type(id))
17
18cli.add_command(outer)
19cli.add_command(inner) # *
20
21if __name__ == '__main__':
22 cli()
23% python3 test.py inner 123
24inner id 123 <class 'str'>
25% python3 test.py outer 123
26outer id 123 <class 'str'>
27Usage: test.py [OPTIONS] ID
28Try 'test.py --help' for help.
29
30Error: Got unexpected extra arguments (2 3)
31%
32% python3 test.py outer 1
33outer id 1 <class 'str'>
34inner id 1 <class 'str'>
35%
36% python3 test.py outer 123
37outer id 123 <class 'str'>
38inner id 123 <class 'str'>
39%
40
Clearly, the decorators are somehow messing with the arguments. Can anybody explain why this is, and how I can achieve the desired behavior of passing on the arguments unchanged? Maybe I am missing something super obvious?
Thanks in advance!
ANSWER
Answered 2021-Sep-10 at 16:18Use the context operations to invoke other commands
1import click
2
3@click.group()
4def cli():
5 pass
6
7@click.command()
8@click.argument('id')
9def outer(id):
10 print('outer id',id,type(id))
11 inner(id) # run inner() from within outer(), pass argument unchanged
12
13@click.command() # *
14@click.argument('id') # *
15def inner(id):
16 print('inner id',id,type(id))
17
18cli.add_command(outer)
19cli.add_command(inner) # *
20
21if __name__ == '__main__':
22 cli()
23% python3 test.py inner 123
24inner id 123 <class 'str'>
25% python3 test.py outer 123
26outer id 123 <class 'str'>
27Usage: test.py [OPTIONS] ID
28Try 'test.py --help' for help.
29
30Error: Got unexpected extra arguments (2 3)
31%
32% python3 test.py outer 1
33outer id 1 <class 'str'>
34inner id 1 <class 'str'>
35%
36% python3 test.py outer 123
37outer id 123 <class 'str'>
38inner id 123 <class 'str'>
39%
40import click
41
42@click.group()
43def cli():
44 pass
45
46@click.command()
47@click.argument('id')
48@click.pass_context
49def outer(ctx, id):
50 print('outer id',id,type(id))
51 ctx.forward(inner) # run inner(), pass argument unchanged
52 ctx.invoke(inner, id=id+1) # run inner(), pass modified argument
53
54@click.command() # *
55@click.argument('id') # *
56def inner(id):
57 print('inner id',id,type(id))
58
59cli.add_command(outer)
60cli.add_command(inner) # *
61
62if __name__ == '__main__':
63 cli()
64
Community Discussions contain sources that include Stack Exchange Network
Tutorials and Learning Resources in Command Line Interface
Tutorials and Learning Resources are not available at this moment for Command Line Interface