问:
Load csv data to table use Hive SQL java error InvocationTargetException
I'm crazy because cannot loading data to table use Hive SQL. Please teach me how fix this bug

To create table in Metadata. I using 2 statement:

1 - Create table:

```<code>CREATE TABLE db1.test_table_file3(
Col1 INT,Col2 SMALLINT,Col3 SMALLINT)
COMMENT 'test_table_file2'
ROW FORMAT DELIMITED
FIELDS TERMINATED BY '\t'
LINES TERMINATED BY '\n'
</code>```

2 - Load data to table:

```<code>LOAD DATA INPATH '/test/test_test_5.csv' INTO TABLE
db1.test_table_file3
</code>```

Code below:

```<code>Connection con = getConnection();
Statement stmt = con.createStatement();
Statement loadDataStmt = con.createStatement();
stmt.execute(createTableQuery);
loadDataStmt .execute(loadDataSQL);
closeConnection(con, stmt);
closeConnection(con, loadDataStmt);
</code>```

And result below:

```<code>Statement 1 create table: Execute successful
Statement 2 Load data: Execute fail

java.sql.SQLException: java.lang.reflect.InvocationTargetException
    at org.apache.hive.jdbc.HiveStatement.execute(HiveStatement.java:296) ~[hive-jdbc-1.2.1.spark2.jar:1.2.1.spark2]
    at com.toshiba.mwcloud.datalake.griddatalake.repository.impl.MetadataRepositoryImpl.loadDataIntoTable(MetadataRepositoryImpl.java:404) ~[bin/:na]
    at com.toshiba.mwcloud.datalake.griddatalake.repository.impl.MetadataRepositoryImpl.createMetadata(MetadataRepositoryImpl.java:49) ~[bin/:na]
    at com.toshiba.mwcloud.datalake.griddatalake.repository.impl.MetadataRepositoryImpl$$FastClassBySpringCGLIB$$10d6b423.invoke(<generated>) ~[bin/:na]
    at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204) ~[spring-core-5.0.2.BUILD-SNAPSHOT.jar:5.0.2.BUILD-SNAPSHOT]
    at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:747) ~[spring-aop-5.0.2.BUILD-SNAPSHOT.jar:5.0.2.BUILD-SNAPSHOT]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:163) ~[spring-aop-5.0.2.BUILD-SNAPSHOT.jar:5.0.2.BUILD-SNAPSHOT]
    at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:139) ~[spring-tx-5.0.2.BUILD-SNAPSHOT.jar:5.0.2.BUILD-SNAPSHOT]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:185) ~[spring-aop-5.0.2.BUILD-SNAPSHOT.jar:5.0.2.BUILD-SNAPSHOT]
    at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:689) ~[spring-aop-5.0.2.BUILD-SNAPSHOT.jar:5.0.2.BUILD-SNAPSHOT]
    at com.toshiba.mwcloud.datalake.griddatalake.repository.impl.MetadataRepositoryImpl$$EnhancerBySpringCGLIB$$bba82441.createMetadata(<generated>) ~[bin/:na]
    at com.toshiba.mwcloud.datalake.griddatalake.service.impl.MetadataServiceImpl.createMetadata(MetadataServiceImpl.java:85) ~[bin/:na]
    at com.toshiba.mwcloud.datalake.griddatalake.controller.MetadataController.createTable(MetadataController.java:117) ~[bin/:na]
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_121]
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_121]
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_121]
    at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_121]
    at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:209) ~[spring-web-5.0.2.BUILD-SNAPSHOT.jar:5.0.2.BUILD-SNAPSHOT]
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:136) ~[spring-web-5.0.2.BUILD-SNAPSHOT.jar:5.0.2.BUILD-SNAPSHOT]
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:102) ~[spring-webmvc-5.0.2.BUILD-SNAPSHOT.jar:5.0.2.BUILD-SNAPSHOT]
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:871) ~[spring-webmvc-5.0.2.BUILD-SNAPSHOT.jar:5.0.2.BUILD-SNAPSHOT]
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:777) ~[spring-webmvc-5.0.2.BUILD-SNAPSHOT.jar:5.0.2.BUILD-SNAPSHOT]
    at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87) ~[spring-webmvc-5.0.2.BUILD-SNAPSHOT.jar:5.0.2.BUILD-SNAPSHOT]
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:991) ~[spring-webmvc-5.0.2.BUILD-SNAPSHOT.jar:5.0.2.BUILD-SNAPSHOT]
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:925) ~[spring-webmvc-5.0.2.BUILD-SNAPSHOT.jar:5.0.2.BUILD-SNAPSHOT]
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:978) [spring-webmvc-5.0.2.BUILD-SNAPSHOT.jar:5.0.2.BUILD-SNAPSHOT]
    at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:881) [spring-webmvc-5.0.2.BUILD-SNAPSHOT.jar:5.0.2.BUILD-SNAPSHOT]
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:661) [tomcat-embed-core-8.5.23.jar:8.5.23]
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:855) [spring-webmvc-5.0.2.BUILD-SNAPSHOT.jar:5.0.2.BUILD-SNAPSHOT]
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:742) [tomcat-embed-core-8.5.23.jar:8.5.23]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231) [tomcat-embed-core-8.5.23.jar:8.5.23]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) [tomcat-embed-core-8.5.23.jar:8.5.23]
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52) [tomcat-embed-websocket-8.5.23.jar:8.5.23]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) [tomcat-embed-core-8.5.23.jar:8.5.23]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) [tomcat-embed-core-8.5.23.jar:8.5.23]
    at org.springframework.web.filter.CorsFilter.doFilterInternal(CorsFilter.java:96) [spring-web-5.0.2.BUILD-SNAPSHOT.jar:5.0.2.BUILD-SNAPSHOT]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-5.0.2.BUILD-SNAPSHOT.jar:5.0.2.BUILD-SNAPSHOT]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) [tomcat-embed-core-8.5.23.jar:8.5.23]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) [tomcat-embed-core-8.5.23.jar:8.5.23]
    at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:99) [spring-web-5.0.2.BUILD-SNAPSHOT.jar:5.0.2.BUILD-SNAPSHOT]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-5.0.2.BUILD-SNAPSHOT.jar:5.0.2.BUILD-SNAPSHOT]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) [tomcat-embed-core-8.5.23.jar:8.5.23]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) [tomcat-embed-core-8.5.23.jar:8.5.23]
    at org.springframework.web.filter.HttpPutFormContentFilter.doFilterInternal(HttpPutFormContentFilter.java:108) [spring-web-5.0.2.BUILD-SNAPSHOT.jar:5.0.2.BUILD-SNAPSHOT]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-5.0.2.BUILD-SNAPSHOT.jar:5.0.2.BUILD-SNAPSHOT]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) [tomcat-embed-core-8.5.23.jar:8.5.23]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) [tomcat-embed-core-8.5.23.jar:8.5.23]
    at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:81) [spring-web-5.0.2.BUILD-SNAPSHOT.jar:5.0.2.BUILD-SNAPSHOT]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-5.0.2.BUILD-SNAPSHOT.jar:5.0.2.BUILD-SNAPSHOT]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) [tomcat-embed-core-8.5.23.jar:8.5.23]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) [tomcat-embed-core-8.5.23.jar:8.5.23]
    at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:200) [spring-web-5.0.2.BUILD-SNAPSHOT.jar:5.0.2.BUILD-SNAPSHOT]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-5.0.2.BUILD-SNAPSHOT.jar:5.0.2.BUILD-SNAPSHOT]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) [tomcat-embed-core-8.5.23.jar:8.5.23]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) [tomcat-embed-core-8.5.23.jar:8.5.23]
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:199) [tomcat-embed-core-8.5.23.jar:8.5.23]
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96) [tomcat-embed-core-8.5.23.jar:8.5.23]
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:478) [tomcat-embed-core-8.5.23.jar:8.5.23]
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140) [tomcat-embed-core-8.5.23.jar:8.5.23]
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:81) [tomcat-embed-core-8.5.23.jar:8.5.23]
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87) [tomcat-embed-core-8.5.23.jar:8.5.23]
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:342) [tomcat-embed-core-8.5.23.jar:8.5.23]
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:803) [tomcat-embed-core-8.5.23.jar:8.5.23]
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66) [tomcat-embed-core-8.5.23.jar:8.5.23]
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:868) [tomcat-embed-core-8.5.23.jar:8.5.23]
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1459) [tomcat-embed-core-8.5.23.jar:8.5.23]
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) [tomcat-embed-core-8.5.23.jar:8.5.23]
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) [na:1.8.0_121]
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) [na:1.8.0_121]
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) [tomcat-embed-core-8.5.23.jar:8.5.23]
    at java.lang.Thread.run(Thread.java:745) [na:1.8.0_121]
</code>```

答:
The issue is at the second statements, Below is the explanation for it.

If you have the data in the HDFS then LOAD DATA INPATH 'hdfs:/test/test_test_5.csv' INTO TABLE
db1.test_table_file3 will work.

If you have the file in local you should use LOCAL INPATH LOAD DATA LOCAL INPATH '/test/test_test_5.csv' INTO TABLE
db1.test_table_file3

Mention the namenode before the file path if you are loading the file from HDFS

I would suggest you run the second statement out of the JAVA first and see what error are you getting. People commonly run into the permission issues with the external tables, please note that HIVE user should have access to the HDFS path.

You can refer this page, explained in a very easy way.

I've noticed another issue from your question, You set the field delimiter as tab '\t' in the table and you are trying to insert a CSV file, not sure if it is the mistake in your question sample or not.

If you ran into some errors please comment with the errors, I would be able to help you.

Body:
I'm crazy because cannot loading data to table use Hive SQL. Please teach me how fix this bug

To create table in Metadata. I using 2 statement:

1 - Create table:

CREATE TABLE db1.test_table_file3(
Col1 INT,Col2 SMALLINT,Col3 SMALLINT)
COMMENT 'test_table_file2'
ROW FORMAT DELIMITED
FIELDS TERMINATED BY '\t'
LINES TERMINATED BY '\n'

2 - Load data to table:

LOAD DATA INPATH '/test/test_test_5.csv' INTO TABLE
db1.test_table_file3

Code below:

Connection con = getConnection();
Statement stmt = con.createStatement();
Statement loadDataStmt = con.createStatement();
stmt.execute(createTableQuery);
loadDataStmt .execute(loadDataSQL);
closeConnection(con, stmt);
closeConnection(con, loadDataStmt);

And result below:

Statement 1 create table: Execute successful
Statement 2 Load data: Execute fail

java.sql.SQLException: java.lang.reflect.InvocationTargetException
    at org.apache.hive.jdbc.HiveStatement.execute(HiveStatement.java:296) ~[hive-jdbc-1.2.1.spark2.jar:1.2.1.spark2]
    at com.toshiba.mwcloud.datalake.griddatalake.repository.impl.MetadataRepositoryImpl.loadDataIntoTable(MetadataRepositoryImpl.java:404) ~[bin/:na]
    at com.toshiba.mwcloud.datalake.griddatalake.repository.impl.MetadataRepositoryImpl.createMetadata(MetadataRepositoryImpl.java:49) ~[bin/:na]
    at com.toshiba.mwcloud.datalake.griddatalake.repository.impl.MetadataRepositoryImpl$$FastClassBySpringCGLIB$$10d6b423.invoke(<generated>) ~[bin/:na]
    at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204) ~[spring-core-5.0.2.BUILD-SNAPSHOT.jar:5.0.2.BUILD-SNAPSHOT]
    at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:747) ~[spring-aop-5.0.2.BUILD-SNAPSHOT.jar:5.0.2.BUILD-SNAPSHOT]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:163) ~[spring-aop-5.0.2.BUILD-SNAPSHOT.jar:5.0.2.BUILD-SNAPSHOT]
    at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:139) ~[spring-tx-5.0.2.BUILD-SNAPSHOT.jar:5.0.2.BUILD-SNAPSHOT]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:185) ~[spring-aop-5.0.2.BUILD-SNAPSHOT.jar:5.0.2.BUILD-SNAPSHOT]
    at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:689) ~[spring-aop-5.0.2.BUILD-SNAPSHOT.jar:5.0.2.BUILD-SNAPSHOT]
    at com.toshiba.mwcloud.datalake.griddatalake.repository.impl.MetadataRepositoryImpl$$EnhancerBySpringCGLIB$$bba82441.createMetadata(<generated>) ~[bin/:na]
    at com.toshiba.mwcloud.datalake.griddatalake.service.impl.MetadataServiceImpl.createMetadata(MetadataServiceImpl.java:85) ~[bin/:na]
    at com.toshiba.mwcloud.datalake.griddatalake.controller.MetadataController.createTable(MetadataController.java:117) ~[bin/:na]
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_121]
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_121]
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_121]
    at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_121]
    at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:209) ~[spring-web-5.0.2.BUILD-SNAPSHOT.jar:5.0.2.BUILD-SNAPSHOT]
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:136) ~[spring-web-5.0.2.BUILD-SNAPSHOT.jar:5.0.2.BUILD-SNAPSHOT]
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:102) ~[spring-webmvc-5.0.2.BUILD-SNAPSHOT.jar:5.0.2.BUILD-SNAPSHOT]
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:871) ~[spring-webmvc-5.0.2.BUILD-SNAPSHOT.jar:5.0.2.BUILD-SNAPSHOT]
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:777) ~[spring-webmvc-5.0.2.BUILD-SNAPSHOT.jar:5.0.2.BUILD-SNAPSHOT]
    at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87) ~[spring-webmvc-5.0.2.BUILD-SNAPSHOT.jar:5.0.2.BUILD-SNAPSHOT]
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:991) ~[spring-webmvc-5.0.2.BUILD-SNAPSHOT.jar:5.0.2.BUILD-SNAPSHOT]
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:925) ~[spring-webmvc-5.0.2.BUILD-SNAPSHOT.jar:5.0.2.BUILD-SNAPSHOT]
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:978) [spring-webmvc-5.0.2.BUILD-SNAPSHOT.jar:5.0.2.BUILD-SNAPSHOT]
    at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:881) [spring-webmvc-5.0.2.BUILD-SNAPSHOT.jar:5.0.2.BUILD-SNAPSHOT]
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:661) [tomcat-embed-core-8.5.23.jar:8.5.23]
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:855) [spring-webmvc-5.0.2.BUILD-SNAPSHOT.jar:5.0.2.BUILD-SNAPSHOT]
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:742) [tomcat-embed-core-8.5.23.jar:8.5.23]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231) [tomcat-embed-core-8.5.23.jar:8.5.23]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) [tomcat-embed-core-8.5.23.jar:8.5.23]
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52) [tomcat-embed-websocket-8.5.23.jar:8.5.23]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) [tomcat-embed-core-8.5.23.jar:8.5.23]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) [tomcat-embed-core-8.5.23.jar:8.5.23]
    at org.springframework.web.filter.CorsFilter.doFilterInternal(CorsFilter.java:96) [spring-web-5.0.2.BUILD-SNAPSHOT.jar:5.0.2.BUILD-SNAPSHOT]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-5.0.2.BUILD-SNAPSHOT.jar:5.0.2.BUILD-SNAPSHOT]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) [tomcat-embed-core-8.5.23.jar:8.5.23]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) [tomcat-embed-core-8.5.23.jar:8.5.23]
    at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:99) [spring-web-5.0.2.BUILD-SNAPSHOT.jar:5.0.2.BUILD-SNAPSHOT]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-5.0.2.BUILD-SNAPSHOT.jar:5.0.2.BUILD-SNAPSHOT]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) [tomcat-embed-core-8.5.23.jar:8.5.23]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) [tomcat-embed-core-8.5.23.jar:8.5.23]
    at org.springframework.web.filter.HttpPutFormContentFilter.doFilterInternal(HttpPutFormContentFilter.java:108) [spring-web-5.0.2.BUILD-SNAPSHOT.jar:5.0.2.BUILD-SNAPSHOT]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-5.0.2.BUILD-SNAPSHOT.jar:5.0.2.BUILD-SNAPSHOT]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) [tomcat-embed-core-8.5.23.jar:8.5.23]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) [tomcat-embed-core-8.5.23.jar:8.5.23]
    at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:81) [spring-web-5.0.2.BUILD-SNAPSHOT.jar:5.0.2.BUILD-SNAPSHOT]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-5.0.2.BUILD-SNAPSHOT.jar:5.0.2.BUILD-SNAPSHOT]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) [tomcat-embed-core-8.5.23.jar:8.5.23]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) [tomcat-embed-core-8.5.23.jar:8.5.23]
    at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:200) [spring-web-5.0.2.BUILD-SNAPSHOT.jar:5.0.2.BUILD-SNAPSHOT]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-5.0.2.BUILD-SNAPSHOT.jar:5.0.2.BUILD-SNAPSHOT]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) [tomcat-embed-core-8.5.23.jar:8.5.23]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) [tomcat-embed-core-8.5.23.jar:8.5.23]
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:199) [tomcat-embed-core-8.5.23.jar:8.5.23]
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96) [tomcat-embed-core-8.5.23.jar:8.5.23]
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:478) [tomcat-embed-core-8.5.23.jar:8.5.23]
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140) [tomcat-embed-core-8.5.23.jar:8.5.23]
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:81) [tomcat-embed-core-8.5.23.jar:8.5.23]
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87) [tomcat-embed-core-8.5.23.jar:8.5.23]
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:342) [tomcat-embed-core-8.5.23.jar:8.5.23]
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:803) [tomcat-embed-core-8.5.23.jar:8.5.23]
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66) [tomcat-embed-core-8.5.23.jar:8.5.23]
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:868) [tomcat-embed-core-8.5.23.jar:8.5.23]
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1459) [tomcat-embed-core-8.5.23.jar:8.5.23]
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) [tomcat-embed-core-8.5.23.jar:8.5.23]
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) [na:1.8.0_121]
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) [na:1.8.0_121]
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) [tomcat-embed-core-8.5.23.jar:8.5.23]
    at java.lang.Thread.run(Thread.java:745) [na:1.8.0_121]


来源: stackexchange

问:
Create a consumption based App Service Plan with Powershell
I found this answer for the question

Does anyone know how to create a Consumption app-service-plan with Azure?

When I look at the properties (using https://resources.azure.com/ ) of one I made (by the Gui), I see the following properties;

```<code>  },
  "sku": {
    "name": "Y1",
    "tier": "Dynamic",
    "size": "Y1",
    "family": "Y",
    "capacity": 0
  }

{
  "id": "/subscriptions/xxxxxxxxxxxxxxxxxxxxxxxx/resourceGroups/MyResourceGroup/providers/Microsoft.Web/serverfarms/MyHandMadeConsumptionAppServicePlan",
  "name": "MyHandMadeConsumptionAppServicePlan",
  "type": "Microsoft.Web/serverfarms",
  "kind": "functionapp",
  "location": "East US",
</code>```

But if I try (the important part being "-Tier Dynamic")

```<code>$plan = New-AzureRmAppServicePlan -Name 'MyPowershellCreatedAppServicePlan' -ResourceGroupName 'MyResourceGroup' -Location 'PickALocation' -Tier Dynamic
</code>```

I get the exception:

Exception -  + Cannot validate argument on parameter 'Tier'. The
argument "Dynamic" does not belong to the set
"Free,Shared,Basic,Standard,Premium,PremiumV2" specified by the
ValidateSet attribute. Supply an argument that is in the set and then
try the command again.

答:
Geeze Louise.

This has been racking me for 3 days.  I finally found some help (urls I mention).

It looks like this cannot be accomplished (currently) with New-AzureRmAppServicePlan.

But you can fall back onto the more generic New-AzureRmResource.

The code I finally got to work:

```<code>function SafeCreateAppServicePlan(
    [Parameter(Mandatory = $true)]
    [System.String]$location,
    [Parameter(Mandatory = $true)]
    [System.String]$resourceGroupName,
    [Parameter(Mandatory = $true)]
    [String]$appServicePlanName
)
{

    Write-Host "SafeCreateAppServicePlan.Parameter:location: $location"
    Write-Host "SafeCreateAppServicePlan.Parameter:resourceGroupName: $resourceGroupName"
    Write-Host "SafeCreateAppServicePlan.Parameter:appServicePlanName: $appServicePlanName"

    $SkuName = "Y1"
    $SkuTier = "Dynamic"
    $WebAppApiVersion = "2015-08-01"

    $fullObject = @{
        location = $location
        sku = @{
            name = $SkuName
            tier = $SkuTier
        }
    }

    Write-Host "Ensuring the $appServicePlanName app service plan exists"
    $plan = Get-AzureRmAppServicePlan -Name $appServicePlanName -ResourceGroupName $resourceGroupName -ErrorAction SilentlyContinue
    if(-not $plan) {
        Write-Host "Creating $appServicePlanName app service plan"
        New-AzureRmResource -ResourceGroupName $resourceGroupName -ResourceType Microsoft.Web/serverfarms -Name $appServicePlanName -IsFullObject -PropertyObject $fullObject -ApiVersion $WebAppApiVersion -Force
    }
    else {
        Write-Host "$appServicePlanName app service plan already exists"
    }

}
</code>```

The help I got:

https://github.com/davidebbo/AzureWebsitesSamples/blob/master/PowerShell/HelperFunctions.ps1

(search the url above for "SkuName" to find the magic lines.

Please note, this is only part of the overall equation to deploy the INFRASTRUCTURE for azure functions (if you are not using arm templates).  When I say the infrastructure, the code below does not deploy the azure-functions themselves, but the below will setup the infrastructure needed to do this.

This guy does a good job of explaining:

https://clouddeveloper.space/2017/10/26/deploy-azure-function-using-powershell/

"clouddeveloper" basically says that for consumption plan azure functions, you need to have a storage account.  This lines up with the "info" button you get when you manually add a Function-App via the azure portal.

"A storage account that supports Blob, Queue, and Table Storage is
  required.  When using a Consumption plan function definitions are
  stored in File Storage."

So my full code, that will create an App-Service-Plan, create a Storage Account, create an App-Service (that is azure functions/function app friendly) and match up the storage-account to the app-service is:

```<code>function SafeCreateAppServicePlan(
    [Parameter(Mandatory = $true)]
    [System.String]$location,
    [Parameter(Mandatory = $true)]
    [System.String]$resourceGroupName,
    [Parameter(Mandatory = $true)]
    [String]$appServicePlanName
)
{

    Write-Host "SafeCreateAppServicePlan.Parameter:location: $location"
    Write-Host "SafeCreateAppServicePlan.Parameter:resourceGroupName: $resourceGroupName"
    Write-Host "SafeCreateAppServicePlan.Parameter:appServicePlanName: $appServicePlanName"

    $SkuName = "Y1"
    $SkuTier = "Dynamic"
    $WebAppApiVersion = "2015-08-01"

    $fullObject = @{
        location = $location
        sku = @{
            name = $SkuName
            tier = $SkuTier
        }
    }

    Write-Host "Ensuring the $appServicePlanName app service plan exists"
    $plan = Get-AzureRmAppServicePlan -Name $appServicePlanName -ResourceGroupName $resourceGroupName -ErrorAction SilentlyContinue
    if(-not $plan) {
        Write-Host "Creating $appServicePlanName app service plan"
        New-AzureRmResource -ResourceGroupName $resourceGroupName -ResourceType Microsoft.Web/serverfarms -Name $appServicePlanName -IsFullObject -PropertyObject $fullObject -ApiVersion $WebAppApiVersion -Force
    }
    else {
        Write-Host "$appServicePlanName app service plan already exists"
    }

}

function SafeCreateAzureFunctionAppService(
    [Parameter(Mandatory = $true)]
    [System.String]$location,
    [Parameter(Mandatory = $true)]
    [System.String]$resourceGroupName,
    [Parameter(Mandatory = $true)]
    [String]$appServicePlanName,
    [Parameter(Mandatory = $true)]
    [String]$functionAppName
)
{

    Write-Host "SafeCreateAzureFunctionAppService.Parameter:location: $location"
    Write-Host "SafeCreateAzureFunctionAppService.Parameter:resourceGroupName: $resourceGroupName"
    Write-Host "SafeCreateAzureFunctionAppService.Parameter:appServicePlanName: $appServicePlanName"
    Write-Host "SafeCreateAzureFunctionAppService.Parameter:functionAppName: $functionAppName"

    [String]$planId = ''

    $plan = Get-AzureRmAppServicePlan -Name $appServicePlanName -ResourceGroupName $resourceGroupName -ErrorAction SilentlyContinue
    if(-not $plan) {
        throw [System.ArgumentOutOfRangeException] "Missing App Service Plan.  (ResourceGroupName='$resourceGroupName', AppServicePlan.Name = '$appServicePlanName')"
    }
    else {
        Write-Host "START AzureRmAppServicePlan Properties"
        $plan.PSObject.Properties
        Write-Host "END AzureRmAppServicePlan Properties"

        #get the planId, so that can be used as the backing-app-service-plan for this AppService
        [String]$planId = $plan.Id
    }

    #wire up the necessary properties for this AppService
    $props = @{
        ServerFarmId = $planId
        }

    $functionAppResource = Get-AzureRmResource | Where-Object { $_.ResourceName -eq $functionAppName -And $_.ResourceType -eq 'Microsoft.Web/Sites' }

    if ($functionAppResource -eq $null)
    {
        New-AzureRmResource -ResourceType 'Microsoft.Web/Sites' -ResourceName $functionAppName -kind 'functionapp' -Location $location -ResourceGroupName $resourceGroupName -Properties $props -force
    }

}

function SafeCreateStorageAccountToBackConsumptionAzureFunctions(
    [Parameter(Mandatory = $true)]
    [System.String]$location,
    [Parameter(Mandatory = $true)]
    [System.String]$resourceGroupName,
    [Parameter(Mandatory = $true)]
    [String]$storageAccountName
)
{

    Write-Host "SafeCreateStorageAccount.Parameter:location: $location"
    Write-Host "SafeCreateStorageAccount.Parameter:resourceGroupName: $resourceGroupName"
    Write-Host "SafeCreateStorageAccount.Parameter:storageAccountName: $storageAccountName"

    $azureRmStorageAccountGetCheck = Get-AzureRmStorageAccount -ResourceGroupName $resourceGroupName -AccountName $storageAccountName -ErrorAction SilentlyContinue

    if(-not $azureRmStorageAccountGetCheck)
    {
        New-AzureRmStorageAccount -ResourceGroupName $resourceGroupName -AccountName $storageAccountName -Location $location -SkuName 'Standard_LRS'
    }
    else
    {
        Write-Host "$storageAccountName storage account already exists"
    }
}

function MatchStorageSettingsToAppService(
    [Parameter(Mandatory = $true)]
    [System.String]$location,
    [Parameter(Mandatory = $true)]
    [System.String]$resourceGroupName,
    [Parameter(Mandatory = $true)]
    [String]$functionAppName,
    [Parameter(Mandatory = $true)]
    [String]$storageAccountName
)
{

    Write-Host "MatchStorageSettingsToAppService.Parameter:location: $location"
    Write-Host "MatchStorageSettingsToAppService.Parameter:resourceGroupName: $resourceGroupName"
    Write-Host "MatchStorageSettingsToAppService.Parameter:functionAppName: $functionAppName"
    Write-Host "MatchStorageSettingsToAppService.Parameter:storageAccountName: $storageAccountName"

    $keys = Get-AzureRmStorageAccountKey -ResourceGroupName $resourceGroupName -AccountName $storageAccountName

    $accountKey = $keys | Where-Object { $_.KeyName -eq "Key1" } | Select Value

    $storageAccountConnectionString = 'DefaultEndpointsProtocol=https;AccountName=' + $storageAccountName + ';AccountKey=' + $accountKey.Value

    $AppSettings = @{}

    $AppSettings = @{'AzureWebJobsDashboard' = $storageAccountConnectionString;

    'AzureWebJobsStorage' = $storageAccountConnectionString;

    'FUNCTIONS_EXTENSION_VERSION' = '~1';

    'WEBSITE_CONTENTAZUREFILECONNECTIONSTRING' = $storageAccountConnectionString;

    'WEBSITE_CONTENTSHARE' = $storageAccountName;

}

    Set-AzureRMWebApp -Name $functionAppName -ResourceGroupName $resourceGroupName -AppSettings $AppSettings

}
</code>```

I got a few hints from this ARM template as well:

https://github.com/Azure/azure-quickstart-templates/blob/master/101-function-app-create-dynamic/azuredeploy.json

ContentLicense: CC BY-SA 4.0

Body:
I found this answer for the question

Does anyone know how to create a Consumption app-service-plan with Azure?

When I look at the properties (using https://resources.azure.com/ ) of one I made (by the Gui), I see the following properties;

  },
  "sku": {
    "name": "Y1",
    "tier": "Dynamic",
    "size": "Y1",
    "family": "Y",
    "capacity": 0
  }

{
  "id": "/subscriptions/xxxxxxxxxxxxxxxxxxxxxxxx/resourceGroups/MyResourceGroup/providers/Microsoft.Web/serverfarms/MyHandMadeConsumptionAppServicePlan",
  "name": "MyHandMadeConsumptionAppServicePlan",
  "type": "Microsoft.Web/serverfarms",
  "kind": "functionapp",
  "location": "East US",

But if I try (the important part being "-Tier Dynamic")

$plan = New-AzureRmAppServicePlan -Name 'MyPowershellCreatedAppServicePlan' -ResourceGroupName 'MyResourceGroup' -Location 'PickALocation' -Tier Dynamic

I get the exception:

Exception -  + Cannot validate argument on parameter 'Tier'. The
argument "Dynamic" does not belong to the set
"Free,Shared,Basic,Standard,Premium,PremiumV2" specified by the
ValidateSet attribute. Supply an argument that is in the set and then
try the command again.

Body:
Geeze Louise.

This has been racking me for 3 days.  I finally found some help (urls I mention).

It looks like this cannot be accomplished (currently) with New-AzureRmAppServicePlan.

But you can fall back onto the more generic New-AzureRmResource.

The code I finally got to work:

function SafeCreateAppServicePlan(
    [Parameter(Mandatory = $true)]
    [System.String]$location,
    [Parameter(Mandatory = $true)]
    [System.String]$resourceGroupName,
    [Parameter(Mandatory = $true)]
    [String]$appServicePlanName
)
{

    Write-Host "SafeCreateAppServicePlan.Parameter:location: $location"
    Write-Host "SafeCreateAppServicePlan.Parameter:resourceGroupName: $resourceGroupName"
    Write-Host "SafeCreateAppServicePlan.Parameter:appServicePlanName: $appServicePlanName"

    $SkuName = "Y1"
    $SkuTier = "Dynamic"
    $WebAppApiVersion = "2015-08-01"

    $fullObject = @{
        location = $location
        sku = @{
            name = $SkuName
            tier = $SkuTier
        }
    }

    Write-Host "Ensuring the $appServicePlanName app service plan exists"
    $plan = Get-AzureRmAppServicePlan -Name $appServicePlanName -ResourceGroupName $resourceGroupName -ErrorAction SilentlyContinue
    if(-not $plan) {
        Write-Host "Creating $appServicePlanName app service plan"
        New-AzureRmResource -ResourceGroupName $resourceGroupName -ResourceType Microsoft.Web/serverfarms -Name $appServicePlanName -IsFullObject -PropertyObject $fullObject -ApiVersion $WebAppApiVersion -Force
    }
    else {
        Write-Host "$appServicePlanName app service plan already exists"
    }

}

The help I got:

https://github.com/davidebbo/AzureWebsitesSamples/blob/master/PowerShell/HelperFunctions.ps1

(search the url above for "SkuName" to find the magic lines.

Please note, this is only part of the overall equation to deploy the INFRASTRUCTURE for azure functions (if you are not using arm templates).  When I say the infrastructure, the code below does not deploy the azure-functions themselves, but the below will setup the infrastructure needed to do this.

This guy does a good job of explaining:

https://clouddeveloper.space/2017/10/26/deploy-azure-function-using-powershell/

"clouddeveloper" basically says that for consumption plan azure functions, you need to have a storage account.  This lines up with the "info" button you get when you manually add a Function-App via the azure portal.

"A storage account that supports Blob, Queue, and Table Storage is
  required.  When using a Consumption plan function definitions are
  stored in File Storage."

So my full code, that will create an App-Service-Plan, create a Storage Account, create an App-Service (that is azure functions/function app friendly) and match up the storage-account to the app-service is:

function SafeCreateAppServicePlan(
    [Parameter(Mandatory = $true)]
    [System.String]$location,
    [Parameter(Mandatory = $true)]
    [System.String]$resourceGroupName,
    [Parameter(Mandatory = $true)]
    [String]$appServicePlanName
)
{

    Write-Host "SafeCreateAppServicePlan.Parameter:location: $location"
    Write-Host "SafeCreateAppServicePlan.Parameter:resourceGroupName: $resourceGroupName"
    Write-Host "SafeCreateAppServicePlan.Parameter:appServicePlanName: $appServicePlanName"

    $SkuName = "Y1"
    $SkuTier = "Dynamic"
    $WebAppApiVersion = "2015-08-01"

    $fullObject = @{
        location = $location
        sku = @{
            name = $SkuName
            tier = $SkuTier
        }
    }

    Write-Host "Ensuring the $appServicePlanName app service plan exists"
    $plan = Get-AzureRmAppServicePlan -Name $appServicePlanName -ResourceGroupName $resourceGroupName -ErrorAction SilentlyContinue
    if(-not $plan) {
        Write-Host "Creating $appServicePlanName app service plan"
        New-AzureRmResource -ResourceGroupName $resourceGroupName -ResourceType Microsoft.Web/serverfarms -Name $appServicePlanName -IsFullObject -PropertyObject $fullObject -ApiVersion $WebAppApiVersion -Force
    }
    else {
        Write-Host "$appServicePlanName app service plan already exists"
    }

}

function SafeCreateAzureFunctionAppService(
    [Parameter(Mandatory = $true)]
    [System.String]$location,
    [Parameter(Mandatory = $true)]
    [System.String]$resourceGroupName,
    [Parameter(Mandatory = $true)]
    [String]$appServicePlanName,
    [Parameter(Mandatory = $true)]
    [String]$functionAppName
)
{

    Write-Host "SafeCreateAzureFunctionAppService.Parameter:location: $location"
    Write-Host "SafeCreateAzureFunctionAppService.Parameter:resourceGroupName: $resourceGroupName"
    Write-Host "SafeCreateAzureFunctionAppService.Parameter:appServicePlanName: $appServicePlanName"
    Write-Host "SafeCreateAzureFunctionAppService.Parameter:functionAppName: $functionAppName"

    [String]$planId = ''

    $plan = Get-AzureRmAppServicePlan -Name $appServicePlanName -ResourceGroupName $resourceGroupName -ErrorAction SilentlyContinue
    if(-not $plan) {
        throw [System.ArgumentOutOfRangeException] "Missing App Service Plan.  (ResourceGroupName='$resourceGroupName', AppServicePlan.Name = '$appServicePlanName')"
    }
    else {
        Write-Host "START AzureRmAppServicePlan Properties"
        $plan.PSObject.Properties
        Write-Host "END AzureRmAppServicePlan Properties"

        #get the planId, so that can be used as the backing-app-service-plan for this AppService
        [String]$planId = $plan.Id
    }

    #wire up the necessary properties for this AppService
    $props = @{
        ServerFarmId = $planId
        }

    $functionAppResource = Get-AzureRmResource | Where-Object { $_.ResourceName -eq $functionAppName -And $_.ResourceType -eq 'Microsoft.Web/Sites' }

    if ($functionAppResource -eq $null)
    {
        New-AzureRmResource -ResourceType 'Microsoft.Web/Sites' -ResourceName $functionAppName -kind 'functionapp' -Location $location -ResourceGroupName $resourceGroupName -Properties $props -force
    }

}

function SafeCreateStorageAccountToBackConsumptionAzureFunctions(
    [Parameter(Mandatory = $true)]
    [System.String]$location,
    [Parameter(Mandatory = $true)]
    [System.String]$resourceGroupName,
    [Parameter(Mandatory = $true)]
    [String]$storageAccountName
)
{

    Write-Host "SafeCreateStorageAccount.Parameter:location: $location"
    Write-Host "SafeCreateStorageAccount.Parameter:resourceGroupName: $resourceGroupName"
    Write-Host "SafeCreateStorageAccount.Parameter:storageAccountName: $storageAccountName"

    $azureRmStorageAccountGetCheck = Get-AzureRmStorageAccount -ResourceGroupName $resourceGroupName -AccountName $storageAccountName -ErrorAction SilentlyContinue

    if(-not $azureRmStorageAccountGetCheck)
    {
        New-AzureRmStorageAccount -ResourceGroupName $resourceGroupName -AccountName $storageAccountName -Location $location -SkuName 'Standard_LRS'
    }
    else
    {
        Write-Host "$storageAccountName storage account already exists"
    }
}

function MatchStorageSettingsToAppService(
    [Parameter(Mandatory = $true)]
    [System.String]$location,
    [Parameter(Mandatory = $true)]
    [System.String]$resourceGroupName,
    [Parameter(Mandatory = $true)]
    [String]$functionAppName,
    [Parameter(Mandatory = $true)]
    [String]$storageAccountName
)
{

    Write-Host "MatchStorageSettingsToAppService.Parameter:location: $location"
    Write-Host "MatchStorageSettingsToAppService.Parameter:resourceGroupName: $resourceGroupName"
    Write-Host "MatchStorageSettingsToAppService.Parameter:functionAppName: $functionAppName"
    Write-Host "MatchStorageSettingsToAppService.Parameter:storageAccountName: $storageAccountName"

    $keys = Get-AzureRmStorageAccountKey -ResourceGroupName $resourceGroupName -AccountName $storageAccountName

    $accountKey = $keys | Where-Object { $_.KeyName -eq "Key1" } | Select Value

    $storageAccountConnectionString = 'DefaultEndpointsProtocol=https;AccountName=' + $storageAccountName + ';AccountKey=' + $accountKey.Value

    $AppSettings = @{}

    $AppSettings = @{'AzureWebJobsDashboard' = $storageAccountConnectionString;

    'AzureWebJobsStorage' = $storageAccountConnectionString;

    'FUNCTIONS_EXTENSION_VERSION' = '~1';

    'WEBSITE_CONTENTAZUREFILECONNECTIONSTRING' = $storageAccountConnectionString;

    'WEBSITE_CONTENTSHARE' = $storageAccountName;

}

    Set-AzureRMWebApp -Name $functionAppName -ResourceGroupName $resourceGroupName -AppSettings $AppSettings

}

I got a few hints from this ARM template as well:

https://github.com/Azure/azure-quickstart-templates/blob/master/101-function-app-create-dynamic/azuredeploy.json

ContentLicense: CC BY-SA 3.0


问:
Convert grouped array elements from Pandas index into individual array elements in Python
I have a 1x100 1D array that looks like :

```<code>(A1,B1,C1,D1),(A2,B2,C2.D2),(A3,B3,C3,D3) ..... (A100,B100,C100,D100)
</code>```

I want to convert this array into a 4x100 2D array that looks like:

```<code>A1, B1, C1, D1
A2, B2, C2, D2
A3, B3, C3, D3
A4, B4, C4, D4

....

A100, B100, C100, D100
</code>```

I tried using Convert a 1D array to a 2D array in numpy to reshape the array, but that doesn't solve the problem of turning my grouped array elements into separate array elements.

EDIT

My dataset was created from a normal Pandas dataframe with 6 columns.

```<code>df = pd.pivot_table(concord, index = ['Col1','Col2','Col3', 'Col4'], columns
= 'Col5', values = 'Col6')
</code>```

This produces an index comprised of 4 columns on a dataframe with as many columns as rows in Col5. I then produce my grouped array with.

```<code>df.index.values
</code>```

Here is an example of what I am dealing with:

```<code>df = pd.DataFrame(np.random.randn(6,4),columns=list('ABCD'))
df = pd.pivot_table(df, index = ['A','B'], columns = 'C', values = 'D')
df.index.values
</code>```

Body:
I have a 1x100 1D array that looks like :

(A1,B1,C1,D1),(A2,B2,C2.D2),(A3,B3,C3,D3) ..... (A100,B100,C100,D100)

I want to convert this array into a 4x100 2D array that looks like:

A1, B1, C1, D1
A2, B2, C2, D2
A3, B3, C3, D3
A4, B4, C4, D4

....

A100, B100, C100, D100

I tried using Convert a 1D array to a 2D array in numpy to reshape the array, but that doesn't solve the problem of turning my grouped array elements into separate array elements.

EDIT

My dataset was created from a normal Pandas dataframe with 6 columns.

df = pd.pivot_table(concord, index = ['Col1','Col2','Col3', 'Col4'], columns
= 'Col5', values = 'Col6')

This produces an index comprised of 4 columns on a dataframe with as many columns as rows in Col5. I then produce my grouped array with.

df.index.values

Here is an example of what I am dealing with:

df = pd.DataFrame(np.random.randn(6,4),columns=list('ABCD'))
df = pd.pivot_table(df, index = ['A','B'], columns = 'C', values = 'D')
df.index.values

Body:
UPDATE:

In [156]: df.index.values
Out[156]:
array([(-1.1589142652108702, 0.9058310711560317), (-0.8998389109349003, -1.3963768690741623), (-0.39909436307375407, 0.19524579552938015), (
0.3879397588199493, -1.6231489531567047),
       (0.4850794016257364, 0.9079649929281776), (1.263583531683934, -0.8985146123002069)], dtype=object)

In [157]: np.array(df.index.values.tolist())
Out[157]:
array([[-1.15891427,  0.90583107],
       [-0.89983891, -1.39637687],
       [-0.39909436,  0.1952458 ],
       [ 0.38793976, -1.62314895],
       [ 0.4850794 ,  0.90796499],
       [ 1.26358353, -0.89851461]])

Old answer:

I think you want to use Pandas:

In [89]: a
Out[89]:
array([['A', 'B', '318443.998', '398601.13'],
       ['C', 'D', '318443.998', '398601.13']],
      dtype='<U10')

In [90]: df = pd.DataFrame(a)

In [91]: df
Out[91]:
   0  1           2          3
0  A  B  318443.998  398601.13
1  C  D  318443.998  398601.13


问:
VS2010 Web Load Testing with User Logins
I am looking to create a Web Performance test that can be bound to a CSV file with usernames and passwords so that I can run concurrent tests with different users. How do I modify a recorded WebTest in order to accomplish this?</p>

答: Have you checked out Walkthrough: Adding Data Binding to a Web Performance Test (CSV File)?</p>

ContentLicense: CC BY-SA 2.5


问:
"Could not resolve hostname" Ansible
I have created my first ansible playbook according to this tutorial, so it looks like this:

```<code>---
- hosts: hostb
  tasks:
      - name: Create file
        file:
            path: /tmp/yallo
            state: touch

- hosts: my_hosts
  sudo: yes
  tasks:
      - name: Create user
        user:
            name: mario
            shell: /bin/zsh

      - name: Install zlib
        yum:
            name: zlib
            state: latest
</code>```

However, I can not figure out which hosts I should put into my hosts file. I have something like this for now:

```<code>[my_hosts]
hostA
hostB
</code>```

Obviously, it is not working and I get this:

```<code>ssh: Could not resolve hostname hostb: Name or service not known
</code>```

So how should I change my hosts file? I am new to ansible so I would be very grateful for some help!

答:
Ok so the Ansible inventory can be based on following format:

HostName => IP Address

HostName => DHCP or Hosts file hostname reference localhost/cassie.local

Create your own alias => hostname ansible_host=IP Address

Group of hosts => [group_name]

That is the most basic structure you can use.

Example

```<code># Grouping
[test-group]

# IP reference
192.168.1.3

# Local hosts file reference
localhost

# Create your own alias
test ansible_host=192.168.1.4

# Create your alias with port and user to login as
test-2 ansible_host=192.168.1.5 ansible_port=1234 ansible_user=ubuntu
</code>```

Grouping of hosts will only end when the end of file or another group detected. So if you wish to have hosts that don't belong to a group, make sure they're defined above the group definition.

I.E. everything in the above example is belong to test-group, and if you do following; it will execute on all of the hosts:

ansible test-group -u ubuntu -m ping

Title: "Could not resolve hostname" Ansible

Body:
I have created my first ansible playbook according to this tutorial, so it looks like this:

---
- hosts: hostb
  tasks:
      - name: Create file
        file:
            path: /tmp/yallo
            state: touch

- hosts: my_hosts
  sudo: yes
  tasks:
      - name: Create user
        user:
            name: mario
            shell: /bin/zsh

      - name: Install zlib
        yum:
            name: zlib
            state: latest

However, I can not figure out which hosts I should put into my hosts file. I have something like this for now:

[my_hosts]
hostA
hostB

Obviously, it is not working and I get this:

ssh: Could not resolve hostname hostb: Name or service not known

So how should I change my hosts file? I am new to ansible so I would be very grateful for some help!

Body:
Ok so the Ansible inventory can be based on following format:

HostName => IP Address

HostName => DHCP or Hosts file hostname reference localhost/cassie.local

Create your own alias => hostname ansible_host=IP Address

Group of hosts => [group_name]

That is the most basic structure you can use.

Example

# Grouping
[test-group]

# IP reference
192.168.1.3

# Local hosts file reference
localhost

# Create your own alias
test ansible_host=192.168.1.4

# Create your alias with port and user to login as
test-2 ansible_host=192.168.1.5 ansible_port=1234 ansible_user=ubuntu

Grouping of hosts will only end when the end of file or another group detected. So if you wish to have hosts that don't belong to a group, make sure they're defined above the group definition.

I.E. everything in the above example is belong to test-group, and if you do following; it will execute on all of the hosts:

ansible test-group -u ubuntu -m ping


问:
.htaccess issue, folder in wordpress?
I have a folder called /mf/ that is not related to the wordpress install but it is in the same root folder. When I visit the folder path (www.domain.com/mf) it gives me a 500 error. I know that this is an .htaccess issue.

I've modded my root .htaccess to do the below code but it still does not work:

```<code> <IfModule mod_rewrite.c>
 RewriteEngine On
 RewriteBase /
 RewriteCond %{REQUEST_URI} ^/mf/(.*)$ [OR]
 RewriteRule ^.*$ - [L]
 </IfModule>

 # BEGIN WordPress
 <IfModule mod_rewrite.c>
 RewriteEngine On
 RewriteBase /
 RewriteRule ^index\.php$ - [L]
 RewriteCond %{REQUEST_FILENAME} !-f
 RewriteCond %{REQUEST_FILENAME} !-d
 RewriteRule . /index.php [L]
 </IfModule>
 # END WordPress
</code>```

Any advice on how to fix this .htaccess issue?

答:
in your "mf" folder create a .htaccess file and there put all the configuration that nedded, and in the main folder-wordpress put only the wordpress part.

in th "mf" change the RewriteBase too.

main-wordpress

```<code># BEGIN WordPress
 <IfModule mod_rewrite.c>
 RewriteEngine On
 RewriteBase /
 RewriteRule ^index\.php$ - [L]
 RewriteCond %{REQUEST_FILENAME} !-f
 RewriteCond %{REQUEST_FILENAME} !-d
 RewriteRule . /index.php [L]
 </IfModule>
 # END WordPress
</code>```

the mf folder

```<code><IfModule mod_rewrite.c>
 RewriteEngine On
 RewriteBase /mf/
 RewriteCond %{REQUEST_URI} ^/mf/(.*)$ [OR]
 RewriteRule ^.*$ - [L]
 </IfModule>
</code>```

Title: .htaccess issue, folder in wordpress?

Body:
I have a folder called /mf/ that is not related to the wordpress install but it is in the same root folder. When I visit the folder path (www.domain.com/mf) it gives me a 500 error. I know that this is an .htaccess issue.

I've modded my root .htaccess to do the below code but it still does not work:

 <IfModule mod_rewrite.c>
 RewriteEngine On
 RewriteBase /
 RewriteCond %{REQUEST_URI} ^/mf/(.*)$ [OR]
 RewriteRule ^.*$ - [L]
 </IfModule>

 # BEGIN WordPress
 <IfModule mod_rewrite.c>
 RewriteEngine On
 RewriteBase /
 RewriteRule ^index\.php$ - [L]
 RewriteCond %{REQUEST_FILENAME} !-f
 RewriteCond %{REQUEST_FILENAME} !-d
 RewriteRule . /index.php [L]
 </IfModule>
 # END WordPress

Any advice on how to fix this .htaccess issue?

Body:
in your "mf" folder create a .htaccess file and there put all the configuration that nedded, and in the main folder-wordpress put only the wordpress part.

in th "mf" change the RewriteBase too.

main-wordpress

# BEGIN WordPress
 <IfModule mod_rewrite.c>
 RewriteEngine On
 RewriteBase /
 RewriteRule ^index\.php$ - [L]
 RewriteCond %{REQUEST_FILENAME} !-f
 RewriteCond %{REQUEST_FILENAME} !-d
 RewriteRule . /index.php [L]
 </IfModule>
 # END WordPress

the mf folder

<IfModule mod_rewrite.c>
 RewriteEngine On
 RewriteBase /mf/
 RewriteCond %{REQUEST_URI} ^/mf/(.*)$ [OR]
 RewriteRule ^.*$ - [L]
 </IfModule>


问:
Meta Tags for FB share - do I need to use regular meta tags as well? what type to use for an html5 game?
I have a FB share link in a game I just published on a website, and don't really know the rules for meta tags on an html page. I have the og tags set up from looking at this document: https://developers.facebook.com/docs/sharing/webmasters/

Questions:

Do i also need regular meta tags - like description, keywords, etc?
Or if I use the fb tags, is that all that's needed?

Do meta tags take
a while to kick in? I set the og tags, and the FB share window still
shows old info

I have the type set up as "website" - is that the og
type I should use for an HTML5 game?

答:
Yes, you should also provide regular metatags

Refresh the tags in the debugger if the are not correct: https://developers.facebook.com/tools/debug/

There is no specific game tag, so "website" should be alright: http://ogp.me/


问:
how to download latest version of android sdk without android studio?
I don't need to android studio, i am developing my project in godot,  godot docs
refer to link to download android sdk, but i did not find any windows executable for standalone sdk on that page. </p>

答: in the official page of android this the sdk in optional downloads come in a zip just unzip them and in the options of androidstudio seleccionalos</p>


问:
Why my smart phone does not render Github page anymore?
I was fine to browse my Github page with my smart phone(iOS or Android), but somehow, I'm not sure what happened that I don't see anything in my smart phone anymore. At first, I thought it's the scale problem but I center pictures and some buttons so I should be able to them in the screen of smart phone. Does my Github page isn't rendered properly?

I use my laptop to browse the Github page, everything looks fine, but just not phone. I have to use mobile devices to access the Github page no matter what, unfortunately.

Here's the link to the page: GitHub page

This is the picture from my iPhone:

Below is my html5 code:

```<code><!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge, chrome=1">

<title>MindScribe</title>
<!--<meta name="description" content="An interactive getting started guide for Brackets.">-->

<!-- Maybe I need. Note that Android and iOS ignore media="handheld"-->
<link rel="stylesheet" media="handheld, only screen and (max-device-width: 320px)" href="phone.css">
<link rel="stylesheet" media="only screen and (min-width: 641px) and (max-width: 800px)" href="ipad.css">

<!-- media="handheld" trick for Windows Mobile -->
<link rel="stylesheet" href="screen.css" media="Screen">
<link rel="stylesheet" href="mobile.css" media="handheld">
<!-- sans serif-->
<!--smartphone conpatible-->
<!--    <meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0" />-->
<meta name="viewport" content="width=device-width,initial-scale=1,user-scalable=yes" />
<!--For iPhone    -->
<meta name="viewport" content="initial-scale=1, maximum-scale=1">

<!-- Home screen icon -->
<link rel="apple-touch-icon" href="/static/images/identity/HTML5_Badge_64.png" />
<link rel="apple-touch-icon-precomposed" href="/static/images/identity/HTML5_Badge_64.png" />

<!--[if lt IE 9]>
    <script src="//html5shiv.googlecode.com/svn/trunk/html5.js"></script>
    <![endif]-->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<link rel="stylesheet" href="css/main.css">
</head>

<body>

<div>
    <a href="javascript:location.reload(true)"><img src="image/MindScribe-cursive.png" id="cursive"></a>
</div>
<div id="container">
    <picture>
        <img src="image/MindScribe-zebra.png" id="ImageEnterVariables" alt="Hello, I'm Stripes">
        <img src="image/MindScribe-zebra2.png" id="onlyShowZebraImage" alt="Hello, I'm Stripes" style=display:none>
    </picture>
    <select id="languageSelection" style=display:none >
        <option value="" disabled selected >Please choose a language</option>
        <option value="1">English (American)</option>
        <option value="2">Chinese (Mandarin)</option>
        <option value="3">Japanese</option>
        <option value="4">Spanish</option>
    </select>
</div>
</div>
</body>
</code>```

答:
The problem is not only in your phone, if you resize the browser window to a size less or equal to 768 pixels then the rules you have in main.css for @media (max-width: 768px) kick in and the content disappear:

```<code>body {
    position: relative; /* REMOVE THIS RULE*/

    box-shadow: 0 0 2px rgba(0, 0, 0, 0.06);
    color: #545454;
    font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
    font-size: 16px;
    line-height: 1.5;
    max-width: 800px;
    bottom: 500px;

    box-sizing: border-box;
    overflow: hidden;
}
</code>```

The problem seems to be with the position:relative rule applied to the body, because it changes the page flow, remove it and the content should be visible also for max-width: 768px.

Body:
I was fine to browse my Github page with my smart phone(iOS or Android), but somehow, I'm not sure what happened that I don't see anything in my smart phone anymore. At first, I thought it's the scale problem but I center pictures and some buttons so I should be able to them in the screen of smart phone. Does my Github page isn't rendered properly?

I use my laptop to browse the Github page, everything looks fine, but just not phone. I have to use mobile devices to access the Github page no matter what, unfortunately.

Here's the link to the page: GitHub page

This is the picture from my iPhone:

Below is my html5 code:

<!DOCTYPE html>

<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge, chrome=1">

<title>MindScribe</title>

<link rel="stylesheet" media="handheld, only screen and (max-device-width: 320px)" href="phone.css">
<link rel="stylesheet" media="only screen and (min-width: 641px) and (max-width: 800px)" href="ipad.css">

<link rel="stylesheet" href="screen.css" media="Screen">
<link rel="stylesheet" href="mobile.css" media="handheld">

<meta name="viewport" content="width=device-width,initial-scale=1,user-scalable=yes" />

<meta name="viewport" content="initial-scale=1, maximum-scale=1">

<link rel="apple-touch-icon" href="/static/images/identity/HTML5_Badge_64.png" />
<link rel="apple-touch-icon-precomposed" href="/static/images/identity/HTML5_Badge_64.png" />

<link rel="stylesheet" href="css/main.css">

    <picture>

    </picture>
    <select id="languageSelection" style=display:none >
        <option value="" disabled selected >Please choose a language</option>
        <option value="1">English (American)</option>
        <option value="2">Chinese (Mandarin)</option>
        <option value="3">Japanese</option>
        <option value="4">Spanish</option>
    </select>

Body:
The problem is not only in your phone, if you resize the browser window to a size less or equal to 768 pixels then the rules you have in main.css for @media (max-width: 768px) kick in and the content disappear:

body {
    position: relative; /* REMOVE THIS RULE*/

    box-shadow: 0 0 2px rgba(0, 0, 0, 0.06);
    color: #545454;
    font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
    font-size: 16px;
    line-height: 1.5;
    max-width: 800px;
    bottom: 500px;

    box-sizing: border-box;
    overflow: hidden;
}

The problem seems to be with the position:relative rule applied to the body, because it changes the page flow, remove it and the content should be visible also for max-width: 768px.


问:
Recent modification to Twitter API?
I wrote a very simple C# application to send Tweets between to Windows machines.  To do this, each endpoint (ie this C#.NET desktop app that uses the TweetSharp library) has a timer, and when the Elapsed event fires all messages are gathered together with a GetDirectMessages() call, then these messages are parsed and processed by the endpoint.

My problem is that I built this over the course of a few hours two weeks ago and everything worked fine.  I dusted it off and executed a week ago as well, no problems.  Now, I break it out today and I am getting a very odd exception (see section EXCEPTION) that originate at the line "IEnumerable directMessage = service.ListDirectMessagesReceived();" (see section SOURCE).  My question is, since my code hasn't changed, is it possible that the API has (I know I know terribly unlikely).  Do any of the upstanding and erudite members of StackO have any thoughts?

Btw, I have checked and my ConsumerKey/Secret are valid, as is the cached OAuth access token that my authentication section uses.  It's odd because I can pull my list of followers, check my rate limiting stats, etc.  Also my NewtonSoft, Hammoch and TweetSharp references have not been updated/changed.

Thanks.

[SOURCE]

```<code>    private struct message
    {
        public long id;
        public string text;

        public message(long i, string t)
        {
            id = i;
            text = t;
        }
    }

    private MessageEngine
    {
        /* Do auth -- excised for obvious reasons */

        Timer timer = new Timer();
        timer.Interval = 15000;
        timer.Tick += new EventHandler(timer_Tick);
        timer.Start();
    }

    private List<message> GetDirectMessages()
    {
        try
        {
            //Declarations:
            message message = new message();
            List<message> messages = new List<message>();
/*line 344*/IEnumerable<TwitterDirectMessage> directMessages = service.ListDirectMessagesReceived();

            //Fetch all current direct message:
            foreach (TwitterDirectMessage directMessage in directMessages)
            {
                //Store each message into a list, in reverse older:
                message = new message(directMessage.Id, directMessage.Text);
                messages.Insert(0, message);
            }

            return messages;
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.ToString());
            return null;
        }
    }

    private void timer_Tick(object sender, EventArgs e)
    {
        try
        {
            List<message> messages = GetDirectMessages();
            LocalExecute(messages);
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.ToString());
        }
    }

    private bool LocalExecute(List<message> messages)
    {
        /* process messages */
    }
</code>```

[EXCEPTION]

```<code>Newtonsoft.Json.JsonSerializationException: Cannot deserialize JSON array into type 'TweetSharp.TwitterDirectMessage'.
   at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.EnsureArrayContract(Type objectType, JsonContract contract) in d:\Development\Releases\Json\Working\Src\Newtonsoft.Json\Serialization\JsonSerializerInternalReader.cs:line 412
   at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateList(JsonReader reader, Type objectType, JsonContract contract, JsonProperty member, Object existingValue, String reference) in d:\Development\Releases\Json\Working\Src\Newtonsoft.Json\Serialization\JsonSerializerInternalReader.cs:line 432
   at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateValueInternal(JsonReader reader, Type objectType, JsonContract contract, JsonProperty member, Object existingValue) in d:\Development\Releases\Json\Working\Src\Newtonsoft.Json\Serialization\JsonSerializerInternalReader.cs:line 222
   at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateValueNonProperty(JsonReader reader, Type objectType, JsonContract contract) in d:\Development\Releases\Json\Working\Src\Newtonsoft.Json\Serialization\JsonSerializerInternalReader.cs:line 205
   at TweetSharp.Serialization.SerializerBase.DeserializeJson(String content, Type type) in C:\Users\Dimebrain\Desktop\Src\tweetsharp\src\vs2010\TweetSharp.Next\Serialization\SerializerBase.cs:line 60
   at TweetSharp.Serialization.JsonSerializer.AddDeserializedItem(String c, Type type, IList collection) in C:\Users\Dimebrain\Desktop\Src\tweetsharp\src\vs2010\TweetSharp.Next\Serialization\JsonSerializer.cs:line 131
   at TweetSharp.Serialization.JsonSerializer.DeserializeCollection[T](String content) in C:\Users\Dimebrain\Desktop\Src\tweetsharp\src\vs2010\TweetSharp.Next\Serialization\JsonSerializer.cs:line 90
   at TweetSharp.Serialization.JsonSerializer.Deserialize[T](String content) in C:\Users\Dimebrain\Desktop\Src\tweetsharp\src\vs2010\TweetSharp.Next\Serialization\JsonSerializer.cs:line 17
   at Hammock.RestClient.DeserializeEntityBody[T](RestBase request, RestResponse`1 response) in C:\Users\Dimebrain\Desktop\Src\hammock\src\net35\Hammock\RestClient.cs:line 2285
   at Hammock.RestClient.BuildResponseFromResult[T](RestBase request, WebQuery query) in C:\Users\Dimebrain\Desktop\Src\hammock\src\net35\Hammock\RestClient.cs:line 2212
   at Hammock.RestClient.Request[T](RestRequest request) in C:\Users\Dimebrain\Desktop\Src\hammock\src\net35\Hammock\RestClient.cs:line 107
   at TweetSharp.TwitterService.WithHammockImpl[T](RestRequest request) in C:\Users\Dimebrain\Desktop\Src\tweetsharp\src\vs2010\TweetSharp.Next\Service\TwitterService.cs:line 401
   at TweetSharp.TwitterService.WithHammock[T](String path) in C:\Users\Dimebrain\Desktop\Src\tweetsharp\src\vs2010\TweetSharp.Next\Service\TwitterService.cs:line 378
   at TweetSharp.TwitterService.WithHammock[T](String path, Object[] segments) in C:\Users\Dimebrain\Desktop\Src\tweetsharp\src\vs2010\TweetSharp.Next\Service\TwitterService.cs:line 383
   at TweetSharp_Test.Form1.GetDirectMessages() in C:\Users\kmarks2\Documents\Visual Studio 2008\Projects\TweetSharp_Test\TweetSharp_Test\Form1.cs:line 344
</code>```

答:
As i can see from stack trace the TweetSharp.TwitterDirectMessage class schema is different from what was expected by Deserializer, may be the Json data passed has changed from last time you checked.

Also I think the Tweetsharp had some issue related to this.

As i checked in changeset on codeplex there was a change to Fix direct messages with IDs using fluent.

Check it out here.

http://tweetsharp.codeplex.com/SourceControl/changeset/changes/8bf46a5230bc

Try downloading new TweetSharp v2.0.0.0 - Preview 9

Title: Recent modification to Twitter API?

Body:
I wrote a very simple C# application to send Tweets between to Windows machines.  To do this, each endpoint (ie this C#.NET desktop app that uses the TweetSharp library) has a timer, and when the Elapsed event fires all messages are gathered together with a GetDirectMessages() call, then these messages are parsed and processed by the endpoint.

My problem is that I built this over the course of a few hours two weeks ago and everything worked fine.  I dusted it off and executed a week ago as well, no problems.  Now, I break it out today and I am getting a very odd exception (see section EXCEPTION) that originate at the line "IEnumerable directMessage = service.ListDirectMessagesReceived();" (see section SOURCE).  My question is, since my code hasn't changed, is it possible that the API has (I know I know terribly unlikely).  Do any of the upstanding and erudite members of StackO have any thoughts?

Btw, I have checked and my ConsumerKey/Secret are valid, as is the cached OAuth access token that my authentication section uses.  It's odd because I can pull my list of followers, check my rate limiting stats, etc.  Also my NewtonSoft, Hammoch and TweetSharp references have not been updated/changed.

Thanks.

[SOURCE]

    private struct message
    {
        public long id;
        public string text;

        public message(long i, string t)
        {
            id = i;
            text = t;
        }
    }

    private MessageEngine
    {
        /* Do auth -- excised for obvious reasons */

        Timer timer = new Timer();
        timer.Interval = 15000;
        timer.Tick += new EventHandler(timer_Tick);
        timer.Start();
    }

    private List<message> GetDirectMessages()
    {
        try
        {
            //Declarations:
            message message = new message();
            List<message> messages = new List<message>();
/*line 344*/IEnumerable<TwitterDirectMessage> directMessages = service.ListDirectMessagesReceived();

            //Fetch all current direct message:
            foreach (TwitterDirectMessage directMessage in directMessages)
            {
                //Store each message into a list, in reverse older:
                message = new message(directMessage.Id, directMessage.Text);
                messages.Insert(0, message);
            }

            return messages;
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.ToString());
            return null;
        }
    }

    private void timer_Tick(object sender, EventArgs e)
    {
        try
        {
            List<message> messages = GetDirectMessages();
            LocalExecute(messages);
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.ToString());
        }
    }

    private bool LocalExecute(List<message> messages)
    {
        /* process messages */
    }

[EXCEPTION]

Newtonsoft.Json.JsonSerializationException: Cannot deserialize JSON array into type 'TweetSharp.TwitterDirectMessage'.
   at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.EnsureArrayContract(Type objectType, JsonContract contract) in d:\Development\Releases\Json\Working\Src\Newtonsoft.Json\Serialization\JsonSerializerInternalReader.cs:line 412
   at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateList(JsonReader reader, Type objectType, JsonContract contract, JsonProperty member, Object existingValue, String reference) in d:\Development\Releases\Json\Working\Src\Newtonsoft.Json\Serialization\JsonSerializerInternalReader.cs:line 432
   at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateValueInternal(JsonReader reader, Type objectType, JsonContract contract, JsonProperty member, Object existingValue) in d:\Development\Releases\Json\Working\Src\Newtonsoft.Json\Serialization\JsonSerializerInternalReader.cs:line 222
   at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateValueNonProperty(JsonReader reader, Type objectType, JsonContract contract) in d:\Development\Releases\Json\Working\Src\Newtonsoft.Json\Serialization\JsonSerializerInternalReader.cs:line 205
   at TweetSharp.Serialization.SerializerBase.DeserializeJson(String content, Type type) in C:\Users\Dimebrain\Desktop\Src\tweetsharp\src\vs2010\TweetSharp.Next\Serialization\SerializerBase.cs:line 60
   at TweetSharp.Serialization.JsonSerializer.AddDeserializedItem(String c, Type type, IList collection) in C:\Users\Dimebrain\Desktop\Src\tweetsharp\src\vs2010\TweetSharp.Next\Serialization\JsonSerializer.cs:line 131
   at TweetSharp.Serialization.JsonSerializer.DeserializeCollection[T](String content) in C:\Users\Dimebrain\Desktop\Src\tweetsharp\src\vs2010\TweetSharp.Next\Serialization\JsonSerializer.cs:line 90
   at TweetSharp.Serialization.JsonSerializer.Deserialize[T](String content) in C:\Users\Dimebrain\Desktop\Src\tweetsharp\src\vs2010\TweetSharp.Next\Serialization\JsonSerializer.cs:line 17
   at Hammock.RestClient.DeserializeEntityBody[T](RestBase request, RestResponse`1 response) in C:\Users\Dimebrain\Desktop\Src\hammock\src\net35\Hammock\RestClient.cs:line 2285
   at Hammock.RestClient.BuildResponseFromResult[T](RestBase request, WebQuery query) in C:\Users\Dimebrain\Desktop\Src\hammock\src\net35\Hammock\RestClient.cs:line 2212
   at Hammock.RestClient.Request[T](RestRequest request) in C:\Users\Dimebrain\Desktop\Src\hammock\src\net35\Hammock\RestClient.cs:line 107
   at TweetSharp.TwitterService.WithHammockImpl[T](RestRequest request) in C:\Users\Dimebrain\Desktop\Src\tweetsharp\src\vs2010\TweetSharp.Next\Service\TwitterService.cs:line 401
   at TweetSharp.TwitterService.WithHammock[T](String path) in C:\Users\Dimebrain\Desktop\Src\tweetsharp\src\vs2010\TweetSharp.Next\Service\TwitterService.cs:line 378
   at TweetSharp.TwitterService.WithHammock[T](String path, Object[] segments) in C:\Users\Dimebrain\Desktop\Src\tweetsharp\src\vs2010\TweetSharp.Next\Service\TwitterService.cs:line 383
   at TweetSharp_Test.Form1.GetDirectMessages() in C:\Users\kmarks2\Documents\Visual Studio 2008\Projects\TweetSharp_Test\TweetSharp_Test\Form1.cs:line 344


问:
Accesing TabLayout's Fragment within the activity
I'm trying to access the fragment's tag within the activity to perform some logic in that particular fragment by triggering one method(refreshData).Since the fragment comes under Tablayout, i'm fully stuck on how to access the fragment under my activity.
The following is the code snippet:

```<code>   private void updateFragment(Intent intent){
        FragmentManager manager = getSupportFragmentManager();
        for (int i = 0; i < manager.getBackStackEntryCount(); i++) {
            if (MyFragment.class.getName().equalsIgnoreCase(manager.getBackStackEntryAt(i).getName())) {
                MyFragment currentFragment = (MyFragment)manager.findFragmentByTag(manager.getBackStackEntryAt(i).getName());
                currentFragment.refreshData(intent);
                break;
            }
        }
    }
</code>```

The following way I'm creating two fragment under TabLayout

```<code> @Override
        public Fragment getItem(int position) {
            switch (position) {
                case 0:
                    MyFragment newsFragment = new MyFragment();

                    return newsFragment;

                case 1:
                    return new MySecondFragment();
            }
            return null;
        }
</code>```

答:
You should create only one object of each fragments, like

```<code>MyFragemnt newsFragment;
MySecondFragment secondFragemnt;
@Override
public Fragment getItem(int position) {
   switch (position) {
     case 0:
       if(newsFragment == null)
           newsFragment = new MyFragment();
       return newsFragment;
     case 1:
       if(secondFragemnt== null)
           secondFragemnt= new MySecondFragment();
       return secondFragemnt;
      }
    return null;
}
</code>```

Then based on position of your adapter, you can access the refreshData() of those fragment.

```<code>Fragment activeFragment = adapter.getItem(pos);
if(pos == 0)
    ((MyFragment)activeFragment).refreshData(...);
</code>```

Hope this will help.

Body:
I'm trying to access the fragment's tag within the activity to perform some logic in that particular fragment by triggering one method(refreshData).Since the fragment comes under Tablayout, i'm fully stuck on how to access the fragment under my activity.
The following is the code snippet:

   private void updateFragment(Intent intent){
        FragmentManager manager = getSupportFragmentManager();
        for (int i = 0; i < manager.getBackStackEntryCount(); i++) {
            if (MyFragment.class.getName().equalsIgnoreCase(manager.getBackStackEntryAt(i).getName())) {
                MyFragment currentFragment = (MyFragment)manager.findFragmentByTag(manager.getBackStackEntryAt(i).getName());
                currentFragment.refreshData(intent);
                break;
            }
        }
    }

The following way I'm creating two fragment under TabLayout

 @Override
        public Fragment getItem(int position) {
            switch (position) {
                case 0:
                    MyFragment newsFragment = new MyFragment();

                    return newsFragment;

                case 1:
                    return new MySecondFragment();
            }
            return null;
        }

Body:
You should create only one object of each fragments, like

MyFragemnt newsFragment;
MySecondFragment secondFragemnt;
@Override
public Fragment getItem(int position) {
   switch (position) {
     case 0:
       if(newsFragment == null)
           newsFragment = new MyFragment();
       return newsFragment;
     case 1:
       if(secondFragemnt== null)
           secondFragemnt= new MySecondFragment();
       return secondFragemnt;
      }
    return null;
}

Then based on position of your adapter, you can access the refreshData() of those fragment.

Fragment activeFragment = adapter.getItem(pos);
if(pos == 0)
    ((MyFragment)activeFragment).refreshData(...);

Hope this will help.


问:
ORA-01422: exact fetch returns more than requested number of rows ORA-06512: at "LPR_PROD.MPKG_LPKREPORT", line 21
I am trying to execute the below query in oracle and i am getting the ORA-01422 error. Below is the query i am using to accomplish my results. This query is a part of Package.

```<code>Select DISTINCT TO_CHAR(RHR.d_end_of_month_s,'MM/dd/yyyy') "Disbursal Date",
RST.st_nam_s "State Name", MLO_COUNTY.loc_nam_s "County Name",RHR.d_pmtdu_s,
MLO_CITY.loc_nam_s "City Name", RHR.recip_s "Original GeoCode",
RHR.lse_s "Lease Number",RHR.unit_lse_s "Asset Number",
REQ.bk_acct_s "Contract Type", REQ.eqt_stat_s "Asset Status",
TO_CHAR(REQ.d_disp_s,'MM/dd/yyyy') "Asset Disposition Date",
RHR.p_st_rat_d "State Rate",(RHR.p_ct_rat_d-RHR.p_ct_trnst_rat_d) "County Rate",
RHR.p_ct_trnst_rat_d "County Transit Rate",
RHR.p_cy_rat_d -RHR.p_cy_trnst_rat_d) "City Rate",
RHR.p_cy_trnst_rat_d "City Transit rate",
RHR.p_st_rat_d +RHR.p_ct_rat_d+RHR.p_cy_rat_d) "Combined Rate",
RHR.nontax_gross_d+RHR.gross_d) "Gross Invoice Billed",
CASE WHEN trim(RHR.lse_s)='UPF STAX' THEN
mpkg_lpkreport.GROSSTAX(trim(RHR.UNIT_LSE_S),RHR.d_end_of_month_s,
trim(RHR.LSE_S),RHR.p_ct_rat_d) ELSE RHR.gross_d END "Taxable Invoice Billed",
mpkg_lpkreport.NCALACCUREDTAXVALUE(RHR.UNIT_LSE_S,0,TO_CHAR(RHR.d_end_of_month_s,'MM/dd/yyyy'),
RHR.LSE_S,TO_CHAR(RHR.d_pmtdu_s,'MM/dd/yyyy'),RHR.p_ct_rat_d) "Accrued State Tax",
mpkg_lpkreport.NCALACCUREDTAXVALUE(RHR.UNIT_LSE_S,1,TO_CHAR(RHR.d_end_of_month_s,'MM/dd/yyyy'),
RHR.LSE_S,TO_CHAR(RHR.d_pmtdu_s,'MM/dd/yyyy'),RHR.p_ct_rat_d ) "Accrued County Tax",
mpkg_lpkreport.NCALACCUREDTAXVALUE(RHR.UNIT_LSE_S,2,TO_CHAR(RHR.d_end_of_month_s,'MM/dd/yyyy'),
RHR.LSE_S,TO_CHAR(RHR.d_pmtdu_s,'MM/dd/yyyy'),RHR.p_ct_rat_d) "Accrued City Tax",
mpkg_lpkreport.NCALACCUREDDISTRICTTAX(RHR.UNIT_LSE_S,1,TO_CHAR(RHR.d_end_of_month_s,'MM/dd/yyyy'),
RHR.LSE_S,TO_CHAR(RHR.d_pmtdu_s,'MM/dd/yyyy')) "Accrued County District Tax",
mpkg_lpkreport.NCALACCUREDDISTRICTTAX(RHR.UNIT_LSE_S,2,TO_CHAR(RHR.d_end_of_month_s,'MM/dd/yyyy'),
RHR.LSE_S,TO_CHAR(RHR.d_pmtdu_s,'MM/dd/yyyy')) "Accrued City District Tax",
TO_CHAR(RLS.d_com_s,'MM/dd/yyyy') "Lease commencement date",
REQ.txp_s "Tax payment code",
replace((State_Geocodes.geo_st_l || substr(RHR.recip_s,3,length(recip_s))),'','')
"Translated GeoCode"
from   RHR
Inner join REQ on REQ.unit_s =RHR.unit_lse_s
and rhr.use_tax_c = case when REQ.txp_s in ('CNTY','CNCI' ) then '1'  when  REQ.txp_s = 'CITY' then
'2' else '0' end
Inner join RLS on RLS.lse_s = REQ.lse_s
Inner join RST on REQ.st_s =RST.st_s
Inner join MLO_COUNTY on MLO_COUNTY.ct_s =REQ.ct_s and MLO_COUNTY.st_s =REQ.st_s
Inner join MLO_CITY on MLO_CITY.cy_s =REQ.cy_s AND MLO_CITY.ct_s =REQ.ct_s
AND MLO_CITY.st_s =REQ.st_s
Inner join State_Geocodes on State_Geocodes.ST_S=substr(RHR.recip_s,1,2)
Where 1=1 and rhr.por_s =' 1' and rhr.d_end_of_month_s = '30-NOV-2017';
</code>```

Is there anything i missed in the query?

Below is the function that has been used in the query mpkg_lpkreport.GROSSTAX. It is showing the error in this function and i am not sure what issue is in this.

```<code>FUNCTION GROSSTAX(sunit_lse_s varchar2,
sd_end_of_month_s date, slse_s varchar2, rat_d FLOAT) return FLOAT
AS
n_grossd FLOAT;
BEGIN
BEGIN
select nvl(gross_d,0) into n_grossd      from RHR
where trim(RHR.lse_s)=slse_s and trim(RHR.unit_lse_s)=sunit_lse_s
and RHR.use_tax_c IN ('0') and RHR.d_end_of_month_s=sd_end_of_month_s
and  RHR.P_CT_RAT_D=rat_d;
EXCEPTION
WHEN NO_DATA_FOUND THEN
n_grossd := 0;
END;
IF n_grossd = 0 THEN
BEGIN
select nvl(gross_d,0) into n_grossd      from RHR
where trim(RHR.lse_s)=slse_s and trim(RHR.unit_lse_s)=sunit_lse_s
and RHR.use_tax_c IN ('1') and RHR.d_end_of_month_s=sd_end_of_month_s
and  RHR.P_CT_RAT_D=rat_d;
EXCEPTION
WHEN NO_DATA_FOUND THEN
n_grossd := 0;
END;
END IF;
IF n_grossd = 0 THEN
BEGIN
select nvl(gross_d,0) into n_grossd      from RHR
where trim(RHR.lse_s)=slse_s and trim(RHR.unit_lse_s)=sunit_lse_s
and RHR.use_tax_c IN ('2') and RHR.d_end_of_month_s=sd_end_of_month_s
and  RHR.P_CT_RAT_D=rat_d ;
EXCEPTION
WHEN NO_DATA_FOUND THEN
n_grossd := 0;
END;
END IF;
return n_grossd;
END GROSSTAX;
</code>```

答:
Please try to debug you query commenting line by line all calls of that functions.
For instance, this piece of code from your function can return >1 recs
 select nvl(gross_d, 0)
      into n_grossd
      from RHR
     where trim(RHR.lse_s) = slse_s
       and trim(RHR.unit_lse_s) = sunit_lse_s
       and RHR.use_tax_c IN ('0')
       and RHR.d_end_of_month_s = sd_end_of_month_s
       and RHR.P_CT_RAT_D = rat_d;</p>

Body:
I am trying to execute the below query in oracle and i am getting the ORA-01422 error. Below is the query i am using to accomplish my results. This query is a part of Package.

Select DISTINCT TO_CHAR(RHR.d_end_of_month_s,'MM/dd/yyyy') "Disbursal Date",
RST.st_nam_s "State Name", MLO_COUNTY.loc_nam_s "County Name",RHR.d_pmtdu_s,
MLO_CITY.loc_nam_s "City Name", RHR.recip_s "Original GeoCode",
RHR.lse_s "Lease Number",RHR.unit_lse_s "Asset Number",
REQ.bk_acct_s "Contract Type", REQ.eqt_stat_s "Asset Status",
TO_CHAR(REQ.d_disp_s,'MM/dd/yyyy') "Asset Disposition Date",
RHR.p_st_rat_d "State Rate",(RHR.p_ct_rat_d-RHR.p_ct_trnst_rat_d) "County Rate",
RHR.p_ct_trnst_rat_d "County Transit Rate",
RHR.p_cy_rat_d -RHR.p_cy_trnst_rat_d) "City Rate",
RHR.p_cy_trnst_rat_d "City Transit rate",
RHR.p_st_rat_d +RHR.p_ct_rat_d+RHR.p_cy_rat_d) "Combined Rate",
RHR.nontax_gross_d+RHR.gross_d) "Gross Invoice Billed",
CASE WHEN trim(RHR.lse_s)='UPF STAX' THEN
mpkg_lpkreport.GROSSTAX(trim(RHR.UNIT_LSE_S),RHR.d_end_of_month_s,
trim(RHR.LSE_S),RHR.p_ct_rat_d) ELSE RHR.gross_d END "Taxable Invoice Billed",
mpkg_lpkreport.NCALACCUREDTAXVALUE(RHR.UNIT_LSE_S,0,TO_CHAR(RHR.d_end_of_month_s,'MM/dd/yyyy'),
RHR.LSE_S,TO_CHAR(RHR.d_pmtdu_s,'MM/dd/yyyy'),RHR.p_ct_rat_d) "Accrued State Tax",
mpkg_lpkreport.NCALACCUREDTAXVALUE(RHR.UNIT_LSE_S,1,TO_CHAR(RHR.d_end_of_month_s,'MM/dd/yyyy'),
RHR.LSE_S,TO_CHAR(RHR.d_pmtdu_s,'MM/dd/yyyy'),RHR.p_ct_rat_d ) "Accrued County Tax",
mpkg_lpkreport.NCALACCUREDTAXVALUE(RHR.UNIT_LSE_S,2,TO_CHAR(RHR.d_end_of_month_s,'MM/dd/yyyy'),
RHR.LSE_S,TO_CHAR(RHR.d_pmtdu_s,'MM/dd/yyyy'),RHR.p_ct_rat_d) "Accrued City Tax",
mpkg_lpkreport.NCALACCUREDDISTRICTTAX(RHR.UNIT_LSE_S,1,TO_CHAR(RHR.d_end_of_month_s,'MM/dd/yyyy'),
RHR.LSE_S,TO_CHAR(RHR.d_pmtdu_s,'MM/dd/yyyy')) "Accrued County District Tax",
mpkg_lpkreport.NCALACCUREDDISTRICTTAX(RHR.UNIT_LSE_S,2,TO_CHAR(RHR.d_end_of_month_s,'MM/dd/yyyy'),
RHR.LSE_S,TO_CHAR(RHR.d_pmtdu_s,'MM/dd/yyyy')) "Accrued City District Tax",
TO_CHAR(RLS.d_com_s,'MM/dd/yyyy') "Lease commencement date",
REQ.txp_s "Tax payment code",
replace((State_Geocodes.geo_st_l || substr(RHR.recip_s,3,length(recip_s))),'','')
"Translated GeoCode"
from   RHR
Inner join REQ on REQ.unit_s =RHR.unit_lse_s
and rhr.use_tax_c = case when REQ.txp_s in ('CNTY','CNCI' ) then '1'  when  REQ.txp_s = 'CITY' then
'2' else '0' end
Inner join RLS on RLS.lse_s = REQ.lse_s
Inner join RST on REQ.st_s =RST.st_s
Inner join MLO_COUNTY on MLO_COUNTY.ct_s =REQ.ct_s and MLO_COUNTY.st_s =REQ.st_s
Inner join MLO_CITY on MLO_CITY.cy_s =REQ.cy_s AND MLO_CITY.ct_s =REQ.ct_s
AND MLO_CITY.st_s =REQ.st_s
Inner join State_Geocodes on State_Geocodes.ST_S=substr(RHR.recip_s,1,2)
Where 1=1 and rhr.por_s =' 1' and rhr.d_end_of_month_s = '30-NOV-2017';

Is there anything i missed in the query?

Below is the function that has been used in the query mpkg_lpkreport.GROSSTAX. It is showing the error in this function and i am not sure what issue is in this.

FUNCTION GROSSTAX(sunit_lse_s varchar2,
sd_end_of_month_s date, slse_s varchar2, rat_d FLOAT) return FLOAT
AS
n_grossd FLOAT;
BEGIN
BEGIN
select nvl(gross_d,0) into n_grossd      from RHR
where trim(RHR.lse_s)=slse_s and trim(RHR.unit_lse_s)=sunit_lse_s
and RHR.use_tax_c IN ('0') and RHR.d_end_of_month_s=sd_end_of_month_s
and  RHR.P_CT_RAT_D=rat_d;
EXCEPTION
WHEN NO_DATA_FOUND THEN
n_grossd := 0;
END;
IF n_grossd = 0 THEN
BEGIN
select nvl(gross_d,0) into n_grossd      from RHR
where trim(RHR.lse_s)=slse_s and trim(RHR.unit_lse_s)=sunit_lse_s
and RHR.use_tax_c IN ('1') and RHR.d_end_of_month_s=sd_end_of_month_s
and  RHR.P_CT_RAT_D=rat_d;
EXCEPTION
WHEN NO_DATA_FOUND THEN
n_grossd := 0;
END;
END IF;
IF n_grossd = 0 THEN
BEGIN
select nvl(gross_d,0) into n_grossd      from RHR
where trim(RHR.lse_s)=slse_s and trim(RHR.unit_lse_s)=sunit_lse_s
and RHR.use_tax_c IN ('2') and RHR.d_end_of_month_s=sd_end_of_month_s
and  RHR.P_CT_RAT_D=rat_d ;
EXCEPTION
WHEN NO_DATA_FOUND THEN
n_grossd := 0;
END;
END IF;
return n_grossd;
END GROSSTAX;


问:
'WSGIRequest' object has no attribute 'some_attribute'
I am trying to render html to pdf and include it as a django action, however, for some odd reason, I seem to keep getting the issue that the object has no attribute 'some_attribute'.

My view looks like this:

```<code>class CreatePdf(ContextMixin, View):
    def get_context_data(self, obj, request):
        cxt = {'some_attribute': obj.some_attribute,
                'today': date.today()}
        return cxt

    def create_pdf(self, some_template, some_dict={}):
        template = get_template(some_template)
        html  = template.render(some_dict)
        result = BytesIO()
        pdf = pisa.pisaDocument(BytesIO(html.encode("ISO-8859-1")), result)
        if not pdf.err:
            return HttpResponse(result.getvalue())
        return None
</code>```

And the action, which had the purpose to call everything and do all the magic, looks like this:

```<code>def get_pdf(self, obj, request):
    pdf_view = views.CreatePdf()
    pdf = pdf_view.create_pdf('templates/some_template.html', pdf_view.get_context_data(obj,request))
    return HttpResponse(pdf)
</code>```

I thought, that using get_context_data will get the fields of the selected object in the admin field, however, it seems to through me the same error.

Last, but not least, in my admin.py I have:

```<code>class MyAdmin(admin.ModelAdmin):
    actions = [get_pdf]
</code>```

答:
There are several errors here.

The main one is that the signature of a ModelAdmin action method is not self, obj, request but self, request, queryset. So you are passing the request in the wrong position, which explains why Django is saying that it is the request that lacks the error.

Note also that the final parameter is a queryset, not an object. This is because an admin action is called on all the items that have the checkbox selected. So, you need to iterate through the queryset and do something with each item. I'm not sure how you will want that to work when your action is creating querysets; it may well be that actions are not what you want here.

Currently, CreatePdf is not actually a view, so I don't know why you are inheriting from view classes; it would work just as well inheriting directly from object. However, the alternative is to make it an actual view, registered via the get_urls() method.

Body:
I am trying to render html to pdf and include it as a django action, however, for some odd reason, I seem to keep getting the issue that the object has no attribute 'some_attribute'.

My view looks like this:

class CreatePdf(ContextMixin, View):
    def get_context_data(self, obj, request):
        cxt = {'some_attribute': obj.some_attribute,
                'today': date.today()}
        return cxt

    def create_pdf(self, some_template, some_dict={}):
        template = get_template(some_template)
        html  = template.render(some_dict)
        result = BytesIO()
        pdf = pisa.pisaDocument(BytesIO(html.encode("ISO-8859-1")), result)
        if not pdf.err:
            return HttpResponse(result.getvalue())
        return None

And the action, which had the purpose to call everything and do all the magic, looks like this:

def get_pdf(self, obj, request):
    pdf_view = views.CreatePdf()
    pdf = pdf_view.create_pdf('templates/some_template.html', pdf_view.get_context_data(obj,request))
    return HttpResponse(pdf)

I thought, that using get_context_data will get the fields of the selected object in the admin field, however, it seems to through me the same error.

Last, but not least, in my admin.py I have:

class MyAdmin(admin.ModelAdmin):
    actions = [get_pdf]


问:
How can I get useful error messages in PHP?
Quite often I will try and run a PHP script and just get a blank screen back. No error message; just an empty screen. The cause might have been a simple syntax error (wrong bracket, missing semicolon), or a failed function call, or something else entirely.

It is very difficult to figure out what went wrong. I end up commenting out code, entering "echo" statements everywhere, etc. trying to narrow down the problem. But there surely must be a better way, right?

Is there a way to get PHP to produce a useful error message, like Java does?

答:
```<code>ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
</code>```


问:
directx mouse click simulation
How can I simulate the mouse click in a directx application?
mouse_event and PostMessage with WM_LBUTTONDOWN don't work...

so it must be something to do with the DirectInput

I haven't found out nothing useful with google, so you may be knowing the answer...

thanks in advance

//update

I wrote the text wrongly, what I want is to make the directx app believe that the mouse has just clicked, but without effectively using the mouse and without using SendInput or mouse_event, which need that the window must be focused

答:
If it is your own application, could you refactor out the click event into something like (in psuedocode):

```<code>void click(int x, int y)  {
     do_action();
}
</code>```

or

```<code>void area_click(int x, int y) {
     do_action();
}
</code>```

which is called by the real click handler.

OwnerDisplayName: eimiar

LastEditorDisplayName: eimiar

Title: directx mouse click simulation

Body:
If it is your own application, could you refactor out the click event into something like (in psuedocode):

void click(int x, int y)  {
     do_action();
}

or

void area_click(int x, int y) {
     do_action();
}

which is called by the real click handler.

OwnerDisplayName: person-b


问:
Curb epsv problem
I'm having a problem using Curb (ruby curl bindings) for FTP downloads.

It looks like curb doesn't fall back to simple passive mode when extended passive mode fails. Extract from the log follows:

```<code>< 250 Directory changed to /outgoing/productcatalog/35591
> EPSV
* Connect data stream passively
< 229 Entering Passive Mode (|||40938|)
*   Trying 216.34.207.42... * Connecting to 216.34.207.42 (216.34.207.42) port 40938
* Connection failed
* Expire cleared
* Closing connection #0
</code>```

Then in throws Curl::Err::ConnectionFailedError: couldn't connect to server

However, if I use curl in the command line, I get

```<code>< 250 Directory changed to /outgoing/productcatalog/35591
> EPSV
* Connect data stream passively
< 229 Entering Passive Mode (|||43267|)
*   Trying 216.34.207.42... Connection refused
* couldn't connect to host
* got positive EPSV response, but can't connect. Disabling EPSV
> PASV
< 227 Entering Passive Mode (216,34,207,42,169,4)
*   Trying 216.34.207.42... connected
</code>```

The solution would be to disable epsv altogether but it seems impossible with Curb, there's no such option. What can be done in this situation?

答: The libcurl option to disable EPSV is a simple boolean option and curb should already support lots of other similar options. Adding support for this should be fairly trivial.</p>

Title: Curb epsv problem

Body:
I'm having a problem using Curb (ruby curl bindings) for FTP downloads.

It looks like curb doesn't fall back to simple passive mode when extended passive mode fails. Extract from the log follows:

< 250 Directory changed to /outgoing/productcatalog/35591
> EPSV
* Connect data stream passively
< 229 Entering Passive Mode (|||40938|)
*   Trying 216.34.207.42... * Connecting to 216.34.207.42 (216.34.207.42) port 40938
* Connection failed
* Expire cleared
* Closing connection #0

Then in throws Curl::Err::ConnectionFailedError: couldn't connect to server

However, if I use curl in the command line, I get

< 250 Directory changed to /outgoing/productcatalog/35591
> EPSV
* Connect data stream passively
< 229 Entering Passive Mode (|||43267|)
*   Trying 216.34.207.42... Connection refused
* couldn't connect to host
* got positive EPSV response, but can't connect. Disabling EPSV
> PASV
< 227 Entering Passive Mode (216,34,207,42,169,4)
*   Trying 216.34.207.42... connected

The solution would be to disable epsv altogether but it seems impossible with Curb, there's no such option. What can be done in this situation?


问:
Pass variable down to dependency helm chart
I have a helm chart with an optional component.  It seems that the preferred way to support optional components is to break them into separate charts and toggle them with tags.

I tried this, but my optional component needs to know a variable from the rest of the chart (the address of a particular service).  This causes things to break

```<code>Error: render error in "subchart/foo-deployment.yaml":
template: superchart/templates/_helpers.tpl:14:40:
executing "superchart.variable <.Values.variable...>:
can't evaluate field name in type interface {}
</code>```

答:
I believe you can do this at install time for the chart

helm install --set option1=value1 --name my-release stable/dask

For more info:
https://docs.helm.sh/helm/#helm-install

Issue:
https://github.com/kubernetes/helm/issues/944

PR:
https://github.com/kubernetes/helm/pull/982

Body:
I have a helm chart with an optional component.  It seems that the preferred way to support optional components is to break them into separate charts and toggle them with tags.

I tried this, but my optional component needs to know a variable from the rest of the chart (the address of a particular service).  This causes things to break

Error: render error in "subchart/foo-deployment.yaml":
template: superchart/templates/_helpers.tpl:14:40:
executing "superchart.variable <.Values.variable...>:
can't evaluate field name in type interface {}


问:
JavaScript is not loaded although it exists in the artifact in the correct path
I am trying to run an xhtml page which uses a javascript file named flotr2.js file.

This is the original script tag:

```<code>    1- <script type="text/javascript" src="../../resources/flotr2_master/flotr2.js"></script>

I also tried the following script tags:

 2- <script type="text/javascript" src="/localhost/enterprisesecvis/resources/flotr2_master/flotr2.js"></script>

 3-<script type="text/javascript" src="http://localhost/enterprisesecvis/resources/flotr2_master/flotr2.js"></script>

 4-<script type="text/javascript" src="#{request.contextPath}//resources/flotr2_master/flotr2.js"></script>
</code>```

The script definitions 1,3 and 4 forms a correct link for the JS file. The script definition 2 forms an incorrect path.

All four definitions ended with 404 error :(

This js file is in the following directory
Project_root\Project_Name\out\artifacts\war_name_exploded\resources\flotr2_master

The link that the explorer tries to load the Js file is

http://localhost:8090/Project_Name/resources/flotr2_master/flotr2.js

Explorer loads the all xhtml pages correctly using a link such as below

http://localhost:8090/Project_Name/pages/folder/aaa.xhtml

The error which explorer developer tool shows is "flotr2.js Failed to load resource: the server responded with a status of 404 (Not Found)"

This is the picture of explorer searching for the path. This view also shows that the path is not wrong for the js file.

I can not continue to my code due to this error. Any help will be appreciated.
Thank you

Ferda

答:
I added these lines to web.xml file and the problem is corrected. It wasn't related to the wrong definition of the path as I expected.

```<code><servlet-mapping>
   <servlet-name>default</servlet-name>
   <url-pattern>*.js</url-pattern>
</servlet-mapping>
<servlet-mapping>
   <servlet-name>default</servlet-name>
   <url-pattern>*.css</url-pattern>
</servlet-mapping>
</code>```

Good Night :)

Body:
I am trying to run an xhtml page which uses a javascript file named flotr2.js file.

This is the original script tag:

    1-

I also tried the following script tags:

 2-

 3-

 4-

The script definitions 1,3 and 4 forms a correct link for the JS file. The script definition 2 forms an incorrect path.

All four definitions ended with 404 error :(

This js file is in the following directory
Project_root\Project_Name\out\artifacts\war_name_exploded\resources\flotr2_master

The link that the explorer tries to load the Js file is

http://localhost:8090/Project_Name/resources/flotr2_master/flotr2.js

Explorer loads the all xhtml pages correctly using a link such as below

http://localhost:8090/Project_Name/pages/folder/aaa.xhtml

The error which explorer developer tool shows is "flotr2.js Failed to load resource: the server responded with a status of 404 (Not Found)"

This is the picture of explorer searching for the path. This view also shows that the path is not wrong for the js file.

I can not continue to my code due to this error. Any help will be appreciated.
Thank you

Ferda

Body:
I added these lines to web.xml file and the problem is corrected. It wasn't related to the wrong definition of the path as I expected.

<servlet-mapping>
   <servlet-name>default</servlet-name>
   <url-pattern>*.js</url-pattern>
</servlet-mapping>
<servlet-mapping>
   <servlet-name>default</servlet-name>
   <url-pattern>*.css</url-pattern>
</servlet-mapping>

Good Night :)