text:
Q: Bibdesk: TEX preview generation failed I use Bibdesk configured for biblatex and have been doing so for years. Today, for some reason, I am not able to generate TEX previews in Bibdesk as I have always been able to do, and my .bib files are not functioning properly when I run LaTeX (pdflatexmk) on my docs with bibliography material. I know the two must be related, but I'm scratching my head as to why, without any changes on my part, things are not working suddenly. Worked yesterday, but not today.
Here is the log for the Bibdesk preview error:
TeX preview generation failed.  Please review the log below to determine the cause.

***** WARNING: You are using a non-standard BibTeX style *****
The style "biblatex" may require additional \usepackage commands to function correctly.

---------- TeX log file ----------
File: "/var/folders/98/j_f65jms7jzcygkvtc7nh9ch0000gn/T/bibdesk.CrjbDN/bibpreview/bibpreview.log"
This is pdfTeX, Version 3.141592653-2.6-1.40.22 (TeX Live 2021) (preloaded format=pdflatex 2021.6.27)  10 SEP 2021 10:54
entering extended mode
 restricted \write18 enabled.
 %&-line parsing enabled.
**bibpreview
(./bibpreview.tex
LaTeX2e <2021-06-01> patch level 1
L3 programming layer <2021-06-18> (/usr/local/texlive/2021/texmf-dist/tex/latex
/base/article.cls
Document Class: article 2021/02/12 v1.4n Standard LaTeX document class
(/usr/local/texlive/2021/texmf-dist/tex/latex/base/size10.clo
File: size10.clo 2021/02/12 v1.4n Standard LaTeX file (size option)
)
\c@part=\count182
\c@section=\count183
\c@subsection=\count184
\c@subsubsection=\count185
\c@paragraph=\count186
\c@subparagraph=\count187
\c@figure=\count188
\c@table=\count189
\abovecaptionskip=\skip47
\belowcaptionskip=\skip48
\bibindent=\dimen138
)
(/usr/local/texlive/2021/texmf-dist/tex/latex/biblatex-chicago/biblatex-chicago
.sty
Package: biblatex-chicago 2021/03/27 v 3.16 biblatex style
(/usr/local/texlive/2021/texmf-dist/tex/latex/etoolbox/etoolbox.sty
Package: etoolbox 2020/10/05 v2.5k e-TeX tools for LaTeX (JAW)
\etb@tempcnta=\count190
) (/usr/local/texlive/2021/texmf-dist/tex/latex/hyperref/nameref.sty
Package: nameref 2021-04-02 v2.47 Cross-referencing by name of section
(/usr/local/texlive/2021/texmf-dist/tex/latex/refcount/refcount.sty
Package: refcount 2019/12/15 v3.6 Data extraction from label references (HO)
(/usr/local/texlive/2021/texmf-dist/tex/generic/ltxcmds/ltxcmds.sty
Package: ltxcmds 2020-05-10 v1.25 LaTeX kernel commands for general use (HO)
) (/usr/local/texlive/2021/texmf-dist/tex/generic/infwarerr/infwarerr.sty
Package: infwarerr 2019/12/03 v1.5 Providing info/warning/error messages (HO)
))
(/usr/local/texlive/2021/texmf-dist/tex/generic/gettitlestring/gettitlestring.s
ty
Package: gettitlestring 2019/12/15 v1.6 Cleanup title references (HO)
(/usr/local/texlive/2021/texmf-dist/tex/latex/kvoptions/kvoptions.sty
Package: kvoptions 2020-10-07 v3.14 Key value format for package options (HO)
(/usr/local/texlive/2021/texmf-dist/tex/latex/graphics/keyval.sty
Package: keyval 2014/10/28 v1.15 key=value parser (DPC)
\KV@toks@=\toks16
) (/usr/local/texlive/2021/texmf-dist/tex/generic/kvsetkeys/kvsetkeys.sty
Package: kvsetkeys 2019/12/15 v1.18 Key value parser (HO)
)))
\c@section@level=\count191
LaTeX Info: Redefining \ref on input line 356.
LaTeX Info: Redefining \pageref on input line 356.
) (/usr/local/texlive/2021/texmf-dist/tex/generic/xstring/xstring.sty (/usr/loc
al/texlive/2021/texmf-dist/tex/generic/xstring/xstring.tex
\integerpart=\count192
\decimalpart=\count193
)
Package: xstring 2019/02/06 v1.83 String manipulations (CT)
) (/usr/local/texlive/2021/texmf-dist/tex/latex/biblatex/biblatex.sty
Package: biblatex 2020/12/31 v3.16 programmable bibliographies (PK/MW)
(/usr/local/texlive/2021/texmf-dist/tex/generic/pdftexcmds/pdftexcmds.sty
Package: pdftexcmds 2020-06-27 v0.33 Utility functions of pdfTeX for LuaTeX (HO
)
(/usr/local/texlive/2021/texmf-dist/tex/generic/iftex/iftex.sty
Package: iftex 2020/03/06 v1.0d TeX engine tests
)
Package pdftexcmds Info: \pdf@primitive is available.
Package pdftexcmds Info: \pdf@ifprimitive is available.
Package pdftexcmds Info: \pdfdraftmode found.
) (/usr/local/texlive/2021/texmf-dist/tex/latex/logreq/logreq.sty
Package: logreq 2010/08/04 v1.0 xml request logger
\lrq@indent=\count194
(/usr/local/texlive/2021/texmf-dist/tex/latex/logreq/logreq.def
File: logreq.def 2010/08/04 v1.0 logreq spec v1.0
)) (/usr/local/texlive/2021/texmf-dist/tex/latex/base/ifthen.sty
Package: ifthen 2020/11/24 v1.1c Standard LaTeX ifthen package (DPC)
) (/usr/local/texlive/2021/texmf-dist/tex/latex/url/url.sty
\Urlmuskip=\muskip16
Package: url 2013/09/16  ver 3.4  Verb mode for urls, etc.
)
\c@tabx@nest=\count195
\c@listtotal=\count196
\c@listcount=\count197
\c@liststart=\count198
\c@liststop=\count199
\c@citecount=\count266
\c@citetotal=\count267
\c@multicitecount=\count268
\c@multicitetotal=\count269
\c@instcount=\count270
\c@maxnames=\count271
\c@minnames=\count272
\c@maxitems=\count273
\c@minitems=\count274
\c@citecounter=\count275
\c@maxcitecounter=\count276
\c@savedcitecounter=\count277
\c@uniquelist=\count278
\c@uniquename=\count279
\c@refsection=\count280
\c@refsegment=\count281
\c@maxextratitle=\count282
\c@maxextratitleyear=\count283
\c@maxextraname=\count284
\c@maxextradate=\count285
\c@maxextraalpha=\count286
\c@abbrvpenalty=\count287
\c@highnamepenalty=\count288
\c@lownamepenalty=\count289
\c@maxparens=\count290
\c@parenlevel=\count291
\blx@tempcnta=\count292
\blx@tempcntb=\count293
\blx@tempcntc=\count294
\blx@maxsection=\count295
\blx@maxsegment@0=\count296
\blx@notetype=\count297
\blx@parenlevel@text=\count298
\blx@parenlevel@foot=\count299
\blx@sectionciteorder@0=\count300
\blx@entrysetcounter=\count301
\blx@biblioinstance=\count302
\labelnumberwidth=\skip49
\labelalphawidth=\skip50
\biblabelsep=\skip51
\bibitemsep=\skip52
\bibnamesep=\skip53
\bibinitsep=\skip54
\bibparsep=\skip55
\bibhang=\skip56
\blx@bcfin=\read2
\blx@bcfout=\write3
\blx@langwohyphens=\language87
\c@mincomprange=\count303
\c@maxcomprange=\count304
\c@mincompwidth=\count305
Package biblatex Info: Trying to load biblatex default data model...
Package biblatex Info: ... file 'blx-dm.def' found.
(/usr/local/texlive/2021/texmf-dist/tex/latex/biblatex/blx-dm.def
File: blx-dm.def 2020/12/31 v3.16 biblatex localization (PK/MW)
)
Package biblatex Info: Trying to load biblatex style data model...
Package biblatex Info: ... file 'chicago-notes.dbx' not found.
Package biblatex Info: Trying to load biblatex custom data model...
Package biblatex Info: ... file 'biblatex-dm.cfg' not found.
\c@afterword=\count306
\c@savedafterword=\count307
\c@annotator=\count308
\c@savedannotator=\count309
\c@author=\count310
\c@savedauthor=\count311
\c@bookauthor=\count312
\c@savedbookauthor=\count313
\c@commentator=\count314
\c@savedcommentator=\count315
\c@editor=\count316
\c@savededitor=\count317
\c@editora=\count318
\c@savededitora=\count319
\c@editorb=\count320
\c@savededitorb=\count321
\c@editorc=\count322
\c@savededitorc=\count323
\c@foreword=\count324
\c@savedforeword=\count325
\c@holder=\count326
\c@savedholder=\count327
\c@introduction=\count328
\c@savedintroduction=\count329
\c@namea=\count330
\c@savednamea=\count331
\c@nameb=\count332
\c@savednameb=\count333
\c@namec=\count334
\c@savednamec=\count335
\c@translator=\count336
\c@savedtranslator=\count337
\c@shortauthor=\count338
\c@savedshortauthor=\count339
\c@shorteditor=\count340
\c@savedshorteditor=\count341
\c@labelname=\count342
\c@savedlabelname=\count343
\c@institution=\count344
\c@savedinstitution=\count345
\c@lista=\count346
\c@savedlista=\count347
\c@listb=\count348
\c@savedlistb=\count349
\c@listc=\count350
\c@savedlistc=\count351
\c@listd=\count352
\c@savedlistd=\count353
\c@liste=\count354
\c@savedliste=\count355
\c@listf=\count356
\c@savedlistf=\count357
\c@location=\count358
\c@savedlocation=\count359
\c@organization=\count360
\c@savedorganization=\count361
\c@origlocation=\count362
\c@savedoriglocation=\count363
\c@origpublisher=\count364
\c@savedorigpublisher=\count365
\c@publisher=\count366
\c@savedpublisher=\count367
\c@language=\count368
\c@savedlanguage=\count369
\c@origlanguage=\count370
\c@savedoriglanguage=\count371
\c@pageref=\count372
\c@savedpageref=\count373
\shorthandwidth=\skip57
\shortjournalwidth=\skip58
\shortserieswidth=\skip59
\shorttitlewidth=\skip60
\shortauthorwidth=\skip61
\shorteditorwidth=\skip62
\locallabelnumberwidth=\skip63
\locallabelalphawidth=\skip64
\localshorthandwidth=\skip65
\localshortjournalwidth=\skip66
\localshortserieswidth=\skip67
\localshorttitlewidth=\skip68
\localshortauthorwidth=\skip69
\localshorteditorwidth=\skip70
Package biblatex Info: Trying to load compatibility code...
Package biblatex Info: ... file 'blx-compat.def' found.
(/usr/local/texlive/2021/texmf-dist/tex/latex/biblatex/blx-compat.def
File: blx-compat.def 2020/12/31 v3.16 biblatex compatibility (PK/MW)
)
Package biblatex Info: Trying to load generic definitions...
Package biblatex Info: ... file 'biblatex.def' found.
(/usr/local/texlive/2021/texmf-dist/tex/latex/biblatex/biblatex.def
File: biblatex.def 2020/12/31 v3.16 biblatex compatibility (PK/MW)
\c@textcitecount=\count374
\c@textcitetotal=\count375
\c@textcitemaxnames=\count376
\c@biburlbigbreakpenalty=\count377
\c@biburlbreakpenalty=\count378
\c@biburlnumpenalty=\count379
\c@biburlucpenalty=\count380
\c@biburllcpenalty=\count381
\biburlbigskip=\muskip17
\biburlnumskip=\muskip18
\biburlucskip=\muskip19
\biburllcskip=\muskip20
\c@smartand=\count382
)
Package biblatex Info: Trying to load bibliography style 'chicago-notes'...
Package biblatex Info: ... file 'chicago-notes.bbx' found.

(/usr/local/texlive/2021/texmf-dist/tex/latex/biblatex-chicago/chicago-notes.bb
x
File: chicago-notes.bbx 2021/03/27 v 3.16 biblatex bibliography style
\lositemsep=\skip71
\cms@tempcnta=\count383
\cms@tempcntb=\count384
\c@bbx:relatedcount=\count385
\c@bbx:relatedtotal=\count386
\c@cms@reviewcount=\count387
\c@cms@currentnote=\count388
)
Package biblatex Info: Trying to load citation style 'chicago-notes'...
Package biblatex Info: ... file 'chicago-notes.cbx' found.

(/usr/local/texlive/2021/texmf-dist/tex/latex/biblatex-chicago/chicago-notes.cb
x
File: chicago-notes.cbx 2021/03/27 v 3.16 biblatex citation style
Package biblatex Info: Redefining '\cite'.
Package biblatex Info: Redefining '\parencite'.
Package biblatex Info: Redefining '\footcite'.
Package biblatex Info: Redefining '\smartcite'.
Package biblatex Info: Redefining '\smartcites'.
Package biblatex Info: Redefining '\footfullcite'.
Package biblatex Info: Redefining '\fullcite'.
Package biblatex Info: Redefining '\citeincitef'.
Package biblatex Info: Redefining '\citeauthor'.
Package biblatex Info: Redefining '\textcite'.
Package biblatex Info: Redefining '\textcites'.
Package biblatex Info: Delimiter 'dateeradelim' in context '' already defined,
overwriting.
)
Package biblatex Info: Trying to load configuration file...
Package biblatex Info: ... file 'biblatex.cfg' found.
(/usr/local/texlive/2021/texmf-dist/tex/latex/biblatex/biblatex.cfg
File: biblatex.cfg
)))
\@quotelevel=\count389
\@quotereset=\count390
(/usr/local/texlive/2021/texmf-dist/tex/latex/l3backend/l3backend-pdftex.def
File: l3backend-pdftex.def 2021-05-07 L3 backend support: PDF output (pdfTeX)
\l__color_backend_stack_int=\count391
\l__pdf_internal_box=\box50
)
No file bibpreview.aux.
\openout1 = `bibpreview.aux'.

LaTeX Font Info:    Checking defaults for OML/cmm/m/it on input line 21.
LaTeX Font Info:    ... okay on input line 21.
LaTeX Font Info:    Checking defaults for OMS/cmsy/m/n on input line 21.
LaTeX Font Info:    ... okay on input line 21.
LaTeX Font Info:    Checking defaults for OT1/cmr/m/n on input line 21.
LaTeX Font Info:    ... okay on input line 21.
LaTeX Font Info:    Checking defaults for T1/cmr/m/n on input line 21.
LaTeX Font Info:    ... okay on input line 21.
LaTeX Font Info:    Checking defaults for TS1/cmr/m/n on input line 21.
LaTeX Font Info:    ... okay on input line 21.
LaTeX Font Info:    Checking defaults for OMX/cmex/m/n on input line 21.
LaTeX Font Info:    ... okay on input line 21.
LaTeX Font Info:    Checking defaults for U/cmr/m/n on input line 21.
LaTeX Font Info:    ... okay on input line 21.
Package biblatex Info: Trying to load language 'english' -> 'cms-american'...
Package biblatex Info: ... file 'cms-american.lbx' found.

(/usr/local/texlive/2021/texmf-dist/tex/latex/biblatex-chicago/cms-american.lbx
File: cms-american.lbx 2021/03/27 v 3.16 biblatex localization
Package biblatex Info: Trying to load language 'american'...
Package biblatex Info: ... file 'american.lbx' found.
(/usr/local/texlive/2021/texmf-dist/tex/latex/biblatex/lbx/american.lbx
File: american.lbx 2020/12/31 v3.16 biblatex localization (PK/MW)
Package biblatex Info: Trying to load language 'english'...
Package biblatex Info: ... file 'english.lbx' found.
(/usr/local/texlive/2021/texmf-dist/tex/latex/biblatex/lbx/english.lbx
File: english.lbx 2020/12/31 v3.16 biblatex localization (PK/MW)
))
Package biblatex Info: Trying to load language 'english'...
Package biblatex Info: ... file 'english.lbx' found.
(/usr/local/texlive/2021/texmf-dist/tex/latex/biblatex/lbx/english.lbx
File: english.lbx 2020/12/31 v3.16 biblatex localization (PK/MW)
))
Package biblatex Info: Input encoding 'utf8' detected.
Package biblatex Info: Automatic encoding selection.
(biblatex)             Assuming data encoding 'utf8'.
Package biblatex Info: Document encoding is UTF8 ....
(/usr/local/texlive/2021/texmf-dist/tex/latex/l3kernel/expl3.sty
Package: expl3 2021-06-18 L3 programming layer (loader)
)
Package biblatex Info: ... and expl3
(biblatex)             2021-06-18 L3 programming layer (loader)
(biblatex)             is new enough (at least 2020/04/06),
(biblatex)             setting 'casechanger=expl3'.
(/usr/local/texlive/2021/texmf-dist/tex/latex/biblatex/blx-case-expl3.sty (/usr
/local/texlive/2021/texmf-dist/tex/latex/l3packages/xparse/xparse.sty
Package: xparse 2021-06-18 L3 Experimental document command parser
)
Package: blx-case-expl3 2020/12/31 v3.16 expl3 case changing code for biblatex
)
\openout3 = `bibpreview.bcf'.

Package biblatex Info: Trying to load bibliographic data...
Package biblatex Info: ... file 'bibpreview.bbl' not found.
No file bibpreview.bbl.
Package biblatex Info: Reference section=0 on input line 21.
Package biblatex Info: Reference segment=0 on input line 21.

LaTeX Warning: Citation 'elmer:prayers' undefined on input line 23.

LaTeX Warning: Empty bibliography on input line 24.

(./bibpreview.aux)

LaTeX Warning: There were undefined references.

Package biblatex Warning: Please (re)run Biber on the file:
(biblatex)                bibpreview
(biblatex)                and rerun LaTeX afterwards.

Package logreq Info: Writing requests to 'bibpreview.run.xml'.
\openout1 = `bibpreview.run.xml'.

 )
Here is how much of TeX's memory you used:
 10637 strings out of 478519
 211652 string characters out of 5849945
 1231164 words of memory out of 5000000
 28570 multiletter control sequences out of 15000+600000
 403430 words of font info for 27 fonts, out of 8000000 for 9000
 1141 hyphenation exceptions out of 8191
 85i,1n,94p,739b,3818s stack positions out of 5000i,500n,10000p,200000b,80000s

No pages of output.
PDF statistics:
 0 PDF objects out of 1000 (max. 8388607)
 0 named destinations out of 1000 (max. 500000)
 1 words of extra memory for PDF output out of 10000 (max. 10000000)

---------- BibTeX log file -------
File: "/var/folders/98/j_f65jms7jzcygkvtc7nh9ch0000gn/T/bibdesk.CrjbDN/bibpreview/bibpreview.blg"
[0] Config.pm:311> INFO - This is Biber 2.16
[0] Config.pm:314> INFO - Logfile is 'bibpreview.blg'
[85] biber-darwin:340> INFO - === Fri Sep 10, 2021, 10:54:46
[105] Biber.pm:415> INFO - Reading 'bibpreview.bcf'
[273] Biber.pm:952> INFO - Found 1 citekeys in bib section 0
[288] Biber.pm:4340> INFO - Processing section 0
[300] Biber.pm:4531> INFO - Looking for bibtex format file 'bibpreview.bib' for section 0
[309] bibtex.pm:1689> INFO - LaTeX decoding ...
[313] bibtex.pm:1494> INFO - Found BibTeX data source 'bibpreview.bib'
[324] Utils.pm:395> WARN - ISBN '979-168-3593-348' in entry 'elmer:prayers' is invalid - run biber with '--validate_datamodel' for details.

---------- BibDesk info ----------
<BDSKTeXTask: 0x6000013242d0> {
ivars:
    delegate = "<BDSKPreviewer: 0x6000007091e0>"
    file name = "bibpreview"
    template = "/Users/Roy/Library/Application Support/BibDesk/previewtemplate.tex"
    TeX file = "/var/folders/98/j_f65jms7jzcygkvtc7nh9ch0000gn/T/bibdesk.CrjbDN/bibpreview/bibpreview.tex"
    BibTeX file = "/var/folders/98/j_f65jms7jzcygkvtc7nh9ch0000gn/T/bibdesk.CrjbDN/bibpreview/bibpreview.bib"
    TeX binary path = /Library/TeX/texbin/pdflatex
    BibTeX binary path = /Library/TeX/texbin/biber
    Encoding = "Western (ASCII)"
    BibTeX style = "biblatex"
    Helper files = (
)

environment:
    SHELL = "/bin/bash"
    BIBINPUTS = "(null)"
    BSTINPUTS = "(null)"
    TEXINPUTS = "(null)"
    TEXCONFIG = "(null)"
    TEXMFCONFIG = "(null)"
    PATH = "/usr/bin:/bin:/usr/sbin:/sbin" }

Any help with this is greatly appreciated. I'm baffled.

A: Well, after restarting my machine, things are now working normally. I guess I should have done that as a first resort. I still don't understand why that corrected the issue, but I am glad it did.
Moral of the story: when you have a problem, restart your computer.


text:
Q: Py2app: saving files on hard drive with easygui I usually save xls files created within Python scripts on my hard drive. That 's usually a pretty straight forward thing to do with pandas, for instance.
My problem is that I'm trying to accomplish this from a py2app-compiled script. I tried using easygui to ask where (which folder) to save the file, but I'm not sure how to go about doing it, and once compiled into an app, it crashes at the end.
Here's what I attempted:
path = easygui.diropenbox() #Easygui is used to get a path in order to save the file to the right place
dfA = pd.DataFrame(A) #the pandas dataframe
C = ['Gen','Density','ASPL','Modularity'] # pandas' excel file header
name = str(n) + "_" + str(NGEN) + "_" + str(nbrhof) + ".xls" # the name of the file (should I add the path here somewhere?)
dfA.to_excel(name, path, header=C,index=False) # exporting the dataframe to excel

Can I modify this script to save the excel file named "name" to the folder chosen with "easygui.diropenbox()", from a py2app-compiled app?
The Traceback is as follow:
Traceback (most recent call last):
File "/Users/myself/Dropbox/Python/Tests/test2/myscript.py", line 135, in <module>
nx.write_gexf(G, path, name+".gexf")
File "<string>", line 2, in write_gexf
File "/Library/Python/2.7/site-packages/networkx-1.8.1-py2.7.egg/networkx/utils/decorators.py", line 241, in _open_file
fobj = _dispatch_dict[ext](path, mode=mode)
IOError: [Errno 21] Is a directory: '/Users/Rodolphe/Desktop/chosenfolder'
[Finished in 65.5s with exit code 1]
[shell_cmd: python -u "/Users/myself/Dropbox/Python/Tests/test2/myscript.py"]
[dir: /Users/Rodolphe/Dropbox/Python/Tests/test2]
[path: /usr/bin:/bin:/usr/sbin:/sbin]

A: Here is a working version:
import pandas as pd
import easygui
import os

A = {'one' : pd.Series([1., 2., 3.], index=['a', 'b', 'c']),
     'two' : pd.Series([1., 2., 3., 4.], index=['a', 'b', 'c', 'd'])}
dfA = pd.DataFrame(A) #the pandas dataframe

path = easygui.diropenbox() # easygui is used to get a path
name = "tmp.xlsx" # the name of the file
path = os.path.join(path, name)  # this is the full pathname
dfA.to_excel(path, 'tmp_sheet') # exporting the dataframe to excel

Note that the to_excel() method has an initial parameter that is the full path name to the Excel sheet you are writing and the second parameter is the name of the worksheet.
Also it seems your stack trace is referring to another part of your script and may be pointing to another bug.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to test my Kubernetes Architecture (With drone.io) I'm currently working on a kubernetes project, and I want to put my work in prod, but before that,  the company wants to be able to test the kubernetes architecture (create the right pod, communicate, etc... ).
About the architecture :
   -It's a single NODE architecture powered by minikube
   - I've got some POD, some JOB, 1 cronJob
   - My jobs are managed by a python script who call the API
I need to be able to test my architecture and my python script (with pytest)
As a CD/CI, the company use Drone.io
I already try kind, pupernetes, and ding.
Any idea?
PS: It's my first post on StackOverflow so if I made any mistake just tell me

A: You need to integrate your version control with drone.io ( i assume you already have)
Configure drone.io to make docker images of you code/app

Push docker images to registry

Configure a webhook that fires a deployment upon getting the new tag for image

Configure the kubernetes yaml manifest for deploymenet that will be deployed to kuberntes

Refine that above steps so that it works for test/dev/prod environmenets.

Ideally you commit code to test/dev , package it as docker image , test it in test namespace , and then port the change to prod branch , followed by new docker build , and kubernetes deployment


text:
Q: Serialize/Deserialize list of objects using json and python How do i serialize a list of objects(Person) to a json file and then read that json file back and deserialize them back into objects? I know how to write to a json file but i'm not clear on how to convert my objects to json properly.
Below is my simplified snippet of code. I have a list containing two people and i want to serialize them and save to a json file. Then deserialize them back to objects of type People.
Thanks for the help.
import json

class Person(object):
    def __init__(self, name, nickname):
        self.name = name
        self.age = 0
        self.nickname = nickname

# create a few people
A = Person('John', 'Joker')
B = Person('Marisa', 'Snickerdoodle')

# add people to list
peeps = []
peeps.append(A)
peeps.append(B)

# dummy data saving to json for testing
data = {
   'name' : 'ACME',
   'shares' : 100,
   'price' : 542.23
}

with open('data.json', 'w') as outfile:
    json.dump(data, outfile)

A: The json module expects lists, dicts, strings, numbers, booleans, and None, not custom classes. You need to make a dictionary out of your People instance. A simple way to do this is with vars(A).

A: You cannot serialize custom classes using JSON.
You should use the pickle module instead. From the docs:
https://docs.python.org/3/library/pickle.html#comparison-with-json

JSON, by default, can only represent a subset of the Python built-in
  types, and no custom classes;

Emphasis mine.
Also, from http://www.json.org/:

JSON is built on two structures:

*

*A collection of name/value pairs. In various languages, this is realized as an object, record, struct, dictionary, hash table, keyed
  list, or associative array.

*An ordered list of values. In most languages, this is realized as an array, vector, list, or sequence.

Again, emphasis is mine. In python, you can serialize dictionaries or lists that contain values, where values can be:

A value can be a string in double quotes, or a number, or true or
  false or null, or an object or an array. These structures can be
  nested.

A: add to_dict method to your person class. try this
In [2]: class Person(object):
   ...:         def __init__(self, name, nickname):
   ...:                 self.name = name
   ...:                 self.age = 0
   ...:                 self.nickname = nickname
   ...:         def to_dict(self):
   ...:             data = {}
   ...:             data['name'] = self.name
   ...:             data['age'] = self.age
   ...:             return data
   ...:
peeps = []
peeps.append(A.to_dict())
peeps.append(B.to_dict())

In [9]: with open('data.json', 'w') as outfile:
   ...:     json.dump(peeps, outfile)

In [10]: !cat data.json
[{"age": 0, "name": "John"}, {"age": 0, "name": "Marisa"}]

Update:
To deserialize json to python object
In [4]: with open('data.json', 'r') as infile:
   ....     data = json.loads(infile.read())
   ...:
In [5]: A = Person(data[0]['name'], data[0]['nickname'])


text:
Q: Method locateStructure of the ServerWorld class returning null For a Fabric mod, I am making an item that locates the nearest Nether Fortress on its use:
@Override
public TypedActionResult<ItemStack> use(World world, PlayerEntity user, Hand hand) {
    if (!world.isClient) {

        ServerPlayerEntity player = (ServerPlayerEntity) user;
        ServerWorld serverWorld = player.getWorld();

        TagKey<ConfiguredStructureFeature<?, ?>> tagKey = TagKey.of(Registry.CONFIGURED_STRUCTURE_FEATURE_KEY, Registry.STRUCTURE_FEATURE.getId(StructureFeature.FORTRESS));
        System.out.println(serverWorld.locateStructure(tagKey, player.getBlockPos(), 1000, false));
    }
    user.getStackInHand(hand).decrement(1);
    return TypedActionResult.consume(user.getStackInHand(hand));
}

However, I have attempted to figure out how to use the locateStructure method for a while now, but I have yet to be able to get a result that does not return null.
I understand that the locateStructure method in the ServerWorld class uses the locateStructure method in the ChunkGenerator class which passes a RegistryEntryList from the structure's TagKey after using the get method as an Optional.
The main issue I have found is in getting an Optional of the Nether Fortress TagKey that doesn't just return Optional.empty.
serverWorld.getRegistryManager().get(Registry.CONFIGURED_STRUCTURE_FEATURE_KEY)

returns
Registry[ResourceKey[minecraft:root / minecraft:worldgen/configured_structure_feature] (Stable)]

and then
serverWorld.getRegistryManager().get(Registry.CONFIGURED_STRUCTURE_FEATURE_KEY).getEntryList(tagKey)

returns Optional.empty despite using the Fortress TagKey and getting the Registry of the configured structure feature.
Having said that, how would you go about using the locateStructure method without it returning null or is there another way to locate the coordinates of a structure?
I apologize if this is a stupid question, but I am at a genuine loss.


text:
Q: angularjs scoping in a modal window I created a plunker at http://plnkr.co/edit/AQl49R?p=preview which demonstrates an issue I am having.
When you click "open" it launches a modal window. Click "xx" and it shows the id for the element that is selected in the select2 select box. Change the selected element in select2. It will update on the screen, but when you click "xx" it does not seem to be refreshing to show the new id.  It looks like a scoping issue to me - but I am not sure what else I need to do.

A: You need to change your ng-model to an object.
 $scope.items = {};
 // or $scope.items = [];
 $scope.items.chosenItem = { id: 3, text: "bamboo" };

And in the HTML:
<input type="hidden" ui-select2="select2ConfigCustomer" style="width: 200px" placeholder="All" ng-model="items.chosenItem">

Here's an updated Plunker.
http://plnkr.co/edit/T8D1Tw?p=preview

A: Select2 is creating its own scope, so when you choose an item, it only affects the  $scope.chosenItem in the select2.
What you need to do is create a hash/Object to hold the chosenItem:
In app.js:
$scope.foo = {};
$scope.foo.chosenItem = { id: 3, text: "bamboo" };

In index.html:
<input type="hidden" ui-select2="select2ConfigCustomer" ng-model="foo.chosenItem">

Children scopes cannot change the parents' scope variables directly, but they can change values inside a hash/Object.


text:
Q: Php Chat implementation Hai
I want to build a web site containing chat. i am working with PHP,  I want  a code to implement a chat with php .Any one help me to do this?  I know Ajax . i don't Know any other languages...

A:
Ajax Chat is a light-weight
  customizable web chat software
  implemented in JavaScript and PHP. The
  script does not require Java, Flash,
  or any other plugins. Features:

*

*Public and private chat.

*Login as a registered user or as a guest.

*Away status, custom colors, smileys, user gender/status icons.

*Ajax Chat can be integrated with a third-party membership system by
  implementing user authentication
  routine. Advanced integration options:
  if user is logged in to the website,
  he can be logged in to the chat
  automatically.

http://www.php-development.ru/javascripts/ajax-chat.php
Also you can read this
Writing a JavaScript/PHP Chat Server

A: You may want to consider using a ready solution instead of reinventing the wheel. Try phpFreeChat.

A: We are currently working with LiveZilla, this very well, the only thing the company must have Windows PC. The operator interface is on ".NET"
livezilla


text:
Q: Home Page background image different from other pages I have a site with about 7 different pages. I'd like to have two different background images, one for the home page and another that will display on every other page. Does this require Javascript/Jquery or simple css?
As I show below, I set my body to display the background image on the six other pages. Then tried using css directly in my HTML index page and display a different background but it failed.
body {
font-family: Helvetica, Arial, sans-serif;
background: url(images/hso-palmtree-background.jpg) no-repeat center center fixed;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
}

A: You can specify a specific class for your body tag on each page.
Say on home:
  <body class="home">

And on each page
 <body class="page-1">
 <body class="page-2">
 ....

Then your css could be separated into several rules that would match each body class, specialization
/* common body css */
body {
font-family: Helvetica, Arial, sans-serif;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
}

/* specialized body for home */
body.home {
   background: url(images/hso-palmtree-background.jpg) no-repeat center center fixed;
}

/* specialized body rules for page 1 */
body.page-1 {
   background: url(images/background-for-page-1.jpg) no-repeat center center fixed;
}

and so on...

A: there alot of ways
make every body have an id or class
or add the background as html <style>background :imgurl</style>


text:
Q: Swift - Accessing AppDelegate window from viewController I make walkthrough (onboarding flow) in my app and I'd like to have a skip button.
The button is located on viewController, so I figured out that the best way to move to another viewController would be access app delegate window.
However, it keeps getting me an error that AppDelegate.Type does not have a member called "window".
@IBAction func skipWalkthrough(sender: AnyObject) {
    let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
    AppDelegate.window!.rootViewController = RootViewController
}

Is there anything wrong with such approach?
Thanks in advance!

A: appDelegate.window!.rootViewController is not working in Swift 5
Here is working code
Add below extension
extension UIWindow {
    static var key: UIWindow! {
        if #available(iOS 13, *) {
            return UIApplication.shared.windows.first { $0.isKeyWindow }
        } else {
            return UIApplication.shared.keyWindow
        }
    }
}

use
let mainSB = UIStoryboard(name: "Main", bundle: nil)

if let RootVc = mainSB.instantiateViewController(withIdentifier: "NavigationController") as? UINavigationController{
    UIWindow.key.rootViewController = RootVc
}

UIWindow.key // to access only window

A: You have a typo it is supposed to be appDelegate not AppDelegate. So like this:
@IBAction func skipWalkthrough(sender: AnyObject) {
    let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
    appDelegate.window!.rootViewController = RootViewController
}

Swift 3.2
@IBAction func skipWalkthrough(_ sender: AnyObject) {
        let appDelegate = UIApplication.shared.delegate as! AppDelegate
        appDelegate.window!.rootViewController = controller
    }

A: You can also use conditional binding to reach the window.
if let window = UIApplication.shared.windows.first {
    // use window here.
}

A: This is for with or without Storyboard and it is working for Swift 3+
let appDelegate = UIApplication.shared.delegate as? AppDelegate
let mainStoryboard = UIStoryboard(name: "Main", bundle: nil)
let homeController = mainStoryboard.instantiateViewController(withIdentifier: "HomeViewController") as! HomeViewController
appDelegate?.window?.rootViewController = homeController

A: You are using the protocol name (i.e. AppDelegate) instead of the instance:
Should be:
appDelegate.window!.rootViewController = RootViewController

A: You can access tab bar anywhere from the app. Use below:
let appDelegate = UIApplication.shared.delegate as! AppDelegate

if let tabBarController = appDelegate.window!.rootViewController as? UITabBarController {
    if let tabItems = tabBarController.tabBar.items {
       let tabItem = tabItems[2]
       tabItem.badgeValue = "5" //enter any value
    }
}

A: Swift 3
This is a better way:
    if let window = NSApplication.shared().windows.first {
        window.acceptsMouseMovedEvents = true;
    }

A: This solution work for :
 After Login / Register Programmatically add UITabbarController
let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
appDelegate.window!.rootViewController = tabs
appDelegate.window!.makeKeyAndVisible()


text:
Q: utilizing a static library to create an import library I am interested in using my static lib to create a dll (implicitly linking). which means I need to (in vs2008)
create a dll project that should generate the following:

*

*header file (which have export function declarations. These are simple wrappers to actual functions in the static lib using __declspec(dllexport) which are in the .cpp )

*import lib which will be made as a result of creating the dll

*the actual dll which is created.

I have made a test program that will utilize the above dll(including the import lib/header files) to test it.
in this I have included all the three items. now the exe compiles/links without issue.
however in the main.cpp when i call the exported functions (with the associated __declspec(dllimport) call it never seems to execute. I am uncertain why this is?
Its almost like the even though the exe can see the exported function in in the dll...the dll cannot call on the code that is in the static lib?
i just cannot answer why my exe can't see the code in the static lib? do i need an archiver/librarian for vs2008 to include all those obj files as part of the import lib?
I am at a loss and am not sure how to test this?
other than just making my static lib directly into a dll. I wanted to try this method. I know i am missing something...i have read all over the place and i am just stuck. There were some threads here that had some people posting something similar but i can't seem to get it.  please be as detailed as possible as I am new to this.  thanks again.
update 1:
ok so currently i added the extern line to the function prototype and now it sees the exported function from the dll. however, now the only issue left is that:
i can't invoke the function that this exported function (aka wrapper) is trying to call. which happens to be in the static library. how should my exe get visibility to that static library function. I know it can be done because I think there was one other person on this board who was able to make this work.
update 2: my setup is exactly like this questioner...
How to force inclusion of an object file in a static library when linking into executable?
but i am not using explicit linking. i am using implicit linking. my real issue is how to call a static lib function in my dll wrapper which is exported to the exe?

A: If the app and DLLs are MFC app/dlls, then make sure that the application and all dlls are either "Debug" versions or "release" versions and not a mix.


text:
Q: I want not to save the logs that are "warning" in the log crontab I want not to save the logs that are "warning" in the log file that the crontab creates, I only want the "error" messages, does anyone know how I can exclude these messages?
I have tried doing a grep -v but it doesn't work:
45  5   *   *   *   /home/username/barc/backupsql.sh 2>&1 | grep -v 'Warning: Using a password on the command line interface can be insecure.'
Thanks in advance for anyone trying to help me.

A: Crontab lets you execute 1 scheduled command/script at a time.
Piping the output of your script to Grep command won't work. Furthermore, crontab by default redirects output to dev/null, therefore you won't see the output unless you save it to a file.
I suggest something like this:

*

*Edit your script to redirect it's output to a file with your grep command. For example by adding

DATE=$(date +"%m_%d_%Y")

some command | grep -v Warning >> /tmp/$DATE.log # Here

*Edit your Cron job to execute the script every day like you did, removing everything after the pipe:

45  5   *   *   *   /home/username/barc/backupsql.sh

*In order to monitor the output you could use tail command as follows:
tail -f /tmp/$DATE.log


text:
Q: How to create hard link on directory in Linux? I know that it is forbidden to create hard links on directories because of the memory errors it will cause, but I want to bypass this restriction. Can it be done?
I create links by using ln and after I try to do something like ln dir1 dir2 I get ln: dir1: hard link not allowed for directory

A: The reason you can't create hard links on directories is not because of memory.  It's because it would create a loop in the filesystem hierarchy and it is prohibited by the filesystem.  This can't be bypassed.
If you want a link to a directory there are several options:

*

*symbolic links (ln -s)

*bind mounts (root only)

*nfs mounts (and other network filesystems) (root only, exported filesystems only)

Having said that, it is actually possible to indirectly make hard links to directories.  Every directory has two hard links to directories in it -- . which links to the directory itself and .. which links to the parent directory.  So if you check the number of hard links a directory has, this is how many subdirectories are in it.  And you can create more hard links by making more subdirectories.  (Note that some filesystems generate these on the fly and don't actually store them.)

A: Possibly, if your chosen filesystem has a tool like debugfs or xfs_db. Use it to create a directory entry that points at your chosen inode number. However, the filesystem checks will probably keep attempting to correct it every time.
If you have a situation where the link needs to cross into/out of a chroot or similar, use a bind mount instead. (Most container or sandbox tools already know how to set up bind mounts.)

A: I did it once,  it was on extfs on kernel 0.95
Linux Soft Landing System distro.
Afterwards I was unable to unlink the doubly linked directory


text:
Q: Basic HTACCESS Issue I have installed WAMPSERVER on my system. Inside the htdocs folder, i have my project folder which is named 'online-store'
so to access my project i write
http://localhost/online-store

I want all requests like
http://locahost/online-store/products/2 or http://localhost/online-store/products/

to be redirected to api.php.
I have written the htaccess code for that but it says
/online-store/products url was not found on the system.

I am rewriting htaccess to make it a restful API.
Below is my HTACCESS CODE.
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule (.*)$ api.php?request=$1 [QSA,NC,L]
</IfModule>

A: Make sure to place this code in htdocs/online-store/.htaccess:
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /online-store/

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ api.php?request=$1 [QSA,L]
</IfModule>

A: you need to change code in httpd.conf
wampdir/bin/apache/apache2.x.x./conf/httpd.conf
<FilesMatch "^\.ht">
    Order allow,deny
    Allow from all
    Satisfy All
</FilesMatch>


text:
Q: Getting 'Uncaught' after catching error in firebase.auth() with async async login({ commit }, { email, password }) {
  let result
  try {
    result = await firebase.auth().signInWithEmailAndPassword(email, password)
    commit('setUser', result.user)
  } catch (err) {
    commit('setError', err)
  }
}

This is an action in Vuex. When this runs, I expect the commit('seteError', err) to be a valid error handler for the error returned from catch (err). Instead, I get an 'Uncaught' exception and execution stops.
Would appreciate any insights from anyone who managed to use async with firebase.auth()

A: I ran into the same issue today - it appears to be due to the implementation of the Closure promise library that firebase auth uses. There is a closed issue in the firebase-js-sdk project here with some details on it. Ultimately, what is happening with this implantation is a timeout is getting set that throws an exception outside of the scope of the try/catch:

To avoid this, the exception needs to be handled by calling .catch() on the returned promise e.g.:
firebase.auth().signInWithEmailAndPassword(email, password)
  .catch((ex) => { /* handle exception */ });

As I have all of my firebase logic wrapped and centralized, what I ended up doing is wrapping the firebase Promise in one of my own:
export async function signIn(email, password) {
  return new Promise((resolve, reject) => {
    firebase.auth().signInWithEmailAndPassword(email, password)
      .then((userCreds) => resolve(userCreds))
      .catch((reason) => reject(reason));
  });
}

The wrapper function can then be called using async await:
try {
  const result = await signIn(email, password)
  // Do what you need to with the result
} catch (ex) {
  // Handle any exceptions
}

A: This is how I managed to handle firebase authentication with async in Vuex. I needed to use onAuthStateChanged
async login({ commit, dispatch }, { email, password }) {
  try {
    await firebase.auth().signInWithEmailAndPassword(email, password)

    await dispatch('session')
  } catch (err) {
    commit('setError', err)
  }
}

Where the 'session' dispatch simply does:
async session({ commit }) {
  let user
  try {
    user = await userInSession()
    commit('setUser', user)
  } catch (err) {
    console.error(err)
    commit('setUser', {})
  }
}

and the userInSession function uses onAuthStateChanged:
const userInSession =  function () {
  return new Promise((resolve, reject) => {
    firebase.auth().onAuthStateChanged((user) => {
      if (user) {
        resolve(user.uid)
      } else {
        reject(Error('No user authenticated'))
      }
    })
  })
}


text:
Q: Show integers pulled from DB as a % inside of chartJS I have a users progress saved into a table studentTakingModule in the database. I am using chartJS to then plot this data to show the user what % they have completed. However, I only seem to be getting one figure returned on the pie chart when there should be 6. Any guidance would be much appreciated.
The SQL query I am using is below (which pulls out the moduleName, pageID & the completed) is executing fine and returning the columns needed. It's the data being plotted into the chart where the issue is.
SELECT `studentTakingModule`.`pageID`, `studentTakingModule`.`completed`, `module`.`moduleName`
FROM `studentTakingModule`
INNER JOIN `module` ON `studentTakingModule`.`moduleID` = `module`.`moduleID`
WHERE `studentID` = ?

There are 12 pages in each section, so, if the user has 12 under pageID in the table, completed will change to a 1 and they would have completed 100% of that section.
The code I am using so far is this:
<canvas id="progOnModules" style="width=5 height=5"></canvas>
<?php
$studentID = $_SESSION['studentID'];

$progress = [];
$moduleName = [];

$stmt = $conn->prepare ("SELECT `studentTakingModule`.`pageID`, `studentTakingModule`.`completed`, `module`.`moduleName` FROM `studentTakingModule` INNER JOIN `module` ON `studentTakingModule`.`moduleID` = `module`.`moduleID` WHERE `studentID` = ? ");

$stmt->bind_param("i", $studentID);
$stmt->execute();
$result = $stmt->get_result();
    while($row = $result -> fetch_assoc())
        {
            $progress[] = $row['pageID'];
            $moduleName[] = $row['moduleName'];
            $completed = $row['completed'];
         }
$modProgress = implode(',',$progress);
$modTotal = 12 - $modProgress;

$modName = json_encode($moduleName);
$modCompleted = $completed;

// This is for the % complete
    if ($modCompleted == 1){
        $modPercent = 100;
    } else {
      $modPercent = (($modProgress-1)/12)*100;
    }
?>

script for the chart:
<script>
var ctx = document.getElementById('progOnModules').getContext('2d');
   var chart = new Chart(ctx, {
   type: 'pie',
   data: {
       labels: <?php echo $modName ?>, //This is to plot the 6 names
       datasets: [{
       label: '`Modules`',
           data: [<?php echo $modPercent ?>], // This is where the 6 %'s should be
               backgroundColor: [
               'rgba(255, 99, 132, 0.2)',
               'rgba(54, 162, 235, 0.2)',
               'rgba(255, 206, 86, 0.2)',
               'rgba(75, 192, 192, 0.2)',
               'rgba(153, 102, 255, 0.2)',
               'rgba(255, 159, 64, 0.2)'
            ],
                borderColor: [
                'rgba(255,99,132,1)',
                'rgba(54, 162, 235, 1)',
                'rgba(255, 206, 86, 1)',
                'rgba(75, 192, 192, 1)',
                'rgba(153, 102, 255, 1)',
                'rgba(255, 159, 64, 1)'
            ],
                borderWidth: 2
            }]
        },
    });
</script>

Error: Notice: A non well formed numeric value encountered
Table Screenshot:


text:
Q: Folder IDs for Content Builder Is there any way to get the folder IDs in Content Builder like we see in data extensions? As you know, when you hover the folder with your mouse in data extension part, you can see the IDs of the folders.

A: Unfortunately, I don't think there is an easy way to get the ID from the content builder folder display.
If you need this as a one-off, there is a workaround:

*

*In the folder tree to the left, right click on the right of the folder you want to ID (if you right click on the folder directly, you get a CB-specific interaction, you want to click on the right of it to get default browser behavior)

*Then select "inspect" or "inspect element". You will see the HTML for it in the browser dev tools:

*Look for the data-id attribute. Like in here 257730.

A: On the email studio -> content builder:

*

*Go to the parent folder

*Click on "show folders" (top center/left)

*Click on the gear icon (top right, under "create")

*Select "ID"


text:
Q: Plotting city locations on Python 3 My question is a follow-up of this:
plotting US cities on a map with matplotlib and basemap.
I would like to use some Python library to plot on a map city locations, starting from a list like this:
    L = ['Paris', 'Lyon', 'Marseille', '...']

In the linked GIS question, this was easily achieved through Basemap, which has however been deprecated in favour of Cartopy and does not currently work on Pyhton 3. Is there a simple way to achieve the same result with Cartopy or another library?
This Reddit thread may be helpful for advanced users but being a newbie I was looking for something more intuitive.


text:
Q: Record is losing its store I'm creating a class with extjs record in config. I keep a reference to this record. On creating the class instance I expected the record and It's completely ok.
Later, in one of the object methods I'm trying to use this record. Quite unexpectedly the record has lost its store reference. Except this the record looks ok with the right data.
I hacked the situation keeping reference to the store in initialization phase:
this.store = this.recordLoosingItsStore.store;

And later I can retrieve my record like this:
var recordOK = this.store.getById( this.recordLoosingItsStore.getId() );

Can anyone shares opinion what's happen and where my record.store disappears? How can I debug it easily? I tried to advice for store datachanged event but this didn't produce any positive results.

A: If you check the documentation, it states that a record instance may only belong to a store instance at a time. Is it possible that you are assigning it to a different store at any point in your code and then destroying that other store? If that is the case, using the .copy method when assigning the record to a different store should solve the issue.
More info: http://docs.sencha.com/ext-js/3-4/#!/api/Ext.data.Record

A: It's hard to say where it's loosing it without looking at your code. Try to post some code here. If it's too big - try to extract places where you first load record and then all places where you do something with the store/record.


text:
Q: Creating playable DASH video encrypted with Clear Key encryption I am attempting to transcode and DASH (with Clear Key encryption) a sample H.264 file for the Google Shaka player. Every set of steps I've been able to piece together online results in a playable version if unencrypted, then breaks down when I attempt to layer in encryption.
Unencrypted
Here are the steps I follow for the working unencrypted version:

*

*Separate video from audio
ffmpeg -i input.mp4 -an -c copy video_only.mp4
ffmpeg -i input.mp4 -map 0:2 -c copy audio_only.m4a

*Transcode the video into a working variant (only 1 for now)
ffmpeg -i video_only.mp4 -an -vcodec libx264 -s 1280x720 -c:v libx264 -b:v 384k -bf 2 -g 90 -sc_threshold 0 -an -strict experimental video_only_384kbps.mp4

3a. Create the mpd
    MP4Box -dash 5000 -segment-name 'outputseg-%s' -url-template -bs-switching no \
        -out output.mpd -rap \
        audio_only.m4a \
        video_only_384kbps.mp4

4a. Load the video into Osmo4 or Google Shaka
It plays.
With Encryption
Now, I attempt to layer in encryption. Starting from after step 2 above:
3b. Encrypt the variants with Clear Key
    MP4Box -crypt drm.xml audio_only.m4a -out audio_only_encrypted.m4a
    MP4Box -crypt drm.xml video_only_384kbps.mp4 -out video_only_384kbps_encrypted.mp4

where drm.xml contains a sample derived straight from the MP4Box/GPAC site:
    <?xml version="1.0" encoding="UTF-8"?>
    <GPACDRM type="CENC AES-CTR">
      <!-- example for GPAC - keys are listed after the content and UL follows -->
      <DRMInfo cypherIV="0x00000000000000000000000000000001" cypherKey="0x6770616363656E6364726D746F6F6C31" cypherOffset="9" type="pssh" version="1">
        <BS ID128="6770616363656E6364726D746F6F6C31"/>
        <BS bits="32" value="2"/>
        <BS ID128="0x279926496a7f5d25da69f2b3b2799a7f"/>
        <BS ID128="0x676cb88f302d10227992649885984045"/>
        <BS bits="8" string="CID=Toto"/>
        <BS ID128="0xccc0f2b3b279926496a7f5d25da692f6"/>
        <BS ID128="0xccc0f2b3b279926496a7f5d25da692d6"/>
      </DRMInfo>
      <CrypTrack IV_size="16" IsEncrypted="1" first_IV="0x0a610676cb88f302d10ac8bc66e039ed" saiSavedBox="senc" trackID="1">
        <key KID="0x279926496a7f5d25da69f2b3b2799a7f" value="0xccc0f2b3b279926496a7f5d25da692f6"/>
      </CrypTrack>
    </GPACDRM>

4b. Create the mpd
MP4Box -dash 5000 -segment-name 'outputseg-%s' -url-template -bs-switching no \
    -out output.mpd -rap \
    audio_only_encrypted.m4a \
    video_only_384kbps_encrypted.mp4

5b. Load the video into Osmo4 or Google Shaka.
* On Osmo4, no errors are found but the player just hangs until I kill it
* On Google Shaka, I consistently receive a player error:
"CustomEvent {detail: Error: No DrmInfo exists!
    at shaka.media.EmeManager.buildKeySystemQueries_ (http://localhost:808…, srcElement: null, target: s…a.p…r.Player, currentTarget: s…a.p…r.Player}
The output.mpd after 5b looks like this:
    <?xml version="1.0"?>
    <!-- MPD file Generated with GPAC version 0.5.2-DEV-rev566-g4c06d0f-master  at 2015-09-03T19:17:57.544Z-->
    <MPD xmlns="urn:mpeg:dash:schema:mpd:2011" minBufferTime="PT1.500S" type="static" mediaPresentationDuration="PT0H0M54.424S" maxSegmentDuration="PT0H0M4.992S" profiles="urn:mpeg:dash:profile:full:2011" xmlns:cenc="urn:mpeg:cenc:2013">
     <ProgramInformation moreInformationURL="http://gpac.sourceforge.net">
      <Title>output.mpd generated by GPAC</Title>
     </ProgramInformation>

     <Period duration="PT0H0M54.424S">
      <AdaptationSet segmentAlignment="true" lang="eng">
       <Representation id="1" mimeType="audio/mp4" codecs="mp4a.40.2" audioSamplingRate="48000" startWithSAP="1" bandwidth="140631">
        <AudioChannelConfiguration schemeIdUri="urn:mpeg:dash:23003:3:audio_channel_configuration:2011" value="2"/>
        <ContentProtection schemeIdUri="urn:mpeg:dash:mp4protection:2011" value="cenc" cenc:default_KID="27992649-6a7f-5d25-da69-f2b3b2799a7f"/>
        <SegmentTemplate timescale="48000" media="outputseg-audio_only_encrypted$Number$.m4s" startNumber="1" duration="239616" initialization="outputseg-audio_only_encryptedinit.mp4"/>
       </Representation>
      </AdaptationSet>
      <AdaptationSet segmentAlignment="true" maxWidth="1280" maxHeight="720" maxFrameRate="24" par="16:9" lang="eng">
       <Representation id="2" mimeType="video/mp4" codecs="avc1.64001f" width="1280" height="720" frameRate="24" sar="1:1" startWithSAP="1" bandwidth="375052">
        <ContentProtection schemeIdUri="urn:mpeg:dash:mp4protection:2011" value="cenc" cenc:default_KID="27992649-6a7f-5d25-da69-f2b3b2799a7f"/>
        <SegmentTemplate timescale="12288" media="outputseg-video_only_384kbps_encrypted$Number$.m4s" startNumber="1" duration="46080" initialization="outputseg-video_only_384kbps_encryptedinit.mp4"/>
       </Representation>
      </AdaptationSet>
     </Period>
    </MPD>

Software versions:

*

*MP4Box: GPAC version 0.5.2-DEV-rev566-g4c06d0f-master

*FFMPEG: ffmpeg version 2.6.3 Copyright (c) 2000-2015 the FFmpeg developers
built with Apple LLVM version 6.1.0 (clang-602.0.53) (based on LLVM 3.6.0svn)

Does anyone have any suggestions on how to proceed?


text:
Q: When does Poopy the Bird come to drop poop on people? I have a mission from Zoe to drop poop from Poopy the Bird onto my citizens. However, I have not seen it yet. When does it arrive?

A: The bird will fly by once in a while at random, there's no set time and no way to make it appear. Look for something that resembles a seagull flying over your little town, and tap on it to fire away.

A: There is no way to make him come, you have to wait and he will come randomly. But here is a tip: When he does come, as you tap on him to make poop fall, he increases speed. So be sure to tap quickly if you want to get him to poop enough! CLICK FAST.

A: He comes at random times and nothing you can do to make him appear. Once you see a FLYING BIRD click on it to drop poop on your citizens.

A: When you see a sea Like gull you need to tap on it to make it poop if you want a lot of poop tap it millions of times


text:
Q: How to add premium subscriptions for commands in discord.py bot? I am thinking of adding a premium subscription to my bot for some commands . The only way striking my head right now is i should make a payments page with any service like razorpay or something and make a list of user id's for users who'll able to access those commands and make a custom check for each command.
Something like this:
list = [user id]
def user_is_premium(ctx):
    return ctx.message.author.id in list

But that thing'll be manual and I need to personally add user id's into list. Is there a way I can skip this hassle and make something where users will pay and their id's will automatically  be added or something like that , something better than this custom check stuff.
Remember, I am talking about subscription not one time payment so users will be need to renew their subscription per month for continuous access.

A: I would suggest using a database of some type firestore might be a good option with the free tier. Alternatively, you can use a google sheet.
You should use zapier as a way to automate it for you, if you don't want to do it your self.
The trigger should be the email you get for payment and with the discord name. Add it to the database and read it in your bot by using docs = db.collection(ctx.guild.id).where('name', '==', ctx.author.name) and check if expiration date is in the future. You can also convert that to id's.
This might not be the perfect solution but it should be east to implment all you need is to set the trigger right


text:
Q: Is there a way to get an email for all bug reports and feedbacks I receive for a published chrome extension? I have a chrome extension published in chrome store. The problem is that I don't receive any emails or notifications for any feedbacks or bug reports users raise. Is there any option to enable them? The only way to find now is to manually check if there are any feedbacks or open bugs, which is very inefficient.

A: Web Store provides no way to access feedback (or reviews), with the exception of web scraping those pages.
Here's the (old) feature request for this. It's in limbo for well over a year.


text:
Q: Issue with HAVING in SQL query Imagine table with two columns (there are more, but not relevant anyhow to this question):
  `EAN` bigint(20) unsigned DEFAULT NULL,
  `parameter_id` mediumint(8) unsigned DEFAULT NULL,

This query does not work and returns error:
SELECT EAN FROM eTovar WHERE EAN GROUP BY EAN HAVING parameter_id IS NULL

Error in query (1054): Unknown column 'parameter_id' in 'having
  clause'

But this query works:
SELECT EAN FROM eTovar WHERE EAN GROUP BY EAN HAVING MIN(parameter_id) != MAX(parameter_id)

I assume that for some reason, HAVING is able to reach MIN(parameter_id) but unable to reach clean parameter_id. Why?
I have MariaDB 5.5 (should be same as MySQL 5.5).

A: According to MySQL 5.5 docs

In standard SQL, a query that includes a GROUP BY clause cannot refer to nonaggregated columns in the HAVING clause that are not named in the GROUP BY clause. A MySQL extension permits references to such columns to simplify calculations. This extension assumes that the nongrouped columns will have the same group-wise values. Otherwise, the result is indeterminate.
  [...]
  In some cases, you can use MIN() and MAX() to obtain a specific column value even if it is not unique.

Have you tried replacing HAVING with WHERE in your first SQL:
SELECT EAN FROM eTovar WHERE EAN AND parameter_id IS NULL GROUP BY EAN;


text:
Q: Microsoft UAA Bus Driver for High Definition Audio Here are my specs first:

*

*ECS P4M800PRO-M478 (V1.0)

*Intel P4 Northwood 2.8 GHz

*2x 512MB PC2-4200 DDR2-533 SDRAM

*Maxtor 120 GB SATA HDD

*Visiontek HD 3650 512 MB DDR2 AGP

I have Microsoft UAA Bus Driver for High Definition Audio as a system device without a driver. However, I don't know where to get an "official" driver for this "device". It just seems so generic. However, I noticed that when I had the video card in another machine, that machine required the same driver. Still, I've downloaded all possible video drivers and that device still needs a driver.
Where can I find it?
EDIT 1: Formatted hard drive, installed XP with the bare essentials, then installed the card & drivers... still the same problem.
EDIT 2: Installed the ATi HDMI Audio Driver after the UAA driver installation failed, due to XP  being SP3 already. Now, the "Found New Hardware" dialog that pops up on start-up doesn't come up anymore, but in the Device Manager, I still get an (!) by Microsoft UAA Bus Driver for High Definition Audio. Hmph...

A: Turns out the audio has always worked... just had a bad cable. Still, the Device Manager still listed a driver conflict with the UAA High Definition Audio and it was never resolved. Switching over the Windows 7 Home Premium, drivers were automatically found and there were no issues at all.

A: The "UAA Driver" is the generic class audio driver.  Video drivers aren't going to help you.  You'll most likely have to get the audio driver from your motherboard manufacturers website.
There is one caveat: ATI video cards (like the one you have) can pass audio over HDMI, and have an embedded audio codec to do that, which does require a driver.  Normally this is packaged in with the latest ATI Catalyst drivers.  I have seen the driver offered standalone before though...
...
Ah!  It's here.

A: You should download and install the related audio driver for your motherboard. In your motherboard's official product page, navigate to Download tab, and expand Sound panel. There are links to Realtek AC'97 Audio Driver (19.9 MB).


text:
Q: Titanium can't remove child view I have a ScrollView which I am adding multiple View's into using this code:
payload = {
    booking : b,
    duration: duration,
    removeBooking: function(view_to_remove) {
        removeBooking(view_to_remove);
    },
    updateBooking: function(view_to_remove, new_booking) {
        removeBooking(view_to_remove);
        overlayBooking(new_booking);
    }
};

booking = Alloy.createController('appointments_bookable_booking', payload).getView(); // returns a View
$.intervals_container.add(booking); // this is adding a View into a ScrollView
...

removeBooking() then gets executed later on as a callback. I am then trying to remove the single View like this:
function removeBooking(booking_view) {

    for (var i = $.intervals_container.children.length - 1; i >= 0; i--) {
        if(booking_view === $.intervals_container.children[i]) {
            Ti.API.info('Found a match');
            $.intervals_container.remove($.intervals_container.children[i]);
        }
    };

}

I'm looping through the children just to show the view I'm trying to remove DOES actually exist in the children views array. I do get the 'Found a match' printed to my console but the view is never actually removed.
There are other views being added into the ScrollView as well. If I loop through the intervals_container.children and remove each one. The other views are removed apart from the ones created using the code above.
Can anyone see why I can't remove the view?
UPDATE
After trying ericfreshz'a answer I can remove ALL the views however this is not working to remove one:
if ($.intervals_container.children) {
        var _viewCount = $.intervals_container.children.length;
        for ( s = 0; s < _viewCount; s++) {
            if($.intervals_container.children[((_viewCount - 1) - s)] === booking_view) {
                Ti.API.info('Removing view');
                $.intervals_container.remove($.intervals_container.children[((_viewCount - 1) - s)]);
            }
    }
}

This should only remove the view which has been passed into the function but it doesn't. I get "Removing view" in my console but the view isn't removed.
UPDATE 2
I did an experiment to see if the scrollview was actually changed and it turns out the view is actually removed as the number of children views actually decreases however the view is still visible.
Ti.API.info('Count BEFORE: ' + $.intervals_container.children.length);

$.intervals_container.remove(booking_view);

Ti.API.info('Count AFTER: ' + $.intervals_container.children.length);

The result is one less.

A: Let's try my code as below :
if ($.intervals_container.children) {
   var _viewCount = $.intervals_container.children.length;
   for ( s = 0; s < _viewCount; s++) {
        $.intervals_container.remove($.intervals_container.children[((_viewCount - 1) - s)]);
   }
}

A: First is why not simply call
$.intervals_container.remove(booking_view);

I dont think you need to go through the hassle of children and children length.
That should work
If it doesn't can you try changing the scrollview layout (height, width,left...) and see if that changes something? (might be a layout update issue).
As a side note you should hold a reference of "children". Every time you access it it needs to make a copy natively. Plus there is a lock there so it might get long.


text:
Q: How to get the true node value in igraph So I have read in a network data in iGraph(R) and would like to store the nodes into a list. Here's what I have done:
G = read_graph("somegraph.graphml",format="graphml")
x = list(V(G))
> x
+ 15/15 vertices, from ecb3920:
[1]  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15

My question is, how do I get the true value, i.e. the actually node id in my data, from V(G). Thanks.
> dput(G)
structure(list(15, FALSE, c(13, 7, 9, 14, 10, 5, 4, 11, 6, 7,
14, 4, 13, 9, 10, 5, 5, 13, 9, 6, 7, 14, 12, 10, 14, 10, 11,
13, 9, 10, 12, 14, 8, 7, 11, 12, 8, 13, 14, 9, 11, 13, 13, 12,
14, 10, 13, 12, 14, 12, 13, 13, 14, 14), c(0, 0, 2, 2, 2, 2,
2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 6,
6, 6, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 10,
10, 10, 11, 11, 12, 12, 13), c(6, 11, 5, 15, 16, 8, 19, 1, 9,
20, 33, 32, 36, 2, 13, 18, 28, 39, 4, 14, 23, 25, 29, 45, 7,
26, 34, 40, 22, 30, 35, 43, 47, 49, 0, 12, 17, 27, 37, 41, 42,
46, 50, 51, 3, 10, 21, 24, 31, 38, 44, 48, 52, 53), c(1, 0, 6,
5, 2, 4, 3, 11, 15, 8, 9, 13, 14, 7, 12, 10, 16, 19, 20, 18,
23, 22, 17, 21, 25, 24, 33, 32, 28, 29, 26, 30, 27, 31, 36, 39,
34, 35, 37, 38, 40, 41, 45, 43, 42, 44, 47, 46, 48, 49, 50, 51,
52, 53), c(0, 0, 0, 0, 0, 2, 5, 7, 11, 13, 18, 24, 28, 34, 44,
54), c(0, 2, 2, 7, 16, 24, 26, 34, 40, 42, 46, 49, 51, 53, 54,
54), list(c(1, 0, 1), structure(list(), .Names = character(0)),
structure(list(id = c("1351920706", "500102244", "1454425532",
"1625050630", "510838353", "1262640078", "681721364", "1351920717",
"1260750116", "1524975171", "1070293410", "727198538", "715215233",
"1351920666", "500920034")), .Names = "id"), list()), <environment>), class = "igraph")

A: Just for closure (and to summarise from our chat): Based on the sample data you give, you can extract additional data for every vertex by indexing the corresponding element.
So
V(g)$id

returns
#[1] "1351920706" "500102244" "1454425532" "1625050630" "510838353"
#[6] "1262640078" "681721364" "1351920717" "1260750116" "1524975171"
#[11] "1070293410" "727198538" "715215233" "1351920666" "500920034"


text:
Q: Массив поиск максимального и минимального элемента Ввести одномерный массив X(N) (N<60). Найти максимальный и минимальный элемент, элементы между ними заменить значениями разности.Массив вывести до и после преобразования.
вопрос состоит в следующем:почему вместо вывода массива с элементами:
55 50 5 21 11

он выводит вот это:
55 50 5 50 50

почему последние два элемента в массиве он выводит неправильно?
Сам код программы
#include<iostream>
using namespace std;
int main()
{
int razniza;
int n;
cout « "Введите количество элементов в массиве: ";
cin » n;
setlocale(LC_ALL, "Russian");
int X[60];
for (int i = 0; i < n; i++) {
cout « "\nX[" « i « "]=";
cin » X[i];
}

cout « endl;
int max = X[0]; int min = X[0];
for (int i = 0; i < n; i++)
{
if (max < X[i]) {
max = X[i];
}
}

for (int i = 0; i < n; i++)
{
if (min > X[i]) {
min = X[i];
}
}
//cout « "Минимальный элемент в массиве:" « min«endl;

//cout « "Максимальный элемент в массиве:" « max«endl;
razniza=max-min;
//cout«"разница между максимальным и минимальным элементом в массиве:"«razniza«endl;

for (int i=0; i<n; i++) { //Модификация массива
if ((X[i]<max)&&(X[i]>min)) {
X[i] = razniza;
}
}
cout « "\nИзмененный массив a: "; //Вывод измененного массива
for (int i = 0; i < n; i++) {
cout « " " « X[i];
}
}

A: Ну, например, так:
void doit(int * X, int n)
{
    auto [m,M] = minmax_element(X,X+n);
    int delta = *M - *m;
    if (m > M) swap(m,M);
    for(++m; m != M; m++) *m = delta;
}

int main(int argc, char * argv[])
{
    int X[] = {55,10,5,21,11};
    doit(X,5);
    for(int i: X) cout << i << " ";
}

См. https://ideone.com/9Conxa


text:
Q: Check Constraint to Confirm Exactly One is not NULL I have a table with the columns CompaniesId and HotelsId. I want to write a check constraint that confirms that one of these columns is null and other one is not.
I tried the following expression:
(CompaniesId is null) <> (HotelsId is null)

When I attempt to save this in the Check Constraints dialog box in SSMS, I get the helpful message:

Error validating constraint 'CK_CostingLineItemVendors'.

Could someone help me with my syntax?
EDIT:
According to the article IS [NOT] NULL (Transact-SQL), the result of IS NULL or IS NOT NULL is Boolean. That's why I would assume I could compare these results for equality.

A: T-SQL does not have a usable boolean type. You can't have an expression that has boolean type and expect to use it like any other expression. All the places in T-SQL where you seemingly can use a boolean expression (like WHERE) are hard-coded places in the syntax. (Yes, this is a deficiency without specific reason.)
Simply abuse a bit or an int as a bool:
IIF(CompaniesId is null, 1, 0) <> IIF(HotelsId is null, 1, 0)

IIF is an intrinsic function that can take a condition as the first argument like a CASE can. You can't define such a function yourself.

A: This works:
   (CompaniesId is null AND HotelsId is not null)
OR (CompaniesId is not null AND HotelsId is null)


text:
Q: ¿Cómo debo usar setImageAlpha para hacer que una imagen sea transparente en Android Studio? Quiero que una imagen de la activity se vuelva transparente con una acción OnClick, no lo puedo hacer añadiendo atributo porque quiero que al darle click a la imagen se haga transparente con el OnClick.
Entonces hay un comando que se llama setImageAlpha(int), lo malo es que está limitado, porque solo puedo poner 0 o 1, con 0 no se ve porque se queda en 0% y con 1 se queda al 100%, ¿existirá algún comando parecido a setImageAlpha(int), pero que sea con un valor float? Necesito un comando en el que la transparencia pueda ser libre, porque quiero un 60% de transparencia. Esa es mi pregunta.

Ok me olvidé de algo, existe el comando setAlpha(), en el cual puse setAlpha(60) y pensé que ya podría funcionar, pero luego a ese comando se transformó a un texto tachado y me salió un mensaje emergente: "setAlpha(int) is deprecated as of API 16: Android Jelly Bean (4.0)" En mi proyecto estoy usando API 20 y me dice que el comando es obsoleto, ¿lo puedo usar igual o no funcionará? Lo veré al compilar.

A: Te recomiendo utilices el comando setVisibility(View.VISIBLE) o (View.INVISIBLE)
Yo lo utilizo para mostrar o no ciertos botones segun seleccion.
Pero si no lo quieres totalmente transparente, puedes utilizar el bakground del selector de color para hacerlo mas o menos transparente. O cambiar la imagen por otra mas ligera como si lo fuera.


text:
Q: Is it possible to refer to css styles as objects in JS code? I want to be able to do this:
import styles from 'switchstyle.css';

const Choice = function (props) {
    const cssClasses = [];

    if (props.active) {
        // i think .active would be defined in the css file
        cssClasses.push(style.active);
    }

    return (
        <div
            onClick={props.onClick}
            className={cssClasses}
        >
            {props.label}
        </div>
    );
};

I saw something like that in a React book, but I cant get it to work -- I think I am missing some webpack plugin (I am guessing).   THank you

A: This should work fine assuming you're using Webpack, except className can't take an array. A simple solution is to make it a string:
className={cssClasses.join(' ')}


text:
Q: Sequelize bulkCreate returns incorrect value? And do not tell me? I use the PostgreSQL base. I have a field code which the trigger before is filled automatically if null.
in sequelize create() works as it should and returns an entry with automatically inserted code.
const response = await models.Cartridge.create(
    { quantity, active, code: null },
    { returning: true }
  );

  // dataValues: {id: 5, quantity: 500, active: true, code: "090217205", updatedAt: Fri Jul 19 2019 16:35:59 GMT+0300 (Eastern European Summer Time), …}

and here, bulkCreate () returns a code with the value that we sent to the server (null), and not the fact that it was actually inserted.
const response = await models.Cartridge.bulkCreate(
    [{ quantity, active, code: null }],
    { returning: true }
  );

  // [ { dataValues: {id: 7, code: null, quantity: 500, active: true, createdAt: Fri Jul 19 2019 16:48:27 GMT+0300 (Eastern European Summer T }]

A: Can you try adding individualHooks. Downside is that will do single saves.
const response = await models.Cartridge.bulkCreate(
[{ quantity, active, code: null }],
{ returning: true, individualHooks: true});


text:
Q: the problem loading the request app in react native Im getting following react native connecting issues
Im getting error while running my expo app in my mobile i have tried some
network tricks but that did not work please suggest me the solution
this is the image


text:
Q: ERROR 000732: Layer Name or Table View: Dataset targetAreas does not exist or is not supported Failed to execute (SelectLayerByAttribute) My goal with this script is to create 9 PDFs and 9 sheets within an Excel workbook. The script utilizes select by location, attributes, and searchcursors to read data to Excel and iterate through user defined areas.
When I run the script with no user defined functions, I do not encounter this error (ERROR 000732: Layer Name or Table View: Dataset targetAreas does not exist or is not supported Failed to execute (SelectLayerByAttribute)). However, when I attempt to consolidate my script into neat functions, the script errors out.
The output should have 9 PDFs in the pdf directory and an Excel sheet with 9 worksheets. I get the desired output when I don't consolidate. However, when I'm iterating the areas in cursor3 (see code snippet below), the first iteration is successful, but the second iteration fails. So my resulting pdf directory only contains one PDF.
# Looping through feature classes
arcpy.MakeFeatureLayer_management(highRiskAreas, 'HRM')
arcpy.MakeFeatureLayer_management(targetAreas, 'targetAreas')
with arcpy.da.SearchCursor('targetAreas', ['Name', 'SHAPE@']) as cursor3:
    for area in cursor3:
        n = 0
        ws = wb.add_sheet('Area {}'.format(area[0]))
        arcpy.SelectLayerByAttribute_management('targetAreas',
                        where_clause="\"Name\" = '{}'".format(area[0]))
        for fc, fields in fieldDict.items():
            n = featureSelector(fc, fields) + 1
        mapMaker(area[1], area[0])
        wb.save('{}.xls'.format(os.path.splitext(
                os.path.basename(studyArea))[0]))

I've read through other questions with the same error, but can't find anything that specifies my issue.
The full consolidated code is below...
import arcpy, os, shutil, xlwt, time
arcpy.env.overwriteOutput = True

# User Defined Functions
def featureSelector(feature, fields):
    '''
    determines amount of fields in searchcursor
    '''
    global n
    fcShort = os.path.splitext(os.path.basename(feature))[0]
    ws.write(n, 0, fcShort, header)
    arcpy.MakeFeatureLayer_management(feature, fcShort)
    arcpy.SelectLayerByLocation_management(fcShort, 'INTERSECT', 'targetAreas')
    arcpy.SelectLayerByLocation_management(fcShort, 'INTERSECT', 'HRM',
                                    selection_type='SUBSET_SELECTION')
    with arcpy.da.SearchCursor(fcShort, fields) as cursor1:
        for i, row in enumerate(cursor1, n):
            ws.write(i + 1, 0, row[0], hraFont)
            try:
                ws.write(i + 1, 1, row[1], hraFont)
            except IndexError:
                pass
            n += 1
    arcpy.SelectLayerByLocation_management(fcShort, 'INTERSECT', 'targetAreas')
    arcpy.SelectLayerByLocation_management(fcShort, 'INTERSECT', 'HRM',
                                    selection_type='REMOVE_FROM_SELECTION')
    with arcpy.da.SearchCursor(fcShort, fields) as cursor2:
        for i, row in enumerate(cursor2, n):
            ws.write(i + 1, 0, row[0], NonHRAFont)
            try:
                ws.write(i + 1, 1, row[1], NonHRAFont)
            except IndexError:
                pass
            n += 1
    return n

def fieldCalc(path = arcpy.env.workspace):
    '''
    Calculates field values for each feature class
    '''
    fcs = arcpy.ListFeatureClasses()
    fieldDict = {}
    for fc in fcs:
        if 'ATM' in fc:
            fieldDict[fc] = ['PRIMARY_AD']
        elif 'Laund' in fc:
            fieldDict[fc] = ['PRIMARY_AD', 'COMPANY_NA']
        elif 'LI_Immin' in fc:
            fieldDict[fc] = ['address']
        elif 'Pawn' in fc:
            fieldDict[fc] = ['IN_SingleL', 'USER_Store']
        elif 'Grocery' in fc:
            fieldDict[fc] = ['PRIMARY_AD', 'COMPANY_NA']
        elif 'Restau' in fc:
            fieldDict[fc] = ['IN_SingleL']
    return fieldDict

def mapMaker(shape, name):
    global pdfDirectory
    # Condition determining landscape or portrait map layout
    if ((shape.extent.XMax - shape.extent.XMin) >
        (shape.extent.YMax - shape.extent.YMin)):
        mxd = arcpy.mapping.MapDocument(landscapemxd)
        df = arcpy.mapping.ListDataFrames(mxd)[0]
        #arcpy.MakeFeatureLayer_management(targetAreas, 'targetAreas')
        layer = arcpy.mapping.Layer('targetAreas')

        # In order to zoom to the selected targetted area, we need to create a
        # feature layer
        # However, we don't want it visible on the hard copy map
        # The template mxd has a set symbology and we want to see that
        layer.visible = False
        arcpy.mapping.AddLayer(df, layer)
        arcpy.SelectLayerByAttribute_management(layer,
                                where_clause="\"Name\" = '{}'".format(name))
        df.extent = layer.getSelectedExtent()
        arcpy.mapping.ExportToPDF(mxd,
                    os.path.join(pdfDirectory, 'Area_{}'.format(name)))
        arcpy.RefreshActiveView()
    else:
        mxd = arcpy.mapping.MapDocument(portraitmxd)
        df = arcpy.mapping.ListDataFrames(mxd)[0]
        #arcpy.MakeFeatureLayer_management(targetAreas, 'targetAreas')
        layer = arcpy.mapping.Layer('targetAreas')
        layer.visible = False
        arcpy.mapping.AddLayer(df, layer)
        arcpy.SelectLayerByAttribute_management(layer,
                    where_clause="\"Name\" = '{}'".format(name))
        df.extent = layer.getSelectedExtent()
        arcpy.mapping.ExportToPDF(mxd, os.path.join(pdfDirectory,
                                    'Area_{}'.format(name)))
        arcpy.RefreshActiveView()

def Start():
    '''
    Calls other functions
    Settings for excel document
    '''
    # Excel Document and settings
    global ws, wb, hraFont, header, NonHRAFont, n, pdfDirectory, area
    wb = xlwt.Workbook()
    hraFont = xlwt.easyxf('font: name Times New Roman, color-index red, bold on')
    header = xlwt.easyxf('font: name Times New Roman, color-index black, bold on')
    NonHRAFont = xlwt.easyxf('font: name Times New Roman, color-index black')
    #areaFont = xlwt.easyxf('font: name Times New Roman, color-index black, height 28')

    # Creating dictionary for environmental features and
    # their required attributes
    fieldDict = fieldCalc()

    # Creating PDF directory
    pdfDirectory = os.path.join(os.getcwd(), 'pdfs')
    if os.path.exists(pdfDirectory):
        shutil.rmtree(pdfDirectory)
        time.sleep(1)
        os.mkdir(pdfDirectory)
    else:
        os.mkdir(pdfDirectory)

    # Looping through feature classes
    arcpy.MakeFeatureLayer_management(highRiskAreas, 'HRM')
    arcpy.MakeFeatureLayer_management(targetAreas, 'targetAreas')
    with arcpy.da.SearchCursor('targetAreas', ['Name', 'SHAPE@']) as cursor3:
        for area in cursor3:
            n = 0
            ws = wb.add_sheet('Area {}'.format(area[0]))
            arcpy.SelectLayerByAttribute_management('targetAreas',
                            where_clause="\"Name\" = '{}'".format(area[0]))
            for fc, fields in fieldDict.items():
                n = featureSelector(fc, fields) + 1
            mapMaker(area[1], area[0])
            wb.save('{}.xls'.format(os.path.splitext(
                    os.path.basename(studyArea))[0]))

# Setting Variables
arcpy.env.workspace = r"xxx"
portraitmxd = r"xxx"
landscapemxd = r"xxx"
studyArea = r"xxxx"
targetAreas = r"xxx"
highRiskAreas = r"xxxx"

# Initializing Script
Start()

Full unconsolidated script...
import arcpy, os, shutil, xlwt, time
# Setting Variables
arcpy.env.workspace = r"C:\Users\tuk36101\Desktop\canvasScript\environmentalFeatures"
portraitmxd = r"C:\Users\tuk36101\Desktop\canvasScript\portrait.mxd"
landscapemxd = r"C:\Users\tuk36101\Desktop\canvasScript\landscape.mxd"
studyArea = r"C:\Users\tuk36101\Desktop\canvasScript\NicetownTioga_CanvassingArea.shp"
targetAreas = r"C:\Users\tuk36101\Desktop\canvasScript\targetAreas.shp"
highRiskAreas = r"C:\Users\tuk36101\Desktop\canvasScript\highRiskArea.shp"
# Initialize time
start = time.time()

arcpy.env.overwriteOutput = True

# User Defined Functions
def featureSelector(feature, fields):
    '''
    determines amount of fields in searchcursor
    '''
    fcShort = os.path.splitext(os.path.basename(feature))[0]
    global n
    ws.write(n, 0, fcShort, header)
    arcpy.MakeFeatureLayer_management(feature, fcShort)
    arcpy.SelectLayerByLocation_management(fcShort, 'INTERSECT', 'targetAreas')
    arcpy.SelectLayerByLocation_management(fcShort, 'INTERSECT', 'HRM', selection_type='SUBSET_SELECTION')
    with arcpy.da.SearchCursor(fcShort, fields) as cursor:
        for i, row in enumerate(cursor, n):
            ws.write(i + 1, 0, row[0], hraFont)
            try:
                ws.write(i + 1, 1, row[1], hraFont)
            except IndexError:
                pass
            n += 1
    arcpy.SelectLayerByLocation_management(fcShort, 'INTERSECT', 'targetAreas')
    arcpy.SelectLayerByLocation_management(fcShort, 'INTERSECT', 'HRM', selection_type='REMOVE_FROM_SELECTION')
    with arcpy.da.SearchCursor(fcShort, fields) as featCur:
        for i, row in enumerate(featCur, n):
            ws.write(i + 1, 0, row[0], NonHRAFont)
            try:
                ws.write(i + 1, 1, row[1], NonHRAFont)
            except IndexError:
                pass
            n += 1

    return n

def fieldCalc(path = arcpy.env.workspace):
    '''
    Calculates field values for each feature class
    '''
    fcs = arcpy.ListFeatureClasses()
    fieldDict = {}
    for fc in fcs:
        if 'ATM' in fc:
            fieldDict[fc] = ['PRIMARY_AD']
        elif 'Laund' in fc:
            fieldDict[fc] = ['PRIMARY_AD', 'COMPANY_NA']
        elif 'LI_Immin' in fc:
            fieldDict[fc] = ['address']
        elif 'Pawn' in fc:
            fieldDict[fc] = ['IN_SingleL', 'USER_Store']
        elif 'Grocery' in fc:
            fieldDict[fc] = ['PRIMARY_AD', 'COMPANY_NA']
        elif 'Restau' in fc:
            fieldDict[fc] = ['IN_SingleL']
    return fieldDict

# --------------------------------------------------------------------------------------------------#

# Excel Formatting
hraFont = xlwt.easyxf('font: name Times New Roman, color-index red, bold on')
header = xlwt.easyxf('font: name Times New Roman, color-index black, bold on')
NonHRAFont = xlwt.easyxf('font: name Times New Roman, color-index black')
#areaFont = xlwt.easyxf('font: name Times New Roman, color-index black, height 28')

# Excel Document
wb = xlwt.Workbook()

# Global Layer
arcpy.MakeFeatureLayer_management(highRiskAreas, 'HRM')
arcpy.MakeFeatureLayer_management(targetAreas, 'targetAreas')

# Returning necessary fields for each feature class
fieldDict = fieldCalc()

# Looping through feature classes
with arcpy.da.SearchCursor('targetAreas', ['Name']) as areaCursor:
    for area in areaCursor:
        n = 0
        ws = wb.add_sheet('Area {}'.format(area[0]))
        arcpy.SelectLayerByAttribute_management('targetAreas', where_clause="\"Name\" = '{}'".format(area[0]))
        for fc, fields in fieldDict.items():
            n = featureSelector(fc, fields) + 1
wb.save('Nicetown.xls')

# Map of Areas
# Final Process

# Housing the map pdfs
pdfDirectory = os.path.join(os.getcwd(), 'pdfs')
if os.path.exists(pdfDirectory):
    shutil.rmtree(pdfDirectory)
    time.sleep(1)
    os.mkdir(pdfDirectory)
else:
    os.mkdir(pdfDirectory)
arcpy.RefreshActiveView()
arcpy.MakeFeatureLayer_management(targetAreas, 'targetAreas')
with arcpy.da.SearchCursor('targetAreas', ['Name', 'SHAPE@']) as cursor:
    for row in cursor:

        # Condition determining landscape or portrait map layout
        if (row[1].extent.XMax - row[1].extent.XMin) > (row[1].extent.YMax - row[1].extent.YMin):
            mxd = arcpy.mapping.MapDocument(landscapemxd)
            df = arcpy.mapping.ListDataFrames(mxd)[0]
            arcpy.MakeFeatureLayer_management(targetAreas, 'targetAreas')
            layer = arcpy.mapping.Layer('targetAreas')

            # In order to zoom to the selected targetted area, we need to create a feature layer
            # However, we don't want it visible on the hard copy map
            # The template mxd has a set symbology and we want to see that
            layer.visible = False
            arcpy.mapping.AddLayer(df, layer)
            arcpy.SelectLayerByAttribute_management(layer, where_clause="\"Name\" = '{}'".format(row[0]))
            df.extent = layer.getSelectedExtent()
            arcpy.mapping.ExportToPDF(mxd, os.path.join(pdfDirectory, 'Area{}'.format(row[0])))
            arcpy.RefreshActiveView()
        else:
            mxd = arcpy.mapping.MapDocument(portraitmxd)
            df = arcpy.mapping.ListDataFrames(mxd)[0]
            arcpy.MakeFeatureLayer_management(targetAreas, 'targetAreas')
            layer = arcpy.mapping.Layer('targetAreas')
            layer.visible = False
            arcpy.mapping.AddLayer(df, layer)
            arcpy.SelectLayerByAttribute_management(layer, where_clause="\"Name\" = '{}'".format(row[0]))
            df.extent = layer.getSelectedExtent()
            arcpy.mapping.ExportToPDF(mxd, r'pdfs\Area{}'.format(row[0]))
            arcpy.RefreshActiveView()

# End time
end = time.time()
total = ('{:.2f} minutes'.format((end-start)/60))
print total

A: I was able to solve this by bringing...
arcpy.MakeFeatureLayer_management(targetAreas, 'targetAreas')

into the for loop directly below it. My speculation is that the feature layer disappears when applied to the mapMaker function so a new feature layer needs to be created for each iteration.


text:
Q: Not able to see Google+ API data and API details when using google as social account provider in django-all-auth We are using google as social provider with below configuration in a django website:
django-allauth==0.23.0

SOCIALACCOUNT_PROVIDERS = {
  'google':
    { 'SCOPE': ['profile', 'email'],
      'AUTH_PARAMS': { 'access_type': 'online' }
    }}

Credentials are created in API Manager in Google developer console. We are able to login to website using google. But,
there is no data (Quota, Traffic etc.) visible in google developer console for this Google+ API.


text:
Q: Erro page nginx I have to apps running in a vps, react app and nodejs api. and this is my nginx configuration
location /app {
            proxy_pass http://myhost:8080;
            proxy_set_header Host $host;
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header X-Forwarded-Server $host;
}

 location / {
            root /var/www/frontend/;
            index index.html;
    }

the location for the frontend app is workin fine.
the problem is that i try to access the api endpoints i get error, the endpoint is not reached.
Example i try to access http://myhost/app/api/v1/user, i get this error:
Cannot GET /app/api/v1/consenting


text:
Q: How to pass values between events in JS? I'm creating simple currency converter as uni project. Doing everything in Django and vanilla JS.
Consider the following problem:
I have some eventListener which uses external API to change image (country flag) on the page. Flag selection is based on select tag in html. Next after that trigger will go with certain picks, I would like to trigger next event; to get from other API value of picked currencies from 1st event. So I need to pass that value from select tag from 1st eventListener into second one.
So basically I have select tag which gives me values from that selection:
const select1 = document.getElementById('selector1');
const select2 = document.getElementById('selector2');

function controlFlag(element, flagId) {
  element.addEventListener('change', function () {
    const selectedCountry = element.value;
    const apiUrl = 'https://www.countryflagicons.com/FLAT/64/' + selectedCountry + '.png';
    const flagImage = document.getElementById(flagId);
    flagImage.src = apiUrl;
  });
}
controlFlag(select1, 'flag1');
controlFlag(select2, 'flag2');

Next i would like to pass "selectedCountry" into other event:
function getRates(currency_name) {
    if(currency_name === "pln"){ return 1; }
    return fetch(`http://api.nbp.pl/api/exchangerates/rates/a/${currency_name}`)
        .then((response) => response.json())
        .then(json_data => {
            console.log(json_data);
            const value_in_pln = json_data.rates[0].mid;
            console.log(`currency_name = ${currency_name} and value_in_pln = ${value_in_pln}`);
            return value_in_pln;
        })
        .catch(error => {
            console.error(error);
        });
}

document.addEventListener('DOMContentLoaded', () => {
  if (conversionButton) {
    conversionButton.addEventListener('click', () => {
        console.log('Button clicked!');
        console.log(`curr1NAME ========== ${curr1Name}`)
        console.log(`curr2NAME ========== ${curr2Name}`)
        Promise.all([getRates(), getRates()]) // here goes 2 currency names
        .then(values => {
            const tab = values;
            console.log("CURR1 = " + tab[0]);
            console.log("CURR2 = " + tab[1]);
            console.log(`${pickedCurrency1.value} to ${pickedCurrency2.value} = ${(tab[0] / tab[1]).toFixed(4)}`);
            console.log(`Amount for curr1 to curr2: ${valueForInput.value}`);
            let valueForOutput = valueForInput.value * ((tab[0] / tab[1]).toFixed(2));
            console.log("valueForOutput = " + valueForOutput);
            outputRatio.innerHTML = `${valueForInput.value} ${curr1Name} => ${valueForOutput} ${curr2Name}`
        });
    });
  } else {
    console.log("Button Not Working!");
  }
});

Both codes works perfectly but do not update values in line: Promise.all([getRates(), getRates()]) // here goes 2 currency names. How to pass arguments into, getRates()?


text:
Q: laravel php artisan migrate issue When I run this command: php artisan migrate I have got an error:

Illuminate\Database\QueryException  : could not find driver (SQL:
  select * from information_schema.tables where table_schema = loag and
  table_name = migrations)

I have set up a vagrant environment with ubuntu 18.04 and PHP, MySQL with versions 7.2. i edited the php.ini file and did all of the 1000 things on 100 sites on the web. i'm getting confused that it still don't work to migrate
composer create-project laravel/laravel projectname

config/database.php
'mysql' => [
            'driver' => 'mysql',
            'host' => '127.0.0.1',//env('DB_HOST', '127.0.0.1'),
            'port' => '3306',//env('DB_PORT', '3306'),
            'database' => 'loag',//env('DB_DATABASE', 'forge'),
            'username' => 'root',//env('DB_USERNAME', 'forge'),
            'password' => 'root',//env('DB_PASSWORD', ''),
            'unix_socket' => '/etc/mysql/mysql.sock',//env('DB_SOCKET', ''),
            'charset' => 'utf8mb4',
            'collation' => 'utf8mb4_unicode_ci',
            'prefix' => '',
            'prefix_indexes' => true,
            'strict' => true,
            'engine' => null,
        ],

.env
APP_NAME="Laendliche Ostbahnen AG"
APP_ENV=local
APP_KEY=base64:SKuPKct0ug16L4DTEvcFD59YuHKf8znDmQrqG973L6w=
APP_DEBUG=true
APP_URL=http://localhost

LOG_CHANNEL=stack

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=loag
DB_USERNAME=root
DB_PASSWORD=root`

composer.json
{
    "name": "laravel/laravel",
    "type": "project",
    "description": "The Laravel Framework.",
    "keywords": [
        "framework",
        "laravel"
    ],
    "license": "MIT",
    "require": {
        "php": "^7.1.3",
        "fideloper/proxy": "^4.0",
        "laravel/framework": "5.7.*",
        "laravel/tinker": "^1.0"
    },
    "require-dev": {
        "beyondcode/laravel-dump-server": "^1.0",
        "filp/whoops": "^2.0",
        "fzaninotto/faker": "^1.4",
        "mockery/mockery": "^1.0",
        "nunomaduro/collision": "^2.0",
        "phpunit/phpunit": "^7.0"
    },
...

installation on ubuntu:enter code here
# Set environment variable
DEBIAN_FRONTEND=noninteractive

# Update Packages
apt-get update

# Upgrade Packages
apt-get dist-upgrade

# Apache
apt-get install -y apache2

# Enable Apache Mods
a2enmod rewrite

# Install PHP
apt-get install -y php7.2

# PHP Apache Mod
apt-get install -y libapache2-mod-php7.2

# Restart Apache
service apache2 restart

# PHP Mods
apt-get install -y php7.2-xml
apt-get install -y php7.2-common
apt-get install -y php7.2-zip

# PHP-MYSQL lib
apt-get install -y php7.2-mysql
apt-get install -y mysql-server

# Disable old apache vhosts config and enable the new one
#a2dissite 000-default.conf

# Restart Apache
sudo systemctl restart apache2.service

DBs in phpmyadmin: (the affected db should be loag(loag and laravel are empty)
information_schema
laravel
loag
mysql
performance_schema
phpmyadmin
sys
need more?
when i do:php artisan migrate the following output is generated:
Illuminate\Database\QueryException  : could not find driver (SQL: select * from information_schema.tables where table_schema = loag and table_name = migrations)

  at C:\Users\Marco Ris\Desktop\Webdevelopment\loag\vendor\laravel\framework\src\Illuminate\Database\Connection.php:664
    660|         // If an exception occurs when attempting to run a query, we'll format the error
    661|         // message to include the bindings with SQL, which will make this exception a
    662|         // lot more helpful to the developer instead of just the database's errors.
    663|         catch (Exception $e) {  > 664|             throw new QueryException(
    665|                 $query, $this->prepareBindings($bindings), $e
    666|             );
    667|         }
    668|

  Exception trace:

  1   PDOException::("could not find driver")
      C:\Users\Marco Ris\Desktop\Webdevelopment\loag\vendor\laravel\framework\src\Illuminate\Database\Connectors\Connector.php:70

  2   PDO::__construct("mysql:unix_socket=/etc/mysql/mysql.sock;dbname=loag", "root", "root", [])      C:\Users\Marco Ris\Desktop\Webdevelopment\loag\vendor\laravel\framework\src\Illuminate\Database\Connectors\Connector.php:70

  Please use the argument -v to see more details

A: May be this will solve your problem,
sudo apt-get install php7-mysql

or
sudo apt-get install php5-mysql

or
sudo apt-get install php-mysql


text:
Q: How to compute the derivative of tr$((MAM^{T})^2)$? I have the following derivation here

Where M is a square matrix,  is also a square matrix (diagonal). But I do not know why the derivative of  is .
I only know before that the derivative of tr$(X^2)$ with respect to $X$ is 2$X$ from the matrix cookbook, but I find it no way to deal with .

A: It can be solved by taking matrix derivative, Let $Y = M \Psi M^\mathrm{T}$ and $J = \text{tr}[( M \Psi M^\mathrm{T})^2]=\text{tr}(Y^2)$, we take derivative w.r.t $Y$ and $M$, respectively,
$$
\begin{aligned}
\mathrm{d} J &= \mathrm{tr}[\mathrm{d}Y^2 ] \\
&=\mathrm{tr}[(\mathrm{d}Y) Y + Y (\mathrm{d}Y)] \\
&=\mathrm{tr}[(2Y (\mathrm{d}Y)] \\
\end{aligned}
$$
so,
$$
\frac{\partial J}{\partial Y} = 2 Y^\mathrm{\mathrm{T}}
$$
and from matrix derivaty, we get,
$$
\begin{aligned}
\mathrm{d} J &= \mathrm{tr}[\frac{\partial^\mathrm{\mathrm{T}} J}{\partial Y}  \mathrm{d}Y ] \\
&=\mathrm{tr}[\frac{\partial^\mathrm{\mathrm{T}} J}{\partial Y}  \mathrm{d}(M \Psi M^\mathrm{\mathrm{T}}) ] \\
&=\mathrm{tr}[\frac{\partial^\mathrm{\mathrm{T}} J}{\partial Y}  (\mathrm{d}M) \Psi M^\mathrm{\mathrm{T}} + \frac{\partial^\mathrm{T} J}{\partial Y} M \Psi (\mathrm{d}M^\mathrm{T})] \\
&=\mathrm{tr}[\Psi M^\mathrm{T}\frac{\partial^\mathrm{T} J}{\partial Y}  (\mathrm{d}M)  + \frac{\partial^\mathrm{T} J}{\partial Y} M \Psi (\mathrm{d}M^\mathrm{T})] \\
&=\mathrm{tr}[\Psi M^\mathrm{T}\frac{\partial^\mathrm{T} J}{\partial Y}  (\mathrm{d}M)]  + \mathrm{tr}[\frac{\partial^\mathrm{T} J}{\partial Y} M \Psi (\mathrm{d}M^\mathrm{T})] \\
&=\mathrm{tr}[\Psi M^\mathrm{T}\frac{\partial^\mathrm{T} J}{\partial Y}  (\mathrm{d}M)]  + \mathrm{tr}[(\mathrm{d}M)   \Psi M^\mathrm{T} \frac{\partial J}{\partial Y}] \\
&=\mathrm{tr}[\Psi M^\mathrm{T}\frac{\partial^\mathrm{T} J}{\partial Y}  (\mathrm{d}M)]  + \mathrm{tr}[   \Psi M^\mathrm{T} \frac{\partial J}{\partial Y} (\mathrm{d}M)] \\
&=\mathrm{tr}[ (\Psi M^\mathrm{T}\frac{\partial^\mathrm{T} J}{\partial Y}   +   \Psi M^\mathrm{T} \frac{\partial J}{\partial Y} )\mathrm{d}M] \\
\end{aligned}
$$
so,
$$
\begin{aligned}
\frac{\partial J}{\partial M} &= \frac{\partial J}{\partial Y} M \Psi + \frac{\partial^\mathrm{T} J}{\partial Y} M \Psi \\
&= 4(M \Psi M^\mathrm{T}) M \Psi
\end{aligned}
$$


text:
Q: Read JSON that is in website source in client-side vanilla javascript I have a simple JSON file sitting in a data folder within the source of my website. In a javascript script I want to read the JSON and update the DOM with the information inside. The file structure of my website is like this
css
design
html
  |____ category.html (this is where the script will be loaded)
js
  |____updateDomScript.js (this is the script that should be loaded)
src
  |____data
          |____jsonFile.json (this is the json that needs to be loaded)

I obviously can't use require() from nodejs because this is on the client side. I don't see how FileReader would work here. All I need to do is read this JSON file from ../src/data/jsonFile.json.

A: I meant the third answer, you can use fetch statement. If you are confused about fetch then I recommend you look it up online first.
fetch("path/to/file")
  .then(response => response.json())
  .then(json => console.log(json));


text:
Q: parse pdf file and conversion i try to edit pdf file and generate other pdf file.
the problem that this conversion not work.
it mean i can save pdf file in the document but it is empty file
aData = [str dataUsingEncoding:NSUTF8StringEncoding];

NSArray *documentPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

// This should be our documents directory
NSString *saveDirectory = [documentPath objectAtIndex:0];

NSString *str=[self convertNsdataToString:nsdata];

//str = [str stringByReplacingOccurrencesOfString:@"<<" withString:@"chikos"];
NSData* aData;
aData = [str dataUsingEncoding:NSUTF8StringEncoding];

//writing the pdf converted in the memory at path

NSString *saveDirectory2 = [saveDirectory stringByAppendingPathComponent:@"Test.pdf"] ;
[aData writeToFile:saveDirectory2 atomically:YES];

A: You can't just do a search and replace on text data in a PDF file. It is not structured like that. You need to parse the content streams (which can be compressed/encrypted) to see what s going on.