问:
react native can only update a mounted or mounting component
I'm using react native v0.51.
I get this error when I navigate to the component again in the second page.

```<code>can only update a mounted or mounting component.
</code>```

I found where it happen but I don't understand why.

```<code>    /*
 * Default Android example
 */

'use strict';

import React, { Component } from 'react';

import {
  AppRegistry,
  StyleSheet,
  Text,
  Navigator,
  TouchableOpacity,
  Linking,
  View,
  Image,
  Geolocation
} from 'react-native';

// third party library
import QRCodeScanner from 'react-native-qrcode-scanner';
import I18n from '../../i18n'
import branch from 'react-native-branch'

// import styles
import { style } from './style';
const { centerText, textBold, buttonTouchable, camera, topViewStyleQR, QRcontainer, customMarkerStyle, imageScanStyle, textScanStyle, sloganScan, viewSlogan, buttonText } = style;

class QrScan extends Component {
  constructor(props) {
    super(props);
    this.state = {
      barcodeText: '',
      scan: {
        glassHash: '',
        latitude: 0,
        longitude: 0,
        isReedeemScan: true,
      },
    }
  }
  componentDidMount() {
    this._unsubscribeFromBranch = branch.subscribe(({ error, params }) => {
      if (error) {
        console.error("Error from Branch: " + error)
        return
      }

      console.log("Branch params: " + JSON.stringify(params))
      if (params) {

      }
      // if (!params['+clicked_branch_link']) return

      // // Get title and url for route
      // let title = params.$og_title
      // let url = params.$canonical_url
      // let image = params.$og_image_url

      // // Now push the view for this URL
      // this.navigator.push({ title: title, url: url, image: image })
    })
  }

  componentWillUnmount() {
    if (this._unsubscribeFromBranch) {
      this._unsubscribeFromBranch()
      this._unsubscribeFromBranch = null
    }
  }

  _getCurrentPosition(){
    navigator.geolocation.getCurrentPosition(
      (position) => {
         const initialPosition = JSON.stringify(position);
         console.log(initialPosition)
         //this.setState({ initialPosition });
      },
      (error) => alert(error.message),
      { enableHighAccuracy: true, timeout: 20000, maximumAge: 1000 }
   );
   this.watchID = navigator.geolocation.watchPosition((position) => {
      const lastPosition = JSON.stringify(position);
     this.setState({scan:{...this.state.scan,latitude:position.latitude,longitude:position.longitude}})

   });
  }

  onSuccess(e) {
    this._getCurrentPosition();

    // Linking
    //   .openURL(e.data)
    //   .catch(err => console.error('An error occured', err));
    this.setState({ barcodeText: e.data });
    console.log(e);
  }
  _renderMaker() {
    return (
      <View style={customMarkerStyle}>
        <Image
          style={imageScanStyle}
          source={require('../../assets/images/iconScanP.png')} />

        <Text style={textScanStyle}>{I18n.t('_scanDrink')}</Text>
        <View style={viewSlogan}>
          <Text style={sloganScan}>SCANDIT</Text>
        </View>
      </View>
    )
  }

  render() {
    return (
      <QRCodeScanner
        onRead={this.onSuccess.bind(this)}
        showMarker={true}
        camType='front'
        topViewStyle={topViewStyleQR}
        containerStyle={QRcontainer}
        cameraStyle={camera}
        customMarker={this._renderMaker()}
        bottomContent={(
          <TouchableOpacity style={buttonTouchable}>
            <Text style={buttonText}>{this.state.barcodeText ? this.state.barcodeText : ''}</Text>
          </TouchableOpacity>
        )}
      />
    );
  }
}

export default QrScan;
</code>```

when I comment this line into the function _getCurrentPosition it's not happening and it works without this issue.

```<code>     // this.setState({scan:{...this.state.scan,latitude:position.latitude,longitude:position.longitude}})
</code>```

is anything I do wrong with this line? I can't update the state into the scope of this function, if yes why?

答:
In your componentWillUnmount try also removing callbacks assigned to geolocation,

```<code>componentWillUnmount() {
  // <---- other logics

  // Remove callbacks assigned to geolocation functions
  navigator.geolocation.clearWatch(watchID);
  navigator.geolocation.stopObserving()
}
</code>```

Body:
I'm using react native v0.51.
I get this error when I navigate to the component again in the second page.

can only update a mounted or mounting component.

I found where it happen but I don't understand why.

    /*
 * Default Android example
 */

'use strict';

import React, { Component } from 'react';

import {
  AppRegistry,
  StyleSheet,
  Text,
  Navigator,
  TouchableOpacity,
  Linking,
  View,
  Image,
  Geolocation
} from 'react-native';

// third party library
import QRCodeScanner from 'react-native-qrcode-scanner';
import I18n from '../../i18n'
import branch from 'react-native-branch'

// import styles
import { style } from './style';
const { centerText, textBold, buttonTouchable, camera, topViewStyleQR, QRcontainer, customMarkerStyle, imageScanStyle, textScanStyle, sloganScan, viewSlogan, buttonText } = style;

class QrScan extends Component {
  constructor(props) {
    super(props);
    this.state = {
      barcodeText: '',
      scan: {
        glassHash: '',
        latitude: 0,
        longitude: 0,
        isReedeemScan: true,
      },
    }
  }
  componentDidMount() {
    this._unsubscribeFromBranch = branch.subscribe(({ error, params }) => {
      if (error) {
        console.error("Error from Branch: " + error)
        return
      }

      console.log("Branch params: " + JSON.stringify(params))
      if (params) {

      }
      // if (!params['+clicked_branch_link']) return

      // // Get title and url for route
      // let title = params.$og_title
      // let url = params.$canonical_url
      // let image = params.$og_image_url

      // // Now push the view for this URL
      // this.navigator.push({ title: title, url: url, image: image })
    })
  }

  componentWillUnmount() {
    if (this._unsubscribeFromBranch) {
      this._unsubscribeFromBranch()
      this._unsubscribeFromBranch = null
    }
  }

  _getCurrentPosition(){
    navigator.geolocation.getCurrentPosition(
      (position) => {
         const initialPosition = JSON.stringify(position);
         console.log(initialPosition)
         //this.setState({ initialPosition });
      },
      (error) => alert(error.message),
      { enableHighAccuracy: true, timeout: 20000, maximumAge: 1000 }
   );
   this.watchID = navigator.geolocation.watchPosition((position) => {
      const lastPosition = JSON.stringify(position);
     this.setState({scan:{...this.state.scan,latitude:position.latitude,longitude:position.longitude}})

   });
  }

  onSuccess(e) {
    this._getCurrentPosition();

    // Linking
    //   .openURL(e.data)
    //   .catch(err => console.error('An error occured', err));
    this.setState({ barcodeText: e.data });
    console.log(e);
  }
  _renderMaker() {
    return (
      <View style={customMarkerStyle}>
        <Image
          style={imageScanStyle}
          source={require('../../assets/images/iconScanP.png')} />

        <Text style={textScanStyle}>{I18n.t('_scanDrink')}</Text>
        <View style={viewSlogan}>
          <Text style={sloganScan}>SCANDIT</Text>
        </View>
      </View>
    )
  }

  render() {
    return (
      <QRCodeScanner
        onRead={this.onSuccess.bind(this)}
        showMarker={true}
        camType='front'
        topViewStyle={topViewStyleQR}
        containerStyle={QRcontainer}
        cameraStyle={camera}
        customMarker={this._renderMaker()}
        bottomContent={(
          <TouchableOpacity style={buttonTouchable}>
            <Text style={buttonText}>{this.state.barcodeText ? this.state.barcodeText : ''}</Text>
          </TouchableOpacity>
        )}
      />
    );
  }
}

export default QrScan;

when I comment this line into the function _getCurrentPosition it's not happening and it works without this issue.

     // this.setState({scan:{...this.state.scan,latitude:position.latitude,longitude:position.longitude}})

is anything I do wrong with this line? I can't update the state into the scope of this function, if yes why?

Body:
In your componentWillUnmount try also removing callbacks assigned to geolocation,

componentWillUnmount() {
  // <---- other logics

  // Remove callbacks assigned to geolocation functions
  navigator.geolocation.clearWatch(watchID);
  navigator.geolocation.stopObserving()
}


来源: stackexchange

问:
Theme.AppCompat theme stacktrace. No solution found in my case
I try to show a dialog in my Activity and I get this error :
"You need to use a Theme.AppCompat theme"

There are lots of question/answers about this, but I don't get it in my situation:
Can someone help me ? I know it has something to do with the app theme, but I think this is ok in my situation. Can please someone take a look:

Error:

```<code>java.lang.RuntimeException:

    Unable to start activity ComponentInfo{chronicbrowser_maps_en/chronicbrowser.ChronicBrowser}: java.lang.IllegalStateException: You need to use a Theme.AppCompat theme (or descendant) with this activity.
                                                         at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2646)
                                                         at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707)
                                                         at android.app.ActivityThread.-wrap12(ActivityThread.java)
                                                         at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460)
                                                         at android.os.Handler.dispatchMessage(Handler.java:102)
                                                         at android.os.Looper.loop(Looper.java:154)
                                                         at android.app.ActivityThread.main(ActivityThread.java:6077)
                                                         at java.lang.reflect.Method.invoke(Native Method)
                                                         at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:866)
                                                         at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:756)
                                                      Caused by: java.lang.IllegalStateException: You need to use a Theme.AppCompat theme (or descendant) with this activity.
                                                         at android.support.v7.app.AppCompatDelegateImplV9.createSubDecor(AppCompatDelegateImplV9.java:359)
                                                         at android.support.v7.app.AppCompatDelegateImplV9.ensureSubDecor(AppCompatDelegateImplV9.java:328)
                                                         at android.support.v7.app.AppCompatDelegateImplV9.setContentView(AppCompatDelegateImplV9.java:289)
                                                         at android.support.v7.app.AppCompatDialog.setContentView(AppCompatDialog.java:83)
                                                         at android.support.v7.app.AlertController.installContent(AlertController.java:225)
</code>```

AndroidManifest.xml:

```<code><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="xxxxxxxxxx.chronicbrowser"
    android:versionCode="${versionCode}"
    android:versionName="${versionName}"
    android:installLocation="auto">

    <uses-sdk android:minSdkVersion="15" android:targetSdkVersion="22"/>
    <uses-permission android:name="com.android.vending.CHECK_LICENSE" />

    <uses-permission android:name="android.permission.INTERNET"></uses-permission>
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"></uses-permission>

    <supports-screens
        android:normalScreens="true"
        android:largeScreens="true"
        android:xlargeScreens="true"
        />

    <application android:name=".ChronicaApplication" android:largeHeap="true" android:icon="${iconpath}" android:label="@string/app_name" android:theme="@style/AppTheme">>
        <meta-data android:name="com.google.android.gms.version" android:value="@integer/google_play_services_version"/>
        <meta-data android:name="com.facebook.sdk.ApplicationId" android:value="${facebookid}" />
            />

        <activity android:name=".ChronicBrowser"  android:configChanges="orientation|keyboardHidden|screenSize" android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>
</code>```

styles.xml:

```<code><!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
    <!-- Customize your theme here. -->
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="colorAccent">@color/colorAccent</item>
</style>
</code>```

My Activity is extending Activity

```<code>public class ChronicBrowser extends Activity {
</code>```

答: Try adding android:theme="@style/AppTheme" in your activity tag in manifest.</p>

ContentLicense: CC BY-SA 3.0

Body:
I try to show a dialog in my Activity and I get this error :
"You need to use a Theme.AppCompat theme"

There are lots of question/answers about this, but I don't get it in my situation:
Can someone help me ? I know it has something to do with the app theme, but I think this is ok in my situation. Can please someone take a look:

Error:

java.lang.RuntimeException:

    Unable to start activity ComponentInfo{chronicbrowser_maps_en/chronicbrowser.ChronicBrowser}: java.lang.IllegalStateException: You need to use a Theme.AppCompat theme (or descendant) with this activity.
                                                         at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2646)
                                                         at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707)
                                                         at android.app.ActivityThread.-wrap12(ActivityThread.java)
                                                         at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460)
                                                         at android.os.Handler.dispatchMessage(Handler.java:102)
                                                         at android.os.Looper.loop(Looper.java:154)
                                                         at android.app.ActivityThread.main(ActivityThread.java:6077)
                                                         at java.lang.reflect.Method.invoke(Native Method)
                                                         at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:866)
                                                         at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:756)
                                                      Caused by: java.lang.IllegalStateException: You need to use a Theme.AppCompat theme (or descendant) with this activity.
                                                         at android.support.v7.app.AppCompatDelegateImplV9.createSubDecor(AppCompatDelegateImplV9.java:359)
                                                         at android.support.v7.app.AppCompatDelegateImplV9.ensureSubDecor(AppCompatDelegateImplV9.java:328)
                                                         at android.support.v7.app.AppCompatDelegateImplV9.setContentView(AppCompatDelegateImplV9.java:289)
                                                         at android.support.v7.app.AppCompatDialog.setContentView(AppCompatDialog.java:83)
                                                         at android.support.v7.app.AlertController.installContent(AlertController.java:225)

AndroidManifest.xml:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="xxxxxxxxxx.chronicbrowser"
    android:versionCode="${versionCode}"
    android:versionName="${versionName}"
    android:installLocation="auto">

    <uses-sdk android:minSdkVersion="15" android:targetSdkVersion="22"/>
    <uses-permission android:name="com.android.vending.CHECK_LICENSE" />

    <uses-permission android:name="android.permission.INTERNET"></uses-permission>
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"></uses-permission>

    <supports-screens
        android:normalScreens="true"
        android:largeScreens="true"
        android:xlargeScreens="true"
        />

    <application android:name=".ChronicaApplication" android:largeHeap="true" android:icon="${iconpath}" android:label="@string/app_name" android:theme="@style/AppTheme">>
        <meta-data android:name="com.google.android.gms.version" android:value="@integer/google_play_services_version"/>
        <meta-data android:name="com.facebook.sdk.ApplicationId" android:value="${facebookid}" />
            />

        <activity android:name=".ChronicBrowser"  android:configChanges="orientation|keyboardHidden|screenSize" android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

styles.xml:

My Activity is extending Activity

public class ChronicBrowser extends Activity {


问:
osxfuse: how to clean cache?
How to clean cache in OSXFUSE? I'm using it to mount custom remote filesystem. And OSXFUSE caching file content. It is great to fast access for the same file - but sometimes I need to re-read file content from remote server. </p>

答:
I am not sure, that you can clean this cache. But you can disable UBC (Unified Buffer Cache) by specifying 'noubc' in mount options (see OSXFUSE mount options)
It will disable caching your responses to 'read' calls and osxfuse will perform calls into your filesystem without using cache.</p>

Title: osxfuse: how to clean cache?


问:
Install a Python package into a different directory using pip?
I know the obvious answer is to use virtualenv and virtualenvwrapper, but for various reasons I can't/don't want to do that.

So how do I modify the command

```<code>pip install package_name
</code>```

to make pip install the package somewhere other than the default site-packages?

答:
I suggest to follow the documentation and create ~/.pip/pip.conf file. Note in the documentation there are missing specified header directory, which leads to following error:

```<code>error: install-base or install-platbase supplied, but installation scheme is incomplete
</code>```

The full working content of conf file is:

```<code>[install]
install-base=$HOME
install-purelib=python/lib
install-platlib=python/lib.$PLAT
install-scripts=python/scripts
install-headers=python/include
install-data=python/data
</code>```

Unfortunatelly I can install, but when try to uninstall pip tells me there is no such package for uninstallation process.... so something is still wrong but the package goes to its predefined location.

Body:
I know the obvious answer is to use virtualenv and virtualenvwrapper, but for various reasons I can't/don't want to do that.

So how do I modify the command

pip install package_name

to make pip install the package somewhere other than the default site-packages?

Body:
I suggest to follow the documentation and create ~/.pip/pip.conf file. Note in the documentation there are missing specified header directory, which leads to following error:

error: install-base or install-platbase supplied, but installation scheme is incomplete

The full working content of conf file is:

[install]
install-base=$HOME
install-purelib=python/lib
install-platlib=python/lib.$PLAT
install-scripts=python/scripts
install-headers=python/include
install-data=python/data

Unfortunatelly I can install, but when try to uninstall pip tells me there is no such package for uninstallation process.... so something is still wrong but the package goes to its predefined location.


问:
Spring transactions - detecting rollback and commit
I have methods annotated @Transactional and I would like to detect rollbacks and commits.

Does exist any way or any Spring object which can check if transaction was commited or rollbacked?

答:
just run your @Transactional method and then, in another transaction, check what's in db.

and remember to make your tests clean/prepare db before each test (after all the last one could have committed something)


问:
Populate default value only for hh:mm:ss part of datetime-local
Something like this works:

```<code><input type="datetime-local" id="myDate" value="2020-01-02T11:42:13">
</code>```

BUt not this one:

```<code><input type="datetime-local" id="myDate" value="yyyy-mm-ddT11:42:13">
</code>```

I want to have date to be selectable from calendar and time to have default value. Any suggestion without using third party library like moment, etc. I can use JQuery though.

Reference url: https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_datetime-local_value2

答:
According to specification https://www.w3.org/TR/2012/WD-html-markup-20120315/input.datetime-local.html#input.datetime-local.attrs.value , this won't be possible. You can use separate date and time input fields and set values like this:

$(document).ready(function(){
  var date = new Date()

  var hours = String(date.getHours()).length==1?"0"+date.getHours():date.getHours()
  var minutes = String(date.getMinutes()).length==1?"0"+date.getMinutes():date.getMinutes()
  var seconds = String(date.getSeconds()).length==1?"0"+date.getSeconds():date.getSeconds()
  var time =  hours+":"+minutes+":"+seconds

  $("#myTime").val(time)
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="date" id="myDate" value="">

<input type="time" id="myTime" value=""></code>```

Body:
Something like this works:

<input type="datetime-local" id="myDate" value="2020-01-02T11:42:13">

BUt not this one:

<input type="datetime-local" id="myDate" value="yyyy-mm-ddT11:42:13">

I want to have date to be selectable from calendar and time to have default value. Any suggestion without using third party library like moment, etc. I can use JQuery though.

Reference url: https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_datetime-local_value2

Body:
According to specification https://www.w3.org/TR/2012/WD-html-markup-20120315/input.datetime-local.html#input.datetime-local.attrs.value , this won't be possible. You can use separate date and time input fields and set values like this:

$(document).ready(function(){
  var date = new Date()

  var hours = String(date.getHours()).length==1?"0"+date.getHours():date.getHours()
  var minutes = String(date.getMinutes()).length==1?"0"+date.getMinutes():date.getMinutes()
  var seconds = String(date.getSeconds()).length==1?"0"+date.getSeconds():date.getSeconds()
  var time =  hours+":"+minutes+":"+seconds

  $("#myTime").val(time)
})

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="date" id="myDate" value="">

<input type="time" id="myTime" value="">


问:
Create new folder with pathlib and write files into it
I'm doing something like this:

```<code>import pathlib

p = pathlib.Path("temp/").mkdir(parents=True, exist_ok=True)

with p.open("temp."+fn, "w", encoding ="utf-8") as f:
    f.write(result)
</code>```

Error message: AttributeError: 'NoneType' object has no attribute 'open'

Obviously, based on the error message, mkdir returns None.

Jean-Francois Fabre suggested this correction:

```<code>p = pathlib.Path("temp/")
p.mkdir(parents=True, exist_ok=True)

with p.open("temp."+fn, "w", encoding ="utf-8") as f:
    ...
</code>```

This triggered a new error message:

File "/Users/user/anaconda/lib/python3.6/pathlib.py", line 1164, in open
      opener=self._opener)

  TypeError: an integer is required (got type str)

答:
You could try:

```<code>p = pathlib.Path("temp/")
p.mkdir(parents=True, exist_ok=True)
fn = "test.txt" # I don't know what is your fn
filepath = p / fn
with filepath.open("w", encoding ="utf-8") as f:
    f.write(result)
</code>```

You shouldn't give a string as path. It is your object filepath which has the method open.

source

ContentLicense: CC BY-SA 4.0

Body:
I'm doing something like this:

import pathlib

p = pathlib.Path("temp/").mkdir(parents=True, exist_ok=True)

with p.open("temp."+fn, "w", encoding ="utf-8") as f:
    f.write(result)

Error message: AttributeError: 'NoneType' object has no attribute 'open'

Obviously, based on the error message, mkdir returns None.

Jean-Francois Fabre suggested this correction:

p = pathlib.Path("temp/")
p.mkdir(parents=True, exist_ok=True)

with p.open("temp."+fn, "w", encoding ="utf-8") as f:
    ...

This triggered a new error message:

File "/Users/user/anaconda/lib/python3.6/pathlib.py", line 1164, in open
      opener=self._opener)

  TypeError: an integer is required (got type str)

Body:
You could try:

p = pathlib.Path("temp/")
p.mkdir(parents=True, exist_ok=True)
fn = "test.txt" # I don't know what is your fn
filepath = p / fn
with filepath.open("w", encoding ="utf-8") as f:
    f.write(result)

You shouldn't give a string as path. It is your object filepath which has the method open.

source


问:
input as float or int
I would like to be able to display double the value of any number the user inputs.

```<code>spam = int(input('choose any number: '))
print('Your number doubled is: ' + str(spam*2))
</code>```

The problem is if the user inputs a decimal, ie 3.4. It comes up with an error since it becomes a float value.

```<code>Traceback (most recent call last):
  File "<pyshell#66>", line 1, in <module>
    spam = int(input('choose any number: '))
ValueError: invalid literal for int() with base 10: '3.4'
</code>```

Is there a simple way to let the user input any number (be it integer or float value)?

This is in python 3, so raw_input doesn't work.

答:
You could use float:

```<code>spam = float(input('choose any number: '))
print('Your number doubled is: ' + str(spam*2))
</code>```

Title: input as float or int

Body:
I would like to be able to display double the value of any number the user inputs.

spam = int(input('choose any number: '))
print('Your number doubled is: ' + str(spam*2))

The problem is if the user inputs a decimal, ie 3.4. It comes up with an error since it becomes a float value.

Traceback (most recent call last):
  File "<pyshell#66>", line 1, in <module>
    spam = int(input('choose any number: '))
ValueError: invalid literal for int() with base 10: '3.4'

Is there a simple way to let the user input any number (be it integer or float value)?

This is in python 3, so raw_input doesn't work.

Body:
You could use float:

spam = float(input('choose any number: '))
print('Your number doubled is: ' + str(spam*2))


问:
portgresql server version 10 - FATAL: password authentication failed for user "postgres"
I'm trying to open a web application in the browser with Tomcat. But when I debug or start Tomcat, I get this error. The database username in the web.xml file in the Dynamic Web Project and in PostgreSQL is already "postgres".
I get:

"HTTP Status 404" error

when I run the server. I do not understand why it's making this mistake.

答: Don't Set Password for PostgreSQL, leave it empty and it will solve your problem.</p>


问:
Could not execute statement
My add code works for every object expect the new table I just added (Report). I can't seem to find the problem and i just get this error:

Could not execute statement when using .save(object)

Report.hbm.xml

```<code><hibernate-mapping>
<class name="com.atp.Models.Report" table="report">
    <meta attribute="class-description">
        This class contains the report details.
    </meta>
    <id name="environmentName" type="string" column="environmentName">
        <generator class="native"/>
    </id>
    <property name="individual" column="Individual" type="int"/>
    <property name="corporation" column="Corporation" type="int"/>
    <property name="dda" column="DDA" type="int"/>
    <property name="sav" column="SAV" type="int"/>
    <property name="mtg" column="MTG" type="int"/>
    <property name="sepaOut" column="SEPAOUT" type="int"/>
    <property name="sepaIn" column="SEPAIN" type="int"/>
    <property name="atm" column="ATM" type="int"/>
</class>
</code>```

MySqL Table

My Sql Table

Java Add to database (all the fields are right)

```<code>    //Create new object
    Report report = new Report();
    report.setEnvironmentName(environmentName);
    report.setIndividual(individual);
    report.setCorporation(corporation);
    report.setDda(dda);
    report.setSav(sav);
    report.setMtg(mtg);
    report.setSepaIn(sepaIn);
    report.setSepaOut(sepaOut);
    report.setAtm(atm);

    ManageCreation.AddToDatabase(report);

public static void AddToDatabase(Object object) {
    SessionFactory factory = HibernateUtil.GetSessionFactory();
    Session session = factory.openSession();
    Transaction tx = null;
    try{
        tx = session.beginTransaction();
        session.save(object);
        tx.commit();
    }catch (HibernateException e) {
        if (tx!=null) tx.rollback();
        e.printStackTrace();
    }finally {
        session.close();
    }
}
</code>```

答:
Without full stacktrace i can only guess that the xml configuration  on the varchar pk (that you actually set and is not autogenerated) is somehow causing the problem... try to remove that

If you set your pk field in the code

```<code>Report report = new Report();
report.setEnvironmentName(environmentName);
</code>```

you have no need for an autogeneration configuration

```<code><generator class="native"/>
</code>```

also i think that hibernate is expecting a number-type of value to autoincrement and this may be actually messing up things

Title: Could not execute statement

Body:
My add code works for every object expect the new table I just added (Report). I can't seem to find the problem and i just get this error:

Could not execute statement when using .save(object)

Report.hbm.xml

<hibernate-mapping>
<class name="com.atp.Models.Report" table="report">
    <meta attribute="class-description">
        This class contains the report details.
    </meta>
    <id name="environmentName" type="string" column="environmentName">
        <generator class="native"/>
    </id>
    <property name="individual" column="Individual" type="int"/>
    <property name="corporation" column="Corporation" type="int"/>
    <property name="dda" column="DDA" type="int"/>
    <property name="sav" column="SAV" type="int"/>
    <property name="mtg" column="MTG" type="int"/>
    <property name="sepaOut" column="SEPAOUT" type="int"/>
    <property name="sepaIn" column="SEPAIN" type="int"/>
    <property name="atm" column="ATM" type="int"/>
</class>

MySqL Table

My Sql Table

Java Add to database (all the fields are right)

    //Create new object
    Report report = new Report();
    report.setEnvironmentName(environmentName);
    report.setIndividual(individual);
    report.setCorporation(corporation);
    report.setDda(dda);
    report.setSav(sav);
    report.setMtg(mtg);
    report.setSepaIn(sepaIn);
    report.setSepaOut(sepaOut);
    report.setAtm(atm);

    ManageCreation.AddToDatabase(report);

public static void AddToDatabase(Object object) {
    SessionFactory factory = HibernateUtil.GetSessionFactory();
    Session session = factory.openSession();
    Transaction tx = null;
    try{
        tx = session.beginTransaction();
        session.save(object);
        tx.commit();
    }catch (HibernateException e) {
        if (tx!=null) tx.rollback();
        e.printStackTrace();
    }finally {
        session.close();
    }
}

Body:
Without full stacktrace i can only guess that the xml configuration  on the varchar pk (that you actually set and is not autogenerated) is somehow causing the problem... try to remove that

If you set your pk field in the code

Report report = new Report();
report.setEnvironmentName(environmentName);

you have no need for an autogeneration configuration

<generator class="native"/>

also i think that hibernate is expecting a number-type of value to autoincrement and this may be actually messing up things


问:
Improve UITableView scrolling performance while loading images
I have a scrolling grid of photos that looks and functions pretty much exactly like the photo picker on the iPhone. It is constructed from a UITableView that uses a custom UITableViewCell which displays a row of photos (very similar to how Three20 implements it).

It works great except that scrolling performance is poor. I'm already following most of the best practices for fast UITableView scrolling (à la Tweetie).

The images are all bundled with the app. I load them on the UI thread, on demand. I use UIImage's imageNamed: so that the images will be cached after they're first loaded. Once I've scrolled through the table view once, it scrolls very smoothly.

The problem is, the first time scrolling through the table view, scrolling is jittery. I've profiled the app and found that the majority of the time is spent loading the images from the file system. They are JPEG images, already sized correctly (small). I tried using PNG images instead, but performance doesn't improve very much.

The iPhone photo picker exhibits much better loading performance. I'm wondering if combining all the photos into a single image, which I load once and then split into smaller images would be faster. It certainly works in games, but I know that's really a totally different story. Has anyone had experience doing that?

Any other ideas for how I can improve performance?

Incidentally, I'm having a similar, albeit less, performance problem for another UITableView that just uses standard UITableViewCells with one image assigned to the imageView per row.

答:
Fantastic.  That does work like a charm!  So efficiently I ended up using insertRowAtIndexPath rather that reloading the table.  Now it behaves the way it

Thanks so much!
Joe

ContentLicense: CC BY-SA 2.5


问:
Cannot implicitly convert type 'void' to System.Action<int>
I am trying to create .net standard delegate, Action with the input parameter int. But I am getting

Cannot implicitly convert type 'void' to System.Action.

I learned that same return type methods can be added to multicast delegates. Below is my code. What is the wrong with this code?  I don't see a compilation error if I write lambda expression.

static void Main(string[] args)
{
    Action<int> AddBook = AddBookwithId(15); // Here is the error
    AddBook += x => Console.WriteLine("Added book with :{0}" , x ); // No compile error here
    AddBook += AddBookwithISBN(56434);// of course, the same error here too.
}

public static void AddBookwithId(int y)
{
    Console.WriteLine( "Added Book to the shelf with the ID : {0} ", y );
}

public static void AddBookwithISBN(int y)
{
    Console.WriteLine("Added Book to the shelf  with the ISBN: {0} ", y + 2);
}
```

答:
Why not to use Lambda expressions?
In fact, you have already used it in this line of code:

```<code>AddBook += x => Console.WriteLine("Added book with :{0}" , x ); // No compile error here
</code>```

This will result in:

```<code>Action<int> AddBook = (x) => AddBookwithId(x); // Here is the error
AddBook += (x) => Console.WriteLine("Added book with :{0}" , x ); // No compile error here
AddBook += (x) => AddBookwithISBN(x);// of course, the same error here too.
</code>```

Body:
Why not to use Lambda expressions?
In fact, you have already used it in this line of code:

AddBook += x => Console.WriteLine("Added book with :{0}" , x ); // No compile error here

This will result in:

Action<int> AddBook = (x) => AddBookwithId(x); // Here is the error
AddBook += (x) => Console.WriteLine("Added book with :{0}" , x ); // No compile error here
AddBook += (x) => AddBookwithISBN(x);// of course, the same error here too.


问:
Exchange name in Pika exchange_declare callback
I try to use the exchange name in my exchange_declare callback. I use the SelectConnection adapter for asynchronous requests in Pika.

My idea is to first build lists of exchanges, queues and bindings in my program. I then dispatch multiple exchange and queue declarations to Pika, and create bindings as soon as the needed queues and exchanges for each binding have got their DeclareOK messages.

This means I need to know the names of exchanges and queues in my callbacks so that I can correlate them with the bindings to create.

Something like this:

```<code>print "Create A"
channel.exchange_declare(callback=on_exchange, exchange="exchangeA")
print "Create B"
channel.exchange_declare(callback=on_exchange, exchange="exchangeB")

def on_exchange(response):
  # How do I know if this was exchangeA or exchangeB ?
  print "Exchange declared"
  print response
</code>```

This gives the following output, which clearly shows that the exchanges are declared first and callbacks triggered later (as expected):

```<code>Create A
Create B
Exchange declared
<METHOD(['method=<Exchange.DeclareOk>', 'channel_number=1', 'frame_type=1'])>
Exchange declared
<METHOD(['method=<Exchange.DeclareOk>', 'channel_number=1', 'frame_type=1'])>
</code>```

I have figured out that response is of type pika.frame.Method but how do I go from there? Are the exchanges perhaps guaranteed to be declared in order?

答:
Closures is a solution to keep the code async:

```<code>def declare_exchanges(self):
    exchange = "exchangeA"
    callback = self.on_exchange(exchange)
    channel.exchange_declare(callback=callback, exchange=exchange)

    exchange = "exchangeB"
    callback = self.on_exchange(exchange)
    channel.exchange_declare(callback=callback, exchange=exchange)

def on_exchange(self, exchange):
    def callback(response):
        print(exchange)

    return callback
</code>```

PS: I opened an issue upstream, https://github.com/pika/pika/issues/898

Body:
I try to use the exchange name in my exchange_declare callback. I use the SelectConnection adapter for asynchronous requests in Pika.

My idea is to first build lists of exchanges, queues and bindings in my program. I then dispatch multiple exchange and queue declarations to Pika, and create bindings as soon as the needed queues and exchanges for each binding have got their DeclareOK messages.

This means I need to know the names of exchanges and queues in my callbacks so that I can correlate them with the bindings to create.

Something like this:

print "Create A"
channel.exchange_declare(callback=on_exchange, exchange="exchangeA")
print "Create B"
channel.exchange_declare(callback=on_exchange, exchange="exchangeB")

def on_exchange(response):
  # How do I know if this was exchangeA or exchangeB ?
  print "Exchange declared"
  print response

This gives the following output, which clearly shows that the exchanges are declared first and callbacks triggered later (as expected):

Create A
Create B
Exchange declared
<METHOD(['method=<Exchange.DeclareOk>', 'channel_number=1', 'frame_type=1'])>
Exchange declared
<METHOD(['method=<Exchange.DeclareOk>', 'channel_number=1', 'frame_type=1'])>

I have figured out that response is of type pika.frame.Method but how do I go from there? Are the exchanges perhaps guaranteed to be declared in order?

Body:
Closures is a solution to keep the code async:

def declare_exchanges(self):
    exchange = "exchangeA"
    callback = self.on_exchange(exchange)
    channel.exchange_declare(callback=callback, exchange=exchange)

    exchange = "exchangeB"
    callback = self.on_exchange(exchange)
    channel.exchange_declare(callback=callback, exchange=exchange)

def on_exchange(self, exchange):
    def callback(response):
        print(exchange)

    return callback

PS: I opened an issue upstream, https://github.com/pika/pika/issues/898


问:
Copying one Azure blob to another blob in Azure Storage Client 2.0
In the old 1.7 storage client there was a CloudBlob.CopyFromBlob(otherBlob) method, but it does not seem to be present in the 2.0 version. What is the recommended best practice for copying blobs? I do see a ICloudBlob.BeginStartCopyFromBlob method. If that is the appropriate method, how do I use it?</p>

答:
Starting Azure Storage 8, to move Blobs between Storage Accounts I use code similar to below, hope it will help somebody:</p>

```<code>//copy blobs - from
CloudStorageAccount sourceStorageAccount = new CloudStorageAccount(new StorageCredentials(storageFromName, storageFromKey), true);
CloudBlobClient sourceCloudBlobClient = sourceStorageAccount.CreateCloudBlobClient();
CloudBlobContainer sourceContainer = sourceCloudBlobClient.GetContainerReference(containerFromName);

//copy blobs - to
CloudStorageAccount targetStorageAccount = new CloudStorageAccount(new StorageCredentials(storageToName, storageToKey), true);
CloudBlobClient targetCloudBlobClient = targetStorageAccount.CreateCloudBlobClient();
CloudBlobContainer targetContainer = targetCloudBlobClient.GetContainerReference(containerToName);

//create target container if didn't exists
try{
    await targetContainer.CreateIfNotExistsAsync();
}
catch(Exception e){
    log.Error(e.Message);
}

CloudBlockBlob sourceBlob = sourceContainer.GetBlockBlobReference(blobName);
CloudBlockBlob targetBlob = targetContainer.GetBlockBlobReference(blobName);

try{
    //initialize copying
    await targetBlob.StartCopyAsync(sourceBlob.Uri);
}
catch(Exception ex){
    log.Error(ex.Message);
    //return error, in my case HTTP
    return req.CreateResponse(HttpStatusCode.BadRequest, "Error, source BLOB probably has private access only: " +ex.Message);
}

//fetch current attributes
targetBlob.FetchAttributes();

//waiting for completion
while (targetBlob.CopyState.Status == CopyStatus.Pending){
    log.Info("Status: " + targetBlob.CopyState.Status);
    Thread.Sleep(500);
    targetBlob.FetchAttributes();
}

//check status
if (targetBlob.CopyState.Status != CopyStatus.Success){
    //return error, in my case HTTP
    return req.CreateResponse(HttpStatusCode.BadRequest, "Copy failed with status: " + targetBlob.CopyState.Status);
}

//finally remove source in case Copy Status was Success
sourceBlob.Delete();

//and return success (in my case HTTP)
return req.CreateResponse(HttpStatusCode.OK, "Done.");
</code>```

Body:
Starting Azure Storage 8, to move Blobs between Storage Accounts I use code similar to below, hope it will help somebody:

//copy blobs - from
CloudStorageAccount sourceStorageAccount = new CloudStorageAccount(new StorageCredentials(storageFromName, storageFromKey), true);
CloudBlobClient sourceCloudBlobClient = sourceStorageAccount.CreateCloudBlobClient();
CloudBlobContainer sourceContainer = sourceCloudBlobClient.GetContainerReference(containerFromName);

//copy blobs - to
CloudStorageAccount targetStorageAccount = new CloudStorageAccount(new StorageCredentials(storageToName, storageToKey), true);
CloudBlobClient targetCloudBlobClient = targetStorageAccount.CreateCloudBlobClient();
CloudBlobContainer targetContainer = targetCloudBlobClient.GetContainerReference(containerToName);

//create target container if didn't exists
try{
    await targetContainer.CreateIfNotExistsAsync();
}
catch(Exception e){
    log.Error(e.Message);
}

CloudBlockBlob sourceBlob = sourceContainer.GetBlockBlobReference(blobName);
CloudBlockBlob targetBlob = targetContainer.GetBlockBlobReference(blobName);

try{
    //initialize copying
    await targetBlob.StartCopyAsync(sourceBlob.Uri);
}
catch(Exception ex){
    log.Error(ex.Message);
    //return error, in my case HTTP
    return req.CreateResponse(HttpStatusCode.BadRequest, "Error, source BLOB probably has private access only: " +ex.Message);
}

//fetch current attributes
targetBlob.FetchAttributes();

//waiting for completion
while (targetBlob.CopyState.Status == CopyStatus.Pending){
    log.Info("Status: " + targetBlob.CopyState.Status);
    Thread.Sleep(500);
    targetBlob.FetchAttributes();
}

//check status
if (targetBlob.CopyState.Status != CopyStatus.Success){
    //return error, in my case HTTP
    return req.CreateResponse(HttpStatusCode.BadRequest, "Copy failed with status: " + targetBlob.CopyState.Status);
}

//finally remove source in case Copy Status was Success
sourceBlob.Delete();

//and return success (in my case HTTP)
return req.CreateResponse(HttpStatusCode.OK, "Done.");


问:
React native clear Stack Navigator stack
I have few screens which I navigate through one by one. Screen1->screen2-screen3->screen4-Home

What I want is when I go to home then the previous history of navigation should be cleared and back pressing back button should not go to last navigated screen which is screen 4. Currently When I press back button on home screen it takes me back to the last route in the stack which is screen4. I have used below code. It is giving me error no route defined or key Home. Which I have already defined in Screens class. Any help would be appreciated.

```<code>const resetAction = NavigationActions.reset({
  index: 0,
  actions: [NavigationActions.navigate({ routeName: 'Home' })],
});

onPress={() =>  this.props.navigation.dispatch(resetAction)}
</code>```

答:
```<code>import {NavigationActions} from 'react-navigation';
const resetAction = NavigationActions.reset({
    index: 0,
    actions: [
      NavigationActions.navigate({ routeName: 'HomeScreen'})
    ] })
this.props.navigation.dispatch(resetAction);
</code>```

you can use this, this works for me..

Body:
I have few screens which I navigate through one by one. Screen1->screen2-screen3->screen4-Home

What I want is when I go to home then the previous history of navigation should be cleared and back pressing back button should not go to last navigated screen which is screen 4. Currently When I press back button on home screen it takes me back to the last route in the stack which is screen4. I have used below code. It is giving me error no route defined or key Home. Which I have already defined in Screens class. Any help would be appreciated.

const resetAction = NavigationActions.reset({
  index: 0,
  actions: [NavigationActions.navigate({ routeName: 'Home' })],
});

onPress={() =>  this.props.navigation.dispatch(resetAction)}

Body:
import {NavigationActions} from 'react-navigation';
const resetAction = NavigationActions.reset({
    index: 0,
    actions: [
      NavigationActions.navigate({ routeName: 'HomeScreen'})
    ] })
this.props.navigation.dispatch(resetAction);

you can use this, this works for me..


问:
XAMPP - Apache could not start - Attempting to start Apache service
While trying to start Apache using XAMPP, I was receiving  - "Attempting to start Apache service..." message in XAMPP UI. No further details were available.

Where can I see the logs (I was running XAMPP as Admin) ?

答:
Had the same issue while updating to PHP7.2

Problem:
First I closed skype and then checked whether port 80 is not an issue. How you can check that? See @AlexT comment above.

In my case, port 80 wasn't an issue. So now I had to figure out what was wrong. So I checked Error Logs Control Panel > Even viewer > Windows Logs > Application and found following error against Apache2.4

httpd.exe: Syntax error on line 520 of C:/xampp/apache/conf/httpd.conf: Syntax error on line 18 of C:/xampp/apache/conf/extra/httpd-xampp.conf: Cannot load C:/xampp/php/php7ts.dll into server: The Apache service named is not a valid Win32 application.

Which means I had installed wrong PHP version. Actually I downloaded win64 version while the required version was Win32 for me.

So I downloaded correct version from: Download PHP 7.2.0 extracted it in C:/xampp/php folder, restarted the apache and it worked :)


问:
Return local variable by reference still shows me the right value
I have this class:

```<code>class A
{
private:
    int a;
public:
    int getA();
    void setA(int a=2) ;
};
</code>```

and a function:

```<code>A& func()
{
A a;
a.setA(777);
return a;
}
</code>```

and in main:

```<code>A a;
a=func();
cout<<a.getA();
</code>```

and i get "777".
but as i know it shouldnt get me any value since the local "a" in the function has been deleted. so why do i get the right value?

答:
Like Bathsheba already answered, returning a reference to a temporary variable causes undefined behaviour.

Unfortunately, in my experience two bad things come together regarding this:

Due to the structure of a compiler, the reference will very often be 'seemingly' correct, like in your example.

The "return reference to temporary" issues only a compiler warning, not an error!

Both things together makes this problem very dangerous, because it can be easily missed and work even for years... until the day of that very important presentation.

Solution is to treat this warning as an error (consult your compiler's documentation for compiler flags) or - even better - treat all warnings as errors.

Body:
I have this class:

class A
{
private:
    int a;
public:
    int getA();
    void setA(int a=2) ;
};

and a function:

A& func()
{
A a;
a.setA(777);
return a;
}

and in main:

A a;
a=func();
cout<<a.getA();

and i get "777".
but as i know it shouldnt get me any value since the local "a" in the function has been deleted. so why do i get the right value?


问:
Checking if a DOM element is draggable and setting equal to JavaScript variable?
What is the most efficient way to create a JavaScript variable equal to the "draggable" state of a DOM element via jQuery?

I tried the following:

```<code>$(document).ready(function() {
    $('#editButton').click(function() {
        var isDraggable = $('.tile').draggable('option', 'disabled');
        if(isDraggable == "true")
        {
            $(function() {
                $('.tile').draggable({
                    containment: '#content',
                    scroll: false
                });
                $('.tile').resizable({
                    maxHeight: 200,
                    maxWidth: 200,
                    minHeight: 100,
                    minWidth: 100
                });
            })
        }
    })
});
</code>```

I didn't get any syntax errors or anything, but the functionality wasn't there.

Here is the accompanying HTML:

```<code><div id="content">
        <div id="navBar">
            <input type="button" id="editButton" value="Edit" />
        </div>
        <ul>
            <li>
                <div id ="google" class="tile">
                    <img src="images/tiles/google/google.png" class="tile_image" width="27" height="41" />
                    <p>Google</p>
                </div>
            </li>
            <li>
                <div id="yahoo" class="tile">
                    <p>Yahoo</p>
                </div>
            </li>
            <li>
                <div id="thelockpeople" class="tile">
                    <p>The Lock People</p>
                </div>
            </li>
            <li>
                <div id="amazon" class="tile">
                    <p>Amazon</p>
                </div>
            </li>
            <li>
                <div id="masterlock" class="tile">
                    <p>Masterlock</p>
                </div>
            </li>
            <li>
                <div id="hpionline" class="tile">
                    <p>Hpionline</p>
                </div>
            </li>
            <li>
                <div id="youtube" class="tile">
                    <p>YouTube</p>
                </div>
            </li>
            <li>
                <div id="kitco" class="tile">
                    <p>Kitco</p>
                </div>
            </li>
            <li>
                <div id="usatoday" class="tile">
                    <p>USA Today</p>
                </div>
            </li>
            <li>
                <div id="gamefly" class="tile">
                    <p>GameFly</p>
                </div>
            </li>
        </ul>
</div>
</code>```

What am I doing wrong?

答:
To make it work, just replace the line that says:

```<code>if(isDraggable == "true")
</code>```

with:

```<code>if (isDraggable)
</code>```

The reason is that isDraggable is an object, if it exists (i.e. the "draggable" method on the ".title" div worked) then it will be true (exists and is non-zero), but it will not be equal to 1, which is the numeric value for true, so your original test fails and you never call the function.

Body:
What is the most efficient way to create a JavaScript variable equal to the "draggable" state of a DOM element via jQuery?

I tried the following:

$(document).ready(function() {
    $('#editButton').click(function() {
        var isDraggable = $('.tile').draggable('option', 'disabled');
        if(isDraggable == "true")
        {
            $(function() {
                $('.tile').draggable({
                    containment: '#content',
                    scroll: false
                });
                $('.tile').resizable({
                    maxHeight: 200,
                    maxWidth: 200,
                    minHeight: 100,
                    minWidth: 100
                });
            })
        }
    })
});

I didn't get any syntax errors or anything, but the functionality wasn't there.

Here is the accompanying HTML:

            <input type="button" id="editButton" value="Edit" />

Google

Yahoo

The Lock People

Amazon

Masterlock

Hpionline

YouTube

Kitco

USA Today

GameFly

What am I doing wrong?

Body:
To make it work, just replace the line that says:

if(isDraggable == "true")

with:

if (isDraggable)

The reason is that isDraggable is an object, if it exists (i.e. the "draggable" method on the ".title" div worked) then it will be true (exists and is non-zero), but it will not be equal to 1, which is the numeric value for true, so your original test fails and you never call the function.


问:
how to store function value in variable and display it on textarea
I am trying to store value of function in the variable and want to display the content in text area t1.

So every time I push the value I can get the print function in the variable s and can display content in textarea t1.

```<code><html>
    <head>
        <title>Stack With Constructor </title>
    </head>
    <body>
        <div>Stack </div>
        <div>
            <h1>stack</h1>
            <h2>Stage1.</h2>
            <p id="p1">
                stack
            </p>
            <textarea id="t1"></textarea>
            <button onclick="doJob()">push</button>
            <button onclick="doJob1()">pop</button>
        </div>
        <textarea id="t"></textarea>
        <script>
            function push(v) {
                if (this.st === 0) {
                    console.log("Stack Overflow");
                } else {
                    this.st = this.st - 1;
                    this.stk[this.st] = v;
                }
            }

            function pop() {
                if (this.st === 10) {
                    console.log("Stack Underflow");
                } else {
                    var temp = this.stk[this.st];
                    this.st = this.st + 1;
                    return temp;
                }
            }

            function print() {
                console.log("Printing Stack");
                for (var i = this.st ; i < 10; i++) {
                    console.log(this.stk[i]);
                }
            };

            function MyStack() {
                this.st = 10;
                this.stk = new Array(10);
                this.push = push;
                this.pop = pop;
                this.print = print;
            };

            var s1 = new MyStack();

            function doJob() {
                var x=document.getElementById("t").value;
                s1.push(x);
                var s=s1.print();
                document.getElementById("t1").value=s;
            }
        </script>
    </body>
</html>
</code>```

I want to display the print function in the text area t1 so it can work as interactive stack.

When I try to push value, I am getting undefined in the textarea.

答:
change your print function like,

```<code>        function print() {
            console.log("Printing Stack");
            var str = "";//empty string
            for (var i = this.st ; i < 10; i++) {
                console.log(this.stk[i]);
                str+=this.stk[i]+'\n';//concatenate the value and a new line
            }
            return str;
        };
</code>```

DEMO

        <title>Stack With Constructor </title>

Stack

stack

Stage1.

                stack

            <textarea id="t1"></textarea>
            <button onclick="doJob()">push</button>
            <button onclick="doJob1()">pop</button>

        <textarea id="t"></textarea>

    ```

Body:
I am trying to store value of function in the variable and want to display the content in text area t1.

So every time I push the value I can get the print function in the variable s and can display content in textarea t1.

        <title>Stack With Constructor </title>

Stack

stack

Stage1.

                stack

            <textarea id="t1"></textarea>
            <button onclick="doJob()">push</button>
            <button onclick="doJob1()">pop</button>

        <textarea id="t"></textarea>

I want to display the print function in the text area t1 so it can work as interactive stack.

When I try to push value, I am getting undefined in the textarea.

Body:
change your print function like,

        function print() {
            console.log("Printing Stack");
            var str = "";//empty string
            for (var i = this.st ; i < 10; i++) {
                console.log(this.stk[i]);
                str+=this.stk[i]+'\n';//concatenate the value and a new line
            }
            return str;
        };

DEMO

<html>
    <head>
        <title>Stack With Constructor </title>
    </head>
    <body>
        <div>Stack </div>
        <div>
            <h1>stack</h1>
            <h2>Stage1.</h2>
            <p id="p1">
                stack
            </p>
            <textarea id="t1"></textarea>
            <button onclick="doJob()">push</button>
            <button onclick="doJob1()">pop</button>
        </div>
        <textarea id="t"></textarea>
        <script>
            function push(v) {
                if (this.st === 0) {
                    console.log("Stack Overflow");
                } else {
                    this.st = this.st - 1;
                    this.stk[this.st] = v;
                }
            }

            function pop() {
                if (this.st === 10) {
                    console.log("Stack Underflow");
                } else {
                    var temp = this.stk[this.st];
                    this.st = this.st + 1;
                    return temp;
                }
            }

            function print() {
                console.log("Printing Stack");
                var str = "";//empty string
                for (var i = this.st ; i < 10; i++) {
                    console.log(this.stk[i]);
                    str+=this.stk[i]+'\n';//concatenate the value and a new line
                }
                return str;
            };

            function MyStack() {
                this.st = 10;
                this.stk = new Array(10);
                this.push = push;
                this.pop = pop;
                this.print = print;
            };

            var s1 = new MyStack();

            function doJob() {
                var x=document.getElementById("t").value;
                s1.push(x);
                var s=s1.print();
                document.getElementById("t1").value=s;
            }
            function doJob1(){
                s1.pop();
                var s=s1.print();
                document.getElementById("t1").value=s;
            }
        </script>
    </body>


问:
Create keyspace, table and generate tables dynamically using Spring Data Cassandra
Using Cassandra, I want to create keyspace and tables dynamically using Spring Boot application. I am using Java based configuration.

I have an entity annotated with @Table whose schema I want to be created before application starts up since it has fixed fields that are known beforehand.

However depending on the logged in user, I also want to create additional tables for those user dynamically and be able to insert entries to those tables.

Can somebody guide me to some resources that I can make use of or point me in right direction in how to go about solving these issues. Thanks a lot for help!

答:
The following cassandra configuration will create a keyspace when it does not exist and also run the start-up script specified

```<code>@Configuration
@PropertySource(value = {"classpath:cassandra.properties"})
@EnableCassandraRepositories
public class CassandraConfig extends AbstractCassandraConfiguration {

  @Value("${cassandra.keyspace}")
  private String cassandraKeyspace;

  @Override
  protected List<CreateKeyspaceSpecification> getKeyspaceCreations() {
    return Collections.singletonList(CreateKeyspaceSpecification.createKeyspace(cassandraKeyspace)
                .ifNotExists()
                .with(KeyspaceOption.DURABLE_WRITES, true)
                .withSimpleReplication());
  }

  @Override
  protected List<String> getStartupScripts() {
    return Collections.singletonList("CREATE TABLE IF NOT EXISTS "+cassandraKeyspace+".test(id UUID PRIMARY KEY, greeting text, occurrence timestamp) WITH default_time_to_live = 600;");
  }

}
</code>```

Body:
The following cassandra configuration will create a keyspace when it does not exist and also run the start-up script specified

@Configuration
@PropertySource(value = {"classpath:cassandra.properties"})
@EnableCassandraRepositories
public class CassandraConfig extends AbstractCassandraConfiguration {

  @Value("${cassandra.keyspace}")
  private String cassandraKeyspace;

  @Override
  protected List<CreateKeyspaceSpecification> getKeyspaceCreations() {
    return Collections.singletonList(CreateKeyspaceSpecification.createKeyspace(cassandraKeyspace)
                .ifNotExists()
                .with(KeyspaceOption.DURABLE_WRITES, true)
                .withSimpleReplication());
  }

  @Override
  protected List<String> getStartupScripts() {
    return Collections.singletonList("CREATE TABLE IF NOT EXISTS "+cassandraKeyspace+".test(id UUID PRIMARY KEY, greeting text, occurrence timestamp) WITH default_time_to_live = 600;");
  }

}


问:
Getting audio markers / cue points with the Web Audio API
If I have an audio file in WAV format containing markers (or "cue points"), is there a way to get an array of those markers, preferably using the Web Audio API?

I seem to remember seeing a method to do so before, but I can't seem to find it.

Any help or suggestions would be great!

答:
Web Audio API doesn't support parsing marker chunks ("cue "s) in WAVE-RIFF, only the audio data itself.

You'll have to parse and extract the marker chunks manually using for example typed arrays and DataView after loading the file as ArrayBuffer (unrelated to Web Audio API per-se).

It's a bit broad for giving a solution, but this article should be able to point you in the right direction as to how.


问:
PostgreSQL with-delete "relation does not exists"
I am using postgreSQL 9.1 and I want to delete duplicates from my table using this tip:
https://stackoverflow.com/a/3822833/2239537

So, my query looks like that:

```<code>WITH cte
 AS (SELECT ROW_NUMBER()
 OVER (PARTITION BY code, card_id, parent_id
     ORDER BY id DESC) RN
     FROM card)
DELETE FROM cte
WHERE RN > 1
</code>```

But it shows me

```<code>ERROR: relation "cte" does not exist
SQL state: 42P01
Character: 157
</code>```

However this statement works fine:

```<code>WITH cte
 AS (SELECT ROW_NUMBER()
 OVER (PARTITION BY code, card_id, parent_id
     ORDER BY id DESC) RN
     FROM merchantcard)
SELECT * FROM cte
WHERE RN > 1
</code>```

Any ideas how to get it work?
Thanks!

答:
For me it worked Like this in Postgres/GreenPlum :</p>

```<code>delete
from card where id in (
with cte as (
    select
        id,
        row_number() over(partition by code, card_id, parent_id order by id desc) as rn
    from card
)
select id from cte where rn > 1);
</code>```

Body:
I am using postgreSQL 9.1 and I want to delete duplicates from my table using this tip:
https://stackoverflow.com/a/3822833/2239537

So, my query looks like that:

WITH cte
 AS (SELECT ROW_NUMBER()
 OVER (PARTITION BY code, card_id, parent_id
     ORDER BY id DESC) RN
     FROM card)
DELETE FROM cte
WHERE RN > 1

But it shows me

ERROR: relation "cte" does not exist
SQL state: 42P01
Character: 157

However this statement works fine:

WITH cte
 AS (SELECT ROW_NUMBER()
 OVER (PARTITION BY code, card_id, parent_id
     ORDER BY id DESC) RN
     FROM merchantcard)
SELECT * FROM cte
WHERE RN > 1

Any ideas how to get it work?
Thanks!

Body:
For me it worked Like this in Postgres/GreenPlum :

delete
from card where id in (
with cte as (
    select
        id,
        row_number() over(partition by code, card_id, parent_id order by id desc) as rn
    from card
)
select id from cte where rn > 1);


问:
Connecting Spark and elasticsearch
I'am trying to run a simple code of Spark that copies the content of an RDD into an elastic search document. Both spark and elastic search are installed on my local machine.

```<code>    import org.elasticsearch.spark.sql._
    import org.apache.spark.sql.SparkSession

    object ES {

   case class Person(ID: Int, name: String, age: Int, numFriends:
  Int);

     def mapper(line: String): Person = {
    val fields = line.split(',')
    val person: Person = Person(fields(0).toInt, fields(1),
    fields(2).toInt, fields(3).toInt)
    return person}

    def main(args: Array[String]): Unit = {

    val spark: SparkSession =
    SparkSession
    .builder().master("local[*]")
    .appName("SparkEs")
       .config("es.index.auto.create", "true")
       .config("es.nodes","localhost:9200")
     .getOrCreate()

import spark.implicits._

val lines = spark.sparkContext.textFile("/home/herch/fakefriends.csv")
val people = lines.map(mapper).toDF()

people.saveToEs("spark/people")

}

}
</code>```

I'am Getting this error. After multiples retries

```<code> INFO HttpMethodDirector: I/O exception (java.net.ConnectException)
 caught when processing request:Connection timed out (Connection timed
 out)

 INFO HttpMethodDirector: Retrying request

 INFO DAGScheduler: ResultStage 0 (runJob at EsSparkSQL.scala:97)
 failed in 525.902 s due to Job aborted due to stage failure: Task 1
 in stage 0.0 failed 1 times, most recent failure: Lost task 1.0 in
 stage 0.0 (TID 1, localhost, executor driver):
 org.elasticsearch.hadoop.rest.EsHadoopNoNodesLeftException:
 Connection error (check network and/or proxy settings)- all nodes
 failed; tried [[192.168.0.22:9200]]
</code>```

It seems to be a connection problem but i cannot identify its cause. Elastic search is running on my local machine on localhost:9200 and i'am able to query it via the terminal.

答:
As seen on the elasticsearch / spark connector documentation page, you need to separate the host and port arguments inside the configuration :

```<code>val options13 = Map("path" -> "spark/index",
                "pushdown" -> "true",
                "es.nodes" -> "someNode", "es.port" -> "9200")
</code>```

See how es.nodes only contains the host name, and es.port contains the HTTP port.

Title: Connecting Spark and elasticsearch

Body:
I'am trying to run a simple code of Spark that copies the content of an RDD into an elastic search document. Both spark and elastic search are installed on my local machine.

    import org.elasticsearch.spark.sql._
    import org.apache.spark.sql.SparkSession

    object ES {

   case class Person(ID: Int, name: String, age: Int, numFriends:
  Int);

     def mapper(line: String): Person = {
    val fields = line.split(',')
    val person: Person = Person(fields(0).toInt, fields(1),
    fields(2).toInt, fields(3).toInt)
    return person}

    def main(args: Array[String]): Unit = {

    val spark: SparkSession =
    SparkSession
    .builder().master("local[*]")
    .appName("SparkEs")
       .config("es.index.auto.create", "true")
       .config("es.nodes","localhost:9200")
     .getOrCreate()

import spark.implicits._

val lines = spark.sparkContext.textFile("/home/herch/fakefriends.csv")
val people = lines.map(mapper).toDF()

people.saveToEs("spark/people")

}

}

I'am Getting this error. After multiples retries

 INFO HttpMethodDirector: I/O exception (java.net.ConnectException)
 caught when processing request:Connection timed out (Connection timed
 out)

 INFO HttpMethodDirector: Retrying request

 INFO DAGScheduler: ResultStage 0 (runJob at EsSparkSQL.scala:97)
 failed in 525.902 s due to Job aborted due to stage failure: Task 1
 in stage 0.0 failed 1 times, most recent failure: Lost task 1.0 in
 stage 0.0 (TID 1, localhost, executor driver):
 org.elasticsearch.hadoop.rest.EsHadoopNoNodesLeftException:
 Connection error (check network and/or proxy settings)- all nodes
 failed; tried [[192.168.0.22:9200]]

It seems to be a connection problem but i cannot identify its cause. Elastic search is running on my local machine on localhost:9200 and i'am able to query it via the terminal.

Body:
As seen on the elasticsearch / spark connector documentation page, you need to separate the host and port arguments inside the configuration :

val options13 = Map("path" -> "spark/index",
                "pushdown" -> "true",
                "es.nodes" -> "someNode", "es.port" -> "9200")

See how es.nodes only contains the host name, and es.port contains the HTTP port.


问:
openapi 2 multiple response types
I know that with openapi 3 I can use oneOf/anyOf but currently we can't upgrade to openapi 3. In one of definitions I need to use many response types which doesn't have common attributes (basically response is interface without any method/attribute and has multiple different implementations). Can I somehow define multiple response types with openapi 2? Is it possible to use for example headers/content-types/... to distinguish between this reponse types and have valid openapi2 definition?

thanks

答:
Update:

Turns out there can be multiple responses as long as they have different HTTP status code as a "key". default keyword is just that, user of API is supposed to expect that if HTTP status is not on the list of responses default should be used. (e.g. if somebody uses switch to handle responses default maps to default case in switch).

As for single HTTP status code signaling multiple possible types of response, that's not supported explicitly. One ugly workaround would be to create type that contain all the fields, and it would be up to a client to discriminate based on which fields hold values.

Title: openapi 2 multiple response types


问:
Reference specific String value inside separate XML file in Android
Inside my res\values folder, I want to place multiple .xml files with duplicate <string> names.

i.e. The .xml file example1.xml will have a string resource of:

<string name="title">Test Example 1</string>

At the same time, I want the .xml file Example2.xml to also have a string resource of the same name, but different value:

<string name="title">Test Example 2</string>

Both .xml files will live in res\values and I want to access the string values programmatically.

I know how to reference the string resource via: R.string.title, but how do I specify from which .xml file?

答:
In android, you can only reference Strings using value provided in name attribute of the String resource  and NOT using name of the XML file. So you can't specify the name of the XML file to reference the String, you just need to have different values for name attribute of each String resource.

Quote from developer.android.com

A string is a simple resource that is referenced using the value
  provided in the name attribute (not the name of the XML file). So, you
  can combine string resources with other simple resources in the one
  XML file, under one  element.


问:
IDEA: IntelliJ/PyCharm not using my .gitconfig data
I have fresh install of IDEA InteliJ and PyCharm installed with git support enabled. However, when I try to Ctrl+K to commit the author field is empty. Moreover, the Ctrl+Space says "No Suggestion".

I have my ~/.gitconfig generated properly by PyCharm is not using its data.

```<code>$ git config --global user.name "John Doe"
$ git config --global user.email johndoe@example.com
</code>```

How to make PyCharm to use the data from regular .gitconfig?

答:
The author field is only supposed to be filled in if the one who wrote the code is different from the commiter. See more about this in this answer

So if you don't explicitly fill in another author in IntelliJ, the author will be the same as the commiter, which is retrieved from the git config. You can't really see what this is in the "Commit Changes" window, except if you hover your mouse over the "Sign-off commit" checkbox.

Body:
I have fresh install of IDEA InteliJ and PyCharm installed with git support enabled. However, when I try to Ctrl+K to commit the author field is empty. Moreover, the Ctrl+Space says "No Suggestion".

I have my ~/.gitconfig generated properly by PyCharm is not using its data.

$ git config --global user.name "John Doe"
$ git config --global user.email johndoe@example.com

How to make PyCharm to use the data from regular .gitconfig?


问:
How do I allow a user to pick a background colour of my website with a colour chooser and store it?

<input name="Color Picker" id="picker" onclick="setColor()" type="color" />
```

<pre class="lang-js prettyprint-override"><code>function setColor() {
  getColor();
  if (localStorage.getItem('background') !== null) {
    getColour = localStorage.background;
    $('body').css('background', getColour);
  }
}

function getColor() {
  localStorage.getItem('background') = picker;

}
</code>```

I want to take the user input for the custom colour and update the website background accordingly.

答:
Stackoverflow snippets doesn't seem to like using localStorage so here is an example how to read and write colors. I commented out the local storage code for you to use in your application instead of the temp variable I used toi demonstrate the code.

Example below uses the onchange and stores the current color on load, has a default color you can apply clicking a button and has another button to apply the store/selected color.

var defaultColor = '#00ff00';
var tempStorage;

function setColor() {
  //localStorage.setItem('background', $('#picker').val());
  tempStorage = $('#picker').val();
  $('body').css('background-color', tempStorage);
  applyBackgroundColor(tempStorage);
}

function getColor() {
  //localStorage.getItem('background');
  $('#picker').val(tempStorage);
  applyBackgroundColor(tempStorage);
}

function getDefaultColor() {
  $('#picker').val(defaultColor);
  applyBackgroundColor(defaultColor);
}

function applyBackgroundColor(colorValue){
  $('body').css('background-color', colorValue);
}

setColor();```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input name="Color Picker" id="picker" onchange="setColor()" type="color" />
<button onclick="getDefaultColor()">Apply Default</button>
<button onclick="getColor()">Apply Stored</button></code>```

Please note I used your own syntax and tried changing as little as
  possible to your original code, i.e: How you call the methods inline,
  etc..

Though in general I would recommend to not use inline bindings but use
  jQuery $(element).on('event', function(){}) instead. i.e:
  $(#picker).on('change', setColor)

Body:
<input name="Color Picker" id="picker" onclick="setColor()" type="color" />

function setColor() {
  getColor();
  if (localStorage.getItem('background') !== null) {
    getColour = localStorage.background;
    $('body').css('background', getColour);
  }
}

function getColor() {
  localStorage.getItem('background') = picker;

}

I want to take the user input for the custom colour and update the website background accordingly.

Body:
Stackoverflow snippets doesn't seem to like using localStorage so here is an example how to read and write colors. I commented out the local storage code for you to use in your application instead of the temp variable I used toi demonstrate the code.

Example below uses the onchange and stores the current color on load, has a default color you can apply clicking a button and has another button to apply the store/selected color.

var defaultColor = '#00ff00';
var tempStorage;

function setColor() {
  //localStorage.setItem('background', $('#picker').val());
  tempStorage = $('#picker').val();
  $('body').css('background-color', tempStorage);
  applyBackgroundColor(tempStorage);
}

function getColor() {
  //localStorage.getItem('background');
  $('#picker').val(tempStorage);
  applyBackgroundColor(tempStorage);
}

function getDefaultColor() {
  $('#picker').val(defaultColor);
  applyBackgroundColor(defaultColor);
}

function applyBackgroundColor(colorValue){
  $('body').css('background-color', colorValue);
}

setColor();

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input name="Color Picker" id="picker" onchange="setColor()" type="color" />
<button onclick="getDefaultColor()">Apply Default</button>
<button onclick="getColor()">Apply Stored</button>

Please note I used your own syntax and tried changing as little as
  possible to your original code, i.e: How you call the methods inline,
  etc..

Though in general I would recommend to not use inline bindings but use
  jQuery $(element).on('event', function(){}) instead. i.e:
  $(#picker).on('change', setColor)


问:
Show PopUp on Mouse Hover and Close it on Mouse Out
I have a code here that create a marker and put it in the map

```<code>var wholeinfo = "This is my message"

marker = L.marker([lat,long], {
  icon: new L.AwesomeNumberMarkers({
  number: '<font color="black" size = "1">' + code + '</font>',
  markerColor: anyColor,
  })}).bindPopup(wholeinfo).openPopup().on('click', markerOnClick).on('mouseover', openPopup());

markers.addLayer(marker);
</code>```

I wonder how can I show the popup of that marker when i hover my pointer on it? then close when i remove my pointer. I try this but no luck

'mouseover', openPopup()

答:
Try to use </p>

```<code>.on('mouseover', function (e) { this.openPopup(); })
.on('mouseout', function (e) { this.closePopup(); });
</code>```

<p>instead of </p>

```<code>.on('mouseover', openPopup())
</code>```

Body:
I have a code here that create a marker and put it in the map

var wholeinfo = "This is my message"

marker = L.marker([lat,long], {
  icon: new L.AwesomeNumberMarkers({
  number: '' + code + '',
  markerColor: anyColor,
  })}).bindPopup(wholeinfo).openPopup().on('click', markerOnClick).on('mouseover', openPopup());

markers.addLayer(marker);

I wonder how can I show the popup of that marker when i hover my pointer on it? then close when i remove my pointer. I try this but no luck

'mouseover', openPopup()

Body:
Try to use

.on('mouseover', function (e) { this.openPopup(); })
.on('mouseout', function (e) { this.closePopup(); });

instead of

.on('mouseover', openPopup())


问:
How to split multiple typed index out to prepare for ES upgrade (where multiple types are deprecated)
We are currently running a cluster with ES 2.3.2 that has one large index with the following properties:

762 GB (366 million docs)

25 data nodes; 3 master nodes; 3 client nodes

23 shards / 1 replica

This one index has 20+ types, each with a few common and many unique fields.  I am redesigning the cluster with the following goals:

1) Remove multiple types in an index so that we can upgrade ES.  Though multi-types are supported in v5, we want to do the work to prep for v6 now.
2) Break up the large index into more manageable smaller indexes

I have set up a new identical cluster.  I modified the indexing so that I have one index per type.  I allocated a shard count based on the relative size of the data with a minimum of 2, and a max of 5 shards.  After indexing all of our data into this new cluster, I am finding that the same query against the new cluster is slower than against the old cluster.

I figured this was due to the explosion of shards (i.e. was 23 primary, and now it is 78).  I closed all but one index (that has a shard count of 2), then ran a test where I targeted a single type against my old monolithic index, and the new single-typed index (using a homebrew tool to run requests in parallel and parse out the "took").  I find that if I do a "size: 0", my new cluster is faster.  When I return 7 or 8 they seem to be in parity.  It then goes downhill where our default query of 30 records returned is about twice as slow.  I am guessing this is because there are fewer threads to do the actual retrieval in the smaller index with two shards vs the large one with 23.

What is the recommendation for moving away from multi-typed indexes when the following is true:
- There are many types
- The types have very different mappings
- There is a huge variance in size per type running from 4 mb to 154 gb

I am currently contemplating putting them all in one type with one massive mapping (I don't think there are any fields with the same name but different mappings), but that seems really ugly.

Any suggestions welcome,

Thanks,
~john

答:
Sharding is the way how elasticsearch scales, so it makes sense that you observe performance degradation for network/IO bound operation when it's executed against 2 shard vs. 23, as it essentially means it was run on 2 nodes in parallel as opposed to 23.

If you want to split the index, you need to go over all of the types and identify the minimum number of shards for each type for your target performance. It'll depend on multiple factors such as the number of documents, document size, request/indexing patterns. As you mentioned that types vary significantly in size, most likely the result will be less balanced than your initial set up (2-5 shards), i.e. some of the indexes will need a higher number of shards, while some will do fine with less, e.g. there is no need to split 4mb index (as in your example) into multiple shards, unless you expect it to grow significantly and have high update rate and you want to scale indexing, otherwise 1 shard is fine.


问:
Uploading and processing a csv file in django using ModelForm
I am trying to upload and fetch the data from csv file uploaded by user. I am using the following code.
This is my html form (upload_csv1.html):

```<code>    <form action="{% url 'myapp:upload_csv' %}" method="post" enctype="multipart/form-data">
    {% csrf_token %}
    <input type="file" name="csv_file1">
    <input type="submit" value="Upload">
</form>
</code>```

This is views.py:

```<code>def uploadcsv(request):
data = {}
if "GET" == request.method:
    return render(request, "myapp/upload_csv1.html", data)
# if not GET, then proceed
try:
    csv_file = request.FILES["csv_file1"]
    if not csv_file.name.endswith('.csv'):
        messages.error(request,'File is not CSV type')
        return HttpResponseRedirect(reverse("myapp:upload_csv"))
    #if file is too large, return
    if csv_file.multiple_chunks():
        messages.error(request,"Uploaded file is too big (%.2f MB)." % (csv_file.size/(1000*1000),))
        return HttpResponseRedirect(reverse("myapp:upload_csv"))

    file_data = csv_file.read().decode("utf-8")

    lines = file_data.split("\n")
    #loop over the lines and save them in db. If error , store as string and then display
    for line in lines:
        fields = line.split(",")
        data_dict = {}
        data_dict["sku"] = fields[0]
        data_dict["item_name"] = fields[1]
        try:
            form = PalazzoForm(data_dict)
            if form.is_valid():
                form.save()
            else:
                logging.getLogger("error_logger").error(form.errors.as_json())
        except Exception as e:
            logging.getLogger("error_logger").error(form.errors.as_json())
            pass

except Exception as e:
    logging.getLogger("error_logger").error("Unable to upload file. "+repr(e))
    messages.error(request,"Unable to upload file. "+repr(e))

return HttpResponseRedirect(reverse("myapp:upload_csv"))
</code>```

And the code is working fine.

What I am not able to get is that when I am printing request.method in views

```<code>def uploadcsv(request):
    print request.method
</code>```

the output is "GET" instead of "POST".

My doubt is,

if the request.method is GET then why the code is not skipping the "try-except" block and how is it processing the csv file?

when the HTML form method is set as "post", why is it showing request.method as "GET" ?

I have looked for this and this (which is somehow related to my question) but there is no final answer on these questions.

I have also tried the append slash redirect by typing the proper URL but the request.method remains "GET".

Can anyone clarify the concept of this?

The code I am using is from this source

答:
Your code is running fine. You can try debugging it with pdb.
You may be printing the method type at the time of loading the page, instead of uploading the .csv file. </p>

Body:
I am trying to upload and fetch the data from csv file uploaded by user. I am using the following code.
This is my html form (upload_csv1.html):

    <form action="{% url 'myapp:upload_csv' %}" method="post" enctype="multipart/form-data">
    {% csrf_token %}
    <input type="file" name="csv_file1">
    <input type="submit" value="Upload">
</form>

This is views.py:

def uploadcsv(request):
data = {}
if "GET" == request.method:
    return render(request, "myapp/upload_csv1.html", data)
# if not GET, then proceed
try:
    csv_file = request.FILES["csv_file1"]
    if not csv_file.name.endswith('.csv'):
        messages.error(request,'File is not CSV type')
        return HttpResponseRedirect(reverse("myapp:upload_csv"))
    #if file is too large, return
    if csv_file.multiple_chunks():
        messages.error(request,"Uploaded file is too big (%.2f MB)." % (csv_file.size/(1000*1000),))
        return HttpResponseRedirect(reverse("myapp:upload_csv"))

    file_data = csv_file.read().decode("utf-8")

    lines = file_data.split("\n")
    #loop over the lines and save them in db. If error , store as string and then display
    for line in lines:
        fields = line.split(",")
        data_dict = {}
        data_dict["sku"] = fields[0]
        data_dict["item_name"] = fields[1]
        try:
            form = PalazzoForm(data_dict)
            if form.is_valid():
                form.save()
            else:
                logging.getLogger("error_logger").error(form.errors.as_json())
        except Exception as e:
            logging.getLogger("error_logger").error(form.errors.as_json())
            pass

except Exception as e:
    logging.getLogger("error_logger").error("Unable to upload file. "+repr(e))
    messages.error(request,"Unable to upload file. "+repr(e))

return HttpResponseRedirect(reverse("myapp:upload_csv"))

And the code is working fine.

What I am not able to get is that when I am printing request.method in views

def uploadcsv(request):
    print request.method

the output is "GET" instead of "POST".

My doubt is,

if the request.method is GET then why the code is not skipping the "try-except" block and how is it processing the csv file?

when the HTML form method is set as "post", why is it showing request.method as "GET" ?

I have looked for this and this (which is somehow related to my question) but there is no final answer on these questions.

I have also tried the append slash redirect by typing the proper URL but the request.method remains "GET".

Can anyone clarify the concept of this?

The code I am using is from this source


问:
adding image src from mysql database
My question is why doesn't the image appear on my php page, i have image url in database under 'imageurl'. I want to echo url to image src and this will show the picture from the folder. The error is Parse error: syntax error, unexpected '<' in .... on line 95. I will put the line 95 in the sample code too.</p>

```<code><html>
   <body>
      <?php while($row = mysql_fetch_assoc($query)): ?>
         <div class="NewsItem">
            <div>
              <h1><?php echo $row['txt']; ?></a> <br>
              <span>posted on <?php echo $row['added']; ?></span><span> by <?php echo $row['adder'];?></span>

             </div>
             <div class="imgdiv"><?php if(($row['imageurl'] == 'NULL') or ($row['imageurl']== '')){
                 //No images
             }
             else{
            Line 95----  <img src="<?php echo $row['imageurl'];?>" width='300' height='300'/>
             }

             ?></div>
             <br>
             <div>
             <form action="comment.php"method="post" name="addComment"><input type="text" placeholder="kommentaar" name="commenttext" maxlenght="100"><input type="submit" name="addComment" value="Lisa kommentaar">
             <input id="prodId3" name="prodId3" type="hidden" value="<?php echo $row['id']; ?>">
             </form>
             </div>
          </div>

      <?php
      endwhile;
      ?>
</code>```

答:
Need to maintain php tags open and close at line #95

So,
Change your else part like this:

```<code>else{ ?>
      <img src="<?php echo $row['imageurl'];?>" width='300' height='300'/>
<?php    }
</code>```

Title: adding image src from mysql database

Body:
My question is why doesn't the image appear on my php page, i have image url in database under 'imageurl'. I want to echo url to image src and this will show the picture from the folder. The error is Parse error: syntax error, unexpected '<' in .... on line 95. I will put the line 95 in the sample code too.

      <?php while($row = mysql_fetch_assoc($query)): ?>

<?php echo $row['txt']; ?>

              posted on <?php echo $row['added']; ?> by <?php echo $row['adder'];?>

<?php if(($row['imageurl'] == 'NULL') or ($row['imageurl']== '')){
                 //No images
             }
             else{
            Line 95----  <img src="<?php echo $row['imageurl'];?>" width='300' height='300'/>
             }

             ?>

             <form action="comment.php"method="post" name="addComment"><input type="text" placeholder="kommentaar" name="commenttext" maxlenght="100"><input type="submit" name="addComment" value="Lisa kommentaar">
             <input id="prodId3" name="prodId3" type="hidden" value="<?php echo $row['id']; ?>">
             </form>

      <?php
      endwhile;
      ?>

Body:
Need to maintain php tags open and close at line #95

So,
Change your else part like this:

else{ ?>
      <img src="<?php echo $row['imageurl'];?>" width='300' height='300'/>
<?php    }


问:
ionic 2: Zoom in ionic slides
I am developing a project for e-commerce, and in product-detail page,i have one slider with product images. in that user can zoom that image.

my html code

```<code>  <ion-slides pager="true" style="height:45%" zoom> <ion-slide *ngFor="let slide of selProd.productImages"> <img src="{{slide.image}}"> </ion-slide> </ion-slides>
</code>```

but when i try to zoom image by pinch or double tap. it gives me error:

```<code>swiper-zoom.js:364 Uncaught TypeError: Cannot read property 'getAttribute' of null
    at toggleZoom (swiper-zoom.js:364)
</code>```

Thank you.

答:
UPDATE

Adding class swiper-zoom-container with div tag in between img tag and ion-slide tag solved the issue.

Ex.:

```<code><ion-slides pager="true" style="height:45%" zoom>
<ion-slide *ngFor="let slide of selProd.productImages">
  <div class="swiper-zoom-container">
    <img src="{{slide.image}}">
  </div>
</ion-slide>
</code>```

Title: ionic 2: Zoom in ionic slides

Body:
I am developing a project for e-commerce, and in product-detail page,i have one slider with product images. in that user can zoom that image.

my html code

  <ion-slides pager="true" style="height:45%" zoom> <ion-slide *ngFor="let slide of selProd.productImages">  </ion-slide> </ion-slides>

but when i try to zoom image by pinch or double tap. it gives me error:

swiper-zoom.js:364 Uncaught TypeError: Cannot read property 'getAttribute' of null
    at toggleZoom (swiper-zoom.js:364)

Thank you.

Body:
UPDATE

Adding class swiper-zoom-container with div tag in between img tag and ion-slide tag solved the issue.

Ex.:

<ion-slides pager="true" style="height:45%" zoom>
<ion-slide *ngFor="let slide of selProd.productImages">
  <div class="swiper-zoom-container">
    <img src="{{slide.image}}">
  </div>
</ion-slide>


问:
App won't launch from email link cause of missing colon
i have a problem to open my iOS app with a link. When I open the link it changes the url from:

```<code>http://myapp://my-url
</code>```

to

```<code>http://myapp//my-url
</code>```

The custom scheme does not work if there's no colon. The app is correctly setup cause when I manually type the colon back in it works like excepted.

Can someone give any advice how proceed here?

答:
you may redirect the response.
First generate the simple url when you click on that url .Redirect to your myapp://my-url(dont add http protocol now) </p>

Body:
i have a problem to open my iOS app with a link. When I open the link it changes the url from:

http://myapp://my-url

to

http://myapp//my-url

The custom scheme does not work if there's no colon. The app is correctly setup cause when I manually type the colon back in it works like excepted.

Can someone give any advice how proceed here?


问:
pytesseract WindowsError: [Error 5] Access is denied
I have installed pytesseract in Windows 10 system. When I try to run the following line,

pytesser=pytesseract.image_to_string(image)

It throws an error saying,

WindowsError: [Error 5] Access is denied

Even after changing the tesseract_cmd path, it throws the same error.

Looking for the other possible ways to sort this issue.TIA

答:
Your code works except the setting of pytesseract.pytesseract.tesseract_cmd. The tesseract_cmd should set to the tesseract executable file installed in your machine. Check if it's pointing to that

See if this helps

Pytesseract Image_to_string returns Windows Error: Access denied error in Python


问:
Alternatives to HTML5 localStorage
What are my alternatives to localStorage for persisting key/value pairs on the client?  Ideally I'm looking for something that the user can't inadvertently delete (as they theoretically could with localStorage). </p>

答:
An alternative could also be localForage, a js library that provides the ease of use of localStorage with all the advanced features of IndexedDB.

One of the benefits: you don’t have to convert your data structures to JSON in order to save them in the datastore.

Its API has support for ECMAScript 6 Promises, which provide a better way of handling asynchronous code.
Unfortunately it doesn’t work well with any IE under 11.

Title: Alternatives to HTML5 localStorage