问:
AWS: Layer code not found when using "sam invoke local"
I'm working on a sample AWS project that creates two lambda functions. These functions share common code from node_modules which has been placed in a separate layer (specifically AWS::Lambda::LayerVersion, not AWS::Serverless::LayerVersion). I can deploy this code and it works correctly when I test the deployed version.

However, when I try to test the code locally using sam invoke local, the common code is not found. I get this error (I'm trying to use the npm package "axios"):

{"errorType":"Runtime.ImportModuleError","errorMessage":"Error: Cannot find module 'axios'\nRequire stack:\n- /var/task/get-timezone.js\n- /var/runtime/UserFunction.js\n- /var/runtime/index.js"}

This is my template.yaml:

```<code>AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Description: AWS Sample

Globals:
  Function:
    Timeout: 30

Resources:
  SampleCommonLayer:
    Type: AWS::Lambda::LayerVersion
    Properties:
      CompatibleRuntimes:
        - nodejs12.x
      Content: nodejs.zip
      Description: Sample Common LayerVersion
      LayerName: SampleCommonLayer

  GetTimezoneFunction:
    Type: AWS::Serverless::Function
    Properties:
      CodeUri: dist/get-timezone
      Handler: get-timezone.getTimezone
      Runtime: nodejs12.x
      Layers:
        - !Ref SampleCommonLayer
      Events:
        GetTimezone:
          Type: Api
          Properties:
            Path: /get-timezone
            Method: get

  ReverseFunction:
    Type: AWS::Serverless::Function
    Properties:
      CodeUri: dist/reverse
      Handler: reverse.reverse
      Runtime: nodejs12.x
      Layers:
        - !Ref SampleCommonLayer
      Events:
        Reverse:
          Type: Api
          Properties:
            Path: /reverse
            Method: get

Outputs:
  GetTimezoneApi:
    Description: "API Gateway endpoint URL for Prod stage for getTimezone function"
    Value: !Sub "https://${ServerlessRestApi}.execute-api.${AWS::Region}.amazonaws.com/Prod/get-timezone/"
  GetTimezoneFunction:
    Description: "getTimezone Lambda Function ARN"
    Value: !GetAtt GetTimezoneFunction.Arn
  GetTimezoneFunctionIamRole:
    Description: "Implicit IAM Role created for getTimezone function"
    Value: !GetAtt GetTimezoneFunctionRole.Arn

  ReverseApi:
    Description: "API Gateway endpoint URL for Prod stage for reverse function"
    Value: !Sub "https://${ServerlessRestApi}.execute-api.${AWS::Region}.amazonaws.com/Prod/reverse/"
  ReverseFunction:
    Description: "reverse Lambda Function ARN"
    Value: !GetAtt ReverseFunction.Arn
  ReverseFunctionIamRole:
    Description: "Implicit IAM Role created for reverse function"
    Value: !GetAtt ReverseFunctionRole.Arn
</code>```

I'm invoking the GetTimezone function like this:

sam local invoke --layer-cache-basedir layer-cache --force-image-build \"GetTimezoneFunction\" --event events/event-timezone.json -d 5858

Nothing ever gets copied into the layer-cache directory, and I'm sure that's part of the problem, but I can't figure out how I'd fix that.

I've searched for answers to this problem, but so far I've only found unanswered questions, or answers that don't match my particular situation.

Most of the somewhat-related questions involve AWS::Serverless::LayerVersion, not AWS::Lambda::LayerVersion. I've tried using Serverless instead, but that hasn't helped.

UPDATE:

If I change...

```<code>      Layers:
        - !Ref SampleCommonLayer
</code>```

...to...

```<code>      Layers:
        - arn:aws:lambda:us-east-2:xxxxxxxxxxxx:layer:SampleCommonLayer:y
</code>```

...using an already-deployed layer (where xxxxxxxxxxxx and y are a specific ID and version) then sam local invoke works. But I don't want to use something I have to deploy first, I want to use the latest local not-yet-deployed code.

答:
This is known issue: https://github.com/awslabs/aws-sam-cli/issues/947

Currently the "workaround" is to use the directory of the layer instead of a zip file.

Body:
I'm working on a sample AWS project that creates two lambda functions. These functions share common code from node_modules which has been placed in a separate layer (specifically AWS::Lambda::LayerVersion, not AWS::Serverless::LayerVersion). I can deploy this code and it works correctly when I test the deployed version.

However, when I try to test the code locally using sam invoke local, the common code is not found. I get this error (I'm trying to use the npm package "axios"):

{"errorType":"Runtime.ImportModuleError","errorMessage":"Error: Cannot find module 'axios'\nRequire stack:\n- /var/task/get-timezone.js\n- /var/runtime/UserFunction.js\n- /var/runtime/index.js"}

This is my template.yaml:

AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Description: AWS Sample

Globals:
  Function:
    Timeout: 30

Resources:
  SampleCommonLayer:
    Type: AWS::Lambda::LayerVersion
    Properties:
      CompatibleRuntimes:
        - nodejs12.x
      Content: nodejs.zip
      Description: Sample Common LayerVersion
      LayerName: SampleCommonLayer

  GetTimezoneFunction:
    Type: AWS::Serverless::Function
    Properties:
      CodeUri: dist/get-timezone
      Handler: get-timezone.getTimezone
      Runtime: nodejs12.x
      Layers:
        - !Ref SampleCommonLayer
      Events:
        GetTimezone:
          Type: Api
          Properties:
            Path: /get-timezone
            Method: get

  ReverseFunction:
    Type: AWS::Serverless::Function
    Properties:
      CodeUri: dist/reverse
      Handler: reverse.reverse
      Runtime: nodejs12.x
      Layers:
        - !Ref SampleCommonLayer
      Events:
        Reverse:
          Type: Api
          Properties:
            Path: /reverse
            Method: get

Outputs:
  GetTimezoneApi:
    Description: "API Gateway endpoint URL for Prod stage for getTimezone function"
    Value: !Sub "https://${ServerlessRestApi}.execute-api.${AWS::Region}.amazonaws.com/Prod/get-timezone/"
  GetTimezoneFunction:
    Description: "getTimezone Lambda Function ARN"
    Value: !GetAtt GetTimezoneFunction.Arn
  GetTimezoneFunctionIamRole:
    Description: "Implicit IAM Role created for getTimezone function"
    Value: !GetAtt GetTimezoneFunctionRole.Arn

  ReverseApi:
    Description: "API Gateway endpoint URL for Prod stage for reverse function"
    Value: !Sub "https://${ServerlessRestApi}.execute-api.${AWS::Region}.amazonaws.com/Prod/reverse/"
  ReverseFunction:
    Description: "reverse Lambda Function ARN"
    Value: !GetAtt ReverseFunction.Arn
  ReverseFunctionIamRole:
    Description: "Implicit IAM Role created for reverse function"
    Value: !GetAtt ReverseFunctionRole.Arn

I'm invoking the GetTimezone function like this:

sam local invoke --layer-cache-basedir layer-cache --force-image-build \"GetTimezoneFunction\" --event events/event-timezone.json -d 5858

Nothing ever gets copied into the layer-cache directory, and I'm sure that's part of the problem, but I can't figure out how I'd fix that.

I've searched for answers to this problem, but so far I've only found unanswered questions, or answers that don't match my particular situation.

Most of the somewhat-related questions involve AWS::Serverless::LayerVersion, not AWS::Lambda::LayerVersion. I've tried using Serverless instead, but that hasn't helped.

UPDATE:

If I change...

      Layers:
        - !Ref SampleCommonLayer

...to...

      Layers:
        - arn:aws:lambda:us-east-2:xxxxxxxxxxxx:layer:SampleCommonLayer:y

...using an already-deployed layer (where xxxxxxxxxxxx and y are a specific ID and version) then sam local invoke works. But I don't want to use something I have to deploy first, I want to use the latest local not-yet-deployed code.


来源: stackexchange

问:
Express.js doesn't register some of the endpoints in other env
This is the code of my index.ts. I build it with TS "build": "tsc -p ./tsconfig.json && cp -R ./src/adminUI ./dist"

```<code>const db = mongoose.connection;
const app = express();

// TODO: whitelist
app.use(cors());
app.use(auth);
app.use('/static', express.static(path.join(__dirname, 'adminUI')));
app.use(bodyParser.urlencoded());
app.use(bodyParser.json());

app.use((req, _, next) => {
    console.log(req.path);
    console.log('Time: ', Date.now());
    next();
});

app.use('/api', endpoints);
app.use('/que', UI);
app.use('/admin', adminUI);

// START APP AFTER DB IS CONNECTED
db.once('open', () => {
    app.listen(process.env.port || 3010, () => console.log(`Listening on port ${process.env.port || 3010}!`));
    routesList.terminal(app);

    new Queue().start(+process.env.cronTime || null);
});

db.on('error', err => dbDebugger('connection error:', err));

// CONNECT TO THE DB
mongoose.connect(`mongodb://${process.env.mongoAuth || ''}${process.env.mongoHost}/admin`);
</code>```

When I run it locally I have all of the endpoints

```<code>      List All Routes        |
|------------------------------|
| Method |         URI         |
|--------|---------------------|
| GET    | api/items           |
| GET    | api/bank            |
| GET    | api/bank/:id        |
| POST   | api/bank            |
| POST   | api/bank/update     |
| POST   | api/bank/remove     |
| POST   | api/parser          |
| GET    | api/parser          |
| GET    | api/parser/bank/:id |
| GET    | api/parser/:id      |
| POST   | api/parser/update   |
| POST   | api/parser/remove   |
| POST   | api/test            |
| GET    | admin               |
| GET    | admin/updatebank    |
| GET    | admin/updateparser
</code>```

When I run it on prod server with the same deps and node js, I get these endpoints

```<code>.-----------------------------.
0|index    | |       List All Routes       |
0|index    | |-----------------------------|
0|index    | | Method |        URI         |
0|index    | |--------|--------------------|
0|index    | | GET    | api                |
0|index    | | GET    | admin              |
0|index    | | GET    | admin/updatebank   |
0|index    | | GET    | admin/updateparser |
0|index    | '-----------------------------'
</code>```

And funny but I don't' have api/ endpoint, it somehome redirects to /api/items

答: Update - It looks like a problem was in some older files in the dist folder. I removed the folder and build the project again and it works. I don't know why and what was causing this, but let's make a rule to remove dist before compile every time :)</p>

ContentLicense: CC BY-SA 4.0

Body:
This is the code of my index.ts. I build it with TS "build": "tsc -p ./tsconfig.json && cp -R ./src/adminUI ./dist"

const db = mongoose.connection;
const app = express();

// TODO: whitelist
app.use(cors());
app.use(auth);
app.use('/static', express.static(path.join(__dirname, 'adminUI')));
app.use(bodyParser.urlencoded());
app.use(bodyParser.json());

app.use((req, _, next) => {
    console.log(req.path);
    console.log('Time: ', Date.now());
    next();
});

app.use('/api', endpoints);
app.use('/que', UI);
app.use('/admin', adminUI);

// START APP AFTER DB IS CONNECTED
db.once('open', () => {
    app.listen(process.env.port || 3010, () => console.log(`Listening on port ${process.env.port || 3010}!`));
    routesList.terminal(app);

    new Queue().start(+process.env.cronTime || null);
});

db.on('error', err => dbDebugger('connection error:', err));

// CONNECT TO THE DB
mongoose.connect(`mongodb://${process.env.mongoAuth || ''}${process.env.mongoHost}/admin`);

When I run it locally I have all of the endpoints

      List All Routes        |
|------------------------------|
| Method |         URI         |
|--------|---------------------|
| GET    | api/items           |
| GET    | api/bank            |
| GET    | api/bank/:id        |
| POST   | api/bank            |
| POST   | api/bank/update     |
| POST   | api/bank/remove     |
| POST   | api/parser          |
| GET    | api/parser          |
| GET    | api/parser/bank/:id |
| GET    | api/parser/:id      |
| POST   | api/parser/update   |
| POST   | api/parser/remove   |
| POST   | api/test            |
| GET    | admin               |
| GET    | admin/updatebank    |
| GET    | admin/updateparser

When I run it on prod server with the same deps and node js, I get these endpoints

.-----------------------------.
0|index    | |       List All Routes       |
0|index    | |-----------------------------|
0|index    | | Method |        URI         |
0|index    | |--------|--------------------|
0|index    | | GET    | api                |
0|index    | | GET    | admin              |
0|index    | | GET    | admin/updatebank   |
0|index    | | GET    | admin/updateparser |
0|index    | '-----------------------------'

And funny but I don't' have api/ endpoint, it somehome redirects to /api/items


问:
"Dark mode" on Laravel 6 exception page

How to activate "Dark mode" in Laravel 6 Ignition (exception page)?

答:
Publish the config files if not already exists.

```<code>php artisan vendor:publish --provider="Facade\Ignition\IgnitionServiceProvider" --tag="ignition-config"
</code>```

Then, in the config/ignition.php set 'theme' => env('IGNITION_THEME', 'dark'),

Title: "Dark mode" on Laravel 6 exception page

Body:
Publish the config files if not already exists.

php artisan vendor:publish --provider="Facade\Ignition\IgnitionServiceProvider" --tag="ignition-config"

Then, in the config/ignition.php set 'theme' => env('IGNITION_THEME', 'dark'),


问:
Passing React button text value around
Say I have this code:

```<code><button id="gnrl"  onClick={() => this.selectChannel()}>General</button>
</code>```

How can I pass the text General around as a parameter? I.e. grep all the text between the 2 button tags?

I have a function that does this:

```<code>  selectChannel = (channelValue) => {
    var x = document.getElementById("general").value;
    this.setState({ channelValue: x })
  }
</code>```

But I don't want to get the value as that has to be a hardcoded property. I would like to be able to change General to anything else e.g. Random and that would be the value passed around. any ideas?

答:
You can get the button text via props to component.

<Button className="btn btn-primary" onClick={this.onClick} >Buttonone</Button>

<button className={props.className} onClick={props.onClick}> {props.children} </button>

Like this you can get Button InnerHtml value to component

ContentLicense: CC BY-SA 3.0

Title: Passing React button text value around

Body:
Say I have this code:

<button id="gnrl"  onClick={() => this.selectChannel()}>General</button>

How can I pass the text General around as a parameter? I.e. grep all the text between the 2 button tags?

I have a function that does this:

  selectChannel = (channelValue) => {
    var x = document.getElementById("general").value;
    this.setState({ channelValue: x })
  }

But I don't want to get the value as that has to be a hardcoded property. I would like to be able to change General to anything else e.g. Random and that would be the value passed around. any ideas?


问:
Conda environment python2.7 tensorflow import error
I have to use python2.7 only. I followed this answer and installed tensorflow using

```<code>conda install -c conda-forge tensorflow
</code>```

After that when I import tensorflow, I get the following error stack trace

```<code>---------------------------------------------------------------------------
ImportError                               Traceback (most recent call last)
<ipython-input-1-67f8173eef8c> in <module>()
      1 # Workspace problem with several narrow gaps
      2
----> 3 import tensorflow as tf
      4 import numpy as np
      5 import matplotlib.pyplot as plt

/home/ultrainstinct/.local/lib/python2.7/site-packages/tensorflow/__init__.py in <module>()
     22
     23 # pylint: disable=g-bad-import-order
---> 24 from tensorflow.python import pywrap_tensorflow  # pylint: disable=unused-import
     25
     26 try:

/home/ultrainstinct/.local/lib/python2.7/site-packages/tensorflow/python/__init__.py in <module>()
     47 import numpy as np
     48
---> 49 from tensorflow.python import pywrap_tensorflow
     50
     51 from tensorflow.python.tools import component_api_helper

/home/ultrainstinct/.local/lib/python2.7/site-packages/tensorflow/python/pywrap_tensorflow.py in <module>()
     72 for some common reasons and solutions.  Include the entire stack trace
     73 above this error message when asking for help.""" % traceback.format_exc()
---> 74   raise ImportError(msg)
     75
     76 # pylint: enable=wildcard-import,g-import-not-at-top,unused-import,line-too-long

ImportError: Traceback (most recent call last):
  File "/home/ultrainstinct/.local/lib/python2.7/site-packages/tensorflow/python/pywrap_tensorflow.py", line 58, in <module>
    from tensorflow.python.pywrap_tensorflow_internal import *
  File "/home/ultrainstinct/.local/lib/python2.7/site-packages/tensorflow/python/pywrap_tensorflow_internal.py", line 28, in <module>
    _pywrap_tensorflow_internal = swig_import_helper()
  File "/home/ultrainstinct/.local/lib/python2.7/site-packages/tensorflow/python/pywrap_tensorflow_internal.py", line 24, in swig_import_helper
    _mod = imp.load_module('_pywrap_tensorflow_internal', fp, pathname, description)
ImportError: /home/ultrainstinct/.local/lib/python2.7/site-packages/tensorflow/python/_pywrap_tensorflow_internal.so: invalid ELF header

Failed to load the native TensorFlow runtime.

See https://www.tensorflow.org/install/errors

for some common reasons and solutions.  Include the entire stack trace
above this error message when asking for help.
</code>```

I went to the site mentioned above, but did not find anything related to this error.

How do resolve this?

答: Try it ,may be helpful:  conda install -c https://conda.anaconda.org/jjhelmus tensorflow

Body:
I have to use python2.7 only. I followed this answer and installed tensorflow using

conda install -c conda-forge tensorflow

After that when I import tensorflow, I get the following error stack trace

---------------------------------------------------------------------------
ImportError                               Traceback (most recent call last)
<ipython-input-1-67f8173eef8c> in <module>()
      1 # Workspace problem with several narrow gaps
      2
----> 3 import tensorflow as tf
      4 import numpy as np
      5 import matplotlib.pyplot as plt

/home/ultrainstinct/.local/lib/python2.7/site-packages/tensorflow/__init__.py in <module>()
     22
     23 # pylint: disable=g-bad-import-order
---> 24 from tensorflow.python import pywrap_tensorflow  # pylint: disable=unused-import
     25
     26 try:

/home/ultrainstinct/.local/lib/python2.7/site-packages/tensorflow/python/__init__.py in <module>()
     47 import numpy as np
     48
---> 49 from tensorflow.python import pywrap_tensorflow
     50
     51 from tensorflow.python.tools import component_api_helper

/home/ultrainstinct/.local/lib/python2.7/site-packages/tensorflow/python/pywrap_tensorflow.py in <module>()
     72 for some common reasons and solutions.  Include the entire stack trace
     73 above this error message when asking for help.""" % traceback.format_exc()
---> 74   raise ImportError(msg)
     75
     76 # pylint: enable=wildcard-import,g-import-not-at-top,unused-import,line-too-long

ImportError: Traceback (most recent call last):
  File "/home/ultrainstinct/.local/lib/python2.7/site-packages/tensorflow/python/pywrap_tensorflow.py", line 58, in <module>
    from tensorflow.python.pywrap_tensorflow_internal import *
  File "/home/ultrainstinct/.local/lib/python2.7/site-packages/tensorflow/python/pywrap_tensorflow_internal.py", line 28, in <module>
    _pywrap_tensorflow_internal = swig_import_helper()
  File "/home/ultrainstinct/.local/lib/python2.7/site-packages/tensorflow/python/pywrap_tensorflow_internal.py", line 24, in swig_import_helper
    _mod = imp.load_module('_pywrap_tensorflow_internal', fp, pathname, description)
ImportError: /home/ultrainstinct/.local/lib/python2.7/site-packages/tensorflow/python/_pywrap_tensorflow_internal.so: invalid ELF header

Failed to load the native TensorFlow runtime.

See https://www.tensorflow.org/install/errors

for some common reasons and solutions.  Include the entire stack trace
above this error message when asking for help.

I went to the site mentioned above, but did not find anything related to this error.

How do resolve this?


问:
Open Link in VSCode Will Create a New Web Browser Under Same Icon as VSCode
I am using VScode version 1.45 with Firefox version 76.0.1 as a default browser (with Ubuntu 18.04.4 LTS). Whenever I tried to open a link in the VSCode, it will open the Firefox browser under same icon as VSCode, and I cannot merge these tabs into existing Firefox web browser.

Same thing also happens when I try to run a program using live server extension. But when I use npm to start the development server, it will create a new window or tab under the Firefox icon.

How could I fix this so whenever I open a browser from VSCode, it will create a new browser or tab under the appropriate (Firefox) icon? Thank you.

答: Try making firefox your default browser thorugh firefox and also do check that firefox is your default browser from vscode


问:
Device compabilities issue in iOS
We uploaded an app where in the first version we added to device capabilities “telephony” to restrict only iPhone devices in the info plist. In the second version we forgot to add “telephony” and we submitted to the App store. Third version we are planning to upload with device capabilities as “telephony” but while submitting to the App Store it shows the warning:

This bundle is invalid. The key UIRequiredDeviceCapabilities in the
  Info.plist may not contain values that would prevent this application
  from running on devices that were supported by previous versions.

How can we resolve this issue, if we require the device capability “telephony” for  application lifetime, but due to my mistake on the second version we forgot to add the required device capabilities? What is the solution for it?

Thanks in advance.

答: You are allowed to relax UIRequiredDeviceCapabilities restrictions, but not tighten them. Once restrictions are relaxed they cannot be tightened back again.</p>

Title: Device compabilities issue in iOS


问:
React.createElement: type is invalid expected a string
I am newbie with react native, I trying to make restaurant app, but getting the following error in the browser console:

React.createElement: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: %s.%s%s, undefined,  You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.

so what I am missing? it telling me that the  error is in the render method but i can't figure it out

app.js :

```<code>import React from 'react';
import { StyleSheet, Text, FlatList, ActivityIndicator, View, Image } from 'react-native';
import { List, ListItem, SearchBar, Avatar } from "react-native-elements";
import { StackNavigator,createAppContainer } from 'react-navigation';
import { createStackNavigator} from 'react-navigation-stack';

import { constants } from 'expo';
import HomeScreen from './src/home';
import DetailScreen from './src/detail';

const AppNavigator = createStackNavigator({
    Home: { screen: HomeScreen,
            navigationOptions: {
                title: 'Home',
                headerBackTitle: 'Back',
            },
          },
    Detail: { screen: DetailScreen,
            navigationOptions: {
              title: 'Detail',
          },
        }
});

export default createAppContainer(AppNavigator);

</code>```

home.js :

```<code>import React from 'react';
import { StyleSheet, Text, FlatList, ActivityIndicator, View, Image } from 'react-native';
import { List, ListItem, SearchBar, Avatar } from "react-native-elements";
import { StackNavigator } from 'react-navigation';

export default class HomeScreen extends React.Component {
 constructor(props) {
    super(props);

    this.state  = {
      loading: false,
      data: [],
      error: null,
      refreshing: false,
      base_url: "http://localhost:8000/api"
    }
  }

  componentDidMount() {
    this.fetchDataFromApi();

  }

  fetchDataFromApi = ()  => {
    const url = "http://localhost:8000/api.json";

    this.setState({ loading: true });

    fetch(url)
      .then(res => res.json())
      .then(res => {

        this.setState({
          data: res,
          error: null,
          loading: false,
          refreshing: false
        });
      })
      .catch(error => {
        this.setState({ error, loading : false });
      })
  };

  handleRefresh = () => {
    this.setState(
      {
        refreshing: true
      },
      () => {
        this.fetchDataFromApi();
      }
    );
  };

  renderSeparator = () => {
    return (
      <View
        style={{
          height: 1,
          width: "86%",
          backgroundColor: "#CED0CE",
          marginLeft: "14%",
          marginTop: "3%"
        }}
      />
    );
  };

  renderHeader = () => {
    return <SearchBar placeholder="Type Here..." lightTheme round />;
  };

  render() {
    return (
      <List containerStyle={{ borderTopWidth: 0, borderBottomWidth: 0 }}>
        <FlatList
          data={this.state.data}
          renderItem={({ item }) => (
            <ListItem
              onPress={() => this.props.navigation.navigate('Detail',
              {name: `${item.name}`, menu: `${item.menu}`,
              img: `${this.state.base_url}${item.photo}`,
              address: `${item.address}`})}
              avatar={<Avatar
                      source={{uri: `${this.state.base_url}${item.photo}`}}
                      onPress={() => console.log("Works!")}
                      containerStyle={{marginBottom: 2}}
                      avatarStyle={{resizeMode: "cover"}}
                      width={140}
                      height={130}
                />}
              title={`${item.name}`}
              titleStyle={{ fontSize: 16}}
              titleContainerStyle = {{ marginLeft: 120 }}
              subtitle={<View style={styles.subtitleView}>
            <Text style={styles.menuText}>{item.menu}</Text>
            <Text style={styles.locText}>{item.address}</Text>
            </View>}
              containerStyle={{ borderBottomWidth: 0, marginBottom: 20 }}
            />
          )}
          keyExtractor={item => item.id}
          ItemSeparatorComponent={this.renderSeparator}
          ListHeaderComponent={this.renderHeader}
          onRefresh={this.handleRefresh}
          refreshing={this.state.refreshing}

        />
      </List>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
  },
   subtitleView: {
    flexDirection: 'column',
    paddingLeft: 10,
    paddingTop: 5,
    marginLeft: 110
  },
  menuText: {
    paddingLeft: 10,
    color: 'grey'
  },
  locText: {
    paddingLeft: 10,
    color: 'grey',
    marginTop: 6,
    fontSize: 12
  },
  titleText: {
    fontWeight: 'bold'
  },
  restaurantImage: {
    width: 600,
    height: 800
  }
});

</code>```

package.json :

```<code>{
  "main": "node_modules/expo/AppEntry.js",
  "scripts": {
    "start": "expo start",
    "android": "expo start --android",
    "ios": "expo start --ios",
    "web": "expo start --web",
    "eject": "expo eject"
  },
  "dependencies": {
    "expo": "~37.0.3",
    "react": "~16.9.0",
    "react-dom": "~16.9.0",
    "react-native": "https://github.com/expo/react-native/archive/sdk-37.0.1.tar.gz",
    "react-native-elements": "^2.0.1",
    "react-native-gesture-handler": "~1.6.0",
    "react-native-web": "~0.11.7",
    "react-navigation": "^4.3.9",
    "react-navigation-stack": "^2.5.1",
    "react-native-reanimated": "~1.7.0",
    "react-native-screens": "~2.2.0",
    "react-native-safe-area-context": "0.7.3",
    "@react-native-community/masked-view": "0.1.6"
  },
  "devDependencies": {
    "babel-preset-expo": "~8.1.0",
    "@babel/core": "^7.8.6"
  },
  "private": true
}

</code>```

答:
Check your imports you probably have imported the wrong component which doesn't exist.

I suspect it's List which you imported from react-native-elements, I think there is no component named List.

Body:
I am newbie with react native, I trying to make restaurant app, but getting the following error in the browser console:

React.createElement: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: %s.%s%s, undefined,  You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.

so what I am missing? it telling me that the  error is in the render method but i can't figure it out

app.js :

import React from 'react';
import { StyleSheet, Text, FlatList, ActivityIndicator, View, Image } from 'react-native';
import { List, ListItem, SearchBar, Avatar } from "react-native-elements";
import { StackNavigator,createAppContainer } from 'react-navigation';
import { createStackNavigator} from 'react-navigation-stack';

import { constants } from 'expo';
import HomeScreen from './src/home';
import DetailScreen from './src/detail';

const AppNavigator = createStackNavigator({
    Home: { screen: HomeScreen,
            navigationOptions: {
                title: 'Home',
                headerBackTitle: 'Back',
            },
          },
    Detail: { screen: DetailScreen,
            navigationOptions: {
              title: 'Detail',
          },
        }
});

export default createAppContainer(AppNavigator);

home.js :

import React from 'react';
import { StyleSheet, Text, FlatList, ActivityIndicator, View, Image } from 'react-native';
import { List, ListItem, SearchBar, Avatar } from "react-native-elements";
import { StackNavigator } from 'react-navigation';

export default class HomeScreen extends React.Component {
 constructor(props) {
    super(props);

    this.state  = {
      loading: false,
      data: [],
      error: null,
      refreshing: false,
      base_url: "http://localhost:8000/api"
    }
  }

  componentDidMount() {
    this.fetchDataFromApi();

  }

  fetchDataFromApi = ()  => {
    const url = "http://localhost:8000/api.json";

    this.setState({ loading: true });

    fetch(url)
      .then(res => res.json())
      .then(res => {

        this.setState({
          data: res,
          error: null,
          loading: false,
          refreshing: false
        });
      })
      .catch(error => {
        this.setState({ error, loading : false });
      })
  };

  handleRefresh = () => {
    this.setState(
      {
        refreshing: true
      },
      () => {
        this.fetchDataFromApi();
      }
    );
  };

  renderSeparator = () => {
    return (
      <View
        style={{
          height: 1,
          width: "86%",
          backgroundColor: "#CED0CE",
          marginLeft: "14%",
          marginTop: "3%"
        }}
      />
    );
  };

  renderHeader = () => {
    return <SearchBar placeholder="Type Here..." lightTheme round />;
  };

  render() {
    return (
      <List containerStyle={{ borderTopWidth: 0, borderBottomWidth: 0 }}>
        <FlatList
          data={this.state.data}
          renderItem={({ item }) => (
            <ListItem
              onPress={() => this.props.navigation.navigate('Detail',
              {name: `${item.name}`, menu: `${item.menu}`,
              img: `${this.state.base_url}${item.photo}`,
              address: `${item.address}`})}
              avatar={<Avatar
                      source={{uri: `${this.state.base_url}${item.photo}`}}
                      onPress={() => console.log("Works!")}
                      containerStyle={{marginBottom: 2}}
                      avatarStyle={{resizeMode: "cover"}}
                      width={140}
                      height={130}
                />}
              title={`${item.name}`}
              titleStyle={{ fontSize: 16}}
              titleContainerStyle = {{ marginLeft: 120 }}
              subtitle={<View style={styles.subtitleView}>
            <Text style={styles.menuText}>{item.menu}</Text>
            <Text style={styles.locText}>{item.address}</Text>
            </View>}
              containerStyle={{ borderBottomWidth: 0, marginBottom: 20 }}
            />
          )}
          keyExtractor={item => item.id}
          ItemSeparatorComponent={this.renderSeparator}
          ListHeaderComponent={this.renderHeader}
          onRefresh={this.handleRefresh}
          refreshing={this.state.refreshing}

        />
      </List>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
  },
   subtitleView: {
    flexDirection: 'column',
    paddingLeft: 10,
    paddingTop: 5,
    marginLeft: 110
  },
  menuText: {
    paddingLeft: 10,
    color: 'grey'
  },
  locText: {
    paddingLeft: 10,
    color: 'grey',
    marginTop: 6,
    fontSize: 12
  },
  titleText: {
    fontWeight: 'bold'
  },
  restaurantImage: {
    width: 600,
    height: 800
  }
});

package.json :

{
  "main": "node_modules/expo/AppEntry.js",
  "scripts": {
    "start": "expo start",
    "android": "expo start --android",
    "ios": "expo start --ios",
    "web": "expo start --web",
    "eject": "expo eject"
  },
  "dependencies": {
    "expo": "~37.0.3",
    "react": "~16.9.0",
    "react-dom": "~16.9.0",
    "react-native": "https://github.com/expo/react-native/archive/sdk-37.0.1.tar.gz",
    "react-native-elements": "^2.0.1",
    "react-native-gesture-handler": "~1.6.0",
    "react-native-web": "~0.11.7",
    "react-navigation": "^4.3.9",
    "react-navigation-stack": "^2.5.1",
    "react-native-reanimated": "~1.7.0",
    "react-native-screens": "~2.2.0",
    "react-native-safe-area-context": "0.7.3",
    "@react-native-community/masked-view": "0.1.6"
  },
  "devDependencies": {
    "babel-preset-expo": "~8.1.0",
    "@babel/core": "^7.8.6"
  },
  "private": true
}


问:
Is there a contain's method?
I know there's a method contain(), it looks like this:

```<code>Dim arr() as string = {"apple","banana","orange"}
For each fruit in arr
 If fruit.contains("app") Then
  Return True
 End If
Next
</code>```

It will return true because "apple" contains letter "a". This is not what I want. I want it to return true only when "apple" contains the whole word "app". Is there any method or function to do this?

答:
"apple" does in fact contain the whole word "app", so Contains() is still probably your best bet.

From MSDN:

String.Contains Method   Returns a
  value indicating whether the specified
  String object occurs within this
  string.

Here is the link to it with samples.

http://msdn.microsoft.com/en-us/library/dy85x1sa.aspx

Title: Is there a contain's method?

Body:
I know there's a method contain(), it looks like this:

Dim arr() as string = {"apple","banana","orange"}
For each fruit in arr
 If fruit.contains("app") Then
  Return True
 End If
Next

It will return true because "apple" contains letter "a". This is not what I want. I want it to return true only when "apple" contains the whole word "app". Is there any method or function to do this?


问:
How to get profiles containing at least all tags (has_and_belongs_to_many relation)
help me please to understand, what is going on here? I have profiles with has_and_belongs_to_many relation with tags. And I want to be able to filter profiles, that contains at least all tags, not any of them. How can I do it?

Im trying to do it this way:

```<code>  Profile.includes(:tags).where(tags: {id: array }).having('COUNT(tags) >= ?', array.count).group('profiles.id, tags.id')
</code>```

But here I have really wierd results:

```<code>array = ['212', '213', '214']
=> ["212", "213", "214"]

profile.tag_ids
=> [212, 214, 213]

array = ['212', '214']
=> ["212", "214"]
irb(main):051:0> Profile.includes(:tags).where(tags: {id: array }).having('COUNT(tags) >= ?', array.count).group('profiles.id, tags.id')
  SQL (0.7ms)  SELECT "profiles"."id" AS t0_r0, "profiles"."user_id" AS t0_r1, "profiles"."description" AS t0_r2, "profiles"."created_at" AS t0_r3, "profiles"."updated_at" AS t0_r4, "profiles"."first_name" AS t0_r5, "profiles"."last_name" AS t0_r6, "profiles"."date_of_birth" AS t0_r7, "profiles"."gender" AS t0_r8, "profiles"."short_time_price" AS t0_r9, "profiles"."long_time_price" AS t0_r10, "profiles"."city" AS t0_r11, "profiles"."line" AS t0_r12, "profiles"."instagram" AS t0_r13, "profiles"."facebook" AS t0_r14, "profiles"."whats_app" AS t0_r15, "profiles"."we_chat" AS t0_r16, "profiles"."other_contacts" AS t0_r17, "profiles"."geo_unit_id" AS t0_r18, "tags"."id" AS t1_r0, "tags"."body_en" AS t1_r1, "tags"."body_ru" AS t1_r2, "tags"."tags_group_id" AS t1_r3 FROM "profiles" LEFT OUTER JOIN "profiles_tags" ON "profiles_tags"."profile_id" = "profiles"."id" LEFT OUTER JOIN "tags" ON "tags"."id" = "profiles_tags"."tag_id" WHERE "tags"."id" IN ($1, $2) GROUP BY profiles.id, tags.id HAVING (COUNT(tags) >= 2) LIMIT $3  [["id", 212], ["id", 214], ["LIMIT", 11]]
=> #<ActiveRecord::Relation []>

array = ['212', '213', '214']
=> ["212", "213", "214"]
irb(main):049:0> Profile.includes(:tags).where(tags: {id: array }).having('COUNT(tags) >= ?', array.count).group('profiles.id, tags.id')
  SQL (0.8ms)  SELECT "profiles"."id" AS t0_r0, "profiles"."user_id" AS t0_r1, "profiles"."description" AS t0_r2, "profiles"."created_at" AS t0_r3, "profiles"."updated_at" AS t0_r4, "profiles"."first_name" AS t0_r5, "profiles"."last_name" AS t0_r6, "profiles"."date_of_birth" AS t0_r7, "profiles"."gender" AS t0_r8, "profiles"."short_time_price" AS t0_r9, "profiles"."long_time_price" AS t0_r10, "profiles"."city" AS t0_r11, "profiles"."line" AS t0_r12, "profiles"."instagram" AS t0_r13, "profiles"."facebook" AS t0_r14, "profiles"."whats_app" AS t0_r15, "profiles"."we_chat" AS t0_r16, "profiles"."other_contacts" AS t0_r17, "profiles"."geo_unit_id" AS t0_r18, "tags"."id" AS t1_r0, "tags"."body_en" AS t1_r1, "tags"."body_ru" AS t1_r2, "tags"."tags_group_id" AS t1_r3 FROM "profiles" LEFT OUTER JOIN "profiles_tags" ON "profiles_tags"."profile_id" = "profiles"."id" LEFT OUTER JOIN "tags" ON "tags"."id" = "profiles_tags"."tag_id" WHERE "tags"."id" IN ($1, $2, $3) GROUP BY profiles.id, tags.id HAVING (COUNT(tags) >= 3) LIMIT $4  [["id", 212], ["id", 213], ["id", 214], ["LIMIT", 11]]
=> #<ActiveRecord::Relation [#<Profile id: 84, ...>]>

array = ['212', '213']
=> ["212", "213"]
irb(main):047:0> Profile.includes(:tags).where(tags: {id: array }).having('COUNT(tags) >= ?', array.count).group('profiles.id, tags.id')
=> #<ActiveRecord::Relation [#<Profile id: 84, ...>]>

array = ['214', '213']
=> ["214", "213"]
irb(main):039:0> Profile.includes(:tags).where(tags: {id: array }).having('COUNT(tags) >= ?', array.count).group('profiles.id, tags.id')
=> #<ActiveRecord::Relation [#<Profile id: 84, ...>]>
</code>```

How is it possible? Maybe there is another way to got profiles, containing all provided tags?

db schema with middle table here:

```<code>  create_table "profiles_tags", force: :cascade do |t|
    t.bigint "profile_id"
    t.bigint "tag_id"
    t.index ["profile_id"], name: "index_profiles_tags_on_profile_id"
    t.index ["tag_id"], name: "index_profiles_tags_on_tag_id"
  end
</code>```

migration with relation is here:

```<code># frozen_string_literal: true

class CreateProfilesTags < ActiveRecord::Migration[6.0]
  def change
    create_table :profiles_tags do |t|
      t.belongs_to :profile
      t.belongs_to :tag
    end
  end
end
</code>```

答:
You are almost there:

```<code>Profile.joins(:tags)                  # <= use `joins` instead of `inclused`
       .where(tags: {id: array })
       .having('COUNT(tags) >= ?', array.count)
       .group('profiles.id')          # <= Do not use anything tags related here
</code>```

It is important to note the difference between includes and joins. Whereas joins always makes a database join included only makes a join under certain conditions, sometimes it simply makes two queries. Use joins when Rails must make a database join to make the query work and use includes when you want to fix a n+1 issue (see Rails :include vs. :joins).

When you need both – a database join and a fix of the n+1 issue – then run the join query as a subquery:

```<code># a new scope in the mode
scope :when_tags, ->(tags) {
  joins(:tags)
    .where(tags: {id: tags })
    .having('COUNT(tags) >= ?', tags.count)
    .group('profiles.id')
}

# the actual nested query with includes:
Profile.where(id: Profile.with_tags(array)).include(:tags)
</code>```

Body:
help me please to understand, what is going on here? I have profiles with has_and_belongs_to_many relation with tags. And I want to be able to filter profiles, that contains at least all tags, not any of them. How can I do it?

Im trying to do it this way:

  Profile.includes(:tags).where(tags: {id: array }).having('COUNT(tags) >= ?', array.count).group('profiles.id, tags.id')

But here I have really wierd results:

array = ['212', '213', '214']
=> ["212", "213", "214"]

profile.tag_ids
=> [212, 214, 213]

array = ['212', '214']
=> ["212", "214"]
irb(main):051:0> Profile.includes(:tags).where(tags: {id: array }).having('COUNT(tags) >= ?', array.count).group('profiles.id, tags.id')
  SQL (0.7ms)  SELECT "profiles"."id" AS t0_r0, "profiles"."user_id" AS t0_r1, "profiles"."description" AS t0_r2, "profiles"."created_at" AS t0_r3, "profiles"."updated_at" AS t0_r4, "profiles"."first_name" AS t0_r5, "profiles"."last_name" AS t0_r6, "profiles"."date_of_birth" AS t0_r7, "profiles"."gender" AS t0_r8, "profiles"."short_time_price" AS t0_r9, "profiles"."long_time_price" AS t0_r10, "profiles"."city" AS t0_r11, "profiles"."line" AS t0_r12, "profiles"."instagram" AS t0_r13, "profiles"."facebook" AS t0_r14, "profiles"."whats_app" AS t0_r15, "profiles"."we_chat" AS t0_r16, "profiles"."other_contacts" AS t0_r17, "profiles"."geo_unit_id" AS t0_r18, "tags"."id" AS t1_r0, "tags"."body_en" AS t1_r1, "tags"."body_ru" AS t1_r2, "tags"."tags_group_id" AS t1_r3 FROM "profiles" LEFT OUTER JOIN "profiles_tags" ON "profiles_tags"."profile_id" = "profiles"."id" LEFT OUTER JOIN "tags" ON "tags"."id" = "profiles_tags"."tag_id" WHERE "tags"."id" IN ($1, $2) GROUP BY profiles.id, tags.id HAVING (COUNT(tags) >= 2) LIMIT $3  [["id", 212], ["id", 214], ["LIMIT", 11]]
=> #<ActiveRecord::Relation []>

array = ['212', '213', '214']
=> ["212", "213", "214"]
irb(main):049:0> Profile.includes(:tags).where(tags: {id: array }).having('COUNT(tags) >= ?', array.count).group('profiles.id, tags.id')
  SQL (0.8ms)  SELECT "profiles"."id" AS t0_r0, "profiles"."user_id" AS t0_r1, "profiles"."description" AS t0_r2, "profiles"."created_at" AS t0_r3, "profiles"."updated_at" AS t0_r4, "profiles"."first_name" AS t0_r5, "profiles"."last_name" AS t0_r6, "profiles"."date_of_birth" AS t0_r7, "profiles"."gender" AS t0_r8, "profiles"."short_time_price" AS t0_r9, "profiles"."long_time_price" AS t0_r10, "profiles"."city" AS t0_r11, "profiles"."line" AS t0_r12, "profiles"."instagram" AS t0_r13, "profiles"."facebook" AS t0_r14, "profiles"."whats_app" AS t0_r15, "profiles"."we_chat" AS t0_r16, "profiles"."other_contacts" AS t0_r17, "profiles"."geo_unit_id" AS t0_r18, "tags"."id" AS t1_r0, "tags"."body_en" AS t1_r1, "tags"."body_ru" AS t1_r2, "tags"."tags_group_id" AS t1_r3 FROM "profiles" LEFT OUTER JOIN "profiles_tags" ON "profiles_tags"."profile_id" = "profiles"."id" LEFT OUTER JOIN "tags" ON "tags"."id" = "profiles_tags"."tag_id" WHERE "tags"."id" IN ($1, $2, $3) GROUP BY profiles.id, tags.id HAVING (COUNT(tags) >= 3) LIMIT $4  [["id", 212], ["id", 213], ["id", 214], ["LIMIT", 11]]
=> #<ActiveRecord::Relation [#<Profile id: 84, ...>]>

array = ['212', '213']
=> ["212", "213"]
irb(main):047:0> Profile.includes(:tags).where(tags: {id: array }).having('COUNT(tags) >= ?', array.count).group('profiles.id, tags.id')
=> #<ActiveRecord::Relation [#<Profile id: 84, ...>]>

array = ['214', '213']
=> ["214", "213"]
irb(main):039:0> Profile.includes(:tags).where(tags: {id: array }).having('COUNT(tags) >= ?', array.count).group('profiles.id, tags.id')
=> #<ActiveRecord::Relation [#<Profile id: 84, ...>]>

How is it possible? Maybe there is another way to got profiles, containing all provided tags?

db schema with middle table here:

  create_table "profiles_tags", force: :cascade do |t|
    t.bigint "profile_id"
    t.bigint "tag_id"
    t.index ["profile_id"], name: "index_profiles_tags_on_profile_id"
    t.index ["tag_id"], name: "index_profiles_tags_on_tag_id"
  end

migration with relation is here:

# frozen_string_literal: true

class CreateProfilesTags < ActiveRecord::Migration[6.0]
  def change
    create_table :profiles_tags do |t|
      t.belongs_to :profile
      t.belongs_to :tag
    end
  end
end

Body:
You are almost there:

Profile.joins(:tags)                  # <= use `joins` instead of `inclused`
       .where(tags: {id: array })
       .having('COUNT(tags) >= ?', array.count)
       .group('profiles.id')          # <= Do not use anything tags related here

It is important to note the difference between includes and joins. Whereas joins always makes a database join included only makes a join under certain conditions, sometimes it simply makes two queries. Use joins when Rails must make a database join to make the query work and use includes when you want to fix a n+1 issue (see Rails :include vs. :joins).

When you need both – a database join and a fix of the n+1 issue – then run the join query as a subquery:

# a new scope in the mode
scope :when_tags, ->(tags) {
  joins(:tags)
    .where(tags: {id: tags })
    .having('COUNT(tags) >= ?', tags.count)
    .group('profiles.id')
}

# the actual nested query with includes:
Profile.where(id: Profile.with_tags(array)).include(:tags)


问:
AWS RDS MYSQL import db Access Denied
I cannot import a database in AWS RDS because of this commands in my sql file:

```<code>SET @@SESSION.SQL_LOG_BIN= 0;
SET @@GLOBAL.GTID_PURGED=/*!80000 '+'*/ '';
SET @@SESSION.SQL_LOG_BIN = @MYSQLDUMP_TEMP_LOG_BIN;
</code>```

Are they important ? whiteout them there is no error.

log_bin_trust_function_creators parameter is set to 1 in a custom parameter.

FYI: MySql 5.7 and 8, same error

```<code>ERROR 1227 (42000) at line 20: Access denied; you need (at least one of) the SUPER, SYSTEM_VARIABLES_ADMIN or SESSION_VARIABLES_ADMIN privilege(s) for this operation
</code>```

答:
```<code>SET @@SESSION.SQL_LOG_BIN=0;
</code>```

This is telling MySQL not to put these INSERT statements into the binary log. If you do not have binary logs enabled (not replicating), then it's not an issue to remove it. As far as I know, there is no way to enable this in RDS; I'm actually trying to figure out a way, which is how I found your question.

```<code>SET @@GLOBAL.GTID_PURGED=/*!80000 '+'*/ '';
</code>```

Did you execute a RESET MASTER on the database where the dump originated from? Check here for an explanation of this value: gtid_purged

```<code>SET @@SESSION.SQL_LOG_BIN = @MYSQLDUMP_TEMP_LOG_BIN;
</code>```

This is setting the @@SESSION.SQL_LOG_BIN variable back to the original setting; you should've seen another line like: SET @MYSQLDUMP_TEMP_LOG_BIN = @@SESSION.SQL_LOG_BIN;

If you're simply recovering this table into a new database that isn't writing to a binary log (for replication), it's safe to remove these lines. Hope this helps!

Title: AWS RDS MYSQL import db Access Denied

Body:
I cannot import a database in AWS RDS because of this commands in my sql file:

SET @@SESSION.SQL_LOG_BIN= 0;
SET @@GLOBAL.GTID_PURGED=/*!80000 '+'*/ '';
SET @@SESSION.SQL_LOG_BIN = @MYSQLDUMP_TEMP_LOG_BIN;

Are they important ? whiteout them there is no error.

log_bin_trust_function_creators parameter is set to 1 in a custom parameter.

FYI: MySql 5.7 and 8, same error

ERROR 1227 (42000) at line 20: Access denied; you need (at least one of) the SUPER, SYSTEM_VARIABLES_ADMIN or SESSION_VARIABLES_ADMIN privilege(s) for this operation

Body:
SET @@SESSION.SQL_LOG_BIN=0;

This is telling MySQL not to put these INSERT statements into the binary log. If you do not have binary logs enabled (not replicating), then it's not an issue to remove it. As far as I know, there is no way to enable this in RDS; I'm actually trying to figure out a way, which is how I found your question.

SET @@GLOBAL.GTID_PURGED=/*!80000 '+'*/ '';

Did you execute a RESET MASTER on the database where the dump originated from? Check here for an explanation of this value: gtid_purged

SET @@SESSION.SQL_LOG_BIN = @MYSQLDUMP_TEMP_LOG_BIN;

This is setting the @@SESSION.SQL_LOG_BIN variable back to the original setting; you should've seen another line like: SET @MYSQLDUMP_TEMP_LOG_BIN = @@SESSION.SQL_LOG_BIN;

If you're simply recovering this table into a new database that isn't writing to a binary log (for replication), it's safe to remove these lines. Hope this helps!


问:
How to Upload an Image to Django
I have spent over three days on this. It appears that something saved to the db, but when I try to access it in the template, I can only get the object of the db. I can not access it. I believe it was not saved successfully because I don't see a media folder where it would be saved. This is what I have so far.

# settings.py
STATIC_URL = '/static/'
STATICFILES_DIRS = (os.path.join(BASE_DIR, 'static'), )
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
```

<pre class="lang-py prettyprint-override"><code># forms.py
from .models import Pic
from django import forms
class ImageForm(forms.ModelForm):
    class Meta:
        model= Pic
        fields= ["picture"]
</code>```

# models.py
class Pic(models.Model):
    picture = models.ImageField(upload_to = 'media/', default = 'media/None/no-img.jpg', null=True, blank= True)
```

<pre class="lang-py prettyprint-override"><code># views.py
def upload(request):
    form = ImageForm
    context = {}
    userBio = Bio.objects.get(userData = User.objects.get(id = request.session['client']['id']))
    if request.method == 'POST':
        # .is_valid checks the models parameters via forms method
        form = ImageForm(request.POST,request.FILES)
        if form.is_valid():
            form.save()
            print("succesful uploaded image")
            return redirect("/dashboard")
        else:
            print("Not a valid input from form....")
            messages.error(request,"Not a valid input")
    return redirect("/dashboard")
</code>```

<form rule="form" class="border border--secondary" method="POST" action="/manageFile" enctype="multipart/form-data">
    {% csrf_token%}
    <input type="file" name = "update">
    <input type = "submit">
</form>
{% if pictures %}
    {% for pic in pictures%}

    {% endfor %}
{% endif%}
```

<p>In the template, it appears as Pic object(1).
In the terminal, it appears as</p>

<blockquote>
  <p>Query set Pic: Pic object (1)</p>
</blockquote>

<p>Here's what I render to the template.</p>

<pre class="lang-py prettyprint-override"><code>def dash(request):
    try:
        _id = request.session['client']['id']
    except:
        return redirect("/loginPg")

    userBio = Bio.objects.get(userData = User.objects.get(id = request.session['client']['id']))
    print("its right here")
    theUploads = Pic.objects.all()
    print("This image object -", theUploads)

    content = {
        "title" : userBio.title,
        "qA" : userBio.quoteA,
        "qB" : userBio.quoteB,
        "desc" : userBio.desc,
        "authorA" : userBio.authorA,
        "authorB" : userBio.authorB,
        "pictures" : theUploads
    }

    return render(request, "GoEnigma/dashboard.html", content)
</code>```

# urls.py
from django.conf.urls.static import static
from django.conf import settings
# urls []
if settings.DEBUG:
     urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
```

Title: How to Upload an Image to Django

Body:
I have spent over three days on this. It appears that something saved to the db, but when I try to access it in the template, I can only get the object of the db. I can not access it. I believe it was not saved successfully because I don't see a media folder where it would be saved. This is what I have so far.

# settings.py
STATIC_URL = '/static/'
STATICFILES_DIRS = (os.path.join(BASE_DIR, 'static'), )
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')

# forms.py
from .models import Pic
from django import forms
class ImageForm(forms.ModelForm):
    class Meta:
        model= Pic
        fields= ["picture"]

# models.py
class Pic(models.Model):
    picture = models.ImageField(upload_to = 'media/', default = 'media/None/no-img.jpg', null=True, blank= True)

# views.py
def upload(request):
    form = ImageForm
    context = {}
    userBio = Bio.objects.get(userData = User.objects.get(id = request.session['client']['id']))
    if request.method == 'POST':
        # .is_valid checks the models parameters via forms method
        form = ImageForm(request.POST,request.FILES)
        if form.is_valid():
            form.save()
            print("succesful uploaded image")
            return redirect("/dashboard")
        else:
            print("Not a valid input from form....")
            messages.error(request,"Not a valid input")
    return redirect("/dashboard")

<form rule="form" class="border border--secondary" method="POST" action="/manageFile" enctype="multipart/form-data">
    {% csrf_token%}
    <input type="file" name = "update">
    <input type = "submit">
</form>
{% if pictures %}
    {% for pic in pictures%}

    {% endfor %}
{% endif%}

In the template, it appears as Pic object(1).
In the terminal, it appears as

Query set Pic: Pic object (1)

Here's what I render to the template.

def dash(request):
    try:
        _id = request.session['client']['id']
    except:
        return redirect("/loginPg")

    userBio = Bio.objects.get(userData = User.objects.get(id = request.session['client']['id']))
    print("its right here")
    theUploads = Pic.objects.all()
    print("This image object -", theUploads)

    content = {
        "title" : userBio.title,
        "qA" : userBio.quoteA,
        "qB" : userBio.quoteB,
        "desc" : userBio.desc,
        "authorA" : userBio.authorA,
        "authorB" : userBio.authorB,
        "pictures" : theUploads
    }

    return render(request, "GoEnigma/dashboard.html", content)

# urls.py
from django.conf.urls.static import static
from django.conf import settings
# urls []
if settings.DEBUG:
     urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

Body:
If the picture is being saved in the database than the error is with rendering the template. To render the images in template you need to get the {{model_class.model_fields.url}} so in your case the class is pic, the field is picture.
try this in your template <img src="{{pic.picture.url}}">


问:
Binning files based on the values in python
I am trying to bin the values into some custom bins for my data. The Coulmn1 in the dataframe consists of a large set of random numbers ranging from 1.4 to 1.9.
Suppose the initial dataframe looks like this:

```<code>Index    Col1
1        1.4678
2        1.5001
3        1.5795
4        1.5234
...      ......
98       1.6754
99       1.6399
100      1.4910
</code>```

What I want to do is to bin the numbers that fall within +/- 0.002 of the bins listed below. i.e., I want to bin all the data that fall within 1.458 and 1.462 for the first bin. The output should look like this

```<code>Index    Col1       Bin_names
1        1.4678      NaN
2        1.5001      1.50
3        1.5795      1.58
4        1.5234      NaN
...      ......      ....
98       1.6754      NaN
99       1.6399      1.64
100      1.4910      NaN
</code>```

I tried the code below, but it bins all the data between 1.46 to 1.48 in one bin, which is not what I want.

```<code>bins = [1.46,1.48,1.5,1.52,1.54,1.56,1.58,1.60,1.62,1.64,1.66,1.68,1.70]
df['Bin_names'] = pd.cut(df['Column1'], bins, labels=['1.48','1.5','1.52','1.54','1.56','1.58','1.60','1.62','1.64','1.66','1.68','1.70'])
</code>```

How can I bin the data based on my requirement?

Body:
I am trying to bin the values into some custom bins for my data. The Coulmn1 in the dataframe consists of a large set of random numbers ranging from 1.4 to 1.9.
Suppose the initial dataframe looks like this:

Index    Col1
1        1.4678
2        1.5001
3        1.5795
4        1.5234
...      ......
98       1.6754
99       1.6399
100      1.4910

What I want to do is to bin the numbers that fall within +/- 0.002 of the bins listed below. i.e., I want to bin all the data that fall within 1.458 and 1.462 for the first bin. The output should look like this

Index    Col1       Bin_names
1        1.4678      NaN
2        1.5001      1.50
3        1.5795      1.58
4        1.5234      NaN
...      ......      ....
98       1.6754      NaN
99       1.6399      1.64
100      1.4910      NaN

I tried the code below, but it bins all the data between 1.46 to 1.48 in one bin, which is not what I want.

bins = [1.46,1.48,1.5,1.52,1.54,1.56,1.58,1.60,1.62,1.64,1.66,1.68,1.70]
df['Bin_names'] = pd.cut(df['Column1'], bins, labels=['1.48','1.5','1.52','1.54','1.56','1.58','1.60','1.62','1.64','1.66','1.68','1.70'])

How can I bin the data based on my requirement?

Body:
By default, the boundary of pd.cut() contains the right edge, so you can start with the label '1.46'.

import pandas as pd
import numpy as np
import random
random.seed(10)

df = pd.DataFrame({'Col1':[round(random.uniform(1.450, 1.700),4) for i in range(100)]}, index=np.arange(1,101,1))

bins = [1.46,1.48,1.50,1.52,1.54,1.56,1.58,1.60,1.62,1.64,1.66,1.68,1.70]
labels = ['1.46','1.48','1.50','1.52','1.54','1.56','1.58','1.60','1.62','1.64','1.66','1.68']

df['Bin_names'] = pd.cut(df['Col1'], bins, labels=labels,right=False)
df.sort_values('Col1', inplace=True)
df2 = df.groupby('Bin_names').agg(list)
df3 = df2['Col1'].apply(pd.Series)
df3['cnt'] = df3.count(axis=1, numeric_only=True)
df3

       0    1   2   3   4   5   6   7   8   9   10  11  cnt
Bin_names
1.46    1.4611  1.4611  1.4657  1.4662  1.4700  1.4742  1.4782  1.4799  NaN NaN NaN NaN 8
1.48    1.4832  1.4835  1.4874  1.4891  1.4901  1.4912  1.4914  1.4916  1.4946  NaN NaN NaN 9
1.50    1.5015  1.5061  1.5104  1.5114  1.5125  1.5187  NaN NaN NaN NaN NaN NaN 6
1.52    1.5209  1.5257  1.5286  1.5299  1.5319  1.5329  1.5369  NaN NaN NaN NaN NaN 7
1.54    1.5415  1.5435  1.5454  1.5476  1.5503  1.5532  1.5535  1.5551  1.5572  1.5583  1.5587  1.5590  12
1.56    1.5603  1.5620  1.5639  1.5642  1.5654  1.5700  1.5723  1.5725  1.5742  NaN NaN NaN 9
1.58    1.5800  1.5802  1.5813  1.5834  1.5847  1.5872  1.5918  1.5929  1.5945  1.5957  1.5961  1.5962  12
1.60    1.6003  1.6005  1.6008  1.6033  1.6043  1.6122  1.6134  1.6145  1.6155  1.6183  1.6187  NaN 11
1.62    1.6215  1.6281  NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN 2
1.64    1.6420  1.6439  1.6444  1.6519  1.6533  1.6545  1.6553  1.6559  NaN NaN NaN NaN 8
1.66    1.6610  1.6638  1.6650  1.6674  1.6745  1.6776  NaN NaN NaN NaN NaN NaN 6
1.68    1.6853  1.6869  1.6882  1.6922  1.6923  1.6956  1.6991  NaN NaN NaN NaN NaN 7


问:
SQL: IF clause within WHERE clause
Is it possible to use an IF clause within a WHERE clause in MS SQL?

Example:

```<code>WHERE
    IF IsNumeric(@OrderNumber) = 1
        OrderNumber = @OrderNumber
    ELSE
        OrderNumber LIKE '%' + @OrderNumber + '%'
</code>```

答:
In sql server I had same problem I wanted to use an and statement only if parameter is false and on true I had to show both values true and false so I used it this way</p>

```<code>(T.IsPublic = @ShowPublic or  @ShowPublic = 1)
</code>```

OwnerDisplayName: Bryan Roth

ContentLicense: CC BY-SA 2.5

Title: SQL: IF clause within WHERE clause

Body:
Is it possible to use an IF clause within a WHERE clause in MS SQL?

Example:

WHERE
    IF IsNumeric(@OrderNumber) = 1
        OrderNumber = @OrderNumber
    ELSE
        OrderNumber LIKE '%' + @OrderNumber + '%'

LastEditorDisplayName: Bryan Roth

Body:
In sql server I had same problem I wanted to use an and statement only if parameter is false and on true I had to show both values true and false so I used it this way

(T.IsPublic = @ShowPublic or  @ShowPublic = 1)


问:
Trouble with large numbers while using <iomanip> larger in cpp
While sorting and displaying big numbers you usually end up displaying the large numbers in enotation. I was trying to display the whole number by using the <iomanip> library in cpp and it fails for very large numbers.

```<code> //big sorting
    #include<bits/stdc++.h>
    #include<iomanip>
    using namespace std;
    int main()
    {
        int n;
        cin>>n;
        double arr[n];
        for (int i = 0;i < n; i++)
            cin>>arr[i];

        sort(arr, arr+n);
        cout<<fixed<<setprecision(0);
        for (int i = 0;i < n; i++)
            cout<<arr[i]<<endl;
    }
</code>```

Input:

```<code>31415926535897932384626433832795
1
3
10
3
5
</code>```

Expected output:

```<code>1
3
3
5
10
31415926535897932384626433832795
</code>```

Actual output:

```<code>1
3
3
5
10
31415926535897933290036940242944
</code>```

The last digit is getting messed up.

答:
Read more about C++, perhaps the C++11 standard n3337.

Read also the documentation of your C++ compiler, e.g. GCC (invoked as g++) or Clang (invoked as clang++). Read of course a good C++ programming book, since C++ is a very difficult programming language. Use C++ standard containers and smart pointers.

Large numbers does not fit natively in a computer memory (or in its registers). For example, with C++ code compiled by GCC on Linux/x86-64, an int has just 32 bits.

Consider using arbitrary precision arithmetic. You might be interested by GMPlib.

Floating point numbers are weird. Be sure to read the famous floating-point-gui.de website, and see also this answer.

    #include<bits/stdc++.h>

is wrong since non-standard. Take the habit of #include-ing only headers needed by your translation unit, except if you use pre-compiled headers.

Take some time to read more about numbers and arithmetic. Some notion of modular arithmetic is incredibly useful when programming: a lot of computers are computing modulo 232 or 264.

Study for inspiration the C++ source code of existing open source software (e.g. on github or gitlab, including FLTK). If you use Linux, its fish-shell has a nice C++ code. You could even glance inside the source code of GCC and of Clang, both being nice C++ open source compilers.

In practice, read also about build automation tools such as GNU make (free software coded in C) or ninja (open source tool coded in C++).

Don't forget to use a version control system (I recommend git).

Read How to debug small programs.

Enable all warnings and debug info when compiling your C++ code (with GCC, use  g++ -Wall -Wextra -g).

Read of course the documentation of your favorite debugger.

I am a happy user of GDB.

Consider using static program analysis tools such as the Clang static analyzer or Frama-C++.

Body:
While sorting and displaying big numbers you usually end up displaying the large numbers in enotation. I was trying to display the whole number by using the <iomanip> library in cpp and it fails for very large numbers.

 //big sorting
    #include<bits/stdc++.h>
    #include<iomanip>
    using namespace std;
    int main()
    {
        int n;
        cin>>n;
        double arr[n];
        for (int i = 0;i < n; i++)
            cin>>arr[i];

        sort(arr, arr+n);
        cout<<fixed<<setprecision(0);
        for (int i = 0;i < n; i++)
            cout<<arr[i]<<endl;
    }

Input:

31415926535897932384626433832795
1
3
10
3
5

Expected output:

1
3
3
5
10
31415926535897932384626433832795

Actual output:

1
3
3
5
10
31415926535897933290036940242944

The last digit is getting messed up.


问:
Is it problematic to run python script constantly in the background?
I've wrote a simple code to send my mother a message every x seconds.

I would like to know :

Can I just run my code in the background 24/7 in the background without issues?

Is there another way ?

This is my code:

```<code>from twilio.rest import Client
import time

account_sid = 'private'
auth_token = 'private'
client = Client(account_sid, auth_token)

starttime=time.time()
while True:
    message = client.messages.create(
    from_='+xxxxx',
    body="message text",
    to = '+xxxxxxxx')
    time.sleep(60.0 - ((time.time() - starttime) % 60.0))
    print(message.sid)

</code>```

答:
In my opinion, there are two options.

Use Nohup to run your script in the background. Like use the following command:

nohup python -u your_script.py &

It will create a nohup.out file, and you can vim it to check the status.

Use Crontab to run your script every x minutes.
In your example, if you want to run your script every minute, you can set crontab as: * * * * * python your_script.py. Please note that crontab cannot support the period less than 1 minute. To do this, you can write a bash file and run it. And you can delete the time.sleep line inside your script.

```<code>#!/bin/bash

while true; do
  python your_script.py
  sleep x
done
</code>```

Body:
I've wrote a simple code to send my mother a message every x seconds.

I would like to know :

Can I just run my code in the background 24/7 in the background without issues?

Is there another way ?

This is my code:

from twilio.rest import Client
import time

account_sid = 'private'
auth_token = 'private'
client = Client(account_sid, auth_token)

starttime=time.time()
while True:
    message = client.messages.create(
    from_='+xxxxx',
    body="message text",
    to = '+xxxxxxxx')
    time.sleep(60.0 - ((time.time() - starttime) % 60.0))
    print(message.sid)

Body:
In my opinion, there are two options.

Use Nohup to run your script in the background. Like use the following command:

nohup python -u your_script.py &

It will create a nohup.out file, and you can vim it to check the status.

Use Crontab to run your script every x minutes.
In your example, if you want to run your script every minute, you can set crontab as: * * * * * python your_script.py. Please note that crontab cannot support the period less than 1 minute. To do this, you can write a bash file and run it. And you can delete the time.sleep line inside your script.

#!/bin/bash

while true; do
  python your_script.py
  sleep x
done


问:
Executing function for every key in array w/o loop
I'm looking for the best practice for executing encodeURIComponent (or some other function) for every key in array, before joining it to one string.

This could be done with a loop like this:

```<code>var dynamicArray = ['uri1', 'uri2', 'hax&%hax'];
var max = dynamicArray.length,
i,
url = '';

for (i=0;i<max;(i++))
{
   url += '/' + encodeURIComponent(dynamicArray[i]);
}

alert(url);

/* RESULT: /uri1/uri2/hax%26%25hax */
</code>```

But I'm looking for something like this (without a loop):

```<code>encodeURIComponent(dynamicArray).join('/'); /* This won't work */
encodeURIComponent(dynamicArray.join('/')); /* Can't do this, wrong result */
</code>```

答:
```<code>dynamicArray.map(encodeURIComponent).join('/');
</code>```

Check out MDC for an implementation of map for non-compatible platforms.

Of course, internally there is a loop in map's implementation.

Body:
I'm looking for the best practice for executing encodeURIComponent (or some other function) for every key in array, before joining it to one string.

This could be done with a loop like this:

var dynamicArray = ['uri1', 'uri2', 'hax&%hax'];
var max = dynamicArray.length,
i,
url = '';

for (i=0;i<max;(i++))
{
   url += '/' + encodeURIComponent(dynamicArray[i]);
}

alert(url);

/* RESULT: /uri1/uri2/hax%26%25hax */

But I'm looking for something like this (without a loop):

encodeURIComponent(dynamicArray).join('/'); /* This won't work */
encodeURIComponent(dynamicArray.join('/')); /* Can't do this, wrong result */

Body:
dynamicArray.map(encodeURIComponent).join('/');

Check out MDC for an implementation of map for non-compatible platforms.

Of course, internally there is a loop in map's implementation.


问:
Datastore error: BadValueError: Expected integer, got [0, 1, 2, 3]
Others have reported a similar error, but the solutions given do not solve my problem.
For example there is a good answer here. The answer in the link mentions how ndb changes from a first use to a later use and suggests there is a problem because a first run produces a None in the Datastore. I cannot reproduce or see that happening in the Datastore for my sdk, but that may be because I am running it here from the interactive console.

I am pretty sure I got an initial good run with the GAE interactive console, but every run since then has failed with the error in my Title to this question.

I have left the print statements in the following code because they show good results and assure me that the error is occuring in the put() at the very end.

```<code>from google.appengine.ext import ndb

class Account(ndb.Model):

    week = ndb.IntegerProperty(repeated=True)
    weeksNS = ndb.IntegerProperty(repeated=True)
    weeksEW = ndb.IntegerProperty(repeated=True)

terry=Account(week=[],weeksNS=[],weeksEW=[])
terry_key=terry.put()
terry = terry_key.get()
print terry

for t in list(range(4)):     #just dummy input, but like real input
    terry.week.append(t)
print terry.week

region = 1                   #same error message for region = 0
if region :
    terry.weeksEW.append(terry.week)
else:
    terry.weeksNS.append(terry.week)

print 'EW'+str(terry.weeksEW)
print 'NS'+str(terry.weeksNS)
terry.week = []
print 'week'+str(terry.week)
terry.put()
</code>```

The idea of my code is to first build up the terry.week list values incrementally and then later store the whole list to the appropriate region, either NS or EW. So I'm looking for a workaround for this scheme.

The error message is likely of no value but I am reproducing it here.

```<code>Traceback (most recent call last):
  File "/Users/brian/google-cloud-sdk/platform/google_appengine/google/appengine/tools/devappserver2/python/runtime/request_handler.py", line 237, in handle_interactive_request
    exec(compiled_code, self._command_globals)
  File "<string>", line 55, in <module>
  File "/Users/brian/google-cloud-sdk/platform/google_appengine/google/appengine/ext/ndb/model.py", line 3458, in _put
    return self._put_async(**ctx_options).get_result()
  File "/Users/brian/google-cloud-sdk/platform/google_appengine/google/appengine/ext/ndb/tasklets.py", line 383, in get_result
    self.check_success()
  File "/Users/brian/google-cloud-sdk/platform/google_appengine/google/appengine/ext/ndb/tasklets.py", line 427, in _help_tasklet_along
    value = gen.throw(exc.__class__, exc, tb)
  File "/Users/brian/google-cloud-sdk/platform/google_appengine/google/appengine/ext/ndb/context.py", line 824, in put
    key = yield self._put_batcher.add(entity, options)
  File "/Users/brian/google-cloud-sdk/platform/google_appengine/google/appengine/ext/ndb/tasklets.py", line 430, in _help_tasklet_along
    value = gen.send(val)
  File "/Users/brian/google-cloud-sdk/platform/google_appengine/google/appengine/ext/ndb/context.py", line 358, in _put_tasklet
    keys = yield self._conn.async_put(options, datastore_entities)
  File "/Users/brian/google-cloud-sdk/platform/google_appengine/google/appengine/datastore/datastore_rpc.py", line 1858, in async_put
    pbs = [entity_to_pb(entity) for entity in entities]
  File "/Users/brian/google-cloud-sdk/platform/google_appengine/google/appengine/ext/ndb/model.py", line 697, in entity_to_pb
    pb = ent._to_pb()
  File "/Users/brian/google-cloud-sdk/platform/google_appengine/google/appengine/ext/ndb/model.py", line 3167, in _to_pb
    prop._serialize(self, pb, projection=self._projection)
  File "/Users/brian/google-cloud-sdk/platform/google_appengine/google/appengine/ext/ndb/model.py", line 1422, in _serialize
    values = self._get_base_value_unwrapped_as_list(entity)
  File "/Users/brian/google-cloud-sdk/platform/google_appengine/google/appengine/ext/ndb/model.py", line 1192, in _get_base_value_unwrapped_as_list
    wrapped = self._get_base_value(entity)
  File "/Users/brian/google-cloud-sdk/platform/google_appengine/google/appengine/ext/ndb/model.py", line 1180, in _get_base_value
    return self._apply_to_values(entity, self._opt_call_to_base_type)
  File "/Users/brian/google-cloud-sdk/platform/google_appengine/google/appengine/ext/ndb/model.py", line 1352, in _apply_to_values
    value[:] = map(function, value)
  File "/Users/brian/google-cloud-sdk/platform/google_appengine/google/appengine/ext/ndb/model.py", line 1234, in _opt_call_to_base_type
    value = _BaseValue(self._call_to_base_type(value))
  File "/Users/brian/google-cloud-sdk/platform/google_appengine/google/appengine/ext/ndb/model.py", line 1255, in _call_to_base_type
    return call(value)
  File "/Users/brian/google-cloud-sdk/platform/google_appengine/google/appengine/ext/ndb/model.py", line 1331, in call
    newvalue = method(self, value)
  File "/Users/brian/google-cloud-sdk/platform/google_appengine/google/appengine/ext/ndb/model.py", line 1781, in _validate
    (value,))
BadValueError: Expected integer, got [0, 1, 2, 3]
</code>```

答:
I believe the error comes from these lines:

```<code>terry.weeksEW.append(terry.week)
terry.weeksNS.append(terry.week)
</code>```

You are not appending another integer; You are appending a list, when an integer is expected.

```<code>>>> aaa = [1,2,3]
>>> bbb = [4,5,6]
>>> aaa.append(bbb)
>>> aaa
[1, 2, 3, [4, 5, 6]]
>>>
</code>```

This fails the ndb.IntegerProperty test.

Try:

```<code>terry.weeksEW += terry.week
terry.weeksNS += terry.week
</code>```

EDIT: To save a list of lists, do not use the IntegerProperty(), but instead the JsonProperty().  Better still, the ndb datastore is deprecated, so...  I recommend Firestore, which uses JSON objects by default. At least use Cloud Datastore, or Cloud NDB.

Body:
Others have reported a similar error, but the solutions given do not solve my problem.
For example there is a good answer here. The answer in the link mentions how ndb changes from a first use to a later use and suggests there is a problem because a first run produces a None in the Datastore. I cannot reproduce or see that happening in the Datastore for my sdk, but that may be because I am running it here from the interactive console.

I am pretty sure I got an initial good run with the GAE interactive console, but every run since then has failed with the error in my Title to this question.

I have left the print statements in the following code because they show good results and assure me that the error is occuring in the put() at the very end.

from google.appengine.ext import ndb

class Account(ndb.Model):

    week = ndb.IntegerProperty(repeated=True)
    weeksNS = ndb.IntegerProperty(repeated=True)
    weeksEW = ndb.IntegerProperty(repeated=True)

terry=Account(week=[],weeksNS=[],weeksEW=[])
terry_key=terry.put()
terry = terry_key.get()
print terry

for t in list(range(4)):     #just dummy input, but like real input
    terry.week.append(t)
print terry.week

region = 1                   #same error message for region = 0
if region :
    terry.weeksEW.append(terry.week)
else:
    terry.weeksNS.append(terry.week)

print 'EW'+str(terry.weeksEW)
print 'NS'+str(terry.weeksNS)
terry.week = []
print 'week'+str(terry.week)
terry.put()

The idea of my code is to first build up the terry.week list values incrementally and then later store the whole list to the appropriate region, either NS or EW. So I'm looking for a workaround for this scheme.

The error message is likely of no value but I am reproducing it here.

Traceback (most recent call last):
  File "/Users/brian/google-cloud-sdk/platform/google_appengine/google/appengine/tools/devappserver2/python/runtime/request_handler.py", line 237, in handle_interactive_request
    exec(compiled_code, self._command_globals)
  File "<string>", line 55, in <module>
  File "/Users/brian/google-cloud-sdk/platform/google_appengine/google/appengine/ext/ndb/model.py", line 3458, in _put
    return self._put_async(**ctx_options).get_result()
  File "/Users/brian/google-cloud-sdk/platform/google_appengine/google/appengine/ext/ndb/tasklets.py", line 383, in get_result
    self.check_success()
  File "/Users/brian/google-cloud-sdk/platform/google_appengine/google/appengine/ext/ndb/tasklets.py", line 427, in _help_tasklet_along
    value = gen.throw(exc.__class__, exc, tb)
  File "/Users/brian/google-cloud-sdk/platform/google_appengine/google/appengine/ext/ndb/context.py", line 824, in put
    key = yield self._put_batcher.add(entity, options)
  File "/Users/brian/google-cloud-sdk/platform/google_appengine/google/appengine/ext/ndb/tasklets.py", line 430, in _help_tasklet_along
    value = gen.send(val)
  File "/Users/brian/google-cloud-sdk/platform/google_appengine/google/appengine/ext/ndb/context.py", line 358, in _put_tasklet
    keys = yield self._conn.async_put(options, datastore_entities)
  File "/Users/brian/google-cloud-sdk/platform/google_appengine/google/appengine/datastore/datastore_rpc.py", line 1858, in async_put
    pbs = [entity_to_pb(entity) for entity in entities]
  File "/Users/brian/google-cloud-sdk/platform/google_appengine/google/appengine/ext/ndb/model.py", line 697, in entity_to_pb
    pb = ent._to_pb()
  File "/Users/brian/google-cloud-sdk/platform/google_appengine/google/appengine/ext/ndb/model.py", line 3167, in _to_pb
    prop._serialize(self, pb, projection=self._projection)
  File "/Users/brian/google-cloud-sdk/platform/google_appengine/google/appengine/ext/ndb/model.py", line 1422, in _serialize
    values = self._get_base_value_unwrapped_as_list(entity)
  File "/Users/brian/google-cloud-sdk/platform/google_appengine/google/appengine/ext/ndb/model.py", line 1192, in _get_base_value_unwrapped_as_list
    wrapped = self._get_base_value(entity)
  File "/Users/brian/google-cloud-sdk/platform/google_appengine/google/appengine/ext/ndb/model.py", line 1180, in _get_base_value
    return self._apply_to_values(entity, self._opt_call_to_base_type)
  File "/Users/brian/google-cloud-sdk/platform/google_appengine/google/appengine/ext/ndb/model.py", line 1352, in _apply_to_values
    value[:] = map(function, value)
  File "/Users/brian/google-cloud-sdk/platform/google_appengine/google/appengine/ext/ndb/model.py", line 1234, in _opt_call_to_base_type
    value = _BaseValue(self._call_to_base_type(value))
  File "/Users/brian/google-cloud-sdk/platform/google_appengine/google/appengine/ext/ndb/model.py", line 1255, in _call_to_base_type
    return call(value)
  File "/Users/brian/google-cloud-sdk/platform/google_appengine/google/appengine/ext/ndb/model.py", line 1331, in call
    newvalue = method(self, value)
  File "/Users/brian/google-cloud-sdk/platform/google_appengine/google/appengine/ext/ndb/model.py", line 1781, in _validate
    (value,))
BadValueError: Expected integer, got [0, 1, 2, 3]

Body:
I believe the error comes from these lines:

terry.weeksEW.append(terry.week)
terry.weeksNS.append(terry.week)

You are not appending another integer; You are appending a list, when an integer is expected.

>>> aaa = [1,2,3]
>>> bbb = [4,5,6]
>>> aaa.append(bbb)
>>> aaa
[1, 2, 3, [4, 5, 6]]
>>>

This fails the ndb.IntegerProperty test.

Try:

terry.weeksEW += terry.week
terry.weeksNS += terry.week

EDIT: To save a list of lists, do not use the IntegerProperty(), but instead the JsonProperty().  Better still, the ndb datastore is deprecated, so...  I recommend Firestore, which uses JSON objects by default. At least use Cloud Datastore, or Cloud NDB.


问:
How to add column using execute immediate
I just want to add column using execute immediate but  I am getting an error.  Please let me know the this PL/SQL block is correct or not?</p>

```<code>create or replace procedure add_column (xyz in varchar2, abc in varchar2) is
begin
    EXECUTE IMMEDIATE 'alter table ' || 'xyz add abc varchar2(20)';
    dbms_output.put_line('New column added');
end;

exec add_column ('students', 'time');

error: Error starting at line : 8 in command -
BEGIN add_column ('students', 'time'); END;

ORA-00942: table or view does not exist
ORA-06512: at "HR.ADD_COLUMN", line 4
ORA-06512: at line 1
</code>```

答:
You need to use string concatanation as:

```<code>EXECUTE IMMEDIATE 'alter table ' || xyz || ' add ' || abc || ' varchar2(20)';
</code>```

Also, DBMS_ASSERT can be used to check for the valid names of the table and column as follows.

```<code>EXECUTE IMMEDIATE 'alter table ' || sys.DBMS_ASSERT.SQL_OBJECT_NAME(xyz)
                   || ' add ' || sys.DBMS_ASSERT.SQL_OBJECT_NAME(abc) || ' varchar2(20)';
</code>```

Here, xyz and abc will be replaced with the input parameter names.

Body:
I just want to add column using execute immediate but  I am getting an error.  Please let me know the this PL/SQL block is correct or not?

create or replace procedure add_column (xyz in varchar2, abc in varchar2) is
begin
    EXECUTE IMMEDIATE 'alter table ' || 'xyz add abc varchar2(20)';
    dbms_output.put_line('New column added');
end;

exec add_column ('students', 'time');

error: Error starting at line : 8 in command -
BEGIN add_column ('students', 'time'); END;

ORA-00942: table or view does not exist
ORA-06512: at "HR.ADD_COLUMN", line 4
ORA-06512: at line 1

Body:
You need to use string concatanation as:

EXECUTE IMMEDIATE 'alter table ' || xyz || ' add ' || abc || ' varchar2(20)';

Also, DBMS_ASSERT can be used to check for the valid names of the table and column as follows.

EXECUTE IMMEDIATE 'alter table ' || sys.DBMS_ASSERT.SQL_OBJECT_NAME(xyz)
                   || ' add ' || sys.DBMS_ASSERT.SQL_OBJECT_NAME(abc) || ' varchar2(20)';

Here, xyz and abc will be replaced with the input parameter names.


问:
In visual stdio 2019 C++ i tried to open an empty peject but it didnt worked out....?
//Simple code
When i tried this code in An empty project so an error came of

the file specified is  not found

```<code>#include<iostream>
using namespace std;

int main()
{
    cout<<"Hell world";
    return 0;
}
</code>```

答: Did you notice this #include<iostream> it should be like this #include<iostream.h>. I think it's not a problem with visual studio.

Body:
//Simple code
When i tried this code in An empty project so an error came of

the file specified is  not found

#include<iostream>
using namespace std;

int main()
{
    cout<<"Hell world";
    return 0;
}


问:
how to auto load mobile templates by agent in codeigniter?
```<code>dir:
</code>```

```
application
 -controllers
 -models
 -views
 -mobile_views
```

How do I auto load templates at mobile_views when I use $this->load->view and view by iphone or other mobile phone?

答:
I do this in my controller:

```<code>public function index()
{
    if($this->agent->is_mobile())
    {
        $this->load_mobile();
    }
    else
    {
        $this->load_web();
    }
}

public function load_mobile()
{
    $this->load->view('mobile/home');
}

public function load_web()
{
    $this->load->view('web/home');
}
</code>```

In this way I can add different data to mobile and to web pages.

I also extend the default controller and add some useful extra features:

Enables the usage of master page/templates.

Can add css and javascript files.

Uses the _output method for controlling the controllers output.

Can load relative content with in the form of modules (views)

So I can manage better the different pages.

Bye!!

Body:
dir:

application
 -controllers
 -models
 -views
 -mobile_views

How do I auto load templates at mobile_views when I use $this->load->view and view by iphone or other mobile phone?

Body:
I do this in my controller:

public function index()
{
    if($this->agent->is_mobile())
    {
        $this->load_mobile();
    }
    else
    {
        $this->load_web();
    }
}

public function load_mobile()
{
    $this->load->view('mobile/home');
}

public function load_web()
{
    $this->load->view('web/home');
}

In this way I can add different data to mobile and to web pages.

I also extend the default controller and add some useful extra features:

Enables the usage of master page/templates.

Can add css and javascript files.

Uses the _output method for controlling the controllers output.

Can load relative content with in the form of modules (views)

So I can manage better the different pages.

Bye!!


Title: Plot with different x-axis and y-axis using matplotlib

Body:
I have been working on Matplotlib to plot different datasets into same plot(say a comparision line plot) with each and every datasets have different x-axis and y-axis values.

for example dataset will look like:

x =  [['12.63', '13.50', '14.15', '15.18', '16.04', '17.28', '18.56', '19.70',
       '20.90', '22.21', '23.25', '24.13'],
      ['13.39', '14.10', '15.05', '16.20', '17.55', '18.43', '19.75', '21.29',
       '22.78', '24.00', '24.85', '24.81'],
      ['13.02', '13.86', '14.82', '15.80', '16.90', '17.99', '19.24', '20.79',
       '22.30', '23.43', '24.38', '24.68']]

y = [['-15.09', '-15.19', '-15.23', '-15.32', '-15.07', '-15.11', '-15.04',
      '-15.08', '-14.97', '-14.98', '-14.89', '-15.12'],
     ['-15.91', '-15.89', '-15.90', '-15.96', '-15.55', '-15.58', '-15.51',
      '-15.48', '-15.42', '-15.40', '-15.85', '-16.64'],
     ['-15.71', '-15.75', '-15.83', '-15.83', '-15.54', '-15.55', '-15.53',
      '-15.47', '-15.41', '-15.33', '-15.43', '-15.97']]

How do i make the comparison chart like below example (refernce from google)

Body:
First, your data is string. You should convert them into floats.

Then, the easiest way to do is to call plot function multiple times, one for each line:

x =  [['12.63', '13.50', '14.15', '15.18', '16.04', '17.28', '18.56', '19.70',
       '20.90', '22.21', '23.25', '24.13'],
      ['13.39', '14.10', '15.05', '16.20', '17.55', '18.43', '19.75', '21.29',
       '22.78', '24.00', '24.85', '24.81'],
      ['13.02', '13.86', '14.82', '15.80', '16.90', '17.99', '19.24', '20.79',
       '22.30', '23.43', '24.38', '24.68']]

y = [['-15.09', '-15.19', '-15.23', '-15.32', '-15.07', '-15.11', '-15.04',
      '-15.08', '-14.97', '-14.98', '-14.89', '-15.12'],
     ['-15.91', '-15.89', '-15.90', '-15.96', '-15.55', '-15.58', '-15.51',
      '-15.48', '-15.42', '-15.40', '-15.85', '-16.64'],
     ['-15.71', '-15.75', '-15.83', '-15.83', '-15.54', '-15.55', '-15.53',
      '-15.47', '-15.41', '-15.33', '-15.43', '-15.97']]

fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
ax.plot([float(n) for n in x[0]], [float(n) for n in y[0]], color='tab:blue')
ax.plot([float(n) for n in x[1]], [float(n) for n in y[1]], color='tab:orange')
ax.plot([float(n) for n in x[2]], [float(n) for n in y[2]], color='tab:red')
plt.show()