问:
npx create-react-app myapp command throwning error
I wanted to create an app in react . I have installed the latest Node js
when I am running the command I am getting error

PS C:\Users\Kumar Sanket\Desktop\React&Redux> npx create-react-app myapp
Error: EEXIST: file already exists, mkdir 'C:\Users\Kumar'
TypeError: Cannot read property 'get' of undefined
    at errorHandler (C:\Program Files\nodejs\node_modules\npm\lib\utils\error-handler.js:205:18)
    at C:\Program Files\nodejs\node_modules\npm\bin\npm-cli.js:78:20
    at cb (C:\Program Files\nodejs\node_modules\npm\lib\npm.js:228:22)
    at C:\Program Files\nodejs\node_modules\npm\lib\npm.js:266:24
    at C:\Program Files\nodejs\node_modules\npm\lib\config\core.js:83:7
    at Array.forEach ()
    at C:\Program Files\nodejs\node_modules\npm\lib\config\core.js:82:13
    at f (C:\Program Files\nodejs\node_modules\npm\node_modules\once\once.js:25:25)
    at afterExtras (C:\Program Files\nodejs\node_modules\npm\lib\config\core.js:173:20)
    at C:\Program Files\nodejs\node_modules\npm\node_modules\mkdirp\index.js:47:53
C:\Program Files\nodejs\node_modules\npm\lib\utils\error-handler.js:205
  if (npm.config.get('json')) {
                 ^

TypeError: Cannot read property 'get' of undefined
    at process.errorHandler (C:\Program Files\nodejs\node_modules\npm\lib\utils\error-handler.js:205:18)
    at process.emit (events.js:189:13)
    at process._fatalException (internal/bootstrap/node.js:496:27)
Install for create-react-app@latest failed with c

答:
Today I encountered a similar issue with npx create-react-app my-app(mkdir failed).

Reason for my error

I had space in my user name folder(ex: Abc Xyz) and thus "npx" couldn't refer to it correctly (It only read Abc, and not Xyz).

I am using VS Code for React, and it didn't had the permission to create new directory

How I fixed it

Opened VS Code with Administrator rights.(fixed permission issue)

Instead of using "npx" I tried the following:

--> npm install -g create-react-app

--> create-react-app my-app

And that got executed successfully.

Hope this helps.


来源: stackexchange

问:
With CSS, how to style a generic, global style?
Update: this question is about global style.  So solution such as #some-id .score is NOT a solution.

At first, I was styling as

```<code>.score { font-size: 32px; color: #777 }
</code>```

And the "score" is something that can happen any where, something of a global style.  But since other style actually might have:

```<code>#summary-panel { font-size: 13px }
</code>```

The one with id will override the one just having classes (the first CSS rule in this post).  (So if score is displayed within summary-panel then the font-size will be overridden to be 13px but the score style is supposed to be global and need a 32px style.) So I was tempted to use

```<code>.score { font-size: 32px !important; color: #777 !important }
</code>```

because the !important can act as the "second level" which override everything ordinary, and act as a global style.

Is this a good way or better way?  One catch is that if sometimes we might have a CSS issue with IE 7 (or IE 6), that we need a separate stylesheet such as ie.css, and in there, there might be also

```<code>#summary-panel { font-size: 12px !important }
</code>```

so in this case, the !important will be overridden because the one having an id will always win over just classes.  So is there a better way?

答:
This is where you use span.

For example the markup:

```<code><div id="sometext">
   <p>Lorem ipsum <span class="score">test</span> dolor sit amet</p>
</div>
</code>```

And the CSS:

```<code>div#sometext {
    font-size: 12px;
    color: yellow;
}

span.score {
    font-size: 42px;
    color: green;
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Update: this question is about global style.  So solution such as #some-id .score is NOT a solution.

At first, I was styling as

.score { font-size: 32px; color: #777 }

And the "score" is something that can happen any where, something of a global style.  But since other style actually might have:

#summary-panel { font-size: 13px }

The one with id will override the one just having classes (the first CSS rule in this post).  (So if score is displayed within summary-panel then the font-size will be overridden to be 13px but the score style is supposed to be global and need a 32px style.) So I was tempted to use

.score { font-size: 32px !important; color: #777 !important }

because the !important can act as the "second level" which override everything ordinary, and act as a global style.

Is this a good way or better way?  One catch is that if sometimes we might have a CSS issue with IE 7 (or IE 6), that we need a separate stylesheet such as ie.css, and in there, there might be also

#summary-panel { font-size: 12px !important }

so in this case, the !important will be overridden because the one having an id will always win over just classes.  So is there a better way?

Body:
This is where you use span.

For example the markup:

<div id="sometext">
   <p>Lorem ipsum <span class="score">test</span> dolor sit amet</p>
</div>

And the CSS:

div#sometext {
    font-size: 12px;
    color: yellow;
}

span.score {
    font-size: 42px;
    color: green;
}


问:
How to fire an wx.EVT_CLOSE from an inner panel
I'm building a wxPython application.
The main frame includes a main panel.
The main panel include other panels.
In one of those panels there is an "Exit" button.
I want the application to close when I press the "Exit" button.
For that, I require to fire a wx.EVT_CLOSE to the main frame of the application. How do I fire that event?
Any other ideas are most welcome too.
Thanks in advance.

I'm adding the example below to show the case:

```<code>    import wx

    class MainScene(wx.Frame):

        def __init__(self, parent, title):
        super(MainScene, self).__init__(parent, title=title, size=(300, 300))
        self.InitUI()

       def InitUI(self):
       # Define Master Panel
           masterPanel = wx.Panel(self)
           masterPanel.SetBackgroundColour("gold")
           horzbox = wx.BoxSizer(wx.HORIZONTAL)
          subPanel=SubPanel(parent=masterPanel, size=(200, 200))

    class SubPanel(wx.Panel):
       def __init__(self, parent, size):
           wx.Panel.__init__(self, parent, size=size)
           self.SetBackgroundColour("gray")
           vbox = wx.BoxSizer(wx.VERTICAL)
           exit_button = wx.Button(self, label="Exit")
           exit_button.Bind(wx.EVT_BUTTON, self.onClose)
           vbox.Add(exit_button, proportion=1, flag=wx.ALL | wx.CENTER, border=5)
           self.SetSizer(vbox)

       def onClose(self, event):
           self.Destroy()

    def main():
       app = wx.App()
       mainFrame = MainScene(None, title='Melanoma Buster')
       mainFrame.Show()
       app.MainLoop()

    if __name__ == '__main__':
       main()
</code>```

enter image description here

And this is after the click on the Exit button:

enter image description here

答:
You can use the wx.Window.Close() method. This method triggers the wx.CloseEvent for you. Take a look at the code below for a way to implement this.

For more details (and some limitations) about the Close() method take a look here and for a way to use your custom event check these answers.

Code:

```<code>import wx

class MyFrame(wx.Frame):
    def __init__(self):
        super().__init__(None, title="Exit button",size=(200,200))
        self.panel = wx.Panel(self)
        self.button = wx.Button(self.panel, label="Exit", pos=(50, 50))
        self.Bind(wx.EVT_BUTTON, self.OnExit)

    def OnExit(self,event):
        """
        According to the wxPython docs self should refer to a top level window.
        This is important in your case because according to your question you
        have a nested GUI. So make sure self is the frame containing everything
        in your window
        """
        self.Close(force=True)

if __name__ == '__main__':
    app = wx.App()
    frame = MyFrame()
    frame.Show()
    app.MainLoop()
else:
    pass
</code>```

EDIT BASED ON QUESTION UPDATE

You can place the Destroy() call either in the MainScene class or in the SubPanel class. When to use one or the other depends on whether the Exit button is something particular to the MainScene class (then I would put the Destroy() call in the MainScene class) or is something that the SubPanel class should always do (then I would put the Destroy() call in the SubPanel class).

Destroy() call in MainScene class:

```<code>import wx

class MainScene(wx.Frame):
  def __init__(self, parent, title):
    super(MainScene, self).__init__(parent, title=title, size=(300, 300))
    self.InitUI()

  def InitUI(self):
    # Define Master Panel
    masterPanel = wx.Panel(self)
    masterPanel.SetBackgroundColour("gold")
    horzbox = wx.BoxSizer(wx.HORIZONTAL)
    subPanel=SubPanel(parent=masterPanel, size=(200, 200))

    subPanel.exit_button.Bind(wx.EVT_BUTTON, self.Close)

  def Close(self, event):
    print('Called from MainScene')
    self.Destroy()

class SubPanel(wx.Panel):
  def __init__(self, parent, size):
    wx.Panel.__init__(self, parent, size=size)
    self.SetBackgroundColour("gray")
    vbox = wx.BoxSizer(wx.VERTICAL)
    self.exit_button = wx.Button(self, label="Exit")
    vbox.Add(self.exit_button, proportion=1, flag=wx.ALL | wx.CENTER, border=5)
    self.SetSizer(vbox)

def main():
  app = wx.App()
  mainFrame = MainScene(None, title='Melanoma Buster')
  mainFrame.Show()
  app.MainLoop()

if __name__ == '__main__':
   main()
</code>```

Destroy() call from SubPanel class:

```<code>import wx

class MainScene(wx.Frame):
  def __init__(self, parent, title):
    super(MainScene, self).__init__(parent, title=title, size=(300, 300))
    self.InitUI()

  def InitUI(self):
    # Define Master Panel
    masterPanel = wx.Panel(self)
    masterPanel.SetBackgroundColour("gold")
    horzbox = wx.BoxSizer(wx.HORIZONTAL)
    subPanel=SubPanel(parent=masterPanel, size=(200, 200), mainWin=self)

class SubPanel(wx.Panel):
  def __init__(self, parent, size, mainWin):
    wx.Panel.__init__(self, parent, size=size)
    self.mainWin = mainWin
    self.SetBackgroundColour("gray")
    vbox = wx.BoxSizer(wx.VERTICAL)
    exit_button = wx.Button(self, label="Exit")
    exit_button.Bind(wx.EVT_BUTTON, self.onClose)
    vbox.Add(exit_button, proportion=1, flag=wx.ALL | wx.CENTER, border=5)
    self.SetSizer(vbox)

  def onClose(self, event):
    print('Called from SubPanel')
    self.mainWin.Destroy()

def main():
  app = wx.App()
  mainFrame = MainScene(None, title='Melanoma Buster')
  mainFrame.Show()
  app.MainLoop()

if __name__ == '__main__':
   main()
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm building a wxPython application.
The main frame includes a main panel.
The main panel include other panels.
In one of those panels there is an "Exit" button.
I want the application to close when I press the "Exit" button.
For that, I require to fire a wx.EVT_CLOSE to the main frame of the application. How do I fire that event?
Any other ideas are most welcome too.
Thanks in advance.

I'm adding the example below to show the case:

    import wx

    class MainScene(wx.Frame):

        def __init__(self, parent, title):
        super(MainScene, self).__init__(parent, title=title, size=(300, 300))
        self.InitUI()

       def InitUI(self):
       # Define Master Panel
           masterPanel = wx.Panel(self)
           masterPanel.SetBackgroundColour("gold")
           horzbox = wx.BoxSizer(wx.HORIZONTAL)
          subPanel=SubPanel(parent=masterPanel, size=(200, 200))

    class SubPanel(wx.Panel):
       def __init__(self, parent, size):
           wx.Panel.__init__(self, parent, size=size)
           self.SetBackgroundColour("gray")
           vbox = wx.BoxSizer(wx.VERTICAL)
           exit_button = wx.Button(self, label="Exit")
           exit_button.Bind(wx.EVT_BUTTON, self.onClose)
           vbox.Add(exit_button, proportion=1, flag=wx.ALL | wx.CENTER, border=5)
           self.SetSizer(vbox)

       def onClose(self, event):
           self.Destroy()

    def main():
       app = wx.App()
       mainFrame = MainScene(None, title='Melanoma Buster')
       mainFrame.Show()
       app.MainLoop()

    if __name__ == '__main__':
       main()

enter image description here

And this is after the click on the Exit button:

enter image description here

Body:
You can use the wx.Window.Close() method. This method triggers the wx.CloseEvent for you. Take a look at the code below for a way to implement this.

For more details (and some limitations) about the Close() method take a look here and for a way to use your custom event check these answers.

Code:

import wx

class MyFrame(wx.Frame):
    def __init__(self):
        super().__init__(None, title="Exit button",size=(200,200))
        self.panel = wx.Panel(self)
        self.button = wx.Button(self.panel, label="Exit", pos=(50, 50))
        self.Bind(wx.EVT_BUTTON, self.OnExit)

    def OnExit(self,event):
        """
        According to the wxPython docs self should refer to a top level window.
        This is important in your case because according to your question you
        have a nested GUI. So make sure self is the frame containing everything
        in your window
        """
        self.Close(force=True)

if __name__ == '__main__':
    app = wx.App()
    frame = MyFrame()
    frame.Show()
    app.MainLoop()
else:
    pass

EDIT BASED ON QUESTION UPDATE

You can place the Destroy() call either in the MainScene class or in the SubPanel class. When to use one or the other depends on whether the Exit button is something particular to the MainScene class (then I would put the Destroy() call in the MainScene class) or is something that the SubPanel class should always do (then I would put the Destroy() call in the SubPanel class).

Destroy() call in MainScene class:

import wx

class MainScene(wx.Frame):
  def __init__(self, parent, title):
    super(MainScene, self).__init__(parent, title=title, size=(300, 300))
    self.InitUI()

  def InitUI(self):
    # Define Master Panel
    masterPanel = wx.Panel(self)
    masterPanel.SetBackgroundColour("gold")
    horzbox = wx.BoxSizer(wx.HORIZONTAL)
    subPanel=SubPanel(parent=masterPanel, size=(200, 200))

    subPanel.exit_button.Bind(wx.EVT_BUTTON, self.Close)

  def Close(self, event):
    print('Called from MainScene')
    self.Destroy()

class SubPanel(wx.Panel):
  def __init__(self, parent, size):
    wx.Panel.__init__(self, parent, size=size)
    self.SetBackgroundColour("gray")
    vbox = wx.BoxSizer(wx.VERTICAL)
    self.exit_button = wx.Button(self, label="Exit")
    vbox.Add(self.exit_button, proportion=1, flag=wx.ALL | wx.CENTER, border=5)
    self.SetSizer(vbox)

def main():
  app = wx.App()
  mainFrame = MainScene(None, title='Melanoma Buster')
  mainFrame.Show()
  app.MainLoop()

if __name__ == '__main__':
   main()

Destroy() call from SubPanel class:

import wx

class MainScene(wx.Frame):
  def __init__(self, parent, title):
    super(MainScene, self).__init__(parent, title=title, size=(300, 300))
    self.InitUI()

  def InitUI(self):
    # Define Master Panel
    masterPanel = wx.Panel(self)
    masterPanel.SetBackgroundColour("gold")
    horzbox = wx.BoxSizer(wx.HORIZONTAL)
    subPanel=SubPanel(parent=masterPanel, size=(200, 200), mainWin=self)

class SubPanel(wx.Panel):
  def __init__(self, parent, size, mainWin):
    wx.Panel.__init__(self, parent, size=size)
    self.mainWin = mainWin
    self.SetBackgroundColour("gray")
    vbox = wx.BoxSizer(wx.VERTICAL)
    exit_button = wx.Button(self, label="Exit")
    exit_button.Bind(wx.EVT_BUTTON, self.onClose)
    vbox.Add(exit_button, proportion=1, flag=wx.ALL | wx.CENTER, border=5)
    self.SetSizer(vbox)

  def onClose(self, event):
    print('Called from SubPanel')
    self.mainWin.Destroy()

def main():
  app = wx.App()
  mainFrame = MainScene(None, title='Melanoma Buster')
  mainFrame.Show()
  app.MainLoop()

if __name__ == '__main__':
   main()


问:
Create PDF thumbnail with Imagick and write to file
I'm trying to create a pdf thumbnail with Imagick and save it on the server in the same location as the pdf.  The code below works fine as is.  The problem is that I don't want to echo the image.  But if I remove the echo statement, the resulting jpg file contains errors and is unreadable.  How can I create the thumbnail and write to a file without sending it to the browser?

```<code>$pdfThumb = new \imagick();
$pdfThumb->setResolution(10, 10);
$pdfThumb->readImage($filePath . $fileName . $fileExt . '[0]');
$pdfThumb->setImageFormat('jpg');
header("Content-Type: image/jpeg");
echo $pdfThumb;
$fp = fopen($filePath . $fileName . '.jpg', "x");
$pdfThumb->writeImageFile($fp);
fclose($fp);
</code>```

DaGhostman Dimitrov provided some helpful code on #16606642, but it doesn't work for me for some reason.

答:
Bonzo's answer requires imagick on the webserver. If imagick is not on the webserver you can try to execute imagemagick from the commandline by php command exec():

```<code>exec('convert -thumbnail  "178^>" -background white -alpha remove -crop 178x178+0+0 my_pdf.pdf[0] my_pdf.png')
</code>```

And if you like to convert all pdfs in one step from same folder where your script is located try this:

```<code>exec('for f in *.pdf; do convert -thumbnail  "178^>" -background white -alpha remove -crop 178x178+0+0 "$f"[0] "${f%.pdf}.png"; done');
</code>```

In this examples I create a png thumbnail 178x178 pixel from the first page (my_pdf.pdf[0] the 0 means first pdf page).

Body:
I'm trying to create a pdf thumbnail with Imagick and save it on the server in the same location as the pdf.  The code below works fine as is.  The problem is that I don't want to echo the image.  But if I remove the echo statement, the resulting jpg file contains errors and is unreadable.  How can I create the thumbnail and write to a file without sending it to the browser?

$pdfThumb = new \imagick();
$pdfThumb->setResolution(10, 10);
$pdfThumb->readImage($filePath . $fileName . $fileExt . '[0]');
$pdfThumb->setImageFormat('jpg');
header("Content-Type: image/jpeg");
echo $pdfThumb;
$fp = fopen($filePath . $fileName . '.jpg', "x");
$pdfThumb->writeImageFile($fp);
fclose($fp);

DaGhostman Dimitrov provided some helpful code on #16606642, but it doesn't work for me for some reason.

Body:
Bonzo's answer requires imagick on the webserver. If imagick is not on the webserver you can try to execute imagemagick from the commandline by php command exec():

exec('convert -thumbnail  "178^>" -background white -alpha remove -crop 178x178+0+0 my_pdf.pdf[0] my_pdf.png')

And if you like to convert all pdfs in one step from same folder where your script is located try this:

exec('for f in *.pdf; do convert -thumbnail  "178^>" -background white -alpha remove -crop 178x178+0+0 "$f"[0] "${f%.pdf}.png"; done');

In this examples I create a png thumbnail 178x178 pixel from the first page (my_pdf.pdf[0] the 0 means first pdf page).


问:
How do I check in SQLite whether a table exists?
How do I, reliably, check in SQLite, whether a particular user table exists?

I am not asking for unreliable ways like checking if a "select *" on the table returned an error or not (is this even a good idea?).

The reason is like this:

In my program, I need to create and then populate some tables if they do not exist already.

If they do already exist, I need to update some tables.

Should I take some other path instead to signal that the tables in question have already been created - say for example, by creating/putting/setting a certain flag in my program initialization/settings file on disk or something?

Or does my approach make sense?

答:
Table exists or not in database in swift</p>

```<code>func tableExists(_ tableName:String) -> Bool {
        sqlStatement = "SELECT name FROM sqlite_master WHERE type='table' AND name='\(tableName)'"
        if sqlite3_prepare_v2(database, sqlStatement,-1, &compiledStatement, nil) == SQLITE_OK {
            if sqlite3_step(compiledStatement) == SQLITE_ROW {
                return true
            }
            else {
                return false
            }
        }
        else {
            return false
        }
            sqlite3_finalize(compiledStatement)
    }
</code>```

Body:
Table exists or not in database in swift

func tableExists(_ tableName:String) -> Bool {
        sqlStatement = "SELECT name FROM sqlite_master WHERE type='table' AND name='\(tableName)'"
        if sqlite3_prepare_v2(database, sqlStatement,-1, &compiledStatement, nil) == SQLITE_OK {
            if sqlite3_step(compiledStatement) == SQLITE_ROW {
                return true
            }
            else {
                return false
            }
        }
        else {
            return false
        }
            sqlite3_finalize(compiledStatement)
    }


问:
Handling uploads multiple images from react js
Good Morning, i got a problem about some codes, fyi im still new to react js, i try to uploads multiple images from react to express and save it to mongoDB
, i already re-search that i need to use multer in my node js, but i dont know the argument need to pass because in react i have 1 name of field of files to upload, but on my submit data has 2 data to send.</p>

```<code>handleSubmit(e){
    e.preventDefault();

    // var formData = new FormData();
    // formData.append('file', e.target.value)
    // formData.append('file2', e.target.value)

    let {imagePreviewUrl} = this.state;
    const dataCategory = this.state.dataCategory;
    let categoryName = this.refs.categoryName.value;
    let categoryImage = this.refs.categoryImage.value;
    let categoryDesc =  this.refs.categoryDesc.value,
        categoryImageCabor = (<img alt="www.google.com" height="100px" src={imagePreviewUrl} />),
        namaCabor = this.refs.namaCabor.value,
        descCabor = this.refs.descCabor.value,
        imageCabor = (<img height="100px" src={this.state.imageCabor.props.src} />)

        fetch('http://localhost:4000/add', {
            mode:'cors',
            method:'post',
            headers:{
                'Content-Type' : 'application/json',
                // "Accept" : "application/json",
                // "type" : "formData"
            },
            body:JSON.stringify({
                categoryName : categoryName,
                categoryDesc : categoryDesc,
                categoryImage: categoryImage,
                categoryImageCabor : categoryImageCabor,
                namaCabor : namaCabor,
                descCabor : descCabor,
                imageCabor : imageCabor,
                status : true
            }),
        }).then(res=>{
            return res.json();
        }).catch(function(err){
            if(err){
                console.log(err);
            }
        })

    this.setState({
        dataCategory : dataCategory,
        imagePreviewUrl : false,
    });
    this.refs.myForm.reset();
    this.refs.myForm.focus();
}

handleChange(e){
    this.setState({
        [e.target.categoryName] : e.target.value,
        [e.target.categoryImage] : e.target.value,
        [e.target.categoryDesc] : e.target.value
    })
}

render(){
    let {imagePreviewUrl} = this.state;
    let $imagePreview = null;

    if(imagePreviewUrl){
        $imagePreview = (<img alt ="www.google.com" height="100px" src={imagePreviewUrl} />)
    }

    return this.state.imageCabor === "" ? <div></div> : (
        <div>
            <h3>Insert Category Cabang Olahraga </h3>
            <form style={{marginTop: 10}} ref="myForm" onSubmit={this.handleSubmit}  >
                <div className="form-group">
                    <label>Nama Category</label>
                    <input
                        name="categoryName"
                        type="text"
                        className="form-control"
                        ref="categoryName"
                        onChange={this.handleChange}
                    />
                    </div>

                    <div className="form-group">
                    <label>Deskripsi Category </label>
                    <textarea

                        name="categoryDesc"
                        type="text"
                        className="form-control"
                        ref="categoryDesc"
                        rows="5"
                        onChange={this.handleChange}
                    />
                    </div>

                    <div className="form-group">
                        <label>Upload Icon Image</label> <br />
                        <div>{$imagePreview}</div>
                    <input
                        name="categoryImage"
                        type="file"
                        ref="categoryImage"
                        className="image-control"
                        onChange={this.imageHandleChange}
                        />
                    </div>

                    <h1>Cabang Olahraga</h1>
                    <div className ="form-group">
                        <label>Nama Cabang Olahraga</label>
                    <input
                        name="namaCabor"
                        type="text"
                        className="form-control"
                        ref="namaCabor"
                        value={this.state.namaCabor}
                        />
                    </div>

                    <div className ="form-group">
                        <label>Deskripsi Cabang Olahraga</label>
                    <textarea
                        name="descCabor"
                        type="text"
                        className="form-control"
                        ref="descCabor"
                        rows="5"
                        value={this.state.descCabor}
                        />
                    </div>

                    <div className="form-group">
                        <label>Icon Cabang Olahraga</label> <br />
                        <div><img height="100px" src={this.state.imageCabor.props.src} /></div>
                    </div>

                    <div className="form-group">
                        <input type="submit" value="Apply" className ="btn btn-primary" />
                    </div>

            </form>
        </div>
    );
}
</code>```

```<code>//node js code
//i dont know the argument need to pass in here
app.post('/', upload.array('catagoryImage', 12), (req, res, next) =>{
    const files = req.files;
    if(!files){
        const error = new Error('Please choose files')
        error.httpStatusCode = 400
        return next(err)
    }
    res.send(files);
}}
</code>```

答:
To send images along with data from frontend to backend, you need to wrap it inside FormData object like this:

```<code>let formData = new FormData();
formdata.append('keyName','value') //replace keyName with your key and value with its value.
</code>```

And do not set any headers in your fetch request. This should do. Try it and let me know.
Hope it helps!!

Body:
Good Morning, i got a problem about some codes, fyi im still new to react js, i try to uploads multiple images from react to express and save it to mongoDB
, i already re-search that i need to use multer in my node js, but i dont know the argument need to pass because in react i have 1 name of field of files to upload, but on my submit data has 2 data to send.

handleSubmit(e){
    e.preventDefault();

    // var formData = new FormData();
    // formData.append('file', e.target.value)
    // formData.append('file2', e.target.value)

    let {imagePreviewUrl} = this.state;
    const dataCategory = this.state.dataCategory;
    let categoryName = this.refs.categoryName.value;
    let categoryImage = this.refs.categoryImage.value;
    let categoryDesc =  this.refs.categoryDesc.value,
        categoryImageCabor = (),
        namaCabor = this.refs.namaCabor.value,
        descCabor = this.refs.descCabor.value,
        imageCabor = ()

        fetch('http://localhost:4000/add', {
            mode:'cors',
            method:'post',
            headers:{
                'Content-Type' : 'application/json',
                // "Accept" : "application/json",
                // "type" : "formData"
            },
            body:JSON.stringify({
                categoryName : categoryName,
                categoryDesc : categoryDesc,
                categoryImage: categoryImage,
                categoryImageCabor : categoryImageCabor,
                namaCabor : namaCabor,
                descCabor : descCabor,
                imageCabor : imageCabor,
                status : true
            }),
        }).then(res=>{
            return res.json();
        }).catch(function(err){
            if(err){
                console.log(err);
            }
        })

    this.setState({
        dataCategory : dataCategory,
        imagePreviewUrl : false,
    });
    this.refs.myForm.reset();
    this.refs.myForm.focus();
}

handleChange(e){
    this.setState({
        [e.target.categoryName] : e.target.value,
        [e.target.categoryImage] : e.target.value,
        [e.target.categoryDesc] : e.target.value
    })
}

render(){
    let {imagePreviewUrl} = this.state;
    let $imagePreview = null;

    if(imagePreviewUrl){
        $imagePreview = ()
    }

    return this.state.imageCabor === "" ?

 : (

Insert Category Cabang Olahraga

            <form style={{marginTop: 10}} ref="myForm" onSubmit={this.handleSubmit}  >

                    Nama Category
                    <input
                        name="categoryName"
                        type="text"
                        className="form-control"
                        ref="categoryName"
                        onChange={this.handleChange}
                    />

                    Deskripsi Category
                    <textarea

                        name="categoryDesc"
                        type="text"
                        className="form-control"
                        ref="categoryDesc"
                        rows="5"
                        onChange={this.handleChange}
                    />

                        Upload Icon Image

{$imagePreview}

                    <input
                        name="categoryImage"
                        type="file"
                        ref="categoryImage"
                        className="image-control"
                        onChange={this.imageHandleChange}
                        />

Cabang Olahraga

                        Nama Cabang Olahraga
                    <input
                        name="namaCabor"
                        type="text"
                        className="form-control"
                        ref="namaCabor"
                        value={this.state.namaCabor}
                        />

                        Deskripsi Cabang Olahraga
                    <textarea
                        name="descCabor"
                        type="text"
                        className="form-control"
                        ref="descCabor"
                        rows="5"
                        value={this.state.descCabor}
                        />

                        Icon Cabang Olahraga

                        <input type="submit" value="Apply" className ="btn btn-primary" />

            </form>

    );
}

//node js code
//i dont know the argument need to pass in here
app.post('/', upload.array('catagoryImage', 12), (req, res, next) =>{
    const files = req.files;
    if(!files){
        const error = new Error('Please choose files')
        error.httpStatusCode = 400
        return next(err)
    }
    res.send(files);
}}

Body:
To send images along with data from frontend to backend, you need to wrap it inside FormData object like this:

let formData = new FormData();
formdata.append('keyName','value') //replace keyName with your key and value with its value.

And do not set any headers in your fetch request. This should do. Try it and let me know.
Hope it helps!!


问:
Error placement on top of select tag for Jquery validation plugin

Started using jquery validation, unable to place the error after the select tag for all other it is placing after the field for only select tag its working like that. How to fix it.

javascript:

答: adding error class after select2-container class resolved my issue</p>


问:
exec() runs differently in command line and script
When I try exec() to execute this code in python console and script, it has different results

python console:

```<code>>>> def test():
...     x = 13
...     exec('b = x + 1')
...     print(b)
...
>>> test()
14
>>>
</code>```

python script

```<code>def test2():
    x = 13
    exec('b = x + 1')
    print(b)
</code>```

```<code>  NameError: name 'b' is not defined
</code>```

But with this code, they are the same

python console

```<code>>>> def test1():
...     x = 0
...     exec('x += 1')
...     print(x)
...
>>> test1()
0
</code>```

python script

```<code>def test1():
    x = 0
    exec('x += 1')
    print(x)

test1()
# 0
</code>```

答:
But, the reason of the that error is that you didn't define b.
That might work

```<code>def test2():
    x = 13
    exec('b = x + 1\nprint(b)')
</code>```

Body:
When I try exec() to execute this code in python console and script, it has different results

python console:

>>> def test():
...     x = 13
...     exec('b = x + 1')
...     print(b)
...
>>> test()
14
>>>

python script

def test2():
    x = 13
    exec('b = x + 1')
    print(b)

  NameError: name 'b' is not defined

But with this code, they are the same

python console

>>> def test1():
...     x = 0
...     exec('x += 1')
...     print(x)
...
>>> test1()
0

python script

def test1():
    x = 0
    exec('x += 1')
    print(x)

test1()
# 0

Body:
But, the reason of the that error is that you didn't define b.
That might work

def test2():
    x = 13
    exec('b = x + 1\nprint(b)')


问:
Sudden error when retrieving emails from Outlook using Python and win32com
EDIT : SOLVED IT!

I added this snippet of code below, in order to trace the position of the main inbox folder

for folder in outlook.Folders:
        print(folder)

This highlighted that something had changed within the underlying Outlook structure and Folder[0] was no longer valid.  I will now tweak code to make it more robust and dynamically choose folder

END EDIT

I wrote some code to pull emails from Outlook and save the attachments.  It worked perfectly up until a few days ago.

I had not touched the code, so I can only assume that something within Outlook has changed.  I work in a corporate environment, so there is remote update of software.

Does anybody have any idea what this error means and why its suddenly cropped up ? I am very bleak, as the code worked so well before this hiccup.  Alternatively, any better way to retrieve emails and attachments from Outlook, using Python ?

```<code>import win32com.client

def main():
    pass

def saveAttachments():
    outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")  # Opens Microsoft Outlook
    mailbox = outlook.Folders[0]  # Based off email address
    inbox = mailbox.Folders["Inbox"]
    emails = inbox.Items
    emails.Sort("[ReceivedTime]", True)

    destPath = "\\\\servername\\path\\"

    try:
        for mail in emails:
            if ("Detailed MTM," in mail.subject) and (mail.Attachments.Count > 0):
                print(mail.Sender)
                print(mail.Subject)
                print(mail.Receivedtime)
                attachments = mail.Attachments
                for file in attachments:
                    if "MTMDetailed" in str(file):
                        file.SaveAsFile(destPath + str("MTMDetailed.xls"))
                break
    except:
        file = open(destPath + "error.log", "w")
        file.write("Problem")
        file.close()

if __name__ == '__main__':
    main()
    saveAttachments()
</code>```

```<code>  File "C:\Tools\Python\lib\site-packages\win32com\client\dynamic.py", line 256, in __getitem__
    return self._get_good_object_(self._oleobj_.Invoke(dispid, LCID, invkind, 1, index))
pywintypes.com_error: (-2147352567, 'Exception occurred.', (4096, 'Microsoft Outlook', 'The attempted operation failed.  An object could not be found.', None, 0, -2147221233), None)
</code>```

答: I added code to iterate through the outlook.Folders to find the one I need, without relying on specific hardcoded position</p>

Body:
EDIT : SOLVED IT!

I added this snippet of code below, in order to trace the position of the main inbox folder

for folder in outlook.Folders:
        print(folder)

This highlighted that something had changed within the underlying Outlook structure and Folder[0] was no longer valid.  I will now tweak code to make it more robust and dynamically choose folder

END EDIT

I wrote some code to pull emails from Outlook and save the attachments.  It worked perfectly up until a few days ago.

I had not touched the code, so I can only assume that something within Outlook has changed.  I work in a corporate environment, so there is remote update of software.

Does anybody have any idea what this error means and why its suddenly cropped up ? I am very bleak, as the code worked so well before this hiccup.  Alternatively, any better way to retrieve emails and attachments from Outlook, using Python ?

import win32com.client

def main():
    pass

def saveAttachments():
    outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")  # Opens Microsoft Outlook
    mailbox = outlook.Folders[0]  # Based off email address
    inbox = mailbox.Folders["Inbox"]
    emails = inbox.Items
    emails.Sort("[ReceivedTime]", True)

    destPath = "\\\\servername\\path\\"

    try:
        for mail in emails:
            if ("Detailed MTM," in mail.subject) and (mail.Attachments.Count > 0):
                print(mail.Sender)
                print(mail.Subject)
                print(mail.Receivedtime)
                attachments = mail.Attachments
                for file in attachments:
                    if "MTMDetailed" in str(file):
                        file.SaveAsFile(destPath + str("MTMDetailed.xls"))
                break
    except:
        file = open(destPath + "error.log", "w")
        file.write("Problem")
        file.close()

if __name__ == '__main__':
    main()
    saveAttachments()

  File "C:\Tools\Python\lib\site-packages\win32com\client\dynamic.py", line 256, in __getitem__
    return self._get_good_object_(self._oleobj_.Invoke(dispid, LCID, invkind, 1, index))
pywintypes.com_error: (-2147352567, 'Exception occurred.', (4096, 'Microsoft Outlook', 'The attempted operation failed.  An object could not be found.', None, 0, -2147221233), None)


问:
How to avoid provide server address when access ImageField url
I have created model - Profile - which presents user's profile. I have one field which is models.ImageFiled and I have method to get absolute url to this image. I have server in development role, so I've exposed /media folder.
When I use full server URL it works. Is there any method to avoid put static web server address?</p>

```<code># Profile
class Profile(models.Model):

    user = models.OneToOneField(settings.AUTH_USER_MODEL)
    date_of_birth = models.DateField(blank=True, null=True)
    photo = models.ImageField(upload_to='users/%Y/%m/%d',blank=True)

    def __str__(self):
        return 'Profile for user {}'.format(self.user.username)

    @property
    def get_absolute_image_url(self):
        return "http://127.0.0.1:8000/{0}".format(self.photo.url)

in settings.py
MEDIA_URL = 'media/'
MEDIA_ROOT = os.path.join(BASE_DIR,'media/')
</code>```

答:
You need an absolute path with a leading slash:</p>

```<code>MEDIA_URL = '/media/'
</code>```

Body:
I have created model - Profile - which presents user's profile. I have one field which is models.ImageFiled and I have method to get absolute url to this image. I have server in development role, so I've exposed /media folder.
When I use full server URL it works. Is there any method to avoid put static web server address?

# Profile
class Profile(models.Model):

    user = models.OneToOneField(settings.AUTH_USER_MODEL)
    date_of_birth = models.DateField(blank=True, null=True)
    photo = models.ImageField(upload_to='users/%Y/%m/%d',blank=True)

    def __str__(self):
        return 'Profile for user {}'.format(self.user.username)

    @property
    def get_absolute_image_url(self):
        return "http://127.0.0.1:8000/{0}".format(self.photo.url)

in settings.py
MEDIA_URL = 'media/'
MEDIA_ROOT = os.path.join(BASE_DIR,'media/')

Body:
You need an absolute path with a leading slash:

MEDIA_URL = '/media/'


问:
for /f Not Reading Text File List
I can't seem to get my batch file to copy only the files listed in a .txt file.

Inside the source folder are three PDF files.
They are apple.pdf, bat.pdf, and cow.pdf.

The text file is two lines containing bat.pdf on the first, and cow.pdf on the second. There is no punctuation, spaces, or anything.

The batch, the list, and the two folders are on my desktop.

```<code>@echo off
set src=C:\Users\weasel\Desktop\source
set dest=C:\Users\weasel\Desktop\dest
set list=C:\Users\weasel\Desktop\animallist.txt
for /f %%F in (%list%) do robocopy "%src%" "%dest%" *.pdf /R:1
</code>```

I want only the animals in the list to be copied, but the code is just copying all .pdf files it can find as if only the robocopy was there alone. I end up with apple, bat, and cow in my destination folder.

I seem to be messing up the "for /f %%F in (%list%)" part, but I don't really know this coding and I can't find anything online that dumbs it down enough for me.

Any help would be greatly appreciated. Thank you.

答:
You haven't included the metavariable in the list. *.pdf means "any file with a .pdf extension."

Try %%F*.pdf instead - or perhaps %%F.pdf if you file is jaguar.pdf and you want only that file.

Note also

The syntax SET "var=value" (where value may be empty) is used to ensure that any stray trailing spaces are NOT included in the value assigned.

Use for /f "usebackq" %%F in ("%list%") to allow a filename containing spaces to be processed

Use for /f "delims=" %%F in (%list%) to allow a data lines containing spaces to be assigned to %%F

Use for /f "usebackqdelims=" %%F in ("%list%") to combine the two

Title: for /f Not Reading Text File List

Body:
I can't seem to get my batch file to copy only the files listed in a .txt file.

Inside the source folder are three PDF files.
They are apple.pdf, bat.pdf, and cow.pdf.

The text file is two lines containing bat.pdf on the first, and cow.pdf on the second. There is no punctuation, spaces, or anything.

The batch, the list, and the two folders are on my desktop.

@echo off
set src=C:\Users\weasel\Desktop\source
set dest=C:\Users\weasel\Desktop\dest
set list=C:\Users\weasel\Desktop\animallist.txt
for /f %%F in (%list%) do robocopy "%src%" "%dest%" *.pdf /R:1

I want only the animals in the list to be copied, but the code is just copying all .pdf files it can find as if only the robocopy was there alone. I end up with apple, bat, and cow in my destination folder.

I seem to be messing up the "for /f %%F in (%list%)" part, but I don't really know this coding and I can't find anything online that dumbs it down enough for me.

Any help would be greatly appreciated. Thank you.


问:
Celery's @shared_task not working with soft_time_limit
Here's some simple code:

```<code>@shared_task(time_limit=10, soft_time_limit=5)
def check_action():
    try:
        __import__("time").sleep(100)
    except celery.exceptions.SoftTimeLimitExceeded as e:
        print("Here", e, type(e))
    except BaseException as e:
        print("There", e, type(e))
</code>```

It's a shared_task with time_limit and soft_time_limit set up, so I expect Here to be printed after 5 seconds (along with SoftTimeLimitExceeded exception info) and then There to be printed with some hard-timeout exception.

Instead, it doesn't raise SoftTimeLimitExceeded at all, only hard time limit is called, full output is:

```<code>celery_1               | [2019-05-31 21:36:36,709: WARNING/MainProcess] There
celery_1               | [2019-05-31 21:36:36,710: WARNING/MainProcess] 10 seconds
celery_1               | [2019-05-31 21:36:36,710: WARNING/MainProcess] <class 'gevent.timeout.Timeout'>
</code>```

As it can be seen from logs, I use gevent workers, if it's of any help.

UPD #1: the problems seems to be with gevent pool (is I remove --pool=gevent, everything works perfectly).

UPD #2: eventlet pool doesn't seem to support any timeout, even the hard one.

答:
It really is the problem with gevent pool, as mentioned in this pull request.

Question can be considered closed.

Body:
Here's some simple code:

@shared_task(time_limit=10, soft_time_limit=5)
def check_action():
    try:
        __import__("time").sleep(100)
    except celery.exceptions.SoftTimeLimitExceeded as e:
        print("Here", e, type(e))
    except BaseException as e:
        print("There", e, type(e))

It's a shared_task with time_limit and soft_time_limit set up, so I expect Here to be printed after 5 seconds (along with SoftTimeLimitExceeded exception info) and then There to be printed with some hard-timeout exception.

Instead, it doesn't raise SoftTimeLimitExceeded at all, only hard time limit is called, full output is:

celery_1               | [2019-05-31 21:36:36,709: WARNING/MainProcess] There
celery_1               | [2019-05-31 21:36:36,710: WARNING/MainProcess] 10 seconds
celery_1               | [2019-05-31 21:36:36,710: WARNING/MainProcess] <class 'gevent.timeout.Timeout'>

As it can be seen from logs, I use gevent workers, if it's of any help.

UPD #1: the problems seems to be with gevent pool (is I remove --pool=gevent, everything works perfectly).

UPD #2: eventlet pool doesn't seem to support any timeout, even the hard one.


问:
Python if statement not working inside function
I'm trying to make a guess the number game in python. However, in the again() function I cannot seem to get the if statement to run.

When I don't use the again function and copy and paste all the code in the respective positions, it works fine. However when I use the again function, the "play again?" question is asked but the if statement is ignored, causing the while loop to continue endlessly. I have tried using the global function but on the second time I input a guess, it comes up with TypeError: 'str' object is not callable .

```<code>import random

def guess():
    global num
    num = random.randint(1,3)
    guessat  = input("Out of 1 to 3, which number do you guess? ")
    return(guessat)

def again():
    global again
    again = input("Play again? ")
    if again in ["y","yes"]:
        guessing = True
    else:
        guessing = False

print("Welcome to Guess the Number!")

guessing = True

while guessing:
    guessy = guess()
    guessy = int(guessy)
    if guessy == num:
        print("You got it right!")
        again()

    elif guessy != num:
        print("Wrong number!")
        again()
quit()
</code>```

When I input "no" or anything else for the question "Play Again?" I expect the program to exit the while loop and quit.

答:
The if/else statement works perfectly, the problem is elsewhere. More specifically, there are 2 things wrong in your code.

the use of the same name again for both the variable and the
function, you should use different names.

the guessing variable should be global as well otherwise the while-loop will never see it changing.

Try this:

```<code>def again():
    global guessing
    _again = input("Play again? ")
    if _again in ["y","yes"]:
        guessing = True
    else:
        guessing = False
</code>```

One more thing. As others commented already, the use of global variables is generally not a good idea, is better to have your function return something instead.

Body:
I'm trying to make a guess the number game in python. However, in the again() function I cannot seem to get the if statement to run.

When I don't use the again function and copy and paste all the code in the respective positions, it works fine. However when I use the again function, the "play again?" question is asked but the if statement is ignored, causing the while loop to continue endlessly. I have tried using the global function but on the second time I input a guess, it comes up with TypeError: 'str' object is not callable .

import random

def guess():
    global num
    num = random.randint(1,3)
    guessat  = input("Out of 1 to 3, which number do you guess? ")
    return(guessat)

def again():
    global again
    again = input("Play again? ")
    if again in ["y","yes"]:
        guessing = True
    else:
        guessing = False

print("Welcome to Guess the Number!")

guessing = True

while guessing:
    guessy = guess()
    guessy = int(guessy)
    if guessy == num:
        print("You got it right!")
        again()

    elif guessy != num:
        print("Wrong number!")
        again()
quit()

When I input "no" or anything else for the question "Play Again?" I expect the program to exit the while loop and quit.

Body:
The if/else statement works perfectly, the problem is elsewhere. More specifically, there are 2 things wrong in your code.

the use of the same name again for both the variable and the
function, you should use different names.

the guessing variable should be global as well otherwise the while-loop will never see it changing.

Try this:

def again():
    global guessing
    _again = input("Play again? ")
    if _again in ["y","yes"]:
        guessing = True
    else:
        guessing = False

One more thing. As others commented already, the use of global variables is generally not a good idea, is better to have your function return something instead.


问:
Create a concatenated table from another table using function
I have a function GetChildren(@id uniqueidentifier) that returns a table of nodes and a table of parents deleted from delete trigger
I want to make a big table of nodes concatenating output of GetChildren for each row.Id of deleted, how do I do that? Please, say how to make it without variables and loops in only pure sql-way

I want something similar to SelectMany from linq c#

example:

deleted table

```<code>+-----+
| Id  |
+-----+
| 111 |
+-----+
| 222 |
+-----+
</code>```

Nodes table

```<code>+-----+----------+
| Id  | ParentId |
+-----+----------+
| 111 | ...      |
+-----+----------+
| 222 | ...      |
+-----+----------+
| 333 | ...      |
+-----+----------+
| 444 | 111      |
+-----+----------+
| 555 | null     |
+-----+----------+
| 666 | 222      |
+-----+----------+
</code>```

GetChildren('111') will produce:

```<code>+-----+
| Id  |
+-----+
| 111 |
+-----+
| 444 |
+-----+
</code>```

GetChildren('222') will produce:

```<code>+-----+
| Id  |
+-----+
| 222 |
+-----+
| 666 |
+-----+
</code>```

I want to get table that is concatenation of 2 above:

```<code>+-----+
| Id  |
+-----+
| 111 |
+-----+
| 444 |
+-----+
| 222 |
+-----+
| 666 |
+-----+
</code>```

If deleted would contain 4 rows I want to concatenate all 4 outputs of GetChildren for each row

答:
You can use CROSS APPLY to return and union multiple resultsets from a table valued function based on rows from another table. In your example that would look like:</p>

```<code>SELECT c.*
FROM deleted d
CROSS APPLY GetChildren(d.Id) c
</code>```

Body:
I have a function GetChildren(@id uniqueidentifier) that returns a table of nodes and a table of parents deleted from delete trigger
I want to make a big table of nodes concatenating output of GetChildren for each row.Id of deleted, how do I do that? Please, say how to make it without variables and loops in only pure sql-way

I want something similar to SelectMany from linq c#

example:

deleted table

+-----+
| Id  |
+-----+
| 111 |
+-----+
| 222 |
+-----+

Nodes table

+-----+----------+
| Id  | ParentId |
+-----+----------+
| 111 | ...      |
+-----+----------+
| 222 | ...      |
+-----+----------+
| 333 | ...      |
+-----+----------+
| 444 | 111      |
+-----+----------+
| 555 | null     |
+-----+----------+
| 666 | 222      |
+-----+----------+

GetChildren('111') will produce:

+-----+
| Id  |
+-----+
| 111 |
+-----+
| 444 |
+-----+

GetChildren('222') will produce:

+-----+
| Id  |
+-----+
| 222 |
+-----+
| 666 |
+-----+

I want to get table that is concatenation of 2 above:

+-----+
| Id  |
+-----+
| 111 |
+-----+
| 444 |
+-----+
| 222 |
+-----+
| 666 |
+-----+

If deleted would contain 4 rows I want to concatenate all 4 outputs of GetChildren for each row

Body:
You can use CROSS APPLY to return and union multiple resultsets from a table valued function based on rows from another table. In your example that would look like:

SELECT c.*
FROM deleted d
CROSS APPLY GetChildren(d.Id) c


问:
Writing a django view that does not return an object
I am writing a django view that just post some data and update a variable in the database. The view will not return anything as I am submitting the data using jquery-ajax.

I am getting the following error:

```<code>The view mysite.views.home didn't return an HttpResponse object
</code>```

Again I do not wish to return an html page or anything of that sort. How can I achieve that?

答:
You still need to return an HttpResponse, even for an Ajax query. If you're sure it doesn't need any content, you can return an empty one:

```<code>return HttpResponse('')
</code>```

but I would at least put 'ok' to indicate to your Javascript that everything went correctly.

Body:
I am writing a django view that just post some data and update a variable in the database. The view will not return anything as I am submitting the data using jquery-ajax.

I am getting the following error:

The view mysite.views.home didn't return an HttpResponse object

Again I do not wish to return an html page or anything of that sort. How can I achieve that?

Body:
You still need to return an HttpResponse, even for an Ajax query. If you're sure it doesn't need any content, you can return an empty one:

return HttpResponse('')

but I would at least put 'ok' to indicate to your Javascript that everything went correctly.


问:
Syntax error: end of file unexpected (expecting "then")
I am making this code for a minecraft server plugin updater
I am a new shell scripter so I don't know alot...

when I run this code I get a error:

```<code>#!/bin/sh
export PATH=$PATH:.
#Options
PLUGINDOWNLOADLINK=http://api.bukget.org/3/plugins/bukkit/$PLUGINNAME/latest/download
# Plugin folder
if [ -f $PWD\plugins ]; then
PLUG=$PWD\plugins
else
PLUG=$PWD\plug-ins
fi

cd $PLUG

if [ ! -f .\update ]; then
mkdir update
echo Making Directory "update"..
fi

# Plugins Found
    for i in $( ls );
    do
        PLUGINNAME=$i
    done
    cd .\update

    wget $PLUGINDOWNLOADLINK

    # No Plugins Found
    if [ ! -f $PLUG ]; then
    echo
echo
echo    No plugin found.
echo
echo
echo
echo   Plugins can be downloaded here:
echo   http://dev.bukkit.org/bukkit-plugins
fi

# stop
sleep 3s
exit
</code>```

I get this error:

```<code>Syntax error: end of file unexpected (expecting "then")
</code>```

so I put "then" in the place it wanted me to and ran it again:

it gave me this error now:

```<code>Syntax error: end of file unexpected
</code>```

I wrote it on windows 7 notepad++

how can I fix this?

答:
It's because of file formatting. I faced the same problem. Just create another file with (.sh) extensions using gedit. Then paste the code into the new document. Hope this will resolve the issue.

gedit file-name.sh

Body:
I am making this code for a minecraft server plugin updater
I am a new shell scripter so I don't know alot...

when I run this code I get a error:

#!/bin/sh
export PATH=$PATH:.
#Options
PLUGINDOWNLOADLINK=http://api.bukget.org/3/plugins/bukkit/$PLUGINNAME/latest/download
# Plugin folder
if [ -f $PWD\plugins ]; then
PLUG=$PWD\plugins
else
PLUG=$PWD\plug-ins
fi

cd $PLUG

if [ ! -f .\update ]; then
mkdir update
echo Making Directory "update"..
fi

# Plugins Found
    for i in $( ls );
    do
        PLUGINNAME=$i
    done
    cd .\update

    wget $PLUGINDOWNLOADLINK

    # No Plugins Found
    if [ ! -f $PLUG ]; then
    echo
echo
echo    No plugin found.
echo
echo
echo
echo   Plugins can be downloaded here:
echo   http://dev.bukkit.org/bukkit-plugins
fi

# stop
sleep 3s
exit

I get this error:

Syntax error: end of file unexpected (expecting "then")

so I put "then" in the place it wanted me to and ran it again:

it gave me this error now:

Syntax error: end of file unexpected

I wrote it on windows 7 notepad++

how can I fix this?


问:
How to bind image to ImageButton dimensions?
I'm having trouble inserting a large image into ImageButtons which are children of a GridLayout...

I'm trying to build a tic-tac-toe board using a GridLayout which holds 9 identical ImageButtons.
I am using images larger than the buttons themselves and everytime I set an image to a button (using setImageDrawable()) the buttons expands to fit the image size...
My board looks like this:

```<code> <GridLayout
            android:id="@+id/grid_main"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:columnCount="3"
            android:rowCount="3">

            <ImageButton
                android:layout_rowWeight="1"
                android:layout_columnWeight="1"
                android:adjustViewBounds="true"
                android:scaleType="fitCenter"
                />

            <ImageButton
                ...
                />

            <ImageButton
                ...
                />

            [...]
   </GridLayout>
</code>```

I've tried adjusting the image size according to the buttons' measurements but getWidth() and getMeasuredWidth() both return 0 (probably because the buttons don't have a defined widht and height).
Is there a way to make my image fit the button size without expanding the button itself?

答:
You appear not to have a set width of height on the imagebuttons. Adjust the width or height as needed.

Try

```<code><ImageButton
      android:layout_width="0dp"
      android:layout_height="0dp"
      android:layout_rowWeight="1"
      android:layout_columnWeight="1"
      android:adjustViewBounds="true"
      android:scaleType="fitCenter"
/>
</code>```

Body:
I'm having trouble inserting a large image into ImageButtons which are children of a GridLayout...

I'm trying to build a tic-tac-toe board using a GridLayout which holds 9 identical ImageButtons.
I am using images larger than the buttons themselves and everytime I set an image to a button (using setImageDrawable()) the buttons expands to fit the image size...
My board looks like this:

 <GridLayout
            android:id="@+id/grid_main"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:columnCount="3"
            android:rowCount="3">

            <ImageButton
                android:layout_rowWeight="1"
                android:layout_columnWeight="1"
                android:adjustViewBounds="true"
                android:scaleType="fitCenter"
                />

            <ImageButton
                ...
                />

            <ImageButton
                ...
                />

            [...]
   </GridLayout>

I've tried adjusting the image size according to the buttons' measurements but getWidth() and getMeasuredWidth() both return 0 (probably because the buttons don't have a defined widht and height).
Is there a way to make my image fit the button size without expanding the button itself?

Body:
You appear not to have a set width of height on the imagebuttons. Adjust the width or height as needed.

Try

<ImageButton
      android:layout_width="0dp"
      android:layout_height="0dp"
      android:layout_rowWeight="1"
      android:layout_columnWeight="1"
      android:adjustViewBounds="true"
      android:scaleType="fitCenter"
/>


问:
boost::asio http server unable to return valid response to Postman
I'm trying to do a minimal server answering to http requests. I think it partially works since the session is disconnected when I'm sending an answer, but when I'm using a tool like Postman, I'm getting a message like "Could not get any response".

Not knowing much about network yet, I guess I'm just probably unaware of some http concepts :)

Here's the code I'm using:

```<code>#define _SECURE_SCL 0
#include <boost/asio.hpp>
#include <iostream>
using namespace std;
using namespace boost::asio;
using namespace boost::asio::ip;

//
// TCP Session
//
class TcpSession : public enable_shared_from_this<TcpSession>
{
  uint8_t      mData[4096];
  tcp::socket  mSocket;
  unsigned int mTcpSessionId;

public:
  TcpSession(tcp::socket && iSocket, unsigned int && iTcpAudioSessionId)
  : mSocket(move(iSocket)),
    mTcpSessionId(iTcpAudioSessionId)
  {}

  ~TcpSession() {}

  void start() {
    doRead();
  }

private:

  void doRead() {
    shared_ptr<TcpSession> self(shared_from_this());

    mSocket.async_read_some( buffer(mData, 4096),
      [this, self](boost::system::error_code ec, size_t iBytesReceived)
    {
      if(ec) {
        cout << "Session error : " << ec.value() << " " << ec.message() << endl;
        return;
      }

      if (iBytesReceived > 0) {
        cout << string(reinterpret_cast<char*>(mData), iBytesReceived) << endl;
        mSocket.send(buffer("HTTP / 1.1 200 OK\r\n\r\n"));
      }

      doRead();
    });
  }

}; // end of TcpSession

//
// TCP Server
//
class TcpServer
{
  tcp::acceptor mAcceptor;
  tcp::socket   mSocket;
  unsigned int  mTcpSessionCount;

public:
  TcpServer(io_service& iService, const short iPort) :
    mAcceptor(iService, tcp::endpoint(tcp::v4(), iPort)),
    mSocket(iService),
    mTcpSessionCount(0) {
    mAcceptor.set_option(tcp::acceptor::reuse_address());
    accept();
  }

private:
  void accept() {
    mAcceptor.async_accept(mSocket, [this](boost::system::error_code ec) {
      if(!ec) {
        make_shared<TcpSession>(move(mSocket), mTcpSessionCount++)->start();
      }
      else {
        cout << "Server error message " << ec.message() << endl;
      }

      accept();
    });
  }
}; // end of TcpServer

int main() {
  io_service ioService;
  TcpServer mTcpServer(ioService, 2112);
  ioService.run();
}
</code>```

答:
Your HTTP response:

```<code>"HTTP / 1.1 200 OK\r\n\r\n"
</code>```

is badly formed as there should not be any spaces between HTTP, / and 1.1.
Also, since you are replying with 200 OK response, the response should contain a content-length field of zero, i.e.:

```<code>"HTTP/1.1 200 OK\r\ncontent-length: 0\r\n\r\n"
</code>```

or you could simply send 204 No Content instead, i.e.:

```<code>"HTTP/1.1 204 No Content\r\n\r\n"
</code>```

For more awareness of http concepts see: RFC7230 Message Format and RFC7231 204 No Content.

Body:
I'm trying to do a minimal server answering to http requests. I think it partially works since the session is disconnected when I'm sending an answer, but when I'm using a tool like Postman, I'm getting a message like "Could not get any response".

Not knowing much about network yet, I guess I'm just probably unaware of some http concepts :)

Here's the code I'm using:

#define _SECURE_SCL 0
#include <boost/asio.hpp>
#include <iostream>
using namespace std;
using namespace boost::asio;
using namespace boost::asio::ip;

//
// TCP Session
//
class TcpSession : public enable_shared_from_this<TcpSession>
{
  uint8_t      mData[4096];
  tcp::socket  mSocket;
  unsigned int mTcpSessionId;

public:
  TcpSession(tcp::socket && iSocket, unsigned int && iTcpAudioSessionId)
  : mSocket(move(iSocket)),
    mTcpSessionId(iTcpAudioSessionId)
  {}

  ~TcpSession() {}

  void start() {
    doRead();
  }

private:

  void doRead() {
    shared_ptr<TcpSession> self(shared_from_this());

    mSocket.async_read_some( buffer(mData, 4096),
      [this, self](boost::system::error_code ec, size_t iBytesReceived)
    {
      if(ec) {
        cout << "Session error : " << ec.value() << " " << ec.message() << endl;
        return;
      }

      if (iBytesReceived > 0) {
        cout << string(reinterpret_cast<char*>(mData), iBytesReceived) << endl;
        mSocket.send(buffer("HTTP / 1.1 200 OK\r\n\r\n"));
      }

      doRead();
    });
  }

}; // end of TcpSession

//
// TCP Server
//
class TcpServer
{
  tcp::acceptor mAcceptor;
  tcp::socket   mSocket;
  unsigned int  mTcpSessionCount;

public:
  TcpServer(io_service& iService, const short iPort) :
    mAcceptor(iService, tcp::endpoint(tcp::v4(), iPort)),
    mSocket(iService),
    mTcpSessionCount(0) {
    mAcceptor.set_option(tcp::acceptor::reuse_address());
    accept();
  }

private:
  void accept() {
    mAcceptor.async_accept(mSocket, [this](boost::system::error_code ec) {
      if(!ec) {
        make_shared<TcpSession>(move(mSocket), mTcpSessionCount++)->start();
      }
      else {
        cout << "Server error message " << ec.message() << endl;
      }

      accept();
    });
  }
}; // end of TcpServer

int main() {
  io_service ioService;
  TcpServer mTcpServer(ioService, 2112);
  ioService.run();
}

Body:
Your HTTP response:

"HTTP / 1.1 200 OK\r\n\r\n"

is badly formed as there should not be any spaces between HTTP, / and 1.1.
Also, since you are replying with 200 OK response, the response should contain a content-length field of zero, i.e.:

"HTTP/1.1 200 OK\r\ncontent-length: 0\r\n\r\n"

or you could simply send 204 No Content instead, i.e.:

"HTTP/1.1 204 No Content\r\n\r\n"

For more awareness of http concepts see: RFC7230 Message Format and RFC7231 204 No Content.


问:
How can I store variable having high range in C program?
Suppose I want to store variable having datatype integer.
Integer provide certain range 2 byte or 4 byte.
Also range of -32768 to 32767.
I want to store 32768.
How can I?</p>

答: On different platforms, ints are different sizes in C. Sometimes, like you said, they are 2 bytes, and sometimes they are 4, etc. So if it's 2 bytes, that's 16 bits, so it can store 2^16 = 65536 different values. Since you're using a signed value, half these values are negative, so that's why you can't put in a bigger value for an int here. However, if you're using C99 or later, you could use int32_t by including stdint.h.  This will allow you to store up to 2^31 - 1 = 2,147,483,647.


问:
I want to insert value in text box but as the elements are dynamically created, I'm unable to define the element id in the javascript
I want to populate the text area with some text. I wrote a script which does this on a button click. The bottleneck here is that the elements of the HTML are dynamic and are created as per the user's count working on it. Well, my script works for a static text area. How can i make my script helpful for dynamic text area.

```<code>  function insertText(elemID, text)
  {
    var elem = document.getElementById(elemID);
    elem.innerHTML += text;
  }

</script>

<input type="button" name="review_type" value="Postitive"  onclick="insertText('txt1', 'Negative - ')"; />
<input type="button" name="review_type" value="Nagative" onclick="insertText('txt1', 'Positive - ')"; />
</code>```

Thanks!

答:
i can't clear what you want but i will try my best.if you want working on exact element that client pushing on it  you can pass element to javascript function like this:

```<code><input type="button" name="review_type" value="Postitive"  onclick="insertText(this)" data-text="any text you want" data-foo = "bar"  data-state ="Positive - " />
</code>```

and then in javascript do what you want on this element:

```<code>  function insertText(element){
   let text = $(element).data("text") # get from 'data-text' attribute
   $(element).text = text; # assign to input
    # do what you want with this element like:
   let input_value = $(element).val()  # result ====> input_value = "Postitive"
   let state =  $(element).data("state") # result ====> state = "Positive - "
   let new_value = $(element).data("foo") #result ===> new_value = "bar"
}
</code>```

maybe helping you.and try working with jQuery . its simple than javascript to select elements and capturing and changing on elements.

Body:
I want to populate the text area with some text. I wrote a script which does this on a button click. The bottleneck here is that the elements of the HTML are dynamic and are created as per the user's count working on it. Well, my script works for a static text area. How can i make my script helpful for dynamic text area.

  function insertText(elemID, text)
  {
    var elem = document.getElementById(elemID);
    elem.innerHTML += text;
  }

</script>

<input type="button" name="review_type" value="Postitive"  onclick="insertText('txt1', 'Negative - ')"; />
<input type="button" name="review_type" value="Nagative" onclick="insertText('txt1', 'Positive - ')"; />

Thanks!

Body:
i can't clear what you want but i will try my best.if you want working on exact element that client pushing on it  you can pass element to javascript function like this:

<input type="button" name="review_type" value="Postitive"  onclick="insertText(this)" data-text="any text you want" data-foo = "bar"  data-state ="Positive - " />

and then in javascript do what you want on this element:

  function insertText(element){
   let text = $(element).data("text") # get from 'data-text' attribute
   $(element).text = text; # assign to input
    # do what you want with this element like:
   let input_value = $(element).val()  # result ====> input_value = "Postitive"
   let state =  $(element).data("state") # result ====> state = "Positive - "
   let new_value = $(element).data("foo") #result ===> new_value = "bar"
}

maybe helping you.and try working with jQuery . its simple than javascript to select elements and capturing and changing on elements.


问:
Error registering IErrorHandler with Rebus
Error below occurred:

System.InvalidOperationException   HResult=0x80131509   Message=A
  circular dependency was detected for the service of type
  'Rebus.Retry.IErrorHandler'.
  Rebus.Retry.IErrorHandler(Rebus.AzureServiceBus.ErrorMessage.ErrorMessageHandler)
  -> Rebus.Retry.IErrorHandler   Source=Microsoft.Extensions.DependencyInjection   StackTrace:    at
  Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteChain.CheckCircularDependency(Type
  serviceType)    at
  Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.CreateCallSite(Type
  serviceType, CallSiteChain callSiteChain)    at
  Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.CreateArgumentCallSites(Type
  serviceType, Type implementationType, CallSiteChain callSiteChain,
  ParameterInfo[] parameters, Boolean throwIfCallSiteNotFound)    at
  Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.CreateConstructorCallSite(Type
  serviceType, Type implementationType, CallSiteChain callSiteChain)

  at
  Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.TryCreateExact(ServiceDescriptor
  descriptor, Type serviceType, CallSiteChain callSiteChain)    at
  Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.TryCreateExact(Type
  serviceType, CallSiteChain callSiteChain)    at
  Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.CreateCallSite(Type
  serviceType, CallSiteChain callSiteChain)    at
  Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngine.CreateServiceAccessor(Type
  serviceType)    at
  System.Collections.Concurrent.ConcurrentDictionary2.GetOrAdd(TKey
  key, Func2 valueFactory)    at
  Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngine.GetService(Type
  serviceType, ServiceProviderEngineScope serviceProviderEngineScope)

  at
  Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetService[T](IServiceProvider
  provider)    at
  RebusSubscriber.<>c__DisplayClass7_0`1.b__5(IResolutionContext
  c) in C:_Repos\AzureServiceBus\Subscriber\RebusSubscriber.cs:line 45
  at Rebus.Injection.Injectionist.ResolutionContext.GetTService

Below registers dependency for IErrorHandler

```<code>services.AddTransient<IErrorHandler, ErrorMessageHandler>();
</code>```

Below is how it resolves ErrorMessageHandler and error above occurred.

```<code>Configure.With(Activator)
                .Options(o =>
                {
                    o.Decorate<IErrorHandler>(c =>
new ErrorMessageHandler(c.Get<IErrorHandler>()));
                    }

public class ErrorMessageHandler : IErrorHandler
    {
        private readonly IErrorHandler _errorHandler;

        public ErrorMessageHandler(IErrorHandler errorHandler)
        {
            _errorHandler = errorHandler;
        }

        public async Task HandlePoisonMessage(TransportMessage transportMessage, ITransactionContext transactionContext, Exception exception)
        {
            // keep original behaviour
            await _errorHandler.HandlePoisonMessage(transportMessage, transactionContext, exception);
        }
    }
</code>```

It seems not using IResolutionContext causes the error.

Is there a solution?

Update

The problem is that IResolutionContext is required to register its own implementation instead of own IoC. It seems the name of IErrorHandler is overused.

My requirement is, given two separate components (Rebus wrapper, and its client), that we need to let client of rebus wrapper to define and use custom error handler, ErrorMessageHandler in this case.

For example, the pseudocode of Rebus wrapper below:

```<code>Configure.With(Activator)
                    .Options(o =>
                    {

//logic to implement below that allow different message handler somehow
//ErrorMessageHandler is this case.
                        o.Decorate<IErrorHandler>(c =>
           xxxxxxx(c.Get<IErrorHandler>()));
                        }
</code>```

Pseudocode of Client of the Rebus wrapper:

```<code> //pass ErrorMessageHandler to the Rebus wrapper above.
</code>```

答:
The error comes from the Microsoft Dependency Injection container – it's caused by the fact that your IErrorHandler implementation takes an IErrorHandler in its constructor, which it doesn't seem to like.

This particular pattern is the Decorator pattern, which helps transparently extend the capabilities of existing services. Rebus encourages you to use it to extend its behavior, which you seem to be doing correctly by registering it with configurer.Decorate<IErrorHandler>(...).

The error in this case seems to be that you're registering your ErrorMessageHandler in your IoC container. Rebus doesn't use your IoC container to resolve its own services, it's ONLY used for resolving message handlers.

Your IErrorHandler is not a message handler, it's the abstraction that decides how Rebus deals with messages once they have failed too many times.

Therefore: Don't register it in your IoC container.

Body:
Error below occurred:

System.InvalidOperationException   HResult=0x80131509   Message=A
  circular dependency was detected for the service of type
  'Rebus.Retry.IErrorHandler'.
  Rebus.Retry.IErrorHandler(Rebus.AzureServiceBus.ErrorMessage.ErrorMessageHandler)
  -> Rebus.Retry.IErrorHandler   Source=Microsoft.Extensions.DependencyInjection   StackTrace:    at
  Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteChain.CheckCircularDependency(Type
  serviceType)    at
  Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.CreateCallSite(Type
  serviceType, CallSiteChain callSiteChain)    at
  Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.CreateArgumentCallSites(Type
  serviceType, Type implementationType, CallSiteChain callSiteChain,
  ParameterInfo[] parameters, Boolean throwIfCallSiteNotFound)    at
  Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.CreateConstructorCallSite(Type
  serviceType, Type implementationType, CallSiteChain callSiteChain)

  at
  Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.TryCreateExact(ServiceDescriptor
  descriptor, Type serviceType, CallSiteChain callSiteChain)    at
  Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.TryCreateExact(Type
  serviceType, CallSiteChain callSiteChain)    at
  Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.CreateCallSite(Type
  serviceType, CallSiteChain callSiteChain)    at
  Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngine.CreateServiceAccessor(Type
  serviceType)    at
  System.Collections.Concurrent.ConcurrentDictionary2.GetOrAdd(TKey
  key, Func2 valueFactory)    at
  Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngine.GetService(Type
  serviceType, ServiceProviderEngineScope serviceProviderEngineScope)

  at
  Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetService[T](IServiceProvider
  provider)    at
  RebusSubscriber.<>c__DisplayClass7_0`1.b__5(IResolutionContext
  c) in C:_Repos\AzureServiceBus\Subscriber\RebusSubscriber.cs:line 45
  at Rebus.Injection.Injectionist.ResolutionContext.GetTService

Below registers dependency for IErrorHandler

services.AddTransient<IErrorHandler, ErrorMessageHandler>();

Below is how it resolves ErrorMessageHandler and error above occurred.

Configure.With(Activator)
                .Options(o =>
                {
                    o.Decorate<IErrorHandler>(c =>
new ErrorMessageHandler(c.Get<IErrorHandler>()));
                    }

public class ErrorMessageHandler : IErrorHandler
    {
        private readonly IErrorHandler _errorHandler;

        public ErrorMessageHandler(IErrorHandler errorHandler)
        {
            _errorHandler = errorHandler;
        }

        public async Task HandlePoisonMessage(TransportMessage transportMessage, ITransactionContext transactionContext, Exception exception)
        {
            // keep original behaviour
            await _errorHandler.HandlePoisonMessage(transportMessage, transactionContext, exception);
        }
    }

It seems not using IResolutionContext causes the error.

Is there a solution?

Update

The problem is that IResolutionContext is required to register its own implementation instead of own IoC. It seems the name of IErrorHandler is overused.

My requirement is, given two separate components (Rebus wrapper, and its client), that we need to let client of rebus wrapper to define and use custom error handler, ErrorMessageHandler in this case.

For example, the pseudocode of Rebus wrapper below:

Configure.With(Activator)
                    .Options(o =>
                    {

//logic to implement below that allow different message handler somehow
//ErrorMessageHandler is this case.
                        o.Decorate<IErrorHandler>(c =>
           xxxxxxx(c.Get<IErrorHandler>()));
                        }

Pseudocode of Client of the Rebus wrapper:

 //pass ErrorMessageHandler to the Rebus wrapper above.


问:
How to count the objects in javascript?
I have a function which takes an array of many data types.

function count(totalObjs) {
    var count = 0;
    for (var i = 0; i <= arr.length; i++) {

        count++;
    }
    return count;
}
```

答:
Not much typical , You just need to extract the object having keys in it and you can get count of them </p>

```<code>Taking an array having null, array, blank object and string and object having value in it.

    var arr = [1, [], null, 3, 4, 5, {key: 'val'}, {}, {}, 'foo']

    const result = arr.filter(val => (val instanceof Object && Object.keys(val).length > 0));

    Now get the count of objects having values in it.

    console.log('result', result.length);
</code>```

Title: How to count the objects in javascript?

Body:
Not much typical , You just need to extract the object having keys in it and you can get count of them

Taking an array having null, array, blank object and string and object having value in it.

    var arr = [1, [], null, 3, 4, 5, {key: 'val'}, {}, {}, 'foo']

    const result = arr.filter(val => (val instanceof Object && Object.keys(val).length > 0));

    Now get the count of objects having values in it.

    console.log('result', result.length);


问:
access variable declared in a %%bash cell from another jupyter cell
In a jupyter notebook I have a bash jupyter cell as follows:

```<code>%%bash

export MYVAR="something"
</code>```

I would like to access $MYVAR in a different python cell. For example

```<code>print(MYVAR)
</code>```

I would expect the cell to print "something", but I get a NameError message.

Example image:

答:
You can try capturing the output to a python variable:

In [1]:

%%bash --out my_var

MYVAR="something"
echo "$MYVAR"
```

<p>In [2]:</p>

<pre class="lang-sh prettyprint-override"><code>print(my_var)
</code>```

```<code>something
</code>```

Also, you might find this blog post useful.

Body:
In a jupyter notebook I have a bash jupyter cell as follows:

%%bash

export MYVAR="something"

I would like to access $MYVAR in a different python cell. For example

print(MYVAR)

I would expect the cell to print "something", but I get a NameError message.

Example image:

Body:
You can try capturing the output to a python variable:

In [1]:

%%bash --out my_var

MYVAR="something"
echo "$MYVAR"

In [2]:

print(my_var)

something

Also, you might find this blog post useful.


问:
Is there a command for formatting HTML in the Atom editor?
I would like to format my HTML with a command, as I do in Visual Studio, using Ctrl+K+D.  Is this possible in Atom? If not, are there other options?

答:
Go to "Packages" in atom editor.

Then in "Packages" view choose "Settings View".

Choose "Install Packages/Themes".

Search for "Atom Beautify" and install it.


问:
How to not overwritten the data in input/output in ADA programming
I need to take the input from user and save the data in a file but data must not be overwritten. The code is running well but data is overwritten. How to correct my code to get desired results?

I could not manage to data to be overwritten. The demand is:"Ask the user to input name, id and CGPA one by one, and then write it in the file. Existing data must not be ". I also have tried the new generated file data to be stored in another file but getting the same result.

```<code>with Ada.Command_Line, Ada.Text_IO;
use Ada.Command_Line, Ada.Text_IO;
procedure Main is
   -- Initializing
   Read_From     : constant String := "inputFile.txt";
   Write_To      : constant String := "studentData.txt";
   name          : String (1 .. 13);
   studentID     : String (1 .. 11);
   cgpa          : String (1 .. 4);
   Input, Output : File_Type;
begin
   -- taking inputs
   Put_Line ("My Student ID Is *******bc150400162*******");
   Put_Line ("Enter the details for first student.");
   Put_Line ("Please enter your name:");
   Get (name);
   Put_Line ("Please enter your Student ID:");
   Get (studentID);
   Put_Line ("Please enter your CGPA:");
   Get (cgpa);
   -- opening file
   begin
      Open (File => Input, Mode => In_File, Name => Read_From);
   exception
      when others =>
         Put_Line
           (Standard_Error,
            "Can not open the file '" & Read_From & "'. Does it exist?");
         Set_Exit_Status (Failure);
         return;
   end;
   -- Creating new file file

   begin
      Create (File => Output, Mode => Out_File, Name => Write_To);
   exception
      when others =>
         Put_Line
           (Standard_Error, "Can not create a file named '" & Write_To & "'.");
         Set_Exit_Status (Failure);
         return;
   end;
   -- Here is the loop.............................................
   ------------------
   loop
      declare
         Line : String := Get_Line (Input);
      begin
         Put_Line (Output, Line);
         Put_Line (Output, "The Student details are: ");
         Put_Line (Output, name);
         Put_Line (Output, studentID);
         Put_Line (Output, cgpa);
      end;
   end loop;
exception
   when End_Error =>
      if Is_Open (Input) then
         Close (Input);
      end if;
      if Is_Open (Output) then
         Close (Output);
      end if;
end Main;
</code>```

答:
The standard way to do this is to try to open the file in append mode, and if that fails create it (again, in append mode). If creating the file fails, you have a different problem (e.g. illegal name? no permissions? file system is read-only? file system is full? none of these addressable in your program!)

Note, open first, create if open fails; the other way round, the file may be reset, which is exactly what you don’t want.

with Ada.Text_IO;
with Ada.Calendar.Formatting;
with Ada.IO_Exceptions;
procedure Appending is
   Output : Ada.Text_IO.File_Type;
   Name : constant String := "appending.dat";
begin
```

<p>We need a block here, so the exception can be caught here.</p>

<pre class="lang-ada prettyprint-override"><code>   begin
</code>```

Try to open the file ...

      Ada.Text_IO.Open (File => Output,
                        Name => Name,
                        Mode => Ada.Text_IO.Append_File);
```

<p><code>Open</code> succeeded!</p>

<pre class="lang-ada prettyprint-override"><code>   exception
      when Ada.IO_Exceptions.Name_Error =>
</code>```

Open failed because the name didn’t represent an openable file. Try to create it ...

         Ada.Text_IO.Create (File => Output,
                             Name => Name,
                             Mode => Ada.Text_IO.Append_File);
```

<p>The file <code>Output</code> is now open, in append mode.<br>
(At first glance, you might wonder what the point of opening a file that must have been empty in append mode is. Normally, of course, it might as well have been opened in standard out mode; the only difference would be if for some reason you had to use the modeless <code>Reset</code>. In that case, if the file was created in append mode it would remain in append mode, so any previous updates wouldn’t be lost.)</p>

<pre class="lang-ada prettyprint-override"><code>   end;
</code>```

Write something 'unique' to it, so we can tell it worked ...

   Ada.Text_IO.Put_Line
     (File => Output,
      Item => Ada.Calendar.Formatting.Image (Ada.Calendar.Clock));
```

<p>... and we’re done. Could leave the OS to close the file for us on exit, but let’s be sure.</p>

<pre class="lang-ada prettyprint-override"><code>   Ada.Text_IO.Close (File => Output);
end Appending;
</code>```

Body:
I need to take the input from user and save the data in a file but data must not be overwritten. The code is running well but data is overwritten. How to correct my code to get desired results?

I could not manage to data to be overwritten. The demand is:"Ask the user to input name, id and CGPA one by one, and then write it in the file. Existing data must not be ". I also have tried the new generated file data to be stored in another file but getting the same result.

with Ada.Command_Line, Ada.Text_IO;
use Ada.Command_Line, Ada.Text_IO;
procedure Main is
   -- Initializing
   Read_From     : constant String := "inputFile.txt";
   Write_To      : constant String := "studentData.txt";
   name          : String (1 .. 13);
   studentID     : String (1 .. 11);
   cgpa          : String (1 .. 4);
   Input, Output : File_Type;
begin
   -- taking inputs
   Put_Line ("My Student ID Is *******bc150400162*******");
   Put_Line ("Enter the details for first student.");
   Put_Line ("Please enter your name:");
   Get (name);
   Put_Line ("Please enter your Student ID:");
   Get (studentID);
   Put_Line ("Please enter your CGPA:");
   Get (cgpa);
   -- opening file
   begin
      Open (File => Input, Mode => In_File, Name => Read_From);
   exception
      when others =>
         Put_Line
           (Standard_Error,
            "Can not open the file '" & Read_From & "'. Does it exist?");
         Set_Exit_Status (Failure);
         return;
   end;
   -- Creating new file file

   begin
      Create (File => Output, Mode => Out_File, Name => Write_To);
   exception
      when others =>
         Put_Line
           (Standard_Error, "Can not create a file named '" & Write_To & "'.");
         Set_Exit_Status (Failure);
         return;
   end;
   -- Here is the loop.............................................
   ------------------
   loop
      declare
         Line : String := Get_Line (Input);
      begin
         Put_Line (Output, Line);
         Put_Line (Output, "The Student details are: ");
         Put_Line (Output, name);
         Put_Line (Output, studentID);
         Put_Line (Output, cgpa);
      end;
   end loop;
exception
   when End_Error =>
      if Is_Open (Input) then
         Close (Input);
      end if;
      if Is_Open (Output) then
         Close (Output);
      end if;
end Main;

Body:
The standard way to do this is to try to open the file in append mode, and if that fails create it (again, in append mode). If creating the file fails, you have a different problem (e.g. illegal name? no permissions? file system is read-only? file system is full? none of these addressable in your program!)

Note, open first, create if open fails; the other way round, the file may be reset, which is exactly what you don’t want.

with Ada.Text_IO;
with Ada.Calendar.Formatting;
with Ada.IO_Exceptions;
procedure Appending is
   Output : Ada.Text_IO.File_Type;
   Name : constant String := "appending.dat";
begin

We need a block here, so the exception can be caught here.

   begin

Try to open the file ...

      Ada.Text_IO.Open (File => Output,
                        Name => Name,
                        Mode => Ada.Text_IO.Append_File);

Open succeeded!

   exception
      when Ada.IO_Exceptions.Name_Error =>

Open failed because the name didn’t represent an openable file. Try to create it ...

         Ada.Text_IO.Create (File => Output,
                             Name => Name,
                             Mode => Ada.Text_IO.Append_File);

The file Output is now open, in append mode.

(At first glance, you might wonder what the point of opening a file that must have been empty in append mode is. Normally, of course, it might as well have been opened in standard out mode; the only difference would be if for some reason you had to use the modeless Reset. In that case, if the file was created in append mode it would remain in append mode, so any previous updates wouldn’t be lost.)

   end;

Write something 'unique' to it, so we can tell it worked ...

   Ada.Text_IO.Put_Line
     (File => Output,
      Item => Ada.Calendar.Formatting.Image (Ada.Calendar.Clock));

... and we’re done. Could leave the OS to close the file for us on exit, but let’s be sure.

   Ada.Text_IO.Close (File => Output);
end Appending;


问:
Cakephp script running fine from command line but not from cron
Before anything I'll say that I've done extensive research online and the offered solutions haven't worked for me. For example I've tried everything posted here (including the linked solutions from there). This is probably due to the uniqueness of my CakePHP installation that I explain below.

My problem is that I have a Cakephp Shell script that when I run from the Command line works fine, for example:

```<code>Console/cake enrolmentlogs update_daily_enrolment_logs
</code>```

However, when I call that script from cron I get an error. Cron call:

```<code>cd /path/to/app/ && Console/cake enrolmentlogs update_daily_enrolment_logs >> /path/to/app/webroot/cron_shell_logs.txt 2>&1
</code>```

Error I get:

```<code>PHP Notice:  Undefined variable: argv in /path/to/app/Console/cake.php on line 48
Error: This file has been loaded incorrectly and cannot continue.
Please make sure that /lib/Cake/Console is in your system path,
and check the cookbook for the correct usage of this command.
(https://book.cakephp.org/)
#0 /path/to/libs/cakephp-2.10.18/Cake/Console/ShellDispatcher.php(54): ShellDispatcher->_initEnvironment()
#1 /path/to/libs/cakephp-2.10.18/Cake/Console/ShellDispatcher.php(65): ShellDispatcher->__construct(NULL)
#2 /path/to/app/Console/cake.php(48): ShellDispatcher::run(NULL)
#3 {main}
</code>```

One thing I have to mention is that my CakePHP installation is formed by several apps that load one same core library, which is in a different folder than the apps themselves. The apps work perfectly fine, it's just this cron script I can get to work. In the cake.php inside the Console folder of the app I've updated the following line to reflect that too (before doing this I was getting a different error I figure because the core Console files weren't found):

```<code>//$install = $root . DS . 'lib';
$install = '/path/to/libs/cakephp-2.10.18';
</code>```

I've looked at all the paths of libraries being loaded, updated the php.ini variables and system PATH as suggested in the linked solutions and CakePHP's own documentation but I still can't get this to work.

I was hoping someone could point me in the right direction. Again, if I run the same script from the command line it works fine, it's when I call it from cron that I have the issue. The shell script is located inside the Console/Command folder of the app.

All this is in a LAMP server using CakePHP 2.10.18.

答: You may call the shell function first in controller and then call controller function in cron. </p>

Body:
Before anything I'll say that I've done extensive research online and the offered solutions haven't worked for me. For example I've tried everything posted here (including the linked solutions from there). This is probably due to the uniqueness of my CakePHP installation that I explain below.

My problem is that I have a Cakephp Shell script that when I run from the Command line works fine, for example:

Console/cake enrolmentlogs update_daily_enrolment_logs

However, when I call that script from cron I get an error. Cron call:

cd /path/to/app/ && Console/cake enrolmentlogs update_daily_enrolment_logs >> /path/to/app/webroot/cron_shell_logs.txt 2>&1

Error I get:

PHP Notice:  Undefined variable: argv in /path/to/app/Console/cake.php on line 48
Error: This file has been loaded incorrectly and cannot continue.
Please make sure that /lib/Cake/Console is in your system path,
and check the cookbook for the correct usage of this command.
(https://book.cakephp.org/)
#0 /path/to/libs/cakephp-2.10.18/Cake/Console/ShellDispatcher.php(54): ShellDispatcher->_initEnvironment()
#1 /path/to/libs/cakephp-2.10.18/Cake/Console/ShellDispatcher.php(65): ShellDispatcher->__construct(NULL)
#2 /path/to/app/Console/cake.php(48): ShellDispatcher::run(NULL)
#3 {main}

One thing I have to mention is that my CakePHP installation is formed by several apps that load one same core library, which is in a different folder than the apps themselves. The apps work perfectly fine, it's just this cron script I can get to work. In the cake.php inside the Console folder of the app I've updated the following line to reflect that too (before doing this I was getting a different error I figure because the core Console files weren't found):

//$install = $root . DS . 'lib';
$install = '/path/to/libs/cakephp-2.10.18';

I've looked at all the paths of libraries being loaded, updated the php.ini variables and system PATH as suggested in the linked solutions and CakePHP's own documentation but I still can't get this to work.

I was hoping someone could point me in the right direction. Again, if I run the same script from the command line it works fine, it's when I call it from cron that I have the issue. The shell script is located inside the Console/Command folder of the app.

All this is in a LAMP server using CakePHP 2.10.18.


问:
Keras: How to access step in model
Is there a way to access the current Keras training step as a tensor in the tensorflow graph?

I am trying to build a model which has an 'epsilon' parameter which is decayed as a function of the current training step.

```<code>epsilon = some_fn_of(K.global_step) # <- Something like this?
self.q = K.Sequential([
    K.layers.InputLayer(input_shape),
    K.layers.Dense(n, name='q'),
    K.layers.Lambda(lambda x: tf.cond(tf.random.uniform((), 0, 1) < epsilon,
        lambda _: tf.constant(0.0),
        lambda ac: ac)
], name='q')
</code>```

FYI: I'm using the Tensorflow bundled Keras.

答: I suspect that Keras does not have any such tensor in the graph and that the only way to access the step is through Callbacks (Keras Docs,Tensorflow Docs). Especially since Keras is meant to be agnostic to the backend, and so would likely maintain the step outside of tensorflow.</p>

Title: Keras: How to access step in model

Body:
Is there a way to access the current Keras training step as a tensor in the tensorflow graph?

I am trying to build a model which has an 'epsilon' parameter which is decayed as a function of the current training step.

epsilon = some_fn_of(K.global_step) # <- Something like this?
self.q = K.Sequential([
    K.layers.InputLayer(input_shape),
    K.layers.Dense(n, name='q'),
    K.layers.Lambda(lambda x: tf.cond(tf.random.uniform((), 0, 1) < epsilon,
        lambda _: tf.constant(0.0),
        lambda ac: ac)
], name='q')

FYI: I'm using the Tensorflow bundled Keras.


问:
Why null is being display on the screen in an Angular 5 app?
I have simple template which display a value of a string:

```<code><span class="fax_number">{{company.fax}}</span>
</code>```

When the value empty, the screen display the string "null" instead of
empty string, this happen in many places in the application, is there
a good way to avoid this ?

答:
I personally prefer: {{company.fax || ''}}

Because it's easy to read.

However, that is probably not the solution, because angular does not display null values. You're properties/fields probably contain the string 'null' instead of begin null.
If this happens all over your application, then you probably have a problem with how you serialize the data.
If you want to overcome this in your html, you can write something like {{company.fax === 'null' ? '' : company.fax}}, but I'd suggest you take a look at how you serialize your data into json, because I am inclined to say that it behaves faulty.

Body:
I have simple template which display a value of a string:

{{company.fax}}

When the value empty, the screen display the string "null" instead of
empty string, this happen in many places in the application, is there
a good way to avoid this ?