问:
npm ERR! invalid json response body at http://registry.npmjs.org/ansi-escapes reason: Unexpected end of JSON input
I have nodejs and npm installed
I tried running the command

npm install -g create-react-app

but it halts at the error below

```<code>freduah@freduah:~$ npm install -g create-react-app
npm WARN registry Unexpected warning for http://registry.npmjs.org/: Miscellaneous Warning EAI_AGAIN: request to http://registry.npmjs.org/create-react-app failed, reason: getaddrinfo EAI_AGAIN registry.npmjs.org
npm WARN registry Using stale data from http://registry.npmjs.org/ due to a request error during revalidation.
npm ERR! code FETCH_ERROR
npm ERR! errno FETCH_ERROR
npm ERR! invalid json response body at http://registry.npmjs.org/ansi-escapes reason: Unexpected end of JSON input

npm ERR! A complete log of this run can be found in:
npm ERR!     /home/freduah/.npm/_logs/2020-10-31T19_11_20_727Z-debug.log
freduah@freduah:~$
</code>```

Below Is The Full Error Log Content

```freduah@freduah:~/Downloads$ cat /home/freduah/.npm/_logs/2020-10-31T19_11_20_727Z-debug.log
0 verbose cli [
0 verbose cli   '/usr/bin/node',
0 verbose cli   '/usr/bin/npm',
0 verbose cli   'install',
0 verbose cli   '-g',
0 verbose cli   'create-react-app'
0 verbose cli ]
1 info using npm@7.0.3
2 info using node@v12.19.0
3 timing config:load:defaults Completed in 2ms
4 timing config:load:file:/usr/share/npm/npmrc Completed in 3ms
5 timing config:load:builtin Completed in 3ms
6 timing config:load:cli Completed in 4ms
7 timing config:load:env Completed in 0ms
8 timing config:load:project Completed in 1ms
9 timing config:load:file:/home/freduah/.npmrc Completed in 1ms
10 timing config:load:user Completed in 1ms
11 timing config:load:file:/etc/npmrc Completed in 0ms
12 timing config:load:global Completed in 0ms
13 timing config:load:cafile Completed in 0ms
14 timing config:load:validate Completed in 2ms
15 timing config:load:setUserAgent Completed in 1ms
16 timing config:load:setEnvs Completed in 1ms
17 timing config:load Completed in 15ms
18 verbose npm-session 3fe07c2ad8478ec0
19 timing npm:load Completed in 27ms
20 timing arborist:ctor Completed in 1ms
21 timing idealTree:init Completed in 3ms
22 timing idealTree:userRequests Completed in 8ms
23 silly idealTree buildDeps
24 silly fetch manifest create-react-app@*
25 warn registry Unexpected warning for http://registry.npmjs.org/: Miscellaneous Warning EAI_AGAIN: request to http://registry.npmjs.org/create-react-app failed, reason: getaddrinfo EAI_AGAIN registry.npmjs.org
26 warn registry Using stale data from http://registry.npmjs.org/ due to a request error during revalidation.
27 http fetch GET 200 http://registry.npmjs.org/create-react-app 10087ms (from cache)
28 silly placeDep ROOT create-react-app@4.0.0 OK for:  want: *
29 silly fetch manifest chalk@4.1.0
30 silly fetch manifest commander@4.1.1
31 silly fetch manifest cross-spawn@7.0.3
32 silly fetch manifest envinfo@7.7.3
33 silly fetch manifest fs-extra@9.0.1
34 silly fetch manifest hyperquest@2.1.3
35 silly fetch manifest inquirer@7.3.3
36 silly fetch manifest semver@7.3.2
37 silly fetch manifest tar-pack@3.4.1
38 silly fetch manifest tmp@0.2.1
39 silly fetch manifest validate-npm-package-name@3.0.0
40 http fetch GET 304 http://registry.npmjs.org/envinfo 23286ms (from cache)
41 http fetch GET 304 http://registry.npmjs.org/cross-spawn 23292ms (from cache)
42 http fetch GET 304 http://registry.npmjs.org/fs-extra 23665ms (from cache)
43 http fetch GET 304 http://registry.npmjs.org/hyperquest 24552ms (from cache)
44 http fetch GET 304 http://registry.npmjs.org/semver 28953ms (from cache)
45 http fetch GET 304 http://registry.npmjs.org/inquirer 28960ms (from cache)
46 http fetch GET 304 http://registry.npmjs.org/tar-pack 29245ms (from cache)
47 http fetch GET 304 http://registry.npmjs.org/tmp 29303ms (from cache)
48 http fetch GET 304 http://registry.npmjs.org/validate-npm-package-name 30877ms (from cache)
49 http fetch GET 304 http://registry.npmjs.org/chalk 36204ms attempt #2 (from cache)
50 http fetch GET 304 http://registry.npmjs.org/commander 36204ms attempt #2 (from cache)
51 timing idealTree:#root Completed in 46313ms
52 silly placeDep node_modules/create-react-app chalk@4.1.0 OK for: create-react-app@4.0.0 want: 4.1.0
53 silly placeDep node_modules/create-react-app commander@4.1.1 OK for: create-react-app@4.0.0 want: 4.1.1
54 silly placeDep node_modules/create-react-app cross-spawn@7.0.3 OK for: create-react-app@4.0.0 want: 7.0.3
55 silly placeDep node_modules/create-react-app envinfo@7.7.3 OK for: create-react-app@4.0.0 want: 7.7.3
56 silly placeDep node_modules/create-react-app fs-extra@9.0.1 OK for: create-react-app@4.0.0 want: 9.0.1
57 silly placeDep node_modules/create-react-app hyperquest@2.1.3 OK for: create-react-app@4.0.0 want: 2.1.3
58 silly placeDep node_modules/create-react-app inquirer@7.3.3 OK for: create-react-app@4.0.0 want: 7.3.3
59 silly placeDep node_modules/create-react-app semver@7.3.2 OK for: create-react-app@4.0.0 want: 7.3.2
60 silly placeDep node_modules/create-react-app tar-pack@3.4.1 OK for: create-react-app@4.0.0 want: 3.4.1
61 silly placeDep node_modules/create-react-app tmp@0.2.1 OK for: create-react-app@4.0.0 want: 0.2.1
62 silly placeDep node_modules/create-react-app validate-npm-package-name@3.0.0 OK for: create-react-app@4.0.0 want: 3.0.0
63 silly fetch manifest ansi-styles@^4.1.0
64 silly fetch manifest supports-color@^7.1.0
65 silly fetch manifest path-key@^3.1.0
66 silly fetch manifest shebang-command@^2.0.0
67 silly fetch manifest which@^2.0.1
68 silly fetch manifest at-least-node@^1.0.0
69 silly fetch manifest graceful-fs@^4.2.0
70 silly fetch manifest jsonfile@^6.0.1
71 silly fetch manifest universalify@^1.0.0
72 silly fetch manifest buffer-from@^0.1.1
73 silly fetch manifest duplexer2@~0.0.2
74 silly fetch manifest through2@~0.6.3
75 silly fetch manifest ansi-escapes@^4.2.1
76 silly fetch manifest cli-cursor@^3.1.0
77 silly fetch manifest cli-width@^3.0.0
78 silly fetch manifest external-editor@^3.0.3
79 silly fetch manifest figures@^3.0.0
80 silly fetch manifest lodash@^4.17.19
81 silly fetch manifest mute-stream@0.0.8
82 silly fetch manifest run-async@^2.4.0
83 silly fetch manifest rxjs@^6.6.0
84 silly fetch manifest string-width@^4.1.0
85 silly fetch manifest strip-ansi@^6.0.0
86 silly fetch manifest through@^2.3.6
87 silly fetch manifest debug@^2.2.0
88 silly fetch manifest fstream@^1.0.10
89 silly fetch manifest fstream-ignore@^1.0.5
90 silly fetch manifest once@^1.3.3
91 silly fetch manifest readable-stream@^2.1.4
92 silly fetch manifest rimraf@^2.5.1
93 silly fetch manifest tar@^2.2.1
94 silly fetch manifest uid-number@^0.0.6
95 silly fetch manifest rimraf@^3.0.0
96 silly fetch manifest builtins@^1.0.3
97 http fetch GET 200 http://registry.npmjs.org/jsonfile 240ms (from cache)
98 http fetch GET 304 http://registry.npmjs.org/ansi-styles 1807ms (from cache)
99 http fetch GET 304 http://registry.npmjs.org/supports-color 1806ms (from cache)
100 http fetch GET 304 http://registry.npmjs.org/which 1866ms (from cache)
101 http fetch GET 304 http://registry.npmjs.org/path-key 1893ms (from cache)
102 http fetch GET 304 http://registry.npmjs.org/at-least-node 1933ms (from cache)
103 http fetch GET 304 http://registry.npmjs.org/graceful-fs 1974ms (from cache)
104 http fetch GET 304 http://registry.npmjs.org/cli-cursor 2773ms (from cache)
105 http fetch GET 304 http://registry.npmjs.org/cli-width 2804ms (from cache)
106 http fetch GET 304 http://registry.npmjs.org/external-editor 2929ms (from cache)
107 http fetch GET 304 http://registry.npmjs.org/mute-stream 2956ms (from cache)
108 http fetch GET 304 http://registry.npmjs.org/lodash 2960ms (from cache)
109 http fetch GET 304 http://registry.npmjs.org/figures 3064ms (from cache)
110 http fetch GET 304 http://registry.npmjs.org/run-async 3500ms (from cache)
111 http fetch GET 304 http://registry.npmjs.org/rxjs 3522ms (from cache)
112 http fetch GET 304 http://registry.npmjs.org/string-width 3555ms (from cache)
113 http fetch GET 304 http://registry.npmjs.org/universalify 3677ms (from cache)
114 http fetch GET 304 http://registry.npmjs.org/buffer-from 3687ms (from cache)
115 http fetch GET 304 http://registry.npmjs.org/strip-ansi 3660ms (from cache)
116 http fetch GET 304 http://registry.npmjs.org/through 3681ms (from cache)
117 http fetch GET 304 http://registry.npmjs.org/debug 3784ms (from cache)
118 http fetch GET 304 http://registry.npmjs.org/fstream 4015ms (from cache)
119 http fetch GET 304 http://registry.npmjs.org/duplexer2 4169ms (from cache)
120 http fetch GET 304 http://registry.npmjs.org/through2 4179ms (from cache)
121 http fetch GET 304 http://registry.npmjs.org/fstream-ignore 4133ms (from cache)
122 http fetch GET 304 http://registry.npmjs.org/readable-stream 4169ms (from cache)
123 http fetch GET 304 http://registry.npmjs.org/rimraf 4200ms (from cache)
124 http fetch GET 304 http://registry.npmjs.org/uid-number 4526ms (from cache)
125 http fetch GET 304 http://registry.npmjs.org/builtins 4520ms (from cache)
126 http fetch GET 304 http://registry.npmjs.org/rimraf 4536ms (from cache)
127 http fetch GET 304 http://registry.npmjs.org/ansi-escapes 4660ms (from cache)
128 http fetch GET 304 http://registry.npmjs.org/tar 4601ms (from cache)
129 http fetch GET 304 http://registry.npmjs.org/shebang-command 5758ms (from cache)
130 http fetch GET 304 http://registry.npmjs.org/once 9981ms (from cache)
131 timing idealTree:node_modules/create-react-app Completed in 10102ms
132 silly placeDep node_modules/create-react-app ansi-styles@4.3.0 OK for: chalk@4.1.0 want: ^4.1.0
133 silly placeDep node_modules/create-react-app supports-color@7.2.0 OK for: chalk@4.1.0 want: ^7.1.0
134 silly fetch manifest color-convert@^2.0.1
135 silly fetch manifest has-flag@^4.0.0
136 http fetch GET 304 http://registry.npmjs.org/has-flag 4131ms (from cache)
137 http fetch GET 304 http://registry.npmjs.org/color-convert 4168ms (from cache)
138 timing idealTree:node_modules/create-react-app/node_modules/chalk Completed in 4176ms
139 silly placeDep node_modules/create-react-app color-convert@2.0.1 OK for: ansi-styles@4.3.0 want: ^2.0.1
140 silly fetch manifest color-name@~1.1.4
141 http fetch GET 304 http://registry.npmjs.org/color-name 3286ms (from cache)
142 timing idealTree:node_modules/create-react-app/node_modules/ansi-styles Completed in 3291ms
143 silly placeDep node_modules/create-react-app color-name@1.1.4 OK for: color-convert@2.0.1 want: ~1.1.4
144 timing idealTree:node_modules/create-react-app/node_modules/color-convert Completed in 2ms
145 timing idealTree:node_modules/create-react-app/node_modules/color-name Completed in 0ms
146 timing idealTree:node_modules/create-react-app/node_modules/commander Completed in 0ms
147 silly placeDep node_modules/create-react-app path-key@3.1.1 OK for: cross-spawn@7.0.3 want: ^3.1.0
148 silly placeDep node_modules/create-react-app shebang-command@2.0.0 OK for: cross-spawn@7.0.3 want: ^2.0.0
149 silly placeDep node_modules/create-react-app which@2.0.2 OK for: cross-spawn@7.0.3 want: ^2.0.1
150 silly fetch manifest shebang-regex@^3.0.0
151 silly fetch manifest isexe@^2.0.0
152 http fetch GET 304 http://registry.npmjs.org/shebang-regex 1543ms (from cache)
153 http fetch GET 304 http://registry.npmjs.org/isexe 2212ms (from cache)
154 timing idealTree:node_modules/create-react-app/node_modules/cross-spawn Completed in 2223ms
155 timing idealTree:node_modules/create-react-app/node_modules/envinfo Completed in 0ms
156 silly placeDep node_modules/create-react-app at-least-node@1.0.0 OK for: fs-extra@9.0.1 want: ^1.0.0
157 silly placeDep node_modules/create-react-app graceful-fs@4.2.4 OK for: fs-extra@9.0.1 want: ^4.2.0
158 silly placeDep node_modules/create-react-app jsonfile@6.1.0 OK for: fs-extra@9.0.1 want: ^6.0.1
159 silly placeDep node_modules/create-react-app universalify@1.0.0 OK for: fs-extra@9.0.1 want: ^1.0.0
160 silly fetch manifest universalify@^2.0.0
161 http fetch GET 304 http://registry.npmjs.org/universalify 387ms (from cache)
162 timing idealTree:node_modules/create-react-app/node_modules/fs-extra Completed in 399ms
163 timing idealTree:node_modules/create-react-app/node_modules/at-least-node Completed in 0ms
164 timing idealTree:node_modules/create-react-app/node_modules/graceful-fs Completed in 0ms
165 silly placeDep node_modules/create-react-app buffer-from@0.1.2 OK for: hyperquest@2.1.3 want: ^0.1.1
166 silly placeDep node_modules/create-react-app duplexer2@0.0.2 OK for: hyperquest@2.1.3 want: ~0.0.2
167 silly placeDep node_modules/create-react-app through2@0.6.5 OK for: hyperquest@2.1.3 want: ~0.6.3
168 silly fetch manifest readable-stream@~1.1.9
169 silly fetch manifest readable-stream@>=1.0.33-1 <1.1.0-0
170 silly fetch manifest xtend@>=4.0.0 <4.1.0-0
171 http fetch GET 304 http://registry.npmjs.org/readable-stream 391ms (from cache)
172 http fetch GET 304 http://registry.npmjs.org/readable-stream 468ms (from cache)
173 http fetch GET 304 http://registry.npmjs.org/xtend 568ms (from cache)
174 timing idealTree:node_modules/create-react-app/node_modules/hyperquest Completed in 581ms
175 timing idealTree:node_modules/create-react-app/node_modules/buffer-from Completed in 0ms
176 silly placeDep node_modules/create-react-app readable-stream@1.1.14 OK for: duplexer2@0.0.2 want: ~1.1.9
177 silly fetch manifest core-util-is@~1.0.0
178 silly fetch manifest isarray@0.0.1
179 silly fetch manifest string_decoder@~0.10.x
180 silly fetch manifest inherits@~2.0.1
181 http fetch GET 304 http://registry.npmjs.org/string_decoder 1910ms (from cache)
182 http fetch GET 304 http://registry.npmjs.org/inherits 1923ms (from cache)
183 http fetch GET 304 http://registry.npmjs.org/isarray 2011ms (from cache)
184 http fetch GET 304 http://registry.npmjs.org/core-util-is 2059ms (from cache)
185 timing idealTree:node_modules/create-react-app/node_modules/duplexer2 Completed in 2066ms
186 silly placeDep node_modules/create-react-app ansi-escapes@ OK for: inquirer@7.3.3 want: ^4.2.1
187 silly placeDep node_modules/create-react-app cli-cursor@3.1.0 OK for: inquirer@7.3.3 want: ^3.1.0
188 silly placeDep node_modules/create-react-app cli-width@3.0.0 OK for: inquirer@7.3.3 want: ^3.0.0
189 silly placeDep node_modules/create-react-app external-editor@3.1.0 OK for: inquirer@7.3.3 want: ^3.0.3
190 silly placeDep node_modules/create-react-app figures@3.2.0 OK for: inquirer@7.3.3 want: ^3.0.0
191 silly placeDep node_modules/create-react-app lodash@ OK for: inquirer@7.3.3 want: ^4.17.19
192 silly placeDep node_modules/create-react-app mute-stream@0.0.8 OK for: inquirer@7.3.3 want: 0.0.8
193 silly placeDep node_modules/create-react-app run-async@2.4.1 OK for: inquirer@7.3.3 want: ^2.4.0
194 silly placeDep node_modules/create-react-app rxjs@ OK for: inquirer@7.3.3 want: ^6.6.0
195 silly placeDep node_modules/create-react-app string-width@4.2.0 OK for: inquirer@7.3.3 want: ^4.1.0
196 silly placeDep node_modules/create-react-app strip-ansi@6.0.0 OK for: inquirer@7.3.3 want: ^6.0.0
197 silly placeDep node_modules/create-react-app through@2.3.8 OK for: inquirer@7.3.3 want: ^2.3.6
198 silly fetch manifest restore-cursor@^3.1.0
199 silly fetch manifest chardet@^0.7.0
200 silly fetch manifest iconv-lite@^0.4.24
201 silly fetch manifest tmp@^0.0.33
202 silly fetch manifest escape-string-regexp@^1.0.5
203 silly fetch manifest emoji-regex@^8.0.0
204 silly fetch manifest is-fullwidth-code-point@^3.0.0
205 silly fetch manifest ansi-regex@^5.0.0
206 http fetch GET 304 http://registry.npmjs.org/restore-cursor 2954ms (from cache)
207 http fetch GET 304 http://registry.npmjs.org/iconv-lite 2955ms (from cache)
208 http fetch GET 304 http://registry.npmjs.org/tmp 3027ms (from cache)
209 http fetch GET 304 http://registry.npmjs.org/escape-string-regexp 3040ms (from cache)
210 http fetch GET 304 http://registry.npmjs.org/emoji-regex 3054ms (from cache)
211 http fetch GET 304 http://registry.npmjs.org/chardet 3129ms (from cache)
212 http fetch GET 304 http://registry.npmjs.org/is-fullwidth-code-point 5774ms (from cache)
213 http fetch GET 304 http://registry.npmjs.org/ansi-regex 5811ms (from cache)
214 timing idealTree:node_modules/create-react-app/node_modules/inquirer Completed in 5883ms
215 timing idealTree:node_modules/create-react-app/node_modules/ansi-escapes Completed in 0ms
216 silly placeDep node_modules/create-react-app restore-cursor@3.1.0 OK for: cli-cursor@3.1.0 want: ^3.1.0
217 silly fetch manifest onetime@^5.1.0
218 silly fetch manifest signal-exit@^3.0.2
219 http fetch GET 304 http://registry.npmjs.org/onetime 1230ms (from cache)
220 http fetch GET 304 http://registry.npmjs.org/signal-exit 1276ms (from cache)
221 timing idealTree:node_modules/create-react-app/node_modules/cli-cursor Completed in 1282ms
222 timing idealTree:node_modules/create-react-app/node_modules/cli-width Completed in 0ms
223 silly placeDep node_modules/create-react-app chardet@0.7.0 OK for: external-editor@3.1.0 want: ^0.7.0
224 silly placeDep node_modules/create-react-app iconv-lite@0.4.24 OK for: external-editor@3.1.0 want: ^0.4.24
225 silly placeDep node_modules/create-react-app/node_modules/external-editor tmp@0.0.33 OK for: external-editor@3.1.0 want: ^0.0.33
226 silly fetch manifest safer-buffer@>= 2.1.2 < 3
227 silly fetch manifest os-tmpdir@~1.0.2
228 http fetch GET 304 http://registry.npmjs.org/os-tmpdir 770ms (from cache)
229 http fetch GET 304 http://registry.npmjs.org/safer-buffer 783ms (from cache)
230 timing idealTree:node_modules/create-react-app/node_modules/external-editor Completed in 792ms
231 timing idealTree:node_modules/create-react-app/node_modules/chardet Completed in 0ms
232 silly placeDep node_modules/create-react-app escape-string-regexp@1.0.5 OK for: figures@3.2.0 want: ^1.0.5
233 timing idealTree:node_modules/create-react-app/node_modules/figures Completed in 3ms
234 timing idealTree:node_modules/create-react-app/node_modules/escape-string-regexp Completed in 0ms
235 silly placeDep node_modules/create-react-app safer-buffer@2.1.2 OK for: iconv-lite@0.4.24 want: >= 2.1.2 < 3
236 timing idealTree:node_modules/create-react-app/node_modules/iconv-lite Completed in 2ms
237 silly placeDep node_modules/create-react-app/node_modules/jsonfile universalify@2.0.0 OK for: jsonfile@6.1.0 want: ^2.0.0
238 timing idealTree:node_modules/create-react-app/node_modules/jsonfile Completed in 2ms
239 timing idealTree:node_modules/create-react-app/node_modules/lodash Completed in 1ms
240 timing idealTree:node_modules/create-react-app/node_modules/mute-stream Completed in 0ms
241 timing idealTree:node_modules/create-react-app/node_modules/path-key Completed in 0ms
242 silly placeDep node_modules/create-react-app core-util-is@1.0.2 OK for: readable-stream@1.1.14 want: ~1.0.0
243 silly placeDep node_modules/create-react-app inherits@2.0.4 OK for: readable-stream@1.1.14 want: ~2.0.1
244 silly placeDep node_modules/create-react-app isarray@0.0.1 OK for: readable-stream@1.1.14 want: 0.0.1
245 silly placeDep node_modules/create-react-app string_decoder@ OK for: readable-stream@1.1.14 want: ~0.10.x
246 timing idealTree:node_modules/create-react-app/node_modules/readable-stream Completed in 6ms
247 timing idealTree:node_modules/create-react-app/node_modules/core-util-is Completed in 1ms
248 timing idealTree:node_modules/create-react-app/node_modules/inherits Completed in 0ms
249 timing idealTree:node_modules/create-react-app/node_modules/isarray Completed in 0ms
250 silly placeDep node_modules/create-react-app onetime@5.1.2 OK for: restore-cursor@3.1.0 want: ^5.1.0
251 silly placeDep node_modules/create-react-app signal-exit@3.0.3 OK for: restore-cursor@3.1.0 want: ^3.0.2
252 silly fetch manifest mimic-fn@^2.1.0
253 http fetch GET 304 http://registry.npmjs.org/mimic-fn 525ms (from cache)
254 timing idealTree:node_modules/create-react-app/node_modules/restore-cursor Completed in 532ms
255 silly placeDep node_modules/create-react-app mimic-fn@2.1.0 OK for: onetime@5.1.2 want: ^2.1.0
256 timing idealTree:node_modules/create-react-app/node_modules/onetime Completed in 3ms
257 timing idealTree:node_modules/create-react-app/node_modules/mimic-fn Completed in 0ms
258 timing idealTree:node_modules/create-react-app/node_modules/run-async Completed in 0ms
259 timing idealTree:node_modules/create-react-app/node_modules/rxjs Completed in 0ms
260 timing idealTree:node_modules/create-react-app/node_modules/safer-buffer Completed in 0ms
261 timing idealTree:node_modules/create-react-app/node_modules/semver Completed in 0ms
262 silly placeDep node_modules/create-react-app shebang-regex@3.0.0 OK for: shebang-command@2.0.0 want: ^3.0.0
263 timing idealTree:node_modules/create-react-app/node_modules/shebang-command Completed in 3ms
264 timing idealTree:node_modules/create-react-app/node_modules/shebang-regex Completed in 0ms
265 timing idealTree:node_modules/create-react-app/node_modules/signal-exit Completed in 0ms
266 timing idealTree:node_modules/create-react-app/node_modules/string_decoder Completed in 0ms
267 silly placeDep node_modules/create-react-app emoji-regex@8.0.0 OK for: string-width@4.2.0 want: ^8.0.0
268 silly placeDep node_modules/create-react-app is-fullwidth-code-point@3.0.0 OK for: string-width@4.2.0 want: ^3.0.0
269 timing idealTree:node_modules/create-react-app/node_modules/string-width Completed in 5ms
270 timing idealTree:node_modules/create-react-app/node_modules/emoji-regex Completed in 0ms
271 timing idealTree:node_modules/create-react-app/node_modules/is-fullwidth-code-point Completed in 0ms
272 silly placeDep node_modules/create-react-app ansi-regex@5.0.0 OK for: strip-ansi@6.0.0 want: ^5.0.0
273 timing idealTree:node_modules/create-react-app/node_modules/strip-ansi Completed in 7ms
274 timing idealTree:node_modules/create-react-app/node_modules/ansi-regex Completed in 0ms
275 silly placeDep node_modules/create-react-app has-flag@4.0.0 OK for: supports-color@7.2.0 want: ^4.0.0
276 timing idealTree:node_modules/create-react-app/node_modules/supports-color Completed in 3ms
277 timing idealTree:node_modules/create-react-app/node_modules/has-flag Completed in 0ms
278 silly placeDep node_modules/create-react-app debug@ OK for: tar-pack@3.4.1 want: ^2.2.0
279 silly placeDep node_modules/create-react-app fstream@1.0.12 OK for: tar-pack@3.4.1 want: ^1.0.10
280 silly placeDep node_modules/create-react-app fstream-ignore@1.0.5 OK for: tar-pack@3.4.1 want: ^1.0.5
281 silly placeDep node_modules/create-react-app once@1.4.0 OK for: tar-pack@3.4.1 want: ^1.3.3
282 silly placeDep node_modules/create-react-app/node_modules/tar-pack readable-stream@2.3.7 OK for: tar-pack@3.4.1 want: ^2.1.4
283 silly placeDep node_modules/create-react-app rimraf@ OK for: tar-pack@3.4.1 want: ^2.5.1
284 silly placeDep node_modules/create-react-app tar@ OK for: tar-pack@3.4.1 want: ^2.2.1
285 silly placeDep node_modules/create-react-app uid-number@0.0.6 OK for: tar-pack@3.4.1 want: ^0.0.6
286 silly fetch manifest mkdirp@>=0.5 0
287 silly fetch manifest minimatch@^3.0.0
288 silly fetch manifest wrappy@1
289 silly fetch manifest isarray@~1.0.0
290 silly fetch manifest process-nextick-args@~2.0.0
291 silly fetch manifest safe-buffer@~5.1.1
292 silly fetch manifest util-deprecate@~1.0.1
293 http fetch GET 304 http://registry.npmjs.org/wrappy 1508ms (from cache)
294 http fetch GET 304 http://registry.npmjs.org/isarray 1522ms (from cache)
295 http fetch GET 304 http://registry.npmjs.org/minimatch 1553ms (from cache)
296 http fetch GET 304 http://registry.npmjs.org/util-deprecate 1596ms (from cache)
297 http fetch GET 304 http://registry.npmjs.org/mkdirp 1829ms (from cache)
298 http fetch GET 304 http://registry.npmjs.org/process-nextick-args 1841ms (from cache)
299 http fetch GET 304 http://registry.npmjs.org/safe-buffer 1892ms (from cache)
300 timing idealTree:node_modules/create-react-app/node_modules/tar-pack Completed in 1928ms
301 timing idealTree:node_modules/create-react-app/node_modules/debug Completed in 0ms
302 silly placeDep node_modules/create-react-app mkdirp@ OK for: fstream@1.0.12 want: >=0.5 0
303 timing idealTree:node_modules/create-react-app/node_modules/fstream Completed in 3ms
304 silly placeDep node_modules/create-react-app minimatch@ OK for: fstream-ignore@1.0.5 want: ^3.0.0
305 timing idealTree:node_modules/create-react-app/node_modules/fstream-ignore Completed in 2ms
306 timing idealTree:node_modules/create-react-app/node_modules/minimatch Completed in 0ms
307 timing idealTree:node_modules/create-react-app/node_modules/mkdirp Completed in 0ms
308 silly placeDep node_modules/create-react-app wrappy@1.0.2 OK for: once@1.4.0 want: 1
309 timing idealTree:node_modules/create-react-app/node_modules/once Completed in 2ms
310 timing idealTree:node_modules/create-react-app/node_modules/rimraf Completed in 0ms
311 timing idealTree:node_modules/create-react-app/node_modules/tar Completed in 0ms
312 timing idealTree:node_modules/create-react-app/node_modules/through Completed in 0ms
313 silly placeDep node_modules/create-react-app/node_modules/through2 readable-stream@1.0.34 OK for: through2@0.6.5 want: >=1.0.33-1 <1.1.0-0
314 silly placeDep node_modules/create-react-app xtend@4.0.2 OK for: through2@0.6.5 want: >=4.0.0 <4.1.0-0
315 timing idealTree:node_modules/create-react-app/node_modules/through2 Completed in 8ms
316 timing idealTree:node_modules/create-react-app/node_modules/tmp Completed in 0ms
317 timing idealTree:node_modules/create-react-app/node_modules/uid-number Completed in 0ms
318 timing idealTree:node_modules/create-react-app/node_modules/universalify Completed in 0ms
319 silly placeDep node_modules/create-react-app builtins@1.0.3 OK for: validate-npm-package-name@3.0.0 want: ^1.0.3
320 timing idealTree:node_modules/create-react-app/node_modules/validate-npm-package-name Completed in 3ms
321 timing idealTree:node_modules/create-react-app/node_modules/builtins Completed in 0ms
322 silly placeDep node_modules/create-react-app isexe@2.0.0 OK for: which@2.0.2 want: ^2.0.0
323 timing idealTree:node_modules/create-react-app/node_modules/which Completed in 2ms
324 timing idealTree:node_modules/create-react-app/node_modules/isexe Completed in 0ms
325 timing idealTree:node_modules/create-react-app/node_modules/wrappy Completed in 0ms
326 timing idealTree:node_modules/create-react-app/node_modules/xtend Completed in 0ms
327 silly placeDep node_modules/create-react-app os-tmpdir@1.0.2 OK for: tmp@0.0.33 want: ~1.0.2
328 timing idealTree:node_modules/create-react-app/node_modules/external-editor/node_modules/tmp Completed in 2ms
329 timing idealTree:node_modules/create-react-app/node_modules/os-tmpdir Completed in 0ms
330 timing idealTree:node_modules/create-react-app/node_modules/jsonfile/node_modules/universalify Completed in 0ms
331 silly placeDep node_modules/create-react-app/node_modules/tar-pack isarray@1.0.0 OK for: readable-stream@2.3.7 want: ~1.0.0
332 silly placeDep node_modules/create-react-app process-nextick-args@2.0.1 OK for: readable-stream@2.3.7 want: ~2.0.0
333 silly placeDep node_modules/create-react-app safe-buffer@5.1.2 OK for: readable-stream@2.3.7 want: ~5.1.1
334 silly placeDep node_modules/create-react-app util-deprecate@1.0.2 OK for: readable-stream@2.3.7 want: ~1.0.1
335 timing idealTree:node_modules/create-react-app/node_modules/tar-pack/node_modules/readable-stream Completed in 12ms
336 timing idealTree:node_modules/create-react-app/node_modules/process-nextick-args Completed in 0ms
337 timing idealTree:node_modules/create-react-app/node_modules/safe-buffer Completed in 0ms
338 timing idealTree:node_modules/create-react-app/node_modules/util-deprecate Completed in 0ms
339 timing idealTree:node_modules/create-react-app/node_modules/tar-pack/node_modules/isarray Completed in 0ms
340 timing idealTree:node_modules/create-react-app/node_modules/through2/node_modules/readable-stream Completed in 0ms
341 timing idealTree:buildDeps Completed in 79656ms
342 timing idealTree:fixDepFlags Completed in 5ms
343 timing idealTree Completed in 79674ms
344 timing command:install Completed in 79679ms
345 verbose type invalid-json
346 verbose stack FetchError: invalid json response body at http://registry.npmjs.org/ansi-escapes reason: Unexpected end of JSON input
346 verbose stack     at /usr/share/npm/node_modules/minipass-fetch/lib/body.js:77:31
346 verbose stack     at async Promise.all (index 12)
346 verbose stack     at async Arborist.[buildDepStep] (/usr/share/npm/node_modules/@npmcli/arborist/lib/arborist/build-ideal-tree.js:785:5)
346 verbose stack     at async Arborist.buildIdealTree (/usr/share/npm/node_modules/@npmcli/arborist/lib/arborist/build-ideal-tree.js:202:7)
346 verbose stack     at async Arborist.reify (/usr/share/npm/node_modules/@npmcli/arborist/lib/arborist/reify.js:121:5)
346 verbose stack     at async install (/usr/share/npm/lib/install.js:40:5)
347 verbose cwd /home/freduah
348 verbose Linux 5.5.0-kali2-amd64
349 verbose argv "/usr/bin/node" "/usr/bin/npm" "install" "-g" "create-react-app"
350 verbose node v12.19.0
351 verbose npm  v7.0.3
352 error code FETCH_ERROR
353 error errno FETCH_ERROR
354 error invalid json response body at http://registry.npmjs.org/ansi-escapes reason: Unexpected end of JSON input
355 verbose exit 1

```

答:
It happens when you have proxy related issues. I solved it following these steps:

```<code>npm cache clean --force

npm config rm proxy

npm config rm https-proxy

npm cache verify
</code>```

Delete the node_modules folder(if using existing package and then run below command otherwise just run below command in CLI)

```<code>npm set registry=https://registry.npmjs.org/
</code>```

then try again whatever you have been installing the new package or just installing node_modules, if it gives you the same error then I recommend you to restart your laptop and run again these above commands

Body:
I have nodejs and npm installed
I tried running the command

npm install -g create-react-app

but it halts at the error below

freduah@freduah:~$ npm install -g create-react-app
npm WARN registry Unexpected warning for http://registry.npmjs.org/: Miscellaneous Warning EAI_AGAIN: request to http://registry.npmjs.org/create-react-app failed, reason: getaddrinfo EAI_AGAIN registry.npmjs.org
npm WARN registry Using stale data from http://registry.npmjs.org/ due to a request error during revalidation.
npm ERR! code FETCH_ERROR
npm ERR! errno FETCH_ERROR
npm ERR! invalid json response body at http://registry.npmjs.org/ansi-escapes reason: Unexpected end of JSON input

npm ERR! A complete log of this run can be found in:
npm ERR!     /home/freduah/.npm/_logs/2020-10-31T19_11_20_727Z-debug.log
freduah@freduah:~$

Below Is The Full Error Log Content

freduah@freduah:~/Downloads$ cat /home/freduah/.npm/_logs/2020-10-31T19_11_20_727Z-debug.log
0 verbose cli [
0 verbose cli   '/usr/bin/node',
0 verbose cli   '/usr/bin/npm',
0 verbose cli   'install',
0 verbose cli   '-g',
0 verbose cli   'create-react-app'
0 verbose cli ]
1 info using npm@7.0.3
2 info using node@v12.19.0
3 timing config:load:defaults Completed in 2ms
4 timing config:load:file:/usr/share/npm/npmrc Completed in 3ms
5 timing config:load:builtin Completed in 3ms
6 timing config:load:cli Completed in 4ms
7 timing config:load:env Completed in 0ms
8 timing config:load:project Completed in 1ms
9 timing config:load:file:/home/freduah/.npmrc Completed in 1ms
10 timing config:load:user Completed in 1ms
11 timing config:load:file:/etc/npmrc Completed in 0ms
12 timing config:load:global Completed in 0ms
13 timing config:load:cafile Completed in 0ms
14 timing config:load:validate Completed in 2ms
15 timing config:load:setUserAgent Completed in 1ms
16 timing config:load:setEnvs Completed in 1ms
17 timing config:load Completed in 15ms
18 verbose npm-session 3fe07c2ad8478ec0
19 timing npm:load Completed in 27ms
20 timing arborist:ctor Completed in 1ms
21 timing idealTree:init Completed in 3ms
22 timing idealTree:userRequests Completed in 8ms
23 silly idealTree buildDeps
24 silly fetch manifest create-react-app@*
25 warn registry Unexpected warning for http://registry.npmjs.org/: Miscellaneous Warning EAI_AGAIN: request to http://registry.npmjs.org/create-react-app failed, reason: getaddrinfo EAI_AGAIN registry.npmjs.org
26 warn registry Using stale data from http://registry.npmjs.org/ due to a request error during revalidation.
27 http fetch GET 200 http://registry.npmjs.org/create-react-app 10087ms (from cache)
28 silly placeDep ROOT create-react-app@4.0.0 OK for:  want: *
29 silly fetch manifest chalk@4.1.0
30 silly fetch manifest commander@4.1.1
31 silly fetch manifest cross-spawn@7.0.3
32 silly fetch manifest envinfo@7.7.3
33 silly fetch manifest fs-extra@9.0.1
34 silly fetch manifest hyperquest@2.1.3
35 silly fetch manifest inquirer@7.3.3
36 silly fetch manifest semver@7.3.2
37 silly fetch manifest tar-pack@3.4.1
38 silly fetch manifest tmp@0.2.1
39 silly fetch manifest validate-npm-package-name@3.0.0
40 http fetch GET 304 http://registry.npmjs.org/envinfo 23286ms (from cache)
41 http fetch GET 304 http://registry.npmjs.org/cross-spawn 23292ms (from cache)
42 http fetch GET 304 http://registry.npmjs.org/fs-extra 23665ms (from cache)
43 http fetch GET 304 http://registry.npmjs.org/hyperquest 24552ms (from cache)
44 http fetch GET 304 http://registry.npmjs.org/semver 28953ms (from cache)
45 http fetch GET 304 http://registry.npmjs.org/inquirer 28960ms (from cache)
46 http fetch GET 304 http://registry.npmjs.org/tar-pack 29245ms (from cache)
47 http fetch GET 304 http://registry.npmjs.org/tmp 29303ms (from cache)
48 http fetch GET 304 http://registry.npmjs.org/validate-npm-package-name 30877ms (from cache)
49 http fetch GET 304 http://registry.npmjs.org/chalk 36204ms attempt #2 (from cache)
50 http fetch GET 304 http://registry.npmjs.org/commander 36204ms attempt #2 (from cache)
51 timing idealTree:#root Completed in 46313ms
52 silly placeDep node_modules/create-react-app chalk@4.1.0 OK for: create-react-app@4.0.0 want: 4.1.0
53 silly placeDep node_modules/create-react-app commander@4.1.1 OK for: create-react-app@4.0.0 want: 4.1.1
54 silly placeDep node_modules/create-react-app cross-spawn@7.0.3 OK for: create-react-app@4.0.0 want: 7.0.3
55 silly placeDep node_modules/create-react-app envinfo@7.7.3 OK for: create-react-app@4.0.0 want: 7.7.3
56 silly placeDep node_modules/create-react-app fs-extra@9.0.1 OK for: create-react-app@4.0.0 want: 9.0.1
57 silly placeDep node_modules/create-react-app hyperquest@2.1.3 OK for: create-react-app@4.0.0 want: 2.1.3
58 silly placeDep node_modules/create-react-app inquirer@7.3.3 OK for: create-react-app@4.0.0 want: 7.3.3
59 silly placeDep node_modules/create-react-app semver@7.3.2 OK for: create-react-app@4.0.0 want: 7.3.2
60 silly placeDep node_modules/create-react-app tar-pack@3.4.1 OK for: create-react-app@4.0.0 want: 3.4.1
61 silly placeDep node_modules/create-react-app tmp@0.2.1 OK for: create-react-app@4.0.0 want: 0.2.1
62 silly placeDep node_modules/create-react-app validate-npm-package-name@3.0.0 OK for: create-react-app@4.0.0 want: 3.0.0
63 silly fetch manifest ansi-styles@^4.1.0
64 silly fetch manifest supports-color@^7.1.0
65 silly fetch manifest path-key@^3.1.0
66 silly fetch manifest shebang-command@^2.0.0
67 silly fetch manifest which@^2.0.1
68 silly fetch manifest at-least-node@^1.0.0
69 silly fetch manifest graceful-fs@^4.2.0
70 silly fetch manifest jsonfile@^6.0.1
71 silly fetch manifest universalify@^1.0.0
72 silly fetch manifest buffer-from@^0.1.1
73 silly fetch manifest duplexer2@~0.0.2
74 silly fetch manifest through2@~0.6.3
75 silly fetch manifest ansi-escapes@^4.2.1
76 silly fetch manifest cli-cursor@^3.1.0
77 silly fetch manifest cli-width@^3.0.0
78 silly fetch manifest external-editor@^3.0.3
79 silly fetch manifest figures@^3.0.0
80 silly fetch manifest lodash@^4.17.19
81 silly fetch manifest mute-stream@0.0.8
82 silly fetch manifest run-async@^2.4.0
83 silly fetch manifest rxjs@^6.6.0
84 silly fetch manifest string-width@^4.1.0
85 silly fetch manifest strip-ansi@^6.0.0
86 silly fetch manifest through@^2.3.6
87 silly fetch manifest debug@^2.2.0
88 silly fetch manifest fstream@^1.0.10
89 silly fetch manifest fstream-ignore@^1.0.5
90 silly fetch manifest once@^1.3.3
91 silly fetch manifest readable-stream@^2.1.4
92 silly fetch manifest rimraf@^2.5.1
93 silly fetch manifest tar@^2.2.1
94 silly fetch manifest uid-number@^0.0.6
95 silly fetch manifest rimraf@^3.0.0
96 silly fetch manifest builtins@^1.0.3
97 http fetch GET 200 http://registry.npmjs.org/jsonfile 240ms (from cache)
98 http fetch GET 304 http://registry.npmjs.org/ansi-styles 1807ms (from cache)
99 http fetch GET 304 http://registry.npmjs.org/supports-color 1806ms (from cache)
100 http fetch GET 304 http://registry.npmjs.org/which 1866ms (from cache)
101 http fetch GET 304 http://registry.npmjs.org/path-key 1893ms (from cache)
102 http fetch GET 304 http://registry.npmjs.org/at-least-node 1933ms (from cache)
103 http fetch GET 304 http://registry.npmjs.org/graceful-fs 1974ms (from cache)
104 http fetch GET 304 http://registry.npmjs.org/cli-cursor 2773ms (from cache)
105 http fetch GET 304 http://registry.npmjs.org/cli-width 2804ms (from cache)
106 http fetch GET 304 http://registry.npmjs.org/external-editor 2929ms (from cache)
107 http fetch GET 304 http://registry.npmjs.org/mute-stream 2956ms (from cache)
108 http fetch GET 304 http://registry.npmjs.org/lodash 2960ms (from cache)
109 http fetch GET 304 http://registry.npmjs.org/figures 3064ms (from cache)
110 http fetch GET 304 http://registry.npmjs.org/run-async 3500ms (from cache)
111 http fetch GET 304 http://registry.npmjs.org/rxjs 3522ms (from cache)
112 http fetch GET 304 http://registry.npmjs.org/string-width 3555ms (from cache)
113 http fetch GET 304 http://registry.npmjs.org/universalify 3677ms (from cache)
114 http fetch GET 304 http://registry.npmjs.org/buffer-from 3687ms (from cache)
115 http fetch GET 304 http://registry.npmjs.org/strip-ansi 3660ms (from cache)
116 http fetch GET 304 http://registry.npmjs.org/through 3681ms (from cache)
117 http fetch GET 304 http://registry.npmjs.org/debug 3784ms (from cache)
118 http fetch GET 304 http://registry.npmjs.org/fstream 4015ms (from cache)
119 http fetch GET 304 http://registry.npmjs.org/duplexer2 4169ms (from cache)
120 http fetch GET 304 http://registry.npmjs.org/through2 4179ms (from cache)
121 http fetch GET 304 http://registry.npmjs.org/fstream-ignore 4133ms (from cache)
122 http fetch GET 304 http://registry.npmjs.org/readable-stream 4169ms (from cache)
123 http fetch GET 304 http://registry.npmjs.org/rimraf 4200ms (from cache)
124 http fetch GET 304 http://registry.npmjs.org/uid-number 4526ms (from cache)
125 http fetch GET 304 http://registry.npmjs.org/builtins 4520ms (from cache)
126 http fetch GET 304 http://registry.npmjs.org/rimraf 4536ms (from cache)
127 http fetch GET 304 http://registry.npmjs.org/ansi-escapes 4660ms (from cache)
128 http fetch GET 304 http://registry.npmjs.org/tar 4601ms (from cache)
129 http fetch GET 304 http://registry.npmjs.org/shebang-command 5758ms (from cache)
130 http fetch GET 304 http://registry.npmjs.org/once 9981ms (from cache)
131 timing idealTree:node_modules/create-react-app Completed in 10102ms
132 silly placeDep node_modules/create-react-app ansi-styles@4.3.0 OK for: chalk@4.1.0 want: ^4.1.0
133 silly placeDep node_modules/create-react-app supports-color@7.2.0 OK for: chalk@4.1.0 want: ^7.1.0
134 silly fetch manifest color-convert@^2.0.1
135 silly fetch manifest has-flag@^4.0.0
136 http fetch GET 304 http://registry.npmjs.org/has-flag 4131ms (from cache)
137 http fetch GET 304 http://registry.npmjs.org/color-convert 4168ms (from cache)
138 timing idealTree:node_modules/create-react-app/node_modules/chalk Completed in 4176ms
139 silly placeDep node_modules/create-react-app color-convert@2.0.1 OK for: ansi-styles@4.3.0 want: ^2.0.1
140 silly fetch manifest color-name@~1.1.4
141 http fetch GET 304 http://registry.npmjs.org/color-name 3286ms (from cache)
142 timing idealTree:node_modules/create-react-app/node_modules/ansi-styles Completed in 3291ms
143 silly placeDep node_modules/create-react-app color-name@1.1.4 OK for: color-convert@2.0.1 want: ~1.1.4
144 timing idealTree:node_modules/create-react-app/node_modules/color-convert Completed in 2ms
145 timing idealTree:node_modules/create-react-app/node_modules/color-name Completed in 0ms
146 timing idealTree:node_modules/create-react-app/node_modules/commander Completed in 0ms
147 silly placeDep node_modules/create-react-app path-key@3.1.1 OK for: cross-spawn@7.0.3 want: ^3.1.0
148 silly placeDep node_modules/create-react-app shebang-command@2.0.0 OK for: cross-spawn@7.0.3 want: ^2.0.0
149 silly placeDep node_modules/create-react-app which@2.0.2 OK for: cross-spawn@7.0.3 want: ^2.0.1
150 silly fetch manifest shebang-regex@^3.0.0
151 silly fetch manifest isexe@^2.0.0
152 http fetch GET 304 http://registry.npmjs.org/shebang-regex 1543ms (from cache)
153 http fetch GET 304 http://registry.npmjs.org/isexe 2212ms (from cache)
154 timing idealTree:node_modules/create-react-app/node_modules/cross-spawn Completed in 2223ms
155 timing idealTree:node_modules/create-react-app/node_modules/envinfo Completed in 0ms
156 silly placeDep node_modules/create-react-app at-least-node@1.0.0 OK for: fs-extra@9.0.1 want: ^1.0.0
157 silly placeDep node_modules/create-react-app graceful-fs@4.2.4 OK for: fs-extra@9.0.1 want: ^4.2.0
158 silly placeDep node_modules/create-react-app jsonfile@6.1.0 OK for: fs-extra@9.0.1 want: ^6.0.1
159 silly placeDep node_modules/create-react-app universalify@1.0.0 OK for: fs-extra@9.0.1 want: ^1.0.0
160 silly fetch manifest universalify@^2.0.0
161 http fetch GET 304 http://registry.npmjs.org/universalify 387ms (from cache)
162 timing idealTree:node_modules/create-react-app/node_modules/fs-extra Completed in 399ms
163 timing idealTree:node_modules/create-react-app/node_modules/at-least-node Completed in 0ms
164 timing idealTree:node_modules/create-react-app/node_modules/graceful-fs Completed in 0ms
165 silly placeDep node_modules/create-react-app buffer-from@0.1.2 OK for: hyperquest@2.1.3 want: ^0.1.1
166 silly placeDep node_modules/create-react-app duplexer2@0.0.2 OK for: hyperquest@2.1.3 want: ~0.0.2
167 silly placeDep node_modules/create-react-app through2@0.6.5 OK for: hyperquest@2.1.3 want: ~0.6.3
168 silly fetch manifest readable-stream@~1.1.9
169 silly fetch manifest readable-stream@>=1.0.33-1 <1.1.0-0
170 silly fetch manifest xtend@>=4.0.0 <4.1.0-0
171 http fetch GET 304 http://registry.npmjs.org/readable-stream 391ms (from cache)
172 http fetch GET 304 http://registry.npmjs.org/readable-stream 468ms (from cache)
173 http fetch GET 304 http://registry.npmjs.org/xtend 568ms (from cache)
174 timing idealTree:node_modules/create-react-app/node_modules/hyperquest Completed in 581ms
175 timing idealTree:node_modules/create-react-app/node_modules/buffer-from Completed in 0ms
176 silly placeDep node_modules/create-react-app readable-stream@1.1.14 OK for: duplexer2@0.0.2 want: ~1.1.9
177 silly fetch manifest core-util-is@~1.0.0
178 silly fetch manifest isarray@0.0.1
179 silly fetch manifest string_decoder@~0.10.x
180 silly fetch manifest inherits@~2.0.1
181 http fetch GET 304 http://registry.npmjs.org/string_decoder 1910ms (from cache)
182 http fetch GET 304 http://registry.npmjs.org/inherits 1923ms (from cache)
183 http fetch GET 304 http://registry.npmjs.org/isarray 2011ms (from cache)
184 http fetch GET 304 http://registry.npmjs.org/core-util-is 2059ms (from cache)
185 timing idealTree:node_modules/create-react-app/node_modules/duplexer2 Completed in 2066ms
186 silly placeDep node_modules/create-react-app ansi-escapes@ OK for: inquirer@7.3.3 want: ^4.2.1
187 silly placeDep node_modules/create-react-app cli-cursor@3.1.0 OK for: inquirer@7.3.3 want: ^3.1.0
188 silly placeDep node_modules/create-react-app cli-width@3.0.0 OK for: inquirer@7.3.3 want: ^3.0.0
189 silly placeDep node_modules/create-react-app external-editor@3.1.0 OK for: inquirer@7.3.3 want: ^3.0.3
190 silly placeDep node_modules/create-react-app figures@3.2.0 OK for: inquirer@7.3.3 want: ^3.0.0
191 silly placeDep node_modules/create-react-app lodash@ OK for: inquirer@7.3.3 want: ^4.17.19
192 silly placeDep node_modules/create-react-app mute-stream@0.0.8 OK for: inquirer@7.3.3 want: 0.0.8
193 silly placeDep node_modules/create-react-app run-async@2.4.1 OK for: inquirer@7.3.3 want: ^2.4.0
194 silly placeDep node_modules/create-react-app rxjs@ OK for: inquirer@7.3.3 want: ^6.6.0
195 silly placeDep node_modules/create-react-app string-width@4.2.0 OK for: inquirer@7.3.3 want: ^4.1.0
196 silly placeDep node_modules/create-react-app strip-ansi@6.0.0 OK for: inquirer@7.3.3 want: ^6.0.0
197 silly placeDep node_modules/create-react-app through@2.3.8 OK for: inquirer@7.3.3 want: ^2.3.6
198 silly fetch manifest restore-cursor@^3.1.0
199 silly fetch manifest chardet@^0.7.0
200 silly fetch manifest iconv-lite@^0.4.24
201 silly fetch manifest tmp@^0.0.33
202 silly fetch manifest escape-string-regexp@^1.0.5
203 silly fetch manifest emoji-regex@^8.0.0
204 silly fetch manifest is-fullwidth-code-point@^3.0.0
205 silly fetch manifest ansi-regex@^5.0.0
206 http fetch GET 304 http://registry.npmjs.org/restore-cursor 2954ms (from cache)
207 http fetch GET 304 http://registry.npmjs.org/iconv-lite 2955ms (from cache)
208 http fetch GET 304 http://registry.npmjs.org/tmp 3027ms (from cache)
209 http fetch GET 304 http://registry.npmjs.org/escape-string-regexp 3040ms (from cache)
210 http fetch GET 304 http://registry.npmjs.org/emoji-regex 3054ms (from cache)
211 http fetch GET 304 http://registry.npmjs.org/chardet 3129ms (from cache)
212 http fetch GET 304 http://registry.npmjs.org/is-fullwidth-code-point 5774ms (from cache)
213 http fetch GET 304 http://registry.npmjs.org/ansi-regex 5811ms (from cache)
214 timing idealTree:node_modules/create-react-app/node_modules/inquirer Completed in 5883ms
215 timing idealTree:node_modules/create-react-app/node_modules/ansi-escapes Completed in 0ms
216 silly placeDep node_modules/create-react-app restore-cursor@3.1.0 OK for: cli-cursor@3.1.0 want: ^3.1.0
217 silly fetch manifest onetime@^5.1.0
218 silly fetch manifest signal-exit@^3.0.2
219 http fetch GET 304 http://registry.npmjs.org/onetime 1230ms (from cache)
220 http fetch GET 304 http://registry.npmjs.org/signal-exit 1276ms (from cache)
221 timing idealTree:node_modules/create-react-app/node_modules/cli-cursor Completed in 1282ms
222 timing idealTree:node_modules/create-react-app/node_modules/cli-width Completed in 0ms
223 silly placeDep node_modules/create-react-app chardet@0.7.0 OK for: external-editor@3.1.0 want: ^0.7.0
224 silly placeDep node_modules/create-react-app iconv-lite@0.4.24 OK for: external-editor@3.1.0 want: ^0.4.24
225 silly placeDep node_modules/create-react-app/node_modules/external-editor tmp@0.0.33 OK for: external-editor@3.1.0 want: ^0.0.33
226 silly fetch manifest safer-buffer@>= 2.1.2 < 3
227 silly fetch manifest os-tmpdir@~1.0.2
228 http fetch GET 304 http://registry.npmjs.org/os-tmpdir 770ms (from cache)
229 http fetch GET 304 http://registry.npmjs.org/safer-buffer 783ms (from cache)
230 timing idealTree:node_modules/create-react-app/node_modules/external-editor Completed in 792ms
231 timing idealTree:node_modules/create-react-app/node_modules/chardet Completed in 0ms
232 silly placeDep node_modules/create-react-app escape-string-regexp@1.0.5 OK for: figures@3.2.0 want: ^1.0.5
233 timing idealTree:node_modules/create-react-app/node_modules/figures Completed in 3ms
234 timing idealTree:node_modules/create-react-app/node_modules/escape-string-regexp Completed in 0ms
235 silly placeDep node_modules/create-react-app safer-buffer@2.1.2 OK for: iconv-lite@0.4.24 want: >= 2.1.2 < 3
236 timing idealTree:node_modules/create-react-app/node_modules/iconv-lite Completed in 2ms
237 silly placeDep node_modules/create-react-app/node_modules/jsonfile universalify@2.0.0 OK for: jsonfile@6.1.0 want: ^2.0.0
238 timing idealTree:node_modules/create-react-app/node_modules/jsonfile Completed in 2ms
239 timing idealTree:node_modules/create-react-app/node_modules/lodash Completed in 1ms
240 timing idealTree:node_modules/create-react-app/node_modules/mute-stream Completed in 0ms
241 timing idealTree:node_modules/create-react-app/node_modules/path-key Completed in 0ms
242 silly placeDep node_modules/create-react-app core-util-is@1.0.2 OK for: readable-stream@1.1.14 want: ~1.0.0
243 silly placeDep node_modules/create-react-app inherits@2.0.4 OK for: readable-stream@1.1.14 want: ~2.0.1
244 silly placeDep node_modules/create-react-app isarray@0.0.1 OK for: readable-stream@1.1.14 want: 0.0.1
245 silly placeDep node_modules/create-react-app string_decoder@ OK for: readable-stream@1.1.14 want: ~0.10.x
246 timing idealTree:node_modules/create-react-app/node_modules/readable-stream Completed in 6ms
247 timing idealTree:node_modules/create-react-app/node_modules/core-util-is Completed in 1ms
248 timing idealTree:node_modules/create-react-app/node_modules/inherits Completed in 0ms
249 timing idealTree:node_modules/create-react-app/node_modules/isarray Completed in 0ms
250 silly placeDep node_modules/create-react-app onetime@5.1.2 OK for: restore-cursor@3.1.0 want: ^5.1.0
251 silly placeDep node_modules/create-react-app signal-exit@3.0.3 OK for: restore-cursor@3.1.0 want: ^3.0.2
252 silly fetch manifest mimic-fn@^2.1.0
253 http fetch GET 304 http://registry.npmjs.org/mimic-fn 525ms (from cache)
254 timing idealTree:node_modules/create-react-app/node_modules/restore-cursor Completed in 532ms
255 silly placeDep node_modules/create-react-app mimic-fn@2.1.0 OK for: onetime@5.1.2 want: ^2.1.0
256 timing idealTree:node_modules/create-react-app/node_modules/onetime Completed in 3ms
257 timing idealTree:node_modules/create-react-app/node_modules/mimic-fn Completed in 0ms
258 timing idealTree:node_modules/create-react-app/node_modules/run-async Completed in 0ms
259 timing idealTree:node_modules/create-react-app/node_modules/rxjs Completed in 0ms
260 timing idealTree:node_modules/create-react-app/node_modules/safer-buffer Completed in 0ms
261 timing idealTree:node_modules/create-react-app/node_modules/semver Completed in 0ms
262 silly placeDep node_modules/create-react-app shebang-regex@3.0.0 OK for: shebang-command@2.0.0 want: ^3.0.0
263 timing idealTree:node_modules/create-react-app/node_modules/shebang-command Completed in 3ms
264 timing idealTree:node_modules/create-react-app/node_modules/shebang-regex Completed in 0ms
265 timing idealTree:node_modules/create-react-app/node_modules/signal-exit Completed in 0ms
266 timing idealTree:node_modules/create-react-app/node_modules/string_decoder Completed in 0ms
267 silly placeDep node_modules/create-react-app emoji-regex@8.0.0 OK for: string-width@4.2.0 want: ^8.0.0
268 silly placeDep node_modules/create-react-app is-fullwidth-code-point@3.0.0 OK for: string-width@4.2.0 want: ^3.0.0
269 timing idealTree:node_modules/create-react-app/node_modules/string-width Completed in 5ms
270 timing idealTree:node_modules/create-react-app/node_modules/emoji-regex Completed in 0ms
271 timing idealTree:node_modules/create-react-app/node_modules/is-fullwidth-code-point Completed in 0ms
272 silly placeDep node_modules/create-react-app ansi-regex@5.0.0 OK for: strip-ansi@6.0.0 want: ^5.0.0
273 timing idealTree:node_modules/create-react-app/node_modules/strip-ansi Completed in 7ms
274 timing idealTree:node_modules/create-react-app/node_modules/ansi-regex Completed in 0ms
275 silly placeDep node_modules/create-react-app has-flag@4.0.0 OK for: supports-color@7.2.0 want: ^4.0.0
276 timing idealTree:node_modules/create-react-app/node_modules/supports-color Completed in 3ms
277 timing idealTree:node_modules/create-react-app/node_modules/has-flag Completed in 0ms
278 silly placeDep node_modules/create-react-app debug@ OK for: tar-pack@3.4.1 want: ^2.2.0
279 silly placeDep node_modules/create-react-app fstream@1.0.12 OK for: tar-pack@3.4.1 want: ^1.0.10
280 silly placeDep node_modules/create-react-app fstream-ignore@1.0.5 OK for: tar-pack@3.4.1 want: ^1.0.5
281 silly placeDep node_modules/create-react-app once@1.4.0 OK for: tar-pack@3.4.1 want: ^1.3.3
282 silly placeDep node_modules/create-react-app/node_modules/tar-pack readable-stream@2.3.7 OK for: tar-pack@3.4.1 want: ^2.1.4
283 silly placeDep node_modules/create-react-app rimraf@ OK for: tar-pack@3.4.1 want: ^2.5.1
284 silly placeDep node_modules/create-react-app tar@ OK for: tar-pack@3.4.1 want: ^2.2.1
285 silly placeDep node_modules/create-react-app uid-number@0.0.6 OK for: tar-pack@3.4.1 want: ^0.0.6
286 silly fetch manifest mkdirp@>=0.5 0
287 silly fetch manifest minimatch@^3.0.0
288 silly fetch manifest wrappy@1
289 silly fetch manifest isarray@~1.0.0
290 silly fetch manifest process-nextick-args@~2.0.0
291 silly fetch manifest safe-buffer@~5.1.1
292 silly fetch manifest util-deprecate@~1.0.1
293 http fetch GET 304 http://registry.npmjs.org/wrappy 1508ms (from cache)
294 http fetch GET 304 http://registry.npmjs.org/isarray 1522ms (from cache)
295 http fetch GET 304 http://registry.npmjs.org/minimatch 1553ms (from cache)
296 http fetch GET 304 http://registry.npmjs.org/util-deprecate 1596ms (from cache)
297 http fetch GET 304 http://registry.npmjs.org/mkdirp 1829ms (from cache)
298 http fetch GET 304 http://registry.npmjs.org/process-nextick-args 1841ms (from cache)
299 http fetch GET 304 http://registry.npmjs.org/safe-buffer 1892ms (from cache)
300 timing idealTree:node_modules/create-react-app/node_modules/tar-pack Completed in 1928ms
301 timing idealTree:node_modules/create-react-app/node_modules/debug Completed in 0ms
302 silly placeDep node_modules/create-react-app mkdirp@ OK for: fstream@1.0.12 want: >=0.5 0
303 timing idealTree:node_modules/create-react-app/node_modules/fstream Completed in 3ms
304 silly placeDep node_modules/create-react-app minimatch@ OK for: fstream-ignore@1.0.5 want: ^3.0.0
305 timing idealTree:node_modules/create-react-app/node_modules/fstream-ignore Completed in 2ms
306 timing idealTree:node_modules/create-react-app/node_modules/minimatch Completed in 0ms
307 timing idealTree:node_modules/create-react-app/node_modules/mkdirp Completed in 0ms
308 silly placeDep node_modules/create-react-app wrappy@1.0.2 OK for: once@1.4.0 want: 1
309 timing idealTree:node_modules/create-react-app/node_modules/once Completed in 2ms
310 timing idealTree:node_modules/create-react-app/node_modules/rimraf Completed in 0ms
311 timing idealTree:node_modules/create-react-app/node_modules/tar Completed in 0ms
312 timing idealTree:node_modules/create-react-app/node_modules/through Completed in 0ms
313 silly placeDep node_modules/create-react-app/node_modules/through2 readable-stream@1.0.34 OK for: through2@0.6.5 want: >=1.0.33-1 <1.1.0-0
314 silly placeDep node_modules/create-react-app xtend@4.0.2 OK for: through2@0.6.5 want: >=4.0.0 <4.1.0-0
315 timing idealTree:node_modules/create-react-app/node_modules/through2 Completed in 8ms
316 timing idealTree:node_modules/create-react-app/node_modules/tmp Completed in 0ms
317 timing idealTree:node_modules/create-react-app/node_modules/uid-number Completed in 0ms
318 timing idealTree:node_modules/create-react-app/node_modules/universalify Completed in 0ms
319 silly placeDep node_modules/create-react-app builtins@1.0.3 OK for: validate-npm-package-name@3.0.0 want: ^1.0.3
320 timing idealTree:node_modules/create-react-app/node_modules/validate-npm-package-name Completed in 3ms
321 timing idealTree:node_modules/create-react-app/node_modules/builtins Completed in 0ms
322 silly placeDep node_modules/create-react-app isexe@2.0.0 OK for: which@2.0.2 want: ^2.0.0
323 timing idealTree:node_modules/create-react-app/node_modules/which Completed in 2ms
324 timing idealTree:node_modules/create-react-app/node_modules/isexe Completed in 0ms
325 timing idealTree:node_modules/create-react-app/node_modules/wrappy Completed in 0ms
326 timing idealTree:node_modules/create-react-app/node_modules/xtend Completed in 0ms
327 silly placeDep node_modules/create-react-app os-tmpdir@1.0.2 OK for: tmp@0.0.33 want: ~1.0.2
328 timing idealTree:node_modules/create-react-app/node_modules/external-editor/node_modules/tmp Completed in 2ms
329 timing idealTree:node_modules/create-react-app/node_modules/os-tmpdir Completed in 0ms
330 timing idealTree:node_modules/create-react-app/node_modules/jsonfile/node_modules/universalify Completed in 0ms
331 silly placeDep node_modules/create-react-app/node_modules/tar-pack isarray@1.0.0 OK for: readable-stream@2.3.7 want: ~1.0.0
332 silly placeDep node_modules/create-react-app process-nextick-args@2.0.1 OK for: readable-stream@2.3.7 want: ~2.0.0
333 silly placeDep node_modules/create-react-app safe-buffer@5.1.2 OK for: readable-stream@2.3.7 want: ~5.1.1
334 silly placeDep node_modules/create-react-app util-deprecate@1.0.2 OK for: readable-stream@2.3.7 want: ~1.0.1
335 timing idealTree:node_modules/create-react-app/node_modules/tar-pack/node_modules/readable-stream Completed in 12ms
336 timing idealTree:node_modules/create-react-app/node_modules/process-nextick-args Completed in 0ms
337 timing idealTree:node_modules/create-react-app/node_modules/safe-buffer Completed in 0ms
338 timing idealTree:node_modules/create-react-app/node_modules/util-deprecate Completed in 0ms
339 timing idealTree:node_modules/create-react-app/node_modules/tar-pack/node_modules/isarray Completed in 0ms
340 timing idealTree:node_modules/create-react-app/node_modules/through2/node_modules/readable-stream Completed in 0ms
341 timing idealTree:buildDeps Completed in 79656ms
342 timing idealTree:fixDepFlags Completed in 5ms
343 timing idealTree Completed in 79674ms
344 timing command:install Completed in 79679ms
345 verbose type invalid-json
346 verbose stack FetchError: invalid json response body at http://registry.npmjs.org/ansi-escapes reason: Unexpected end of JSON input
346 verbose stack     at /usr/share/npm/node_modules/minipass-fetch/lib/body.js:77:31
346 verbose stack     at async Promise.all (index 12)
346 verbose stack     at async Arborist.[buildDepStep] (/usr/share/npm/node_modules/@npmcli/arborist/lib/arborist/build-ideal-tree.js:785:5)
346 verbose stack     at async Arborist.buildIdealTree (/usr/share/npm/node_modules/@npmcli/arborist/lib/arborist/build-ideal-tree.js:202:7)
346 verbose stack     at async Arborist.reify (/usr/share/npm/node_modules/@npmcli/arborist/lib/arborist/reify.js:121:5)
346 verbose stack     at async install (/usr/share/npm/lib/install.js:40:5)
347 verbose cwd /home/freduah
348 verbose Linux 5.5.0-kali2-amd64
349 verbose argv "/usr/bin/node" "/usr/bin/npm" "install" "-g" "create-react-app"
350 verbose node v12.19.0
351 verbose npm  v7.0.3
352 error code FETCH_ERROR
353 error errno FETCH_ERROR
354 error invalid json response body at http://registry.npmjs.org/ansi-escapes reason: Unexpected end of JSON input
355 verbose exit 1

Body:
It happens when you have proxy related issues. I solved it following these steps:

npm cache clean --force

npm config rm proxy

npm config rm https-proxy

npm cache verify

Delete the node_modules folder(if using existing package and then run below command otherwise just run below command in CLI)

npm set registry=https://registry.npmjs.org/

then try again whatever you have been installing the new package or just installing node_modules, if it gives you the same error then I recommend you to restart your laptop and run again these above commands


来源: stackexchange

问:
How to replace deprecated SeekToCurrentErrorHandler with DefaultErrorHandler (spring-kafka)?
I am trying to find a way to use the new DefaultErrorHandler instead of deprecated SeekToCurrentErrorHandler in spring-kafka 2.8.1, in order to override the retry default behavior in case of errors. I want to "stop" the retry process, so if an error occurs, no retry should be done.

Now I have, in a config class, the following bean that works as expected:

```<code>@Bean
public KafkaListenerContainerFactory<ConcurrentMessageListenerContainer<String, String>> kafkaListenerContainerFactory() {
    ConcurrentKafkaListenerContainerFactory<String, String> factory = new ConcurrentKafkaListenerContainerFactory<>();
    factory.setErrorHandler(new **SeekToCurrentErrorHandler(new FixedBackOff(0L, 1L)**));
    factory.setConsumerFactory(requestConsumerFactory());
    factory.setReplyTemplate(kafkaTemplate());
    return factory;
}
</code>```

Since in this spring kafka version, the STCEH is deprecated, I tried to do the following, in the same config class:

```<code>@Bean
public DefaultErrorHandler eh() {
    return new DefaultErrorHandler(new FixedBackOff(0, 1));
}
</code>```

But it seems that it is not working. In case of error, the retry number is the default one, as I can see in logs:

[org.springframework.kafka.KafkaListenerEndpointContainer#0-0-C-1] ERROR DefaultErrorHandler              - Backoff FixedBackOff{interval=0, currentAttempts=10, maxAttempts=9} exhausted for topicX

How should this DefaultErrorHandler be used in order to achieve the desired behavior? Or should I use something else?

Thx in advance!

答:
factory.setCommonErrorHandler(new Default....)

Boot auto configuration of a CommonErrorHandler bean requires Boot 2.6.

https://github.com/spring-projects/spring-boot/commit/c3583a4b06cff3f53b3322cd79f2b64d17211d0e

ContentLicense: CC BY-SA 4.0

Body:
I am trying to find a way to use the new DefaultErrorHandler instead of deprecated SeekToCurrentErrorHandler in spring-kafka 2.8.1, in order to override the retry default behavior in case of errors. I want to "stop" the retry process, so if an error occurs, no retry should be done.

Now I have, in a config class, the following bean that works as expected:

@Bean
public KafkaListenerContainerFactory<ConcurrentMessageListenerContainer<String, String>> kafkaListenerContainerFactory() {
    ConcurrentKafkaListenerContainerFactory<String, String> factory = new ConcurrentKafkaListenerContainerFactory<>();
    factory.setErrorHandler(new **SeekToCurrentErrorHandler(new FixedBackOff(0L, 1L)**));
    factory.setConsumerFactory(requestConsumerFactory());
    factory.setReplyTemplate(kafkaTemplate());
    return factory;
}

Since in this spring kafka version, the STCEH is deprecated, I tried to do the following, in the same config class:

@Bean
public DefaultErrorHandler eh() {
    return new DefaultErrorHandler(new FixedBackOff(0, 1));
}

But it seems that it is not working. In case of error, the retry number is the default one, as I can see in logs:

[org.springframework.kafka.KafkaListenerEndpointContainer#0-0-C-1] ERROR DefaultErrorHandler              - Backoff FixedBackOff{interval=0, currentAttempts=10, maxAttempts=9} exhausted for topicX

How should this DefaultErrorHandler be used in order to achieve the desired behavior? Or should I use something else?

Thx in advance!


问:
Invalid prop `data` supplied to `MaterialTable`, expected one of type [function]
I am working in a jhipster application, with data coming from postgress sql. The api is http://localhost:8080/api/agreements and I am trying to display the data in a react material table but I am getting this error "Invalid prop data supplied to MaterialTable, expected one of type [function]" on my console after writing my functions.

Let me walk you through my codes below:

Inside the React component

```<code>  const apiUrl = 'http://localhost:8080/api/agreements';
  const [data, setData] = useState([]);

    useEffect(() => {
    getAgreementsData();
    }, []);

    const getAgreementsData = () => {
    fetch(apiUrl)
  .then(res => res.json())
  .then(res => setData(res));
</code>```

};

Inside the JSX

```<code>      <MaterialTable
      title="Agreements"
      data={data}
      columns={columns}/>

</code>```

The columns are displaying but the data is not.

And this warning is on the console " GET http://localhost:8080/api/agreements 401 (Unauthorized)"

答:
I later resolved the error by using axios get instead of fetch.</p>
```<code>     useEffect(() => {
     getAgreementsData();
      }, []);

     const getAgreementsData = () => {
     axios.get(apiUrl).then(res => setData(res.data));
      };
</code>```

Body:
I am working in a jhipster application, with data coming from postgress sql. The api is http://localhost:8080/api/agreements and I am trying to display the data in a react material table but I am getting this error "Invalid prop data supplied to MaterialTable, expected one of type [function]" on my console after writing my functions.

Let me walk you through my codes below:

Inside the React component

  const apiUrl = 'http://localhost:8080/api/agreements';
  const [data, setData] = useState([]);

    useEffect(() => {
    getAgreementsData();
    }, []);

    const getAgreementsData = () => {
    fetch(apiUrl)
  .then(res => res.json())
  .then(res => setData(res));

};

Inside the JSX

      <MaterialTable
      title="Agreements"
      data={data}
      columns={columns}/>

The columns are displaying but the data is not.

And this warning is on the console " GET http://localhost:8080/api/agreements 401 (Unauthorized)"

Body:
I later resolved the error by using axios get instead of fetch.

     useEffect(() => {
     getAgreementsData();
      }, []);

     const getAgreementsData = () => {
     axios.get(apiUrl).then(res => setData(res.data));
      };


问:
Get last entry of a range with identical numbers in R, vectorized
I’ve got this data:

```<code>tribble(
    ~ranges, ~last,
    0,     NA,
    1,     NA,
    1,     NA,
    1,     NA,
    1,     NA,
    2,     NA,
    2,     NA,
    2,     NA,
    3,     NA,
    3,     NA
)
</code>```

and I want to fill the last column only at the row index at the last entry of the number by the ranges column. That means, it should look like this:

```<code>tribble(
    ~ranges, ~last,
    0,     0,
    1,     NA,
    1,     NA,
    1,     NA,
    1,     1,
    2,     NA,
    2,     NA,
    2,     2,
    3,     NA,
    3,     3
)
</code>```

So far I came up with a row-wise approach:

```<code>for (r in seq.int(max(tmp$ranges))) {
  print(r)
  range <- which(tmp$ranges == r) |> max()
  tmp$last[range] <- r
}
</code>```

The main issue is that it is terribly slow. I am looking for a vectorized approach to this issue. Any creative solution out there?

答:
Here's a dplyr solution:

```<code>library(dplyr)
tmp %>%
  group_by(ranges) %>%
  mutate(
    last = case_when(row_number() == n() ~ ranges, TRUE ~ NA_real_)
  ) %>%
  ungroup()
# # A tibble: 10 × 2
#    ranges  last
#     <dbl> <dbl>
#  1      0     0
#  2      1    NA
#  3      1    NA
#  4      1    NA
#  5      1     1
#  6      2    NA
#  7      2    NA
#  8      2     2
#  9      3    NA
# 10      3     3
</code>```

Or we could do something clever with base R for the same result. Here we calculate the difference of ranges to identify when the next row is different (i.e., the last of a group). We then stick a TRUE on the end so the last row is included. This assumes your data is already sorted by ranges.

```<code>tmp$last = ifelse(c(diff(tmp$ranges) != 0, TRUE), tmp$ranges, NA)
</code>```

Body:
I’ve got this data:

tribble(
    ~ranges, ~last,
    0,     NA,
    1,     NA,
    1,     NA,
    1,     NA,
    1,     NA,
    2,     NA,
    2,     NA,
    2,     NA,
    3,     NA,
    3,     NA
)

and I want to fill the last column only at the row index at the last entry of the number by the ranges column. That means, it should look like this:

tribble(
    ~ranges, ~last,
    0,     0,
    1,     NA,
    1,     NA,
    1,     NA,
    1,     1,
    2,     NA,
    2,     NA,
    2,     2,
    3,     NA,
    3,     3
)

So far I came up with a row-wise approach:

for (r in seq.int(max(tmp$ranges))) {
  print(r)
  range <- which(tmp$ranges == r) |> max()
  tmp$last[range] <- r
}

The main issue is that it is terribly slow. I am looking for a vectorized approach to this issue. Any creative solution out there?

Body:
Here's a dplyr solution:

library(dplyr)
tmp %>%
  group_by(ranges) %>%
  mutate(
    last = case_when(row_number() == n() ~ ranges, TRUE ~ NA_real_)
  ) %>%
  ungroup()
# # A tibble: 10 × 2
#    ranges  last
#     <dbl> <dbl>
#  1      0     0
#  2      1    NA
#  3      1    NA
#  4      1    NA
#  5      1     1
#  6      2    NA
#  7      2    NA
#  8      2     2
#  9      3    NA
# 10      3     3

Or we could do something clever with base R for the same result. Here we calculate the difference of ranges to identify when the next row is different (i.e., the last of a group). We then stick a TRUE on the end so the last row is included. This assumes your data is already sorted by ranges.

tmp$last = ifelse(c(diff(tmp$ranges) != 0, TRUE), tmp$ranges, NA)


问:
How to work with protobuf schema messages in Python Apache pulsar pulsar-client package?
Is there a way to publish message to an Apache Pulsar topic using Protobuf schema using pulsar-client package using python?

As per the documentation, it supports only Avro, String, Json and bytes. Any work around for this?
https://pulsar.apache.org/docs/ko/2.8.1/client-libraries-python/

答:
That enhancement is not complete yet

https://github.com/apache/pulsar/issues/12949

It is there for Java

https://medium.com/streamnative/apache-pulsar-2-7-0-25c505658589


问:
how to get and set the value of a cell in WPF DataGrid by providing columnidnex and row index?
Can you please tell ,  how to get and set the value of a cell in WPF  DataGrid by providing columnidnex and row index

Thanks

答:
```<code> // Getting Data from Grid Cell
 string cellContent = ((TextBox)(GetCell(3).Content)).Text; //As I want the value of 3 column

 public DataGridCell GetCell(int column)
        {
            DataGridRow rowContainer = GetRow();

            if (rowContainer != null)
            {
                DataGridCellsPresenter presenter = GetVisualChild<DataGridCellsPresenter>(rowContainer);

                // Try to get the cell but it may possibly be virtualized.
                DataGridCell cell = (DataGridCell)presenter.ItemContainerGenerator.ContainerFromIndex(column);
                if (cell == null)
                {
                    // Now try to bring into view and retreive the cell.
                    customDataGrid.UCdataGridView.ScrollIntoView(rowContainer, customDataGrid.UCdataGridView.Columns[column]);
                    cell = (DataGridCell)presenter.ItemContainerGenerator.ContainerFromIndex(column);
                }
                return cell;
            }
            return null;
        }

 public DataGridRow GetRow()
        {
            DataGridRow row = (DataGridRow)customDataGrid.UCdataGridView.ItemContainerGenerator.ContainerFromIndex(_currentRowIndex);
            if (row == null)
            {
                // May be virtualized, bring into view and try again.
                customDataGrid.UCdataGridView.UpdateLayout();
                customDataGrid.UCdataGridView.ScrollIntoView(customDataGrid.UCdataGridView.Items[_currentRowIndex]);
                row = (DataGridRow)customDataGrid.UCdataGridView.ItemContainerGenerator.ContainerFromIndex(_currentRowIndex);
            }
            return row;
        }

        public static T GetVisualChild<T>(Visual parent) where T : Visual
        {
            T child = default(T);
            int numVisuals = VisualTreeHelper.GetChildrenCount(parent);
            for (int i = 0; i < numVisuals; i++)
            {
                Visual v = (Visual)VisualTreeHelper.GetChild(parent, i);
                child = v as T;
                if (child == null)
                {
                    child = GetVisualChild<T>(v);
                }
                if (child != null)
                {
                    break;
                }
            }
            return child;
        }

// Setting Data to Grid Cell
if (GetCell(3).Content is TextBlock) // if grid cell is not editable
{
      ((TextBlock)(GetCell(3).Content)).Text = "sometext";
}
else // TextBox  - if grid cell is editable
{
        ((TextBox)(GetCell(3).Content)).Text = "sometext";
}
</code>```

ContentLicense: CC BY-SA 3.0


问:
helm helpers file can't evaluate field type interface array/string
I am rather new to helm, and I am trying to create a chart, but running into values not transforming from the values.yaml file into my generated chart.

here are my values.yaml

```<code>apiVersion: security.istio.io/v1alpha2
kind: RequestAuthentication
metadata:
  name: name01
  namespace: ns-01
spec:
  selector:
    matchLabels:
      app: app-label
  jwtRules:
    - issuer: foo
      jwksUri: bar
      forwardOriginalToken: true
      audiences:
        - user1
        - user2
</code>```

then with my helm template:

```<code>apiVersion: networking.istio.io/v1alpha2
kind: RequestAuthentication
metadata:
  name: name01
spec:
  selector:
    matchLabels:
      app: {{ .Values.spec.selector.matchLabels.app }}
  jwtRules:
    - issuer: foo
      jwksUri: bar
      forwardOriginalToken: true
      audiences: |-
        {{- range .Values.spec.jwtRules.audiences }}
          - {{ . | title | quote }}
      {{ end }}
---
</code>```

I also have a helpers file.

_helpers.tpl

```<code>{{/* vim: set filetype=mustache: */}}
{{- define "jwtRules.audiences" -}}
{{- range $.Values.spec.jwtRules.audiences }}
      audiences:
        - {{ . | quote }}
{{- end }}
{{- end }}
</code>```

the error its producing: at <.Values.spec.jwtRules.audiences>: can't evaluate field audiences in type interface {}

答:
This one is simple - you don't have a spec.jwtRules.audiences in your values file! jwtRules contains an array, so you'll have to use some index or iterate over it. Also, i don't think that neither your indentation, nor using of |- for audiences is correct, per docs it should be an array of strings.

So i came up with this example (your values are unchanged):

apiVersion: networking.istio.io/v1alpha2
kind: RequestAuthentication
metadata:
  name: name01
spec:
  selector:
    matchLabels:
      app: {{ .Values.spec.selector.matchLabels.app }}
  jwtRules:
    - issuer: foo
      jwksUri: bar
      forwardOriginalToken: true
      audiences:
      {{- with (first .Values.spec.jwtRules) }}
      {{- range .audiences }}
        - {{ . | title | quote -}}
      {{- end }}
      {{- end }}
```
<p>renders into:</p>
<pre class="lang-yaml prettyprint-override"><code>apiVersion: networking.istio.io/v1alpha2
kind: RequestAuthentication
metadata:
  name: name01
spec:
  selector:
    matchLabels:
      app: app-label
  jwtRules:
    - issuer: foo
      jwksUri: bar
      forwardOriginalToken: true
      audiences:
        - "User1"
        - "User2"
</code>```

In this case it uses a first element of array

Body:
I am rather new to helm, and I am trying to create a chart, but running into values not transforming from the values.yaml file into my generated chart.

here are my values.yaml

apiVersion: security.istio.io/v1alpha2
kind: RequestAuthentication
metadata:
  name: name01
  namespace: ns-01
spec:
  selector:
    matchLabels:
      app: app-label
  jwtRules:
    - issuer: foo
      jwksUri: bar
      forwardOriginalToken: true
      audiences:
        - user1
        - user2

then with my helm template:

apiVersion: networking.istio.io/v1alpha2
kind: RequestAuthentication
metadata:
  name: name01
spec:
  selector:
    matchLabels:
      app: {{ .Values.spec.selector.matchLabels.app }}
  jwtRules:
    - issuer: foo
      jwksUri: bar
      forwardOriginalToken: true
      audiences: |-
        {{- range .Values.spec.jwtRules.audiences }}
          - {{ . | title | quote }}
      {{ end }}
---

I also have a helpers file.

_helpers.tpl

{{/* vim: set filetype=mustache: */}}
{{- define "jwtRules.audiences" -}}
{{- range $.Values.spec.jwtRules.audiences }}
      audiences:
        - {{ . | quote }}
{{- end }}
{{- end }}

the error its producing: at <.Values.spec.jwtRules.audiences>: can't evaluate field audiences in type interface {}

Body:
This one is simple - you don't have a spec.jwtRules.audiences in your values file! jwtRules contains an array, so you'll have to use some index or iterate over it. Also, i don't think that neither your indentation, nor using of |- for audiences is correct, per docs it should be an array of strings.

So i came up with this example (your values are unchanged):

apiVersion: networking.istio.io/v1alpha2
kind: RequestAuthentication
metadata:
  name: name01
spec:
  selector:
    matchLabels:
      app: {{ .Values.spec.selector.matchLabels.app }}
  jwtRules:
    - issuer: foo
      jwksUri: bar
      forwardOriginalToken: true
      audiences:
      {{- with (first .Values.spec.jwtRules) }}
      {{- range .audiences }}
        - {{ . | title | quote -}}
      {{- end }}
      {{- end }}

renders into:

apiVersion: networking.istio.io/v1alpha2
kind: RequestAuthentication
metadata:
  name: name01
spec:
  selector:
    matchLabels:
      app: app-label
  jwtRules:
    - issuer: foo
      jwksUri: bar
      forwardOriginalToken: true
      audiences:
        - "User1"
        - "User2"

In this case it uses a first element of array


问:
Warning: The label [number] is never explicitly referenced
```<code>boolean t = true;
first:
{
    second:
    {
        third:
        {
            System.out.println("Before the break");
            if (t) {
                break second;
            }
            System.out.println("This wont execute");
        }
        System.out.println("Neither this one");
    }
    System.out.println("this will execute");

}
</code>```

In the code, before "first" and before "third" there shows a warning: The label first/third  is never explicitly referenced.
Can ypu tell why is this warning showing?

答:
Warning: Never explicitly reference

First of all this warning shows because of the label is never explicitly referenced. Though there is no role of that label, you still using the label in your code. and the main problem is here that the label will never closed. So, if you want to turn off the warning then you use 'break' statement.

```<code>    Boolean t = true;

    first:
    {

        second:
        {
            third:
            {
                System.out.println("Before the break statement.");

                if(t)
                {
                    break second;
                }
                System.out.println("This won't execute.");
                break third;
            }
            System.out.println("This won't execute.");
        }

        System.out.println("This is after second block.");
        break first;
    }
</code>```

Body:
boolean t = true;
first:
{
    second:
    {
        third:
        {
            System.out.println("Before the break");
            if (t) {
                break second;
            }
            System.out.println("This wont execute");
        }
        System.out.println("Neither this one");
    }
    System.out.println("this will execute");

}

In the code, before "first" and before "third" there shows a warning: The label first/third  is never explicitly referenced.
Can ypu tell why is this warning showing?

Body:
Warning: Never explicitly reference

First of all this warning shows because of the label is never explicitly referenced. Though there is no role of that label, you still using the label in your code. and the main problem is here that the label will never closed. So, if you want to turn off the warning then you use 'break' statement.

    Boolean t = true;

    first:
    {

        second:
        {
            third:
            {
                System.out.println("Before the break statement.");

                if(t)
                {
                    break second;
                }
                System.out.println("This won't execute.");
                break third;
            }
            System.out.println("This won't execute.");
        }

        System.out.println("This is after second block.");
        break first;
    }


问:
Scala Option something like flatMap but for None case?
I have an Option[A] and I want to say: If it's a None then computes another Option[A], otherwise stay as is. getOrElse[A] accepts an A (I need to pass an Option[A]) and flatMap applies to the Some case (I want to handle the None case) . Essentially I want the following code but in the most succinct way possible:

val a: Option[A] = ???
a match {
  case None => ??? // returns an Option[A] here
  case Some(x) => a
}

```

答:
This is embarrassing.

For other lazy people out there like myself the answer is orElse


问:
iPython/Jupyter %run magic appending .py to filename and causing error
I'm attempting to use the %run magic like so:

```<code>%run ../Tools/imports.ipynb
</code>```

I am running this code in two notebooks in the same directory, however, in one of them I get this error:

```<code>ERROR:root:File `'../Tools/imports.ipynb.py'` not found.
</code>```

I'm not sure what I'm missing here but I'm guessing there's some nuance as I did not write the first of the two notebooks. Anyone have any idea? Thanks.

答:
I see that your question has some time but I just got the same problem.
Looks that when you run the %run command alone on a cell it will not do the append and the command will run successfully, but if in the same cell you add some other code, it will do the append and fails with the error you had.
To fix this you can run with dbutils

```<code>dbutils.notebook.run()
</code>```

check more info here: https://docs.databricks.com/notebooks/notebook-workflows.html

Body:
I'm attempting to use the %run magic like so:

%run ../Tools/imports.ipynb

I am running this code in two notebooks in the same directory, however, in one of them I get this error:

ERROR:root:File `'../Tools/imports.ipynb.py'` not found.

I'm not sure what I'm missing here but I'm guessing there's some nuance as I did not write the first of the two notebooks. Anyone have any idea? Thanks.

Body:
I see that your question has some time but I just got the same problem.
Looks that when you run the %run command alone on a cell it will not do the append and the command will run successfully, but if in the same cell you add some other code, it will do the append and fails with the error you had.
To fix this you can run with dbutils

dbutils.notebook.run()

check more info here: https://docs.databricks.com/notebooks/notebook-workflows.html


问:
C# - Make copy of a big class (model) by value not reference
I do project by asp.net core mvc. when I do copy of the model and change its values, the values of the original model is changing too because it made copy of the model by reference, so the value place in data is same.
I need way that I can do copy for values of the model doesn't connect with original model.</p>

答:
option 1 use AutoMapper

option 2 create Copy using Reflection

```<code>        public class PropertyCopier<TParent, TChild> where TParent : class
                                       where TChild : class
    {
        public static void Copy(TParent parent, TChild child)
        {
            var parentProperties = parent.GetType().GetProperties();
            var childProperties = child.GetType().GetProperties();

            foreach (var parentProperty in parentProperties)
            {
                foreach (var childProperty in childProperties)
                {
                    if (parentProperty.Name == childProperty.Name && parentProperty.PropertyType == childProperty.PropertyType)
                    {
                        childProperty.SetValue(child, parentProperty.GetValue(parent));
                        break;
                    }
                }
            }
        }
    }
</code>```

Body:
option 1 use AutoMapper

option 2 create Copy using Reflection

        public class PropertyCopier<TParent, TChild> where TParent : class
                                       where TChild : class
    {
        public static void Copy(TParent parent, TChild child)
        {
            var parentProperties = parent.GetType().GetProperties();
            var childProperties = child.GetType().GetProperties();

            foreach (var parentProperty in parentProperties)
            {
                foreach (var childProperty in childProperties)
                {
                    if (parentProperty.Name == childProperty.Name && parentProperty.PropertyType == childProperty.PropertyType)
                    {
                        childProperty.SetValue(child, parentProperty.GetValue(parent));
                        break;
                    }
                }
            }
        }
    }


问:
Do Git and TFS Play Well Together?
I tried to do a git init on a directory under TFS control - and no .git files were created.  When I tried again to do a git init - it recognized I had already tried - but still no gitattributes or gitignore files.  Do Git and TFS work on the same directories?</p>

答:
git init doesn't add any files by default, it just initializes a git repo locally (adds a hidden .git folder to track git data in. You'll need to add these files manually.

With regards to "in TFS", if you mean TFVC, I don't recommend mixing TFVC and git in the same working folders. It throws off Visual Studio considerably. Though you can probably get it to work from the commandline if you exclude tf$/ in git and ignore .git/ in TFVC.

Title: Do Git and TFS Play Well Together?


问:
get all the documents having max value using aggregation in mongodb
I want to fetch "all the documents" having highest value for specific field and than group by another field.

Consider below data:

```<code>_id:1, country:india,  quantity:12,  name:xyz
_id:2, country:USA,    quantity:5,   name:abc
_id:3, country:USA,    quantity:6,   name:xyz
_id:4, country:india,  quantity:8,   name:def
_id:5, country:USA,    quantity:10,  name:jkl
_id:6, country:india,  quantity:12,  name:jkl
</code>```

Answer should be

```<code>country:india max-quantity:12
name xyz
name jkl

country:USA max-quantity:10
name jkl
</code>```

I have tried several queries, but I can get only the max value without the name or i can go group by but it shows all the values.

```<code>db.coll.aggregate([{
    $group:{
        _id:"$country",
        "maxQuantity":{$max:"$quantity"}
    }
}])
</code>```

for example above will give max quantity on every country but how to combine with other field such that it shows all the documents of max quantity.

答:
Another possibility close to Blakes Seven's solution to simplify a bit the setDifference + map part by a filter of the array of documents.

db.coll.aggregate([
    { "$group":{
        "_id": "$country",
        "maxQuantity": { "$max": "$quantity" },
        "docs": { "$push": {
            "_id": "$_id",
            "name": "$name",
            "quantity": "$quantity"
        }}
    }},
    { "$project": {
        "maxQuantity": 1,
        "docs": {
            "$filter": {
              "input": "$docs",
              "as": "doc",
              "cond": { $eq: ["$$doc.quantity", "$maxQuantity"] }
            }
        }
    }}
])
```

Body:
I want to fetch "all the documents" having highest value for specific field and than group by another field.

Consider below data:

_id:1, country:india,  quantity:12,  name:xyz
_id:2, country:USA,    quantity:5,   name:abc
_id:3, country:USA,    quantity:6,   name:xyz
_id:4, country:india,  quantity:8,   name:def
_id:5, country:USA,    quantity:10,  name:jkl
_id:6, country:india,  quantity:12,  name:jkl

Answer should be

country:india max-quantity:12
name xyz
name jkl

country:USA max-quantity:10
name jkl

I have tried several queries, but I can get only the max value without the name or i can go group by but it shows all the values.

db.coll.aggregate([{
    $group:{
        _id:"$country",
        "maxQuantity":{$max:"$quantity"}
    }
}])

for example above will give max quantity on every country but how to combine with other field such that it shows all the documents of max quantity.


问:
How to set the max value at 5 in a radar graph in Excel whereas all the values are smaller than 4
I have an excel radar graph.

I have many criteria. Every criteria has to have a value between 0 and 5. But if all the values are strictly smaller than 4, then the graph considers 4 as the max value, but I still want 5 to be the max value.

How to do that ?

Thanks,

答:
Coincidently enough had the same issue with the same max value.

First right click for "Select Data..." On the left side for Legend Entries. Click on "Add" and you will come to an "Edit Series" popup. Give it a "Series name" and for the "Series values" input "={5}" instead of the default "={1}". And that's it. You should have two Legend Entries; one for your main data source i.e. Series1 and the new one just created.


问:
Dynamically position text within, right to or left to an element
I am completely new to CSS. I want to display a simple Gantt chart and I am looking for a way to position the text indicating the number of month within, left to or right to the colored gantt bar.

Right now all the text is within in the bar and as the bar gets narrower it increases in height as the text needs to be wrapped.

In contrast to what the screenshot currently shows, I would want to have the text for Step 1 to be displayed to the right of the bar, the one for step 5 to be displayed to the left. The rest of the text should remain the same as long as the next is not too long to be wrapped over multiple lines, in that case the next should be displayed on that side right next to the bar where there is more space.

2months

 ```

答:
Check out the white-space: nowrap; and overflow: visible; properties. This won't completely solve your problem - it'll probably just stop the bar from getting too small to contain the text, I'm guessing.

See this link from CSS-tricks for some inspiration. You might be able to use the line-height trick to hide the inner text. To then show text outside the block, you could have a hidden div (either to the left or right) on 'stand-by' that gets displayed only when the inside one is hidden.


问:
No operations defined in spec! while specifying multiple paths in swagger ui
I want to display two REST API endpoints in Swagger ui: /cart and /post.

When I specify either /cart or /post works fine but with both showing me error as

No operations defined in spec!

in swagger-ui

```<code>@Bean
public Docket api() {
        return new Docket(DocumentationType.SWAGGER_2)
        .select()
        .apis(RequestHandlerSelectors.any())
        .paths(PathSelectors.ant("/cart"))
        .paths(PathSelectors.ant("/post"))
        .build();
}
</code>```

答:
With Spring boot 2.6.x you also need:

spring:
  mvc:
    pathmatch:
      matching-strategy: ant_path_matcher
```

Body:
I want to display two REST API endpoints in Swagger ui: /cart and /post.

When I specify either /cart or /post works fine but with both showing me error as

No operations defined in spec!

in swagger-ui

@Bean
public Docket api() {
        return new Docket(DocumentationType.SWAGGER_2)
        .select()
        .apis(RequestHandlerSelectors.any())
        .paths(PathSelectors.ant("/cart"))
        .paths(PathSelectors.ant("/post"))
        .build();
}


问:
StringBuilder.Append Vs StringBuilder.AppendFormat
I was wondering about StringBuilder and I've got a question that I was hoping the community would be able to explain.

Let's just forget about code readability, which of these is faster and why?

StringBuilder.Append:

```<code>StringBuilder sb = new StringBuilder();
sb.Append(string1);
sb.Append("----");
sb.Append(string2);
</code>```

StringBuilder.AppendFormat:

```<code>StringBuilder sb = new StringBuilder();
sb.AppendFormat("{0}----{1}",string1,string2);
</code>```

答:
It's impossible to say, not knowing the size of string1 and string2.

With the call to AppendFormat, it will preallocate the buffer just once given the length of the format string and the strings that will be inserted and then concatenate everything and insert it into the buffer.  For very large strings, this will be advantageous over separate calls to Append which might cause the buffer to expand multiple times.

However, the three calls to Append might or might not trigger growth of the buffer and that check is performed each call.  If the strings are small enough and no buffer expansion is triggered, then it will be faster than the call to AppendFormat because it won't have to parse the format string to figure out where to do the replacements.

More data is needed for a definitive answer

It should be noted that there is little discussion of using the static Concat method on the String class (Jon's answer using AppendWithCapacity reminded me of this).  His test results show that to be the best case (assuming you don't have to take advantage of specific format specifier).  String.Concat does the same thing in that it will predetermine the length of the strings to concatenate and preallocate the buffer (with slightly more overhead due to looping constructs through the parameters).  It's performance is going to be comparable to Jon's AppendWithCapacity method.

Or, just the plain addition operator, since it compiles to a call to String.Concat anyways, with the caveat that all of the additions are in the same expression:

```<code>// One call to String.Concat.
string result = a + b + c;
</code>```

NOT

```<code>// Two calls to String.Concat.
string result = a + b;
result = result + c;
</code>```

For all those putting up test code

You need to run your test cases in separate runs (or at the least, perform a GC between the measuring of separate test runs).  The reason for this is that if you do say, 1,000,000 runs, creating a new StringBuilder in each iteration of the loop for one test, and then you run the next test that loops the same number of times, creating an additional 1,000,000 StringBuilder instances, the GC will more than likely step in during the second test and hinder its timing.

OwnerDisplayName: Sergio

ContentLicense: CC BY-SA 2.5

Body:
I was wondering about StringBuilder and I've got a question that I was hoping the community would be able to explain.

Let's just forget about code readability, which of these is faster and why?

StringBuilder.Append:

StringBuilder sb = new StringBuilder();
sb.Append(string1);
sb.Append("----");
sb.Append(string2);

StringBuilder.AppendFormat:

StringBuilder sb = new StringBuilder();
sb.AppendFormat("{0}----{1}",string1,string2);

LastEditorDisplayName: Samuel

Body:
It's impossible to say, not knowing the size of string1 and string2.

With the call to AppendFormat, it will preallocate the buffer just once given the length of the format string and the strings that will be inserted and then concatenate everything and insert it into the buffer.  For very large strings, this will be advantageous over separate calls to Append which might cause the buffer to expand multiple times.

However, the three calls to Append might or might not trigger growth of the buffer and that check is performed each call.  If the strings are small enough and no buffer expansion is triggered, then it will be faster than the call to AppendFormat because it won't have to parse the format string to figure out where to do the replacements.

More data is needed for a definitive answer

It should be noted that there is little discussion of using the static Concat method on the String class (Jon's answer using AppendWithCapacity reminded me of this).  His test results show that to be the best case (assuming you don't have to take advantage of specific format specifier).  String.Concat does the same thing in that it will predetermine the length of the strings to concatenate and preallocate the buffer (with slightly more overhead due to looping constructs through the parameters).  It's performance is going to be comparable to Jon's AppendWithCapacity method.

Or, just the plain addition operator, since it compiles to a call to String.Concat anyways, with the caveat that all of the additions are in the same expression:

// One call to String.Concat.
string result = a + b + c;

NOT

// Two calls to String.Concat.
string result = a + b;
result = result + c;

For all those putting up test code

You need to run your test cases in separate runs (or at the least, perform a GC between the measuring of separate test runs).  The reason for this is that if you do say, 1,000,000 runs, creating a new StringBuilder in each iteration of the loop for one test, and then you run the next test that loops the same number of times, creating an additional 1,000,000 StringBuilder instances, the GC will more than likely step in during the second test and hinder its timing.

OwnerDisplayName: casperOne

LastEditorDisplayName: casperOne


问:
MKAnnotationView: Memory leak
I'm using the following code to make a pin for annotation:

```<code>- (MKAnnotationView *) mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>)           annotation
{
    MKPinAnnotationView *annView=[[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:@"currentloc"];
    annView.pinColor = MKPinAnnotationColorGreen;
    annView.animatesDrop=TRUE;
    annView.canShowCallout = YES;
    annView.calloutOffset = CGPointMake(-5, 5);

    return annView;
}
</code>```

Everything works perfectly, however Analyze in XCode shows memory leak in this code. In fact, I see it too cos I allocated object and then did not released it.
How can I avoid memory leak here?

答:
In fact, I see it too cos I allocated object and then did not released it.

You are right about the reason of the leak. If you need to return an alloced object from a method then the idea is to autorelease that.

```<code>- (MyClass *)getObject {
    MyClass *obj = [[MyClass alloc] init];
    return [obj autorelease];
}
</code>```

Then you will retain the returned object in caller if needed.

Or name the method in such a way that it is clear that the returned object need to be released in caller. And then release in the caller.

Title: MKAnnotationView: Memory leak

Body:
I'm using the following code to make a pin for annotation:

- (MKAnnotationView *) mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>)           annotation
{
    MKPinAnnotationView *annView=[[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:@"currentloc"];
    annView.pinColor = MKPinAnnotationColorGreen;
    annView.animatesDrop=TRUE;
    annView.canShowCallout = YES;
    annView.calloutOffset = CGPointMake(-5, 5);

    return annView;
}

Everything works perfectly, however Analyze in XCode shows memory leak in this code. In fact, I see it too cos I allocated object and then did not released it.
How can I avoid memory leak here?

Body:
In fact, I see it too cos I allocated object and then did not released it.

You are right about the reason of the leak. If you need to return an alloced object from a method then the idea is to autorelease that.

- (MyClass *)getObject {
    MyClass *obj = [[MyClass alloc] init];
    return [obj autorelease];
}

Then you will retain the returned object in caller if needed.

Or name the method in such a way that it is clear that the returned object need to be released in caller. And then release in the caller.