问:
AMQP(RabbitMQ) Could not deserialize object, ClassNotFoundException
I want to implement a RabbitMq(AMQP) messaging in java SpringBoot, but when I receive the message it says that the messaGE could not be deserialize because I the class for the object that I supposed to receive was not found even if I have that class int the classpath.

RabbitMqListener.java:

```<code>@EnableRabbit
@Component
public class RabbitMqListener {
    Logger logger = Logger.getLogger(RabbitMqListener.class);

    @RabbitListener(queues = "queue2")
    public void processQueue1(Product message) {

        logger.info("Received from queue 2: " + message);
    }

}
</code>```

RabbitConfiguration.java:

```<code>@Configuration
public class RabbitConfiguration {
    Logger logger = Logger.getLogger(RabbitConfiguration.class);
    @Bean
    public ConnectionFactory connectionFactory() {
        CachingConnectionFactory connectionFactory =
                new CachingConnectionFactory("localhost");
        return connectionFactory;
    }

    @Bean
    public AmqpAdmin amqpAdmin() {
        return new RabbitAdmin(connectionFactory());
    }

    @Bean
    public MessageConverter jsonMessageConverter(){
        return new JsonMessageConverter();
    }

    @Bean
    public RabbitTemplate rabbitTemplate() {
        RabbitTemplate template = new RabbitTemplate(connectionFactory());
        template.setMessageConverter(jsonMessageConverter());
        return template;
    }

    @Bean
    public Queue myQueue1() {

        return new Queue("queue1");
    }

    @Bean
    public Queue myQueue2() {

        return new Queue("queue2");
    }

}
</code>```

SampleController.java:

```<code>@Controller
public class SampleController {
    Logger logger = Logger.getLogger(SampleController.class);

    @Autowired
    AmqpTemplate template;

    @RequestMapping("/emit")
    @ResponseBody
    String queue1() {
        logger.info("Emit to queue1");
        template.convertAndSend("queue1","Message to queue 1");
        return "Emit to queue 1";
    }
}
</code>```

Product.java:

```<code>public class Product implements Serializable{

    private Long id;

    private String name;

    private int stock;

    private int price;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getStock() {
        return stock;
    }

    public void setStock(int stock) {
        this.stock = stock;
    }

    public Product() {
    }

    @Override
    public String toString() {
        return "Product{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", stock=" + stock +
                ", price=" + price +
                '}';
    }
}
</code>```

And the stacktrace:

```<code>2016-07-11 09:34:02.840  WARN [order-service,,,] 4084 --- [cTaskExecutor-1] s.a.r.l.ConditionalRejectingErrorHandler : Execution of Rabbit message listener failed.

org.springframework.amqp.rabbit.listener.exception.ListenerExecutionFailedException: Listener threw exception
    at org.springframework.amqp.rabbit.listener.AbstractMessageListenerContainer.wrapToListenerExecutionFailedExceptionIfNeeded(AbstractMessageListenerContainer.java:865) ~[spring-rabbit-1.5.6.RELEASE.jar:na]
    at org.springframework.amqp.rabbit.listener.AbstractMessageListenerContainer.doInvokeListener(AbstractMessageListenerContainer.java:760) ~[spring-rabbit-1.5.6.RELEASE.jar:na]
    at org.springframework.amqp.rabbit.listener.AbstractMessageListenerContainer.invokeListener(AbstractMessageListenerContainer.java:680) ~[spring-rabbit-1.5.6.RELEASE.jar:na]
    at org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer.access$001(SimpleMessageListenerContainer.java:93) [spring-rabbit-1.5.6.RELEASE.jar:na]
    at org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer$1.invokeListener(SimpleMessageListenerContainer.java:183) ~[spring-rabbit-1.5.6.RELEASE.jar:na]
    at org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer.invokeListener(SimpleMessageListenerContainer.java:1358) [spring-rabbit-1.5.6.RELEASE.jar:na]
    at org.springframework.amqp.rabbit.listener.AbstractMessageListenerContainer.executeListener(AbstractMessageListenerContainer.java:661) ~[spring-rabbit-1.5.6.RELEASE.jar:na]
    at org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer.doReceiveAndExecute(SimpleMessageListenerContainer.java:1102) [spring-rabbit-1.5.6.RELEASE.jar:na]
    at org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer.receiveAndExecute(SimpleMessageListenerContainer.java:1086) [spring-rabbit-1.5.6.RELEASE.jar:na]
    at org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer.access$1100(SimpleMessageListenerContainer.java:93) [spring-rabbit-1.5.6.RELEASE.jar:na]
    at org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer$AsyncMessageProcessingConsumer.run(SimpleMessageListenerContainer.java:1203) [spring-rabbit-1.5.6.RELEASE.jar:na]
    at java.lang.Thread.run(Thread.java:745) [na:1.8.0_91]
Caused by: java.lang.IllegalStateException: Could not deserialize object type
    at org.springframework.amqp.utils.SerializationUtils.deserialize(SerializationUtils.java:82) ~[spring-amqp-1.5.6.RELEASE.jar:na]
    at org.springframework.amqp.support.converter.SimpleMessageConverter.fromMessage(SimpleMessageConverter.java:110) ~[spring-amqp-1.5.6.RELEASE.jar:na]
    at org.springframework.amqp.rabbit.listener.adapter.AbstractAdaptableMessageListener.extractMessage(AbstractAdaptableMessageListener.java:185) ~[spring-rabbit-1.5.6.RELEASE.jar:na]
    at org.springframework.amqp.rabbit.listener.adapter.MessagingMessageListenerAdapter$MessagingMessageConverterAdapter.extractPayload(MessagingMessageListenerAdapter.java:173) ~[spring-rabbit-1.5.6.RELEASE.jar:na]
    at org.springframework.amqp.support.converter.MessagingMessageConverter.fromMessage(MessagingMessageConverter.java:118) ~[spring-amqp-1.5.6.RELEASE.jar:na]
    at org.springframework.amqp.rabbit.listener.adapter.MessagingMessageListenerAdapter.toMessagingMessage(MessagingMessageListenerAdapter.java:102) ~[spring-rabbit-1.5.6.RELEASE.jar:na]
    at org.springframework.amqp.rabbit.listener.adapter.MessagingMessageListenerAdapter.onMessage(MessagingMessageListenerAdapter.java:88) ~[spring-rabbit-1.5.6.RELEASE.jar:na]
    at org.springframework.amqp.rabbit.listener.AbstractMessageListenerContainer.doInvokeListener(AbstractMessageListenerContainer.java:757) ~[spring-rabbit-1.5.6.RELEASE.jar:na]
    ... 10 common frames omitted
Caused by: java.lang.ClassNotFoundException: com.productservice.model.Product
    at java.net.URLClassLoader.findClass(URLClassLoader.java:381) ~[na:1.8.0_91]
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424) ~[na:1.8.0_91]
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331) ~[na:1.8.0_91]
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357) ~[na:1.8.0_91]
    at org.springframework.util.ClassUtils.forName(ClassUtils.java:250) ~[spring-core-4.2.7.RELEASE.jar:4.2.7.RELEASE]
    at org.springframework.core.ConfigurableObjectInputStream.resolveClass(ConfigurableObjectInputStream.java:75) ~[spring-core-4.2.7.RELEASE.jar:4.2.7.RELEASE]
    at org.springframework.amqp.support.converter.SimpleMessageConverter$1.resolveClass(SimpleMessageConverter.java:179) ~[spring-amqp-1.5.6.RELEASE.jar:na]
    at java.io.ObjectInputStream.readNonProxyDesc(ObjectInputStream.java:1620) ~[na:1.8.0_91]
    at java.io.ObjectInputStream.readClassDesc(ObjectInputStream.java:1521) ~[na:1.8.0_91]
    at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1781) ~[na:1.8.0_91]
    at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1353) ~[na:1.8.0_91]
    at java.io.ObjectInputStream.readObject(ObjectInputStream.java:373) ~[na:1.8.0_91]
    at org.springframework.amqp.utils.SerializationUtils.deserialize(SerializationUtils.java:76) ~[spring-amqp-1.5.6.RELEASE.jar:na]
    ... 17 common frames omitted

Process finished with exit code -1
</code>```

答:
When you use rabbitmq, you shoud keep your class in the same name package,
such as : com.xxx.entity.Order. If class is in a different package like com.xxx.consumer.entity.Order``com.xxx.producer.entity.Order it will throw errors.

Body:
I want to implement a RabbitMq(AMQP) messaging in java SpringBoot, but when I receive the message it says that the messaGE could not be deserialize because I the class for the object that I supposed to receive was not found even if I have that class int the classpath.

RabbitMqListener.java:

@EnableRabbit
@Component
public class RabbitMqListener {
    Logger logger = Logger.getLogger(RabbitMqListener.class);

    @RabbitListener(queues = "queue2")
    public void processQueue1(Product message) {

        logger.info("Received from queue 2: " + message);
    }

}

RabbitConfiguration.java:

@Configuration
public class RabbitConfiguration {
    Logger logger = Logger.getLogger(RabbitConfiguration.class);
    @Bean
    public ConnectionFactory connectionFactory() {
        CachingConnectionFactory connectionFactory =
                new CachingConnectionFactory("localhost");
        return connectionFactory;
    }

    @Bean
    public AmqpAdmin amqpAdmin() {
        return new RabbitAdmin(connectionFactory());
    }

    @Bean
    public MessageConverter jsonMessageConverter(){
        return new JsonMessageConverter();
    }

    @Bean
    public RabbitTemplate rabbitTemplate() {
        RabbitTemplate template = new RabbitTemplate(connectionFactory());
        template.setMessageConverter(jsonMessageConverter());
        return template;
    }

    @Bean
    public Queue myQueue1() {

        return new Queue("queue1");
    }

    @Bean
    public Queue myQueue2() {

        return new Queue("queue2");
    }

}

SampleController.java:

@Controller
public class SampleController {
    Logger logger = Logger.getLogger(SampleController.class);

    @Autowired
    AmqpTemplate template;

    @RequestMapping("/emit")
    @ResponseBody
    String queue1() {
        logger.info("Emit to queue1");
        template.convertAndSend("queue1","Message to queue 1");
        return "Emit to queue 1";
    }
}

Product.java:

public class Product implements Serializable{

    private Long id;

    private String name;

    private int stock;

    private int price;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getStock() {
        return stock;
    }

    public void setStock(int stock) {
        this.stock = stock;
    }

    public Product() {
    }

    @Override
    public String toString() {
        return "Product{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", stock=" + stock +
                ", price=" + price +
                '}';
    }
}

And the stacktrace:

2016-07-11 09:34:02.840  WARN [order-service,,,] 4084 --- [cTaskExecutor-1] s.a.r.l.ConditionalRejectingErrorHandler : Execution of Rabbit message listener failed.

org.springframework.amqp.rabbit.listener.exception.ListenerExecutionFailedException: Listener threw exception
    at org.springframework.amqp.rabbit.listener.AbstractMessageListenerContainer.wrapToListenerExecutionFailedExceptionIfNeeded(AbstractMessageListenerContainer.java:865) ~[spring-rabbit-1.5.6.RELEASE.jar:na]
    at org.springframework.amqp.rabbit.listener.AbstractMessageListenerContainer.doInvokeListener(AbstractMessageListenerContainer.java:760) ~[spring-rabbit-1.5.6.RELEASE.jar:na]
    at org.springframework.amqp.rabbit.listener.AbstractMessageListenerContainer.invokeListener(AbstractMessageListenerContainer.java:680) ~[spring-rabbit-1.5.6.RELEASE.jar:na]
    at org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer.access$001(SimpleMessageListenerContainer.java:93) [spring-rabbit-1.5.6.RELEASE.jar:na]
    at org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer$1.invokeListener(SimpleMessageListenerContainer.java:183) ~[spring-rabbit-1.5.6.RELEASE.jar:na]
    at org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer.invokeListener(SimpleMessageListenerContainer.java:1358) [spring-rabbit-1.5.6.RELEASE.jar:na]
    at org.springframework.amqp.rabbit.listener.AbstractMessageListenerContainer.executeListener(AbstractMessageListenerContainer.java:661) ~[spring-rabbit-1.5.6.RELEASE.jar:na]
    at org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer.doReceiveAndExecute(SimpleMessageListenerContainer.java:1102) [spring-rabbit-1.5.6.RELEASE.jar:na]
    at org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer.receiveAndExecute(SimpleMessageListenerContainer.java:1086) [spring-rabbit-1.5.6.RELEASE.jar:na]
    at org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer.access$1100(SimpleMessageListenerContainer.java:93) [spring-rabbit-1.5.6.RELEASE.jar:na]
    at org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer$AsyncMessageProcessingConsumer.run(SimpleMessageListenerContainer.java:1203) [spring-rabbit-1.5.6.RELEASE.jar:na]
    at java.lang.Thread.run(Thread.java:745) [na:1.8.0_91]
Caused by: java.lang.IllegalStateException: Could not deserialize object type
    at org.springframework.amqp.utils.SerializationUtils.deserialize(SerializationUtils.java:82) ~[spring-amqp-1.5.6.RELEASE.jar:na]
    at org.springframework.amqp.support.converter.SimpleMessageConverter.fromMessage(SimpleMessageConverter.java:110) ~[spring-amqp-1.5.6.RELEASE.jar:na]
    at org.springframework.amqp.rabbit.listener.adapter.AbstractAdaptableMessageListener.extractMessage(AbstractAdaptableMessageListener.java:185) ~[spring-rabbit-1.5.6.RELEASE.jar:na]
    at org.springframework.amqp.rabbit.listener.adapter.MessagingMessageListenerAdapter$MessagingMessageConverterAdapter.extractPayload(MessagingMessageListenerAdapter.java:173) ~[spring-rabbit-1.5.6.RELEASE.jar:na]
    at org.springframework.amqp.support.converter.MessagingMessageConverter.fromMessage(MessagingMessageConverter.java:118) ~[spring-amqp-1.5.6.RELEASE.jar:na]
    at org.springframework.amqp.rabbit.listener.adapter.MessagingMessageListenerAdapter.toMessagingMessage(MessagingMessageListenerAdapter.java:102) ~[spring-rabbit-1.5.6.RELEASE.jar:na]
    at org.springframework.amqp.rabbit.listener.adapter.MessagingMessageListenerAdapter.onMessage(MessagingMessageListenerAdapter.java:88) ~[spring-rabbit-1.5.6.RELEASE.jar:na]
    at org.springframework.amqp.rabbit.listener.AbstractMessageListenerContainer.doInvokeListener(AbstractMessageListenerContainer.java:757) ~[spring-rabbit-1.5.6.RELEASE.jar:na]
    ... 10 common frames omitted
Caused by: java.lang.ClassNotFoundException: com.productservice.model.Product
    at java.net.URLClassLoader.findClass(URLClassLoader.java:381) ~[na:1.8.0_91]
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424) ~[na:1.8.0_91]
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331) ~[na:1.8.0_91]
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357) ~[na:1.8.0_91]
    at org.springframework.util.ClassUtils.forName(ClassUtils.java:250) ~[spring-core-4.2.7.RELEASE.jar:4.2.7.RELEASE]
    at org.springframework.core.ConfigurableObjectInputStream.resolveClass(ConfigurableObjectInputStream.java:75) ~[spring-core-4.2.7.RELEASE.jar:4.2.7.RELEASE]
    at org.springframework.amqp.support.converter.SimpleMessageConverter$1.resolveClass(SimpleMessageConverter.java:179) ~[spring-amqp-1.5.6.RELEASE.jar:na]
    at java.io.ObjectInputStream.readNonProxyDesc(ObjectInputStream.java:1620) ~[na:1.8.0_91]
    at java.io.ObjectInputStream.readClassDesc(ObjectInputStream.java:1521) ~[na:1.8.0_91]
    at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1781) ~[na:1.8.0_91]
    at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1353) ~[na:1.8.0_91]
    at java.io.ObjectInputStream.readObject(ObjectInputStream.java:373) ~[na:1.8.0_91]
    at org.springframework.amqp.utils.SerializationUtils.deserialize(SerializationUtils.java:76) ~[spring-amqp-1.5.6.RELEASE.jar:na]
    ... 17 common frames omitted

Process finished with exit code -1


来源: stackexchange

问:
Learning React: Trouble understanding why my component won't render/ API/KEYS
I am fairly new to learning React and need some help.
I want to create a meal finder app using the MealDb API, my problem is it won't render.

Here is my code, in my app component:

```<code> import React, { useState } from 'react';
 import './App.css';
 import Search from './components/Search';
 import Meals from './components/Meals';
 import axios from 'axios';

 function App() {
 const [meals, setMeals] = useState({});

 const searchMeals = async meals => {
 const res = await axios.get(
  `https://www.themealdb.com/api/json/v1/1/search.php?s=${meals}`
  );
 console.log(res.data);
 setMeals({ meals: res.data });
 };

 return (
 <div className='App'>
  <Search searchMeals={searchMeals}></Search>
  <Meals searchMeals={searchMeals} meals={meals}></Meals>
 </div>
  );
  }

export default App;
</code>```

I created a component Meals with this inside:

```<code>import React from 'react'
import MealsItem from './MealsItem'

const Meals = ({ meals}) => {

 return (

<div >
  {Object.keys(meals).map(meal=>(
    <MealsItem key={meal.idMeal} meal={meal}/>
  ))}
</div>

);

};

 export default Meals
</code>```

and then for the rendering part I created a MealsItems component:

```<code>import React, { Fragment } from 'react';

const MealsItem = ({ meal :{strMealThumb, strMeal,}}) => {
 return (
 <Fragment>
  <div id='result-heading'>
    <h2>Search result for: {strMeal}</h2>
  </div>
  <div className='meal'>
    <img src={strMealThumb} alt={strMeal} />
    <div className='meal-info'>
      <h3>{strMeal}</h3>
    </div>
  </div>
  </Fragment>
 );
};
export default MealsItem;
</code>```

When I search something: I see a unique item with nothing in it. No title, no image. In the console when I inspect the app I read {meals: Array(8)} and "Warning: Each child in a list should have a unique "key" prop." I thought did write a unique key: key={meal.idMeal}.

EDIT: I did try to write

```<code>{meals.map(meal=>(
</code>```

         ))}

to no avail, unfortunately. It gives me a type error meals.map is not a function.

This is the structure of the API:

```<code>{
  "meals": [
    {
      "idMeal": "52772",
      "strMeal": "Teriyaki Chicken Casserole",
      "strDrinkAlternate": null,
      "strCategory": "Chicken"
}
]
}
</code>```

Edit # 2: This is what I get when I console.log(meals)

console.log(meals)

Thank you to anyone willing to help! Have a good day!

答:
Reason is that you are using
Object.keys(meals).map.
Instead, do this

```<code>{meals.map(meal=>(
   <MealsItem key={meal.idMeal} meal={meal}/>
))}
</code>```

EDIT: Also set default value of meals state.

```<code>const [meals, setMeals] = useState([]); // dont use  useState({})
</code>```

Otherwise in the initial render before meals are fetched there will be error as we try to map over an object.

ContentLicense: CC BY-SA 4.0

Body:
I am fairly new to learning React and need some help.
I want to create a meal finder app using the MealDb API, my problem is it won't render.

Here is my code, in my app component:

 import React, { useState } from 'react';
 import './App.css';
 import Search from './components/Search';
 import Meals from './components/Meals';
 import axios from 'axios';

 function App() {
 const [meals, setMeals] = useState({});

 const searchMeals = async meals => {
 const res = await axios.get(
  `https://www.themealdb.com/api/json/v1/1/search.php?s=${meals}`
  );
 console.log(res.data);
 setMeals({ meals: res.data });
 };

 return (

  <Search searchMeals={searchMeals}></Search>
  <Meals searchMeals={searchMeals} meals={meals}></Meals>

  );
  }

export default App;

I created a component Meals with this inside:

import React from 'react'
import MealsItem from './MealsItem'

const Meals = ({ meals}) => {

 return (

  {Object.keys(meals).map(meal=>(
    <MealsItem key={meal.idMeal} meal={meal}/>
  ))}

);

};

 export default Meals

and then for the rendering part I created a MealsItems component:

import React, { Fragment } from 'react';

const MealsItem = ({ meal :{strMealThumb, strMeal,}}) => {
 return (
 <Fragment>

Search result for: {strMeal}

{strMeal}

  </Fragment>
 );
};
export default MealsItem;

When I search something: I see a unique item with nothing in it. No title, no image. In the console when I inspect the app I read {meals: Array(8)} and "Warning: Each child in a list should have a unique "key" prop." I thought did write a unique key: key={meal.idMeal}.

EDIT: I did try to write

{meals.map(meal=>(

         ))}

to no avail, unfortunately. It gives me a type error meals.map is not a function.

This is the structure of the API:

{
  "meals": [
    {
      "idMeal": "52772",
      "strMeal": "Teriyaki Chicken Casserole",
      "strDrinkAlternate": null,
      "strCategory": "Chicken"
}
]
}

Edit # 2: This is what I get when I console.log(meals)

console.log(meals)

Thank you to anyone willing to help! Have a good day!

Body:
Reason is that you are using
Object.keys(meals).map.
Instead, do this

{meals.map(meal=>(
   <MealsItem key={meal.idMeal} meal={meal}/>
))}

EDIT: Also set default value of meals state.

const [meals, setMeals] = useState([]); // dont use  useState({})

Otherwise in the initial render before meals are fetched there will be error as we try to map over an object.


问:
Python expression evaluation
Why does python obtain such a result?

```<code>>>> 1 in [] == False
False
</code>```

Obviously, '1 in []' is evaluated to False, and 'False == False' is evaluated to True. And 1 in ([] == False) is not valid expression.

On the other hand '(1 in []) == False' is evaluated to True, but I still do not understand why '1 in [] == False' is evaluated to False,

答:
Python interprets 1 in [] == False as

1 in [] AND [] == False.  Both of which are False.

Also 1 in [1] == False is False since

1 in [1] AND [1] == False generates True and False.  True and False gives us False.

Title: Python expression evaluation

Body:
Why does python obtain such a result?

>>> 1 in [] == False
False

Obviously, '1 in []' is evaluated to False, and 'False == False' is evaluated to True. And 1 in ([] == False) is not valid expression.

On the other hand '(1 in []) == False' is evaluated to True, but I still do not understand why '1 in [] == False' is evaluated to False,


问:
Calling mysql procedure in python with parameter and getting errors
I use pymysql to connect to db. Here is the way I call the procedure.

cur.execute("call delete_shop_tables(?,?,?,?,?)", args)

The procedure expects 5 string variables.

args has five string variables in an array (args = ["one","two","three","four", "five"])

I get the following errors when the above line is executed.

TypeError: not all arguments converted during string formatting

What could I be missing?

答:
try  call delete_shop_tables(args)

This is the right way to call procedures.


问:
How can I configure Apache Tomcat to output a timezone in the timestamp of the catalina.out file?
I'm trying to configure Apache Tomcat 9 to output a timezone with the timestamp in the catalina.out file.  Right now, I'm just using the default logging.properties configuration, the pertinent part shown here:

```<code>handlers = 1catalina.org.apache.juli.AsyncFileHandler, 2localhost.org.apache.juli.AsyncFileHandler, 3manager.org.apache.juli.AsyncFileHandler, 4host-manager.org.apache.juli.AsyncFileHandler, java.util.logging.ConsoleHandler

.handlers = 1catalina.org.apache.juli.AsyncFileHandler, java.util.logging.ConsoleHandler

############################################################
# Handler specific properties.
# Describes specific configuration info for Handlers.
############################################################

1catalina.org.apache.juli.AsyncFileHandler.level = FINE
1catalina.org.apache.juli.AsyncFileHandler.directory = ${catalina.base}/logs
1catalina.org.apache.juli.AsyncFileHandler.prefix = catalina.
1catalina.org.apache.juli.AsyncFileHandler.maxDays = 90
1catalina.org.apache.juli.AsyncFileHandler.encoding = UTF-8

2localhost.org.apache.juli.AsyncFileHandler.level = FINE
2localhost.org.apache.juli.AsyncFileHandler.directory = ${catalina.base}/logs
2localhost.org.apache.juli.AsyncFileHandler.prefix = localhost.
2localhost.org.apache.juli.AsyncFileHandler.maxDays = 90
2localhost.org.apache.juli.AsyncFileHandler.encoding = UTF-8

3manager.org.apache.juli.AsyncFileHandler.level = FINE
3manager.org.apache.juli.AsyncFileHandler.directory = ${catalina.base}/logs
3manager.org.apache.juli.AsyncFileHandler.prefix = manager.
3manager.org.apache.juli.AsyncFileHandler.maxDays = 90
3manager.org.apache.juli.AsyncFileHandler.encoding = UTF-8

4host-manager.org.apache.juli.AsyncFileHandler.level = FINE
4host-manager.org.apache.juli.AsyncFileHandler.directory = ${catalina.base}/logs
4host-manager.org.apache.juli.AsyncFileHandler.prefix = host-manager.
4host-manager.org.apache.juli.AsyncFileHandler.maxDays = 90
4host-manager.org.apache.juli.AsyncFileHandler.encoding = UTF-8

java.util.logging.ConsoleHandler.level = FINE
java.util.logging.ConsoleHandler.formatter = org.apache.juli.OneLineFormatter
java.util.logging.ConsoleHandler.encoding = UTF-8
</code>```

I tried using the "java.util.logging.SimpleFormatter" in place of the "org.apache.juli.OneLineFormatter", like so:

```<code>#java.util.logging.ConsoleHandler.formatter = org.apache.juli.OneLineFormatter
java.util.logging.ConsoleHandler.formatter = java.util.logging.SimpleFormatter
java.util.logging.ConsoleHandler.format = "%1$tb %1$td, %1$tY %1$tH:%1$tM:%1$tS %1$tz %2$s%n%4$s: %5$s%n"
</code>```

I can see it's using the SimpleFormatter because the timestamp format does change slightly.  However, it does not change to what I specified in the "java.util.logging.ConsoleHandler.format" property.

Is there a way to do this without switching to use something like log4j?  What am I missing in my configuration?

Apache Tomcat 9.0.22
OpenJDK 1.8.0_222

Edit:

Here are some examples showing the first line of output of Tomcat on startup.  From the default configuration "logging.properties" file (distributed with the Apache Tomcat tar.gz distribution), I get the following on startup:

```<code>20-Nov-2019 11:46:45.056 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log Server version name:   Apache Tomcat/9.0.22
</code>```

If I modifiy the "conf/logging.properties" file, changing the "java.util.logging.ConsoleHandler.formatter" property like so:

```<code>#java.util.logging.ConsoleHandler.formatter = org.apache.juli.OneLineFormatter
java.util.logging.ConsoleHandler.formatter = java.util.logging.SimpleFormatter
</code>```

I now get this:

```<code>Nov 20, 2019 11:50:05 AM org.apache.catalina.startup.VersionLoggerListener log
INFO: Server version name:   Apache Tomcat/9.0.22
</code>```

As the first event in the file (it's actually 2 lines).  So it actually changed which tells me I'm in the right place.  Now I would like to format the line.

When I set the format property:

```<code>#java.util.logging.ConsoleHandler.formatter = org.apache.juli.OneLineFormatter
java.util.logging.ConsoleHandler.formatter = java.util.logging.SimpleFormatter
java.util.logging.SimpleFormatter.format=%d %5p %tz %c{1}:%L:(%t) - %m%n
</code>```

I get the following on startup:

```<code>Nov 20, 2019 11:56:44 AM org.apache.catalina.startup.VersionLoggerListener log
INFO: Server version name:   Apache Tomcat/9.0.22
</code>```

which looks essentially identical to the log output where the format property was not set.

答:
Setting up the format is not enough. you also need to explicitly tell the logger to use this format:

add this to your logging.properties file:

```<code>java.util.logging.SimpleFormatter.format="%1$tb %1$td, %1$tY %1$tH:%1$tM:%1$tS %1$tz %2$s%n%4$s: %5$s%n"
</code>```

For each logger add this line: (example on the Catalina logger)

```<code>1catalina.org.apache.juli.AsyncFileHandler.formatter = java.util.logging.SimpleFormatter
</code>```

like this:

```<code>1catalina.org.apache.juli.AsyncFileHandler.level = FINE
1catalina.org.apache.juli.AsyncFileHandler.formatter = java.util.logging.SimpleFormatter
1catalina.org.apache.juli.AsyncFileHandler.directory = ${catalina.base}/logs
1catalina.org.apache.juli.AsyncFileHandler.prefix = catalina.
1catalina.org.apache.juli.AsyncFileHandler.maxDays = 90
1catalina.org.apache.juli.AsyncFileHandler.encoding = UTF-8
</code>```

After your logger will use the right formatter you can play with the format to fit your timestamp/timezone needs.

Don't forget to restart the Tomcat.

Let me know if you need anything else.

Body:
I'm trying to configure Apache Tomcat 9 to output a timezone with the timestamp in the catalina.out file.  Right now, I'm just using the default logging.properties configuration, the pertinent part shown here:

handlers = 1catalina.org.apache.juli.AsyncFileHandler, 2localhost.org.apache.juli.AsyncFileHandler, 3manager.org.apache.juli.AsyncFileHandler, 4host-manager.org.apache.juli.AsyncFileHandler, java.util.logging.ConsoleHandler

.handlers = 1catalina.org.apache.juli.AsyncFileHandler, java.util.logging.ConsoleHandler

############################################################
# Handler specific properties.
# Describes specific configuration info for Handlers.
############################################################

1catalina.org.apache.juli.AsyncFileHandler.level = FINE
1catalina.org.apache.juli.AsyncFileHandler.directory = ${catalina.base}/logs
1catalina.org.apache.juli.AsyncFileHandler.prefix = catalina.
1catalina.org.apache.juli.AsyncFileHandler.maxDays = 90
1catalina.org.apache.juli.AsyncFileHandler.encoding = UTF-8

2localhost.org.apache.juli.AsyncFileHandler.level = FINE
2localhost.org.apache.juli.AsyncFileHandler.directory = ${catalina.base}/logs
2localhost.org.apache.juli.AsyncFileHandler.prefix = localhost.
2localhost.org.apache.juli.AsyncFileHandler.maxDays = 90
2localhost.org.apache.juli.AsyncFileHandler.encoding = UTF-8

3manager.org.apache.juli.AsyncFileHandler.level = FINE
3manager.org.apache.juli.AsyncFileHandler.directory = ${catalina.base}/logs
3manager.org.apache.juli.AsyncFileHandler.prefix = manager.
3manager.org.apache.juli.AsyncFileHandler.maxDays = 90
3manager.org.apache.juli.AsyncFileHandler.encoding = UTF-8

4host-manager.org.apache.juli.AsyncFileHandler.level = FINE
4host-manager.org.apache.juli.AsyncFileHandler.directory = ${catalina.base}/logs
4host-manager.org.apache.juli.AsyncFileHandler.prefix = host-manager.
4host-manager.org.apache.juli.AsyncFileHandler.maxDays = 90
4host-manager.org.apache.juli.AsyncFileHandler.encoding = UTF-8

java.util.logging.ConsoleHandler.level = FINE
java.util.logging.ConsoleHandler.formatter = org.apache.juli.OneLineFormatter
java.util.logging.ConsoleHandler.encoding = UTF-8

I tried using the "java.util.logging.SimpleFormatter" in place of the "org.apache.juli.OneLineFormatter", like so:

#java.util.logging.ConsoleHandler.formatter = org.apache.juli.OneLineFormatter
java.util.logging.ConsoleHandler.formatter = java.util.logging.SimpleFormatter
java.util.logging.ConsoleHandler.format = "%1$tb %1$td, %1$tY %1$tH:%1$tM:%1$tS %1$tz %2$s%n%4$s: %5$s%n"

I can see it's using the SimpleFormatter because the timestamp format does change slightly.  However, it does not change to what I specified in the "java.util.logging.ConsoleHandler.format" property.

Is there a way to do this without switching to use something like log4j?  What am I missing in my configuration?

Apache Tomcat 9.0.22
OpenJDK 1.8.0_222

Edit:

Here are some examples showing the first line of output of Tomcat on startup.  From the default configuration "logging.properties" file (distributed with the Apache Tomcat tar.gz distribution), I get the following on startup:

20-Nov-2019 11:46:45.056 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log Server version name:   Apache Tomcat/9.0.22

If I modifiy the "conf/logging.properties" file, changing the "java.util.logging.ConsoleHandler.formatter" property like so:

#java.util.logging.ConsoleHandler.formatter = org.apache.juli.OneLineFormatter
java.util.logging.ConsoleHandler.formatter = java.util.logging.SimpleFormatter

I now get this:

Nov 20, 2019 11:50:05 AM org.apache.catalina.startup.VersionLoggerListener log
INFO: Server version name:   Apache Tomcat/9.0.22

As the first event in the file (it's actually 2 lines).  So it actually changed which tells me I'm in the right place.  Now I would like to format the line.

When I set the format property:

#java.util.logging.ConsoleHandler.formatter = org.apache.juli.OneLineFormatter
java.util.logging.ConsoleHandler.formatter = java.util.logging.SimpleFormatter
java.util.logging.SimpleFormatter.format=%d %5p %tz %c{1}:%L:(%t) - %m%n

I get the following on startup:

Nov 20, 2019 11:56:44 AM org.apache.catalina.startup.VersionLoggerListener log
INFO: Server version name:   Apache Tomcat/9.0.22

which looks essentially identical to the log output where the format property was not set.

Body:
Setting up the format is not enough. you also need to explicitly tell the logger to use this format:

add this to your logging.properties file:

java.util.logging.SimpleFormatter.format="%1$tb %1$td, %1$tY %1$tH:%1$tM:%1$tS %1$tz %2$s%n%4$s: %5$s%n"

For each logger add this line: (example on the Catalina logger)

1catalina.org.apache.juli.AsyncFileHandler.formatter = java.util.logging.SimpleFormatter

like this:

1catalina.org.apache.juli.AsyncFileHandler.level = FINE
1catalina.org.apache.juli.AsyncFileHandler.formatter = java.util.logging.SimpleFormatter
1catalina.org.apache.juli.AsyncFileHandler.directory = ${catalina.base}/logs
1catalina.org.apache.juli.AsyncFileHandler.prefix = catalina.
1catalina.org.apache.juli.AsyncFileHandler.maxDays = 90
1catalina.org.apache.juli.AsyncFileHandler.encoding = UTF-8

After your logger will use the right formatter you can play with the format to fit your timestamp/timezone needs.

Don't forget to restart the Tomcat.

Let me know if you need anything else.


问:
How can I output MySQL query results in CSV format?
Is there an easy way to run a MySQL query from the Linux command line and output the results in CSV format?

Here's what I'm doing now:

mysql -u uid -ppwd -D dbname << EOQ | sed -e 's/        /,/g' | tee list.csv
select id, concat("\"",name,"\"") as name
from students
EOQ
```

It gets messy when there are a lot of columns that need to be surrounded by quotes, or if there are quotes in the results that need to be escaped.

答:
I encountered the same problem and Paul's Answer wasn't an option since it was Amazon RDS. Replacing the tab with the commas did not work as the data had embedded commas and tabs. I found that mycli, which is a drop-in alternative for the mysql-client, supports CSV output out of the box with the --csv flag:

mycli db_name --csv -e "select * from flowers" > flowers.csv
```

OwnerDisplayName: MCS

Body:
Is there an easy way to run a MySQL query from the Linux command line and output the results in CSV format?

Here's what I'm doing now:

mysql -u uid -ppwd -D dbname << EOQ | sed -e 's/        /,/g' | tee list.csv
select id, concat("\"",name,"\"") as name
from students
EOQ

It gets messy when there are a lot of columns that need to be surrounded by quotes, or if there are quotes in the results that need to be escaped.


问:
Calling paint event inside a function
IDE: Microsoft Visual Studio 2010
Platform : C#.Net

I am trying to call paint event inside a function in one of my forms in C#. The function is currently having two integer arguments, but I want the paint event of a panel to be called in that function, but I am getting error while calling the paint event. Any suggestions ?

答:
None of the previous answers worked for me. After a while investigating, I have managed to raise paint event with the following instruction:</p>

```<code>this.InvokePaint(this, new PaintEventArgs(this.CreateGraphics(), this.DisplayRectangle));
</code>```

ContentLicense: CC BY-SA 3.0

Title: Calling paint event inside a function

Body:
None of the previous answers worked for me. After a while investigating, I have managed to raise paint event with the following instruction:

this.InvokePaint(this, new PaintEventArgs(this.CreateGraphics(), this.DisplayRectangle));


问:
Azure Blob and Queue Thread Safety
I need some help in understanding the thread safety in azure CloudBlobClient, CloudQueueClient and CloudBlob classes.

I am developing a worker role which includes multiple independent job processors where each of these job processors read from a specific queue and write/update to some blob containers which may be the same.

I want to make sure that these job processors are not stepping on each other toe.

1> How can I make sure that this is the case without using any kind of lock? If I assign a separate CloudBlobClient and CloudQueueClient to each of my job processors (who all live within same process), is it enough to say that they are independent from each other and because every job processors uses a separate client instance, they will not run into each other at all?

2> Within same job processor, if I try to have parallelism on CloudBlobClient using Parallel.ForEach to say call  GetBlobReference or UploadText in parallel, do I need to incorporate some sort of synchronization or are these methods thread safe? Azure documentation says they are not but most examples that I have seen online do not seem to apply any kind of synchronization mechanism on these methods. What is the best way to achieve this? I mean the best way to use one CloudBlobClient and call GetBlobReference or UploadText in Parallel?

答: The documentation for a randomly chosen function says "Any public static...members of this type are thread safe. Any instance members are not guaranteed to be thread safe.", but I would assume this is boilerplate put in because someone could not be bothered to think about it.  I suggest you examine the classes using Reflector, but I would expect they would be fine because all the classes you refer to are just repositories for properties that end up being put into HTTP REST requests when you make a call like UploadText.  So long as you do not change properties for one object in different threads (and I don't think you will need to - create a CloudBlobReference for each iteration of your Parrallel.ForEach) then I reckon you will be safe.</p>

Title: Azure Blob and Queue Thread Safety


问:
Destroying bookshelf/knex connection pool
I have a db api that uses Bookshelf/Knex.

I have multiple Bookshelf models that look something like this:

```<code>import bookshelf from '../bookshelf';

var Product = bookshelf.Model.extend({
  tableName: 'product'
  // ...
});
export default Product;
</code>```

The bookshelf include looks like :

```<code>import dbConfig from './dbConfig';

const knex = require('knex')(dbConfig);
const bookshelf = require('bookshelf')(knex);

module.exports = bookshelf;
</code>```

I also have multiple api action calls that look something like this:

```<code>import Product from '../../Models/Product';

export default function getProducts(bookshelf) {

  return new Promise((resolve) => {

    Product.collection().fetch().then((products) => {
      resolve({
        products
      });
    });
  });
}
</code>```

My problem is that knex pools connections and I need to destroy the connection pool before I resolve the request in the action files. However, in order to do that I need access to the bookshelf or knex objects which are imported in the model.

I can't think of a neat way of doing this. I could create the knex object in the top level file that calls the action, and then that process could destroy the connections when it receives the response. But then I would have to pass it to the actions and then to the models.  How can I do this so that the connection pool is destroyed without having to pass the knex object around everywhere?

答:
This tutorial shows how to use knex.destroy() on APIs importing bookshelf.

On the bookshelf:

module.exports.knex = knex;

On the API calling bookshelf:

const knex = require('./bookshelf').knex;
...
Product.collection().fetch()
.then((products) => {
      resolve({
        products
      });})
.finally(() => { knex.destroy(); });

```

Body:
I have a db api that uses Bookshelf/Knex.

I have multiple Bookshelf models that look something like this:

import bookshelf from '../bookshelf';

var Product = bookshelf.Model.extend({
  tableName: 'product'
  // ...
});
export default Product;

The bookshelf include looks like :

import dbConfig from './dbConfig';

const knex = require('knex')(dbConfig);
const bookshelf = require('bookshelf')(knex);

module.exports = bookshelf;

I also have multiple api action calls that look something like this:

import Product from '../../Models/Product';

export default function getProducts(bookshelf) {

  return new Promise((resolve) => {

    Product.collection().fetch().then((products) => {
      resolve({
        products
      });
    });
  });
}

My problem is that knex pools connections and I need to destroy the connection pool before I resolve the request in the action files. However, in order to do that I need access to the bookshelf or knex objects which are imported in the model.

I can't think of a neat way of doing this. I could create the knex object in the top level file that calls the action, and then that process could destroy the connections when it receives the response. But then I would have to pass it to the actions and then to the models.  How can I do this so that the connection pool is destroyed without having to pass the knex object around everywhere?


问:
Using group_by to summarize the data while looping
For example, here is my df:

```<code>GP_A <- c(rep("a",3),rep("b",2),rep("c",2))
GP_B <- c(rep("d",2),rep("e",4),rep("f",1))
GENDER <- c(rep("M",4),rep("F",3))
LOC <- c(rep("HK",2),rep("UK",3),rep("JP",2))
SCORE <- c(50,70,80,20,30,80,90)
df <- data.frame(GP_A,GP_B,GENDER,LOC,SCORE)

> df

GP_A GP_B GENDER LOC SCORE
1    a    d      M  HK    50
2    a    d      M  HK    70
3    a    e      M  UK    80
4    b    e      M  UK    20
5    b    e      F  UK    30
6    c    e      F  JP    80
7    c    f      F  JP    90
</code>```

What I want is:

```<code>result[[GP_A]] <- df %>% group_by(GP_A,GENDER,LOC) %>% summarize(SCORE=mean(SCORE))
result[[GP_B]] <- df %>% group_by(GP_B,GENDER,LOC) %>% summarize(SCORE=mean(SCORE))
...
</code>```

I have tried:

```<code>result <- list()
for (i in c("GP_A","GP_B")){
result[[i]] <- df %>% group_by(i,GENDER,LOC) %>% summarize(SCORE=mean(SCORE))
}
</code>```

Here is the error:

Error: Column I is unknown

I also have tried to use setNames, i.e.

```<code>... %>% group_by(setNames(nm=i),GENDER,LOC) %>% ...
</code>```

But it also doesn't work...

答:
The group_by_at() function allows you to group by string inputs and is probably the best use here.

```<code>GP_A <- c(rep("a",3),rep("b",2),rep("c",2))
GP_B <- c(rep("d",2),rep("e",4),rep("f",1))
GENDER <- c(rep("M",4),rep("F",3))
LOC <- c(rep("HK",2),rep("UK",3),rep("JP",2))
SCORE <- c(50,70,80,20,30,80,90)
df <- data.frame(GP_A,GP_B,GENDER,LOC,SCORE)

result <- list()

for(i in c("GP_A","GP_B"))
{
  result[[i]] <-
    df %>%
      group_by_at(c(i,"GENDER", "LOC")) %>%
      summarise(SCORE = mean(SCORE)) %>%
      ungroup()
}
</code>```

Remember that it's always best practice to ungroup() your variables once you finish. This is so that in future you don't have unwanted grouping levels.

Body:
For example, here is my df:

GP_A <- c(rep("a",3),rep("b",2),rep("c",2))
GP_B <- c(rep("d",2),rep("e",4),rep("f",1))
GENDER <- c(rep("M",4),rep("F",3))
LOC <- c(rep("HK",2),rep("UK",3),rep("JP",2))
SCORE <- c(50,70,80,20,30,80,90)
df <- data.frame(GP_A,GP_B,GENDER,LOC,SCORE)

> df

GP_A GP_B GENDER LOC SCORE
1    a    d      M  HK    50
2    a    d      M  HK    70
3    a    e      M  UK    80
4    b    e      M  UK    20
5    b    e      F  UK    30
6    c    e      F  JP    80
7    c    f      F  JP    90

What I want is:

result[[GP_A]] <- df %>% group_by(GP_A,GENDER,LOC) %>% summarize(SCORE=mean(SCORE))
result[[GP_B]] <- df %>% group_by(GP_B,GENDER,LOC) %>% summarize(SCORE=mean(SCORE))
...

I have tried:

result <- list()
for (i in c("GP_A","GP_B")){
result[[i]] <- df %>% group_by(i,GENDER,LOC) %>% summarize(SCORE=mean(SCORE))
}

Here is the error:

Error: Column I is unknown

I also have tried to use setNames, i.e.

... %>% group_by(setNames(nm=i),GENDER,LOC) %>% ...

But it also doesn't work...

Body:
The group_by_at() function allows you to group by string inputs and is probably the best use here.

GP_A <- c(rep("a",3),rep("b",2),rep("c",2))
GP_B <- c(rep("d",2),rep("e",4),rep("f",1))
GENDER <- c(rep("M",4),rep("F",3))
LOC <- c(rep("HK",2),rep("UK",3),rep("JP",2))
SCORE <- c(50,70,80,20,30,80,90)
df <- data.frame(GP_A,GP_B,GENDER,LOC,SCORE)

result <- list()

for(i in c("GP_A","GP_B"))
{
  result[[i]] <-
    df %>%
      group_by_at(c(i,"GENDER", "LOC")) %>%
      summarise(SCORE = mean(SCORE)) %>%
      ungroup()
}

Remember that it's always best practice to ungroup() your variables once you finish. This is so that in future you don't have unwanted grouping levels.


问:
Asp.Net Core Api Default Routing
I have a very basic Asp.Net Core Api; my controller looks like this:

```<code>[ApiController]
[Route("[controller]")]
public class TestController : ControllerBase
{
    [HttpGet("{id}")]
    public IEnumerable<Resource> Test(string id)
    {
         // Breakpoint here
    }
</code>```

I would expect the following URL to invoke the method, and fire the breakpoint:

```<code>https://localhost:5012/test/test/1
</code>```

However, it doesn't. In fact, the following URL does:

```<code>https://localhost:5012/test/1
</code>```

I was under the impression that the format for the URL was as follows (from startup):

```<code>app.UseEndpoints(endpoints =>
{
    endpoints.MapControllerRoute(
        name: "default",
        pattern: "{controller}/{action=Index}/{id?}");
});
</code>```

So, unless that action is Index:

```<code>https://localhost:5012/controller/action/id
</code>```

But it appears that the accepted format is:

```<code>https://localhost:5012/controller/id
</code>```

My question is, why is this?

答:
Actually it is ApiController attribute, who breaks your routing. Looks like app.UseEndpoints configures routes just for MVC. So the solution is to remove all attributes to have the following code

```<code>public class TestController : ControllerBase
{
    public string Test(string id)
    {
        return "OK";
    }
}
</code>```

Or, if you want to keep ApiController attribute, you would need to adjust Route value as well. You can remove app.UseEndpoints, if you don't use MVC in your project

```<code>[ApiController]
[Route("[controller]/[action]")]
public class TestController : ControllerBase
{
    [HttpGet("{id}")]
    public string Test(string id)
    {
        return "OK";
    }
}
</code>```

Title: Asp.Net Core Api Default Routing

Body:
I have a very basic Asp.Net Core Api; my controller looks like this:

[ApiController]
[Route("[controller]")]
public class TestController : ControllerBase
{
    [HttpGet("{id}")]
    public IEnumerable<Resource> Test(string id)
    {
         // Breakpoint here
    }

I would expect the following URL to invoke the method, and fire the breakpoint:

https://localhost:5012/test/test/1

However, it doesn't. In fact, the following URL does:

https://localhost:5012/test/1

I was under the impression that the format for the URL was as follows (from startup):

app.UseEndpoints(endpoints =>
{
    endpoints.MapControllerRoute(
        name: "default",
        pattern: "{controller}/{action=Index}/{id?}");
});

So, unless that action is Index:

https://localhost:5012/controller/action/id

But it appears that the accepted format is:

https://localhost:5012/controller/id

My question is, why is this?

Body:
Actually it is ApiController attribute, who breaks your routing. Looks like app.UseEndpoints configures routes just for MVC. So the solution is to remove all attributes to have the following code

public class TestController : ControllerBase
{
    public string Test(string id)
    {
        return "OK";
    }
}

Or, if you want to keep ApiController attribute, you would need to adjust Route value as well. You can remove app.UseEndpoints, if you don't use MVC in your project

[ApiController]
[Route("[controller]/[action]")]
public class TestController : ControllerBase
{
    [HttpGet("{id}")]
    public string Test(string id)
    {
        return "OK";
    }
}


问:
Ionic 4 angular data.map is not a function
I'm trying to store a response from my http request into a model. I followed this guide and managed to pass the data into the model. However I think I am doing it wrong as I can't get it to display on the html and the output I am seeing from the console is a little jumbled up.

I believe my error is in accessing the json response, but I can't seem to find the error. Can anyone help point out my error?

My models.

```<code>// data.model.ts
import { Fruits } from './fruitsId.model';
import { Deserializable } from './deserialize.model';

export class Data implements Deserializable {
  data: Fruits[];

  deserialize(input: any): this {
    Object.assign(this, input);
    this.data = input.data.map(data => new Fresh().deserialize(data));

    return this;
  }
}
</code>```

```<code>// fruits.model.ts
import { Deserializable } from './deserialize.model';
import { FruitsId } from './fruitsId.model';
import { CustomerId } from './customerId.model';
import { StoreId } from './storeId.model';

export class Fresh implements Deserializable {
    public fruitsId: FruitsId;
    public time: string;
    public customerId: CustomerId;
    public storeId: StoreId;
    public name: string;
    public text: string;

    deserialize(input: any): this {
    Object.assign(this, input);
    this.fruitsId = new FreshId().deserialize(input.freshId);
    this.customerId = new HumanId().deserialize(input.humanId);
    this.storeId = new MasterId().deserialize(input.masterId);

    return this;
    }
}
</code>```

```<code>// fruitsId.model.ts
import { Deserializable } from './deserialize.model';

export class FruitsId implements Deserializable {
    type: string;
    id: string;

    deserialize(input: any): this {
       return Object.assign(this, input);
    }
}
</code>```

Followed by customerId.model.ts and storeId.model.ts with the same format as freshId.model.ts.

My Service.

```<code>// fruits.service.ts
public getAllThings(): Observable<any> {
// Some httpOptions here
// ...
return this.http
  .get(`${this.url}`, httpOptions)
  .pipe(
    // ERROR HERE: data.map is not a function
    map(data => data.map(data => new Data().deserialize(data))),
  );
}
</code>```

Sample response from HTTP GET.

```<code>{
  "data": [
    {
      "id": {
        "type": "red",
        "id": "123"
      },
      "time": 1579677349193,
      "customerId": {
        "type": "retailer",
        "id: "234"
      },
      "storeId": {
        "type": "abc Store",
        "id": "001"
      },
      "name": "Apple",
      "text": "very delicious"
    }
  ]
}
</code>```

Finally at the home.page.ts

```<code>// Some imports
// ...

export class DashboardPage implements OnInit {

  fruitsList: any = [];
  data: Data[];

  constructor(private fruitsService: FruitsService) { }

  ionViewWillEnter() {
    this.getFruits();
  }

  getFruits() {
    this.fruitsService.getFreshes().subscribe(
      res => this.data = res
    );
  }

}
</code>```

答:
Author of the guide here.

Your response is not an array, but calling .map on the response assumes exactly that. Looking at your Response the correct deserialization would be

```<code>map(response => response.data.map(...))
</code>```

since data would just be the entire response which holds the actual data in a data property.

You can always look at the shape of your response by replacing the lambda function with:

```<code>map(response => {
  console.log(response);
  return response.data.map(...);
})
</code>```

Body:
I'm trying to store a response from my http request into a model. I followed this guide and managed to pass the data into the model. However I think I am doing it wrong as I can't get it to display on the html and the output I am seeing from the console is a little jumbled up.

I believe my error is in accessing the json response, but I can't seem to find the error. Can anyone help point out my error?

My models.

// data.model.ts
import { Fruits } from './fruitsId.model';
import { Deserializable } from './deserialize.model';

export class Data implements Deserializable {
  data: Fruits[];

  deserialize(input: any): this {
    Object.assign(this, input);
    this.data = input.data.map(data => new Fresh().deserialize(data));

    return this;
  }
}

// fruits.model.ts
import { Deserializable } from './deserialize.model';
import { FruitsId } from './fruitsId.model';
import { CustomerId } from './customerId.model';
import { StoreId } from './storeId.model';

export class Fresh implements Deserializable {
    public fruitsId: FruitsId;
    public time: string;
    public customerId: CustomerId;
    public storeId: StoreId;
    public name: string;
    public text: string;

    deserialize(input: any): this {
    Object.assign(this, input);
    this.fruitsId = new FreshId().deserialize(input.freshId);
    this.customerId = new HumanId().deserialize(input.humanId);
    this.storeId = new MasterId().deserialize(input.masterId);

    return this;
    }
}

// fruitsId.model.ts
import { Deserializable } from './deserialize.model';

export class FruitsId implements Deserializable {
    type: string;
    id: string;

    deserialize(input: any): this {
       return Object.assign(this, input);
    }
}

Followed by customerId.model.ts and storeId.model.ts with the same format as freshId.model.ts.

My Service.

// fruits.service.ts
public getAllThings(): Observable<any> {
// Some httpOptions here
// ...
return this.http
  .get(`${this.url}`, httpOptions)
  .pipe(
    // ERROR HERE: data.map is not a function
    map(data => data.map(data => new Data().deserialize(data))),
  );
}

Sample response from HTTP GET.

{
  "data": [
    {
      "id": {
        "type": "red",
        "id": "123"
      },
      "time": 1579677349193,
      "customerId": {
        "type": "retailer",
        "id: "234"
      },
      "storeId": {
        "type": "abc Store",
        "id": "001"
      },
      "name": "Apple",
      "text": "very delicious"
    }
  ]
}

Finally at the home.page.ts

// Some imports
// ...

export class DashboardPage implements OnInit {

  fruitsList: any = [];
  data: Data[];

  constructor(private fruitsService: FruitsService) { }

  ionViewWillEnter() {
    this.getFruits();
  }

  getFruits() {
    this.fruitsService.getFreshes().subscribe(
      res => this.data = res
    );
  }

}

Body:
Author of the guide here.

Your response is not an array, but calling .map on the response assumes exactly that. Looking at your Response the correct deserialization would be

map(response => response.data.map(...))

since data would just be the entire response which holds the actual data in a data property.

You can always look at the shape of your response by replacing the lambda function with:

map(response => {
  console.log(response);
  return response.data.map(...);
})


问:
How to know variables from different..."namespaces"?
How can I reach some variable declared in another place from within an external javascript file ?

Suppose in an html file I have the following

```<code><head>
 <script>
   var a = 'something';
 </script>
<head>
<body>
<iframe src="otherfile.html"/>
</body>
</code>```

and inside otherfile.html, in the  section, I have

```<code>alert(a);
</code>```

How can I make sure I get an alert message saying "something" ?

I think Google Adsense does this, their code is:

```<code><script type="text/javascript"><!--
google_ad_client = "youdontneedtoknowthis";
google_ad_slot = "5404192644";
google_ad_width = 728;
google_ad_height = 90;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script>
</code>```

How can the script in http://pagead2.googlesyndication.com/pagead/show_ads.js know those variables (e.g. google_ad_client) ?

答:
It doesn't matter.

All

Body:
How can I reach some variable declared in another place from within an external javascript file ?

Suppose in an html file I have the following

and inside otherfile.html, in the  section, I have

alert(a);

How can I make sure I get an alert message saying "something" ?

I think Google Adsense does this, their code is:

How can the script in http://pagead2.googlesyndication.com/pagead/show_ads.js know those variables (e.g. google_ad_client) ?

Body:
It doesn't matter.

All <script> blocks in the page share the same context and variables.


问:
Why keyup function is not working in CKEDITOR?
In my application, I have a textarea and I am handling it with ck editor. I am trying to call the keyup function on ck editor and print a text to console on the condition whether it has input or not. But it is not working as I expected and I am unable to find the error as it is not at least printing any errors to the console. Also, I want to get only the text from ck editor (except white spaces) to the variable editorInput. I am pasting my code here, please someone look into this and correct my error and modify it to get only the text. Thanks in advance.

CK Editor

```<code><div class="form-group {{ $errors->has('template_content') ? 'has-error' : '' }}">
    {{ Form::label('template_content', 'Template Content') }}
    {{ Form::textarea('template_content', null, array('class' => 'form-control', 'id' => 'ckeditor',
    'name' => 'ckeditor', 'required', 'data-error="Template content is required"')) }}
    {!! $errors->first('template_content', '<span class="help-block">:message</span>') !!}
    <div class="help-block with-errors"></div>
</div>
</code>```

Keyup Function

```<code>$(document).ready(function () {
        CKEDITOR.instances.ckeditor.on('key', function() {
            var editorInput = CKEDITOR.instances["ckeditor"].getData();
            if(editorInput == '') {
                console.log('no-content');
            }
            else {
                console.log('has-content');
            }
        });
    });
</code>```

答:
here is an example with just js.

<!DOCTYPE html>

                <meta charset="utf-8">
                <title>CKEditor</title>

                <textarea name="editor1"></textarea>

```

Body:
In my application, I have a textarea and I am handling it with ck editor. I am trying to call the keyup function on ck editor and print a text to console on the condition whether it has input or not. But it is not working as I expected and I am unable to find the error as it is not at least printing any errors to the console. Also, I want to get only the text from ck editor (except white spaces) to the variable editorInput. I am pasting my code here, please someone look into this and correct my error and modify it to get only the text. Thanks in advance.

CK Editor

has('template_content') ? 'has-error' : '' }}">
    {{ Form::label('template_content', 'Template Content') }}
    {{ Form::textarea('template_content', null, array('class' => 'form-control', 'id' => 'ckeditor',
    'name' => 'ckeditor', 'required', 'data-error="Template content is required"')) }}
    {!! $errors->first('template_content', ':message') !!}

Keyup Function

$(document).ready(function () {
        CKEDITOR.instances.ckeditor.on('key', function() {
            var editorInput = CKEDITOR.instances["ckeditor"].getData();
            if(editorInput == '') {
                console.log('no-content');
            }
            else {
                console.log('has-content');
            }
        });
    });

Body:
here is an example with just js.

<!DOCTYPE html>
<html>
        <head>
                <meta charset="utf-8">
                <title>CKEditor</title>
                <script src="https://cdn.ckeditor.com/4.13.1/standard/ckeditor.js"></script>
        </head>
        <body>
                <textarea name="editor1"></textarea>
                <script>
                        CKEDITOR.replace( 'editor1' );
                </script>
        </body>
</html>


问:
mysql GROUP_CONCAT DISTINCT multiple columns
I have a tag field for a blog posts. tags have unique id but their displayName might be duplicated. What I want is a query that selects posts and in all_tags field we get couples of (id,displayName) is this way:

```<code>id1,name1;id2,name2;id3,name3
</code>```

My query looks like:

```<code>select ....
CONCAT_WS(';', DISTINCT (CONCAT_WS(',',tags.id,tags.displayName))) AS all_tags
Join ...post content ...
Join ...post_tags ...
Join ...tags ...
ORDER BY posts.id
</code>```

This line causes problem:

```<code>CONCAT_WS(';', DISTINCT (CONCAT_WS(',',tags.id,tags.displayName))) AS all_tags
</code>```

How should I modify it?

Some people use an inner (SELECT .. FROM) but as I have heard, it is so inefficien

```<code>SELECT `posts`.*,`categories`.*,`creators`.*,`editors`.*
CONCAT_WS(';', DISTINCT GROUP_CONCAT(CONCAT_WS(',',tags.id,tags.displayName))) AS all_ids
FROM (`posts`)
LEFT JOIN `languages` ON `posts`.`language_id`=`languages`.`id`
LEFT JOIN `users` as creators ON `posts`.`creatorUser_id`=`creators`.`id`
LEFT JOIN `users` as editors ON `posts`.`lastEditorUser_id`=`editors`.`id`
LEFT JOIN `userProfiles` as editors_profile ON `editors`.`profile_id`=`editors_profile`.`id`
LEFT JOIN `categories` ON `posts`.`category_id`=`categories`.`id`
LEFT JOIN `postTags` ON `postTags`.`post_id`=`posts`.`id`
LEFT JOIN `tags` ON `postTags`.`tag_id`=`tags`.`id`
LEFT JOIN `postTags` as `nodetag_checks` ON `nodetag_checks`.`post_id`=`posts`.`id`
LEFT JOIN `tags` as `tag_checks` ON `nodetag_checks`.`tag_id`=`tag_checks`.`id`
WHERE ( 9 IN(`tag_checks`.`id`,`tag_checks`.`cached_parents`) OR 10 IN(`tag_checks`.`id`,`tag_checks`.`cached_parents`) OR 11 IN(`tag_checks`.`id`,`tag_checks`.`cached_parents`))
GROUP BY `posts`.`id` ORDER BY `posts`.`created` desc LIMIT 0, 20
</code>```

答:
As advised by @Willa, I add my comment as an anwser :

GROUP_CONCAT allows you to concat multiple fields :

```<code>GROUP_CONCAT(tags.id, ',', tags.displayName)
</code>```

The only difference with Stephan's answer is in case your code allows the same tag to be affected several times to one post OR if you JOIN sequence leads you to multiselect the same record in the tag table. In those case, my solution will return the same tags multiple times.

Body:
I have a tag field for a blog posts. tags have unique id but their displayName might be duplicated. What I want is a query that selects posts and in all_tags field we get couples of (id,displayName) is this way:

id1,name1;id2,name2;id3,name3

My query looks like:

select ....
CONCAT_WS(';', DISTINCT (CONCAT_WS(',',tags.id,tags.displayName))) AS all_tags
Join ...post content ...
Join ...post_tags ...
Join ...tags ...
ORDER BY posts.id

This line causes problem:

CONCAT_WS(';', DISTINCT (CONCAT_WS(',',tags.id,tags.displayName))) AS all_tags

How should I modify it?

Some people use an inner (SELECT .. FROM) but as I have heard, it is so inefficien

SELECT `posts`.*,`categories`.*,`creators`.*,`editors`.*
CONCAT_WS(';', DISTINCT GROUP_CONCAT(CONCAT_WS(',',tags.id,tags.displayName))) AS all_ids
FROM (`posts`)
LEFT JOIN `languages` ON `posts`.`language_id`=`languages`.`id`
LEFT JOIN `users` as creators ON `posts`.`creatorUser_id`=`creators`.`id`
LEFT JOIN `users` as editors ON `posts`.`lastEditorUser_id`=`editors`.`id`
LEFT JOIN `userProfiles` as editors_profile ON `editors`.`profile_id`=`editors_profile`.`id`
LEFT JOIN `categories` ON `posts`.`category_id`=`categories`.`id`
LEFT JOIN `postTags` ON `postTags`.`post_id`=`posts`.`id`
LEFT JOIN `tags` ON `postTags`.`tag_id`=`tags`.`id`
LEFT JOIN `postTags` as `nodetag_checks` ON `nodetag_checks`.`post_id`=`posts`.`id`
LEFT JOIN `tags` as `tag_checks` ON `nodetag_checks`.`tag_id`=`tag_checks`.`id`
WHERE ( 9 IN(`tag_checks`.`id`,`tag_checks`.`cached_parents`) OR 10 IN(`tag_checks`.`id`,`tag_checks`.`cached_parents`) OR 11 IN(`tag_checks`.`id`,`tag_checks`.`cached_parents`))
GROUP BY `posts`.`id` ORDER BY `posts`.`created` desc LIMIT 0, 20

Body:
As advised by @Willa, I add my comment as an anwser :

GROUP_CONCAT allows you to concat multiple fields :

GROUP_CONCAT(tags.id, ',', tags.displayName)

The only difference with Stephan's answer is in case your code allows the same tag to be affected several times to one post OR if you JOIN sequence leads you to multiselect the same record in the tag table. In those case, my solution will return the same tags multiple times.


问:
How to get pixel data from a UIImage (Cocoa Touch) or CGImage (Core Graphics)?
I have a UIImage (Cocoa Touch). From that, I'm happy to get a CGImage or anything else you'd like that's available. I'd like to write this function:</p>

```<code>- (int)getRGBAFromImage:(UIImage *)image atX:(int)xx andY:(int)yy {
  // [...]
  // What do I want to read about to help
  // me fill in this bit, here?
  // [...]

  int result = (red << 24) | (green << 16) | (blue << 8) | alpha;
  return result;
}
</code>```

答:
Swift 5 version

The answers given here are either outdated or incorrect because they don't take into account the following:

The pixel size of the image can differ from its point size that is returned by image.size.width/image.size.height.

There can be various layouts used by pixel components in the image, such as BGRA, ABGR, ARGB etc. or may not have an alpha component at all, such as BGR and RGB. For example, UIView.drawHierarchy(in:afterScreenUpdates:) method can produce BGRA images.

Color components can be premultiplied by the alpha for all pixels in the image and need to be divided by alpha in order to restore the original color.

For memory optimization used by CGImage, the size of a pixel row in bytes can be greater than the mere multiplication of the pixel width by 4.

The code below is to provide a universal Swift 5 solution to get the UIColor of a pixel for all such special cases. The code is optimized for usability and clarity, not for performance.

public extension UIImage {

    var pixelWidth: Int {
        return cgImage?.width ?? 0
    }

    var pixelHeight: Int {
        return cgImage?.height ?? 0
    }

    func pixelColor(x: Int, y: Int) -> UIColor {
        assert(
            0..<pixelWidth ~= x && 0..<pixelHeight ~= y,
            "Pixel coordinates are out of bounds")

        guard
            let cgImage = cgImage,
            let data = cgImage.dataProvider?.data,
            let dataPtr = CFDataGetBytePtr(data),
            let colorSpaceModel = cgImage.colorSpace?.model,
            let componentLayout = cgImage.bitmapInfo.componentLayout
        else {
            assertionFailure("Could not get a pixel of an image")
            return .clear
        }

        assert(
            colorSpaceModel == .rgb,
            "The only supported color space model is RGB")
        assert(
            cgImage.bitsPerPixel == 32 || cgImage.bitsPerPixel == 24,
            "A pixel is expected to be either 4 or 3 bytes in size")

        let bytesPerRow = cgImage.bytesPerRow
        let bytesPerPixel = cgImage.bitsPerPixel/8
        let pixelOffset = y*bytesPerRow + x*bytesPerPixel

        if componentLayout.count == 4 {
            let components = (
                dataPtr[pixelOffset + 0],
                dataPtr[pixelOffset + 1],
                dataPtr[pixelOffset + 2],
                dataPtr[pixelOffset + 3]
            )

            var alpha: UInt8 = 0
            var red: UInt8 = 0
            var green: UInt8 = 0
            var blue: UInt8 = 0

            switch componentLayout {
            case .bgra:
                alpha = components.3
                red = components.2
                green = components.1
                blue = components.0
            case .abgr:
                alpha = components.0
                red = components.3
                green = components.2
                blue = components.1
            case .argb:
                alpha = components.0
                red = components.1
                green = components.2
                blue = components.3
            case .rgba:
                alpha = components.3
                red = components.0
                green = components.1
                blue = components.2
            default:
                return .clear
            }

            // If chroma components are premultiplied by alpha and the alpha is `0`,
            // keep the chroma components to their current values.
            if cgImage.bitmapInfo.chromaIsPremultipliedByAlpha && alpha != 0 {
                let invUnitAlpha = 255/CGFloat(alpha)
                red = UInt8((CGFloat(red)*invUnitAlpha).rounded())
                green = UInt8((CGFloat(green)*invUnitAlpha).rounded())
                blue = UInt8((CGFloat(blue)*invUnitAlpha).rounded())
            }

            return .init(red: red, green: green, blue: blue, alpha: alpha)

        } else if componentLayout.count == 3 {
            let components = (
                dataPtr[pixelOffset + 0],
                dataPtr[pixelOffset + 1],
                dataPtr[pixelOffset + 2]
            )

            var red: UInt8 = 0
            var green: UInt8 = 0
            var blue: UInt8 = 0

            switch componentLayout {
            case .bgr:
                red = components.2
                green = components.1
                blue = components.0
            case .rgb:
                red = components.0
                green = components.1
                blue = components.2
            default:
                return .clear
            }

            return .init(red: red, green: green, blue: blue, alpha: UInt8(255))

        } else {
            assertionFailure("Unsupported number of pixel components")
            return .clear
        }
    }

}

public extension UIColor {

    convenience init(red: UInt8, green: UInt8, blue: UInt8, alpha: UInt8) {
        self.init(
            red: CGFloat(red)/255,
            green: CGFloat(green)/255,
            blue: CGFloat(blue)/255,
            alpha: CGFloat(alpha)/255)
    }

}

public extension CGBitmapInfo {

    enum ComponentLayout {

        case bgra
        case abgr
        case argb
        case rgba
        case bgr
        case rgb

        var count: Int {
            switch self {
            case .bgr, .rgb: return 3
            default: return 4
            }
        }

    }

    var componentLayout: ComponentLayout? {
        guard let alphaInfo = CGImageAlphaInfo(rawValue: rawValue & Self.alphaInfoMask.rawValue) else { return nil }
        let isLittleEndian = contains(.byteOrder32Little)

        if alphaInfo == .none {
            return isLittleEndian ? .bgr : .rgb
        }
        let alphaIsFirst = alphaInfo == .premultipliedFirst || alphaInfo == .first || alphaInfo == .noneSkipFirst

        if isLittleEndian {
            return alphaIsFirst ? .bgra : .abgr
        } else {
            return alphaIsFirst ? .argb : .rgba
        }
    }

    var chromaIsPremultipliedByAlpha: Bool {
        let alphaInfo = CGImageAlphaInfo(rawValue: rawValue & Self.alphaInfoMask.rawValue)
        return alphaInfo == .premultipliedFirst || alphaInfo == .premultipliedLast
    }

}
```

OwnerDisplayName: Olie

Body:
I have a UIImage (Cocoa Touch). From that, I'm happy to get a CGImage or anything else you'd like that's available. I'd like to write this function:

- (int)getRGBAFromImage:(UIImage *)image atX:(int)xx andY:(int)yy {
  // [...]
  // What do I want to read about to help
  // me fill in this bit, here?
  // [...]

  int result = (red << 24) | (green << 16) | (blue << 8) | alpha;
  return result;
}

LastEditorDisplayName: Chris Hanson


问:
How to convert server datatime to clients datetime ? C#.NET
I am having a issue that the when clients saves their data it saves the data in server date..Due to this they are unable to fetch their data according to date and time..Server Time is in Usa and clients time is in India ? Your ideas will be welcome </p>

答: You will need to convert USA date to Indian date. I have read this tutorial and says how you can do that and more! Please check it. MSFT Tutorial</p>


问:
SQL database: use one table with 3,5M entries or many tables with less entries?
I'm building a football game that allows people to create leagues online.

Say I have 1000 league after some time. I store my data in SQL. Should I:

1) Create 1 single database with the table "rosters" and insert all the players of all the leagues into it (which would approximate 3,5 to 4 million entries for 1000 leagues)

2) Create 1 single database with 20 tables "rosters1, rosters2, etc" and split the leagues rosters between those 20 tables

3) Create 1 database for each league with a table "rosters" in each

4) Create 20 databases with one table "rosters" in each and split the leagues rosters between the 20 databases.

What is the best option for performance and quick SQL queries?

答:
It sounds like you need to learn a few database basics, first, so please spend some time making sure you understand Database Normalization and indexes.

However, in principal, you probably need a "players" table (player id, name, etc), a "roster" table (roster id, name, maybe owner_id), and a player_roster_map (player_id, roster_id) that links the two. You'll probably want a unique constraint on the composite value of player_id and roster_id, and you should have a foreign key constraint on both player_id and roster_id  in that mapping table.

(I'm presuming that players are not really unique per roster; you can still model similarly if there are attributes that are overridden by the person that owns them, but I'm guessing based on my understanding of your description of the model.)

Your database engine will probably index anything that you mark as a primary key by default, and may index anything that you mark as a foreign key, but this is database dependent, and I am not particularly an expert on MySql; you'll need to do some research.

Proper indexes will help you when you execute queries, at a generally small cost in terms of insert performance. If you end up with large numbers of identical values or a high utilization of queries in which only a small range of values (such as time ranges), you may eventually need to understand partitioning, as well. Partitioning allows you to get the benefits of dealing with fairly large number of records without the modeling problems that denormalization would introduce. However, don't prematurely take this step; you'll probably find that a correct database design will be enough with the size of dataset that you're implying.


问:
Iterate over string with commas
I have two strings:

```<code>x = 'a1,a2,a3'
y = 'b1,b2,b3'
</code>```

I want to concatenate these two string as:

```<code>z = ['a1b1','a1b2','a1b3','a2b1','a2b2','a2b3','a3b1','a3b2','a3b3']
</code>```

I used the code snippet:

```<code>for i in x:
     for j in y:
         z.append(i+j)
</code>```

But the result was not as required. How can I obtain the required result?

答:
This is what you are looking for.</p>

```<code>x = 'a1,a2,a3'.split(',')
y = 'b1,b2,b3'.split(',')

[a+b for a in x for b in y]

</code>```

Title: Iterate over string with commas

Body:
I have two strings:

x = 'a1,a2,a3'
y = 'b1,b2,b3'

I want to concatenate these two string as:

z = ['a1b1','a1b2','a1b3','a2b1','a2b2','a2b3','a3b1','a3b2','a3b3']

I used the code snippet:

for i in x:
     for j in y:
         z.append(i+j)

But the result was not as required. How can I obtain the required result?

Body:
This is what you are looking for.

x = 'a1,a2,a3'.split(',')
y = 'b1,b2,b3'.split(',')

[a+b for a in x for b in y]


问:
How to convert C# Linq to query in SQL Server?
I'm a junior developer and trying to convert the following linq statement to T-SQL:

```<code>var items = from u in DataContext.Users_SearchUsers(searchPara.UserFirstName,
                                                    searchPara.UserLastName,
                                                    searchPara.UserEmailAddress,
                                                    fetchOptions.page,
                                                    fetchOptions.rp,
                                                    fetchOptions.sortname,
                                                    fetchOptions.sortorder)
                                 .ToList()
            join a in DataContext.UserAccesses
                                 .Where(x => x.Access.AccessTypeId == 4).ToList() on u.UserID equals a.UserId into accessGroup
            select new {};
</code>```

Can one please help me ? into accessGroup ---> (very important)

答:
you can use this code </p>

```<code>select *(you can put your columns instead *)
from Users
join UserAccesses
on Users.userid = UserAccesses.userid
where UserAccesses.typeid = 4;
</code>```

Body:
I'm a junior developer and trying to convert the following linq statement to T-SQL:

var items = from u in DataContext.Users_SearchUsers(searchPara.UserFirstName,
                                                    searchPara.UserLastName,
                                                    searchPara.UserEmailAddress,
                                                    fetchOptions.page,
                                                    fetchOptions.rp,
                                                    fetchOptions.sortname,
                                                    fetchOptions.sortorder)
                                 .ToList()
            join a in DataContext.UserAccesses
                                 .Where(x => x.Access.AccessTypeId == 4).ToList() on u.UserID equals a.UserId into accessGroup
            select new {};

Can one please help me ? into accessGroup ---> (very important)

Body:
you can use this code

select *(you can put your columns instead *)
from Users
join UserAccesses
on Users.userid = UserAccesses.userid
where UserAccesses.typeid = 4;


问:
Redirecting updated request does not show
I'm trying to pass updated request (req.update), adding an object to it, but when redirecting from one route ('/') to another ('/dashboard') it does not hold the updates on the (req.update).</p>

```<code>router.post('/signin' , myAuth, signIn);
function signIn (req , res , next){
  console.log(req.userId, 'woooooooooooooorked');
  // router.get('/dashboard');
  res.redirect(303 ,'/dashboard');
  // next(res.redirect('/dashboard'));
}
</code>```

```<code>router.get('/dashboard' , dashboard) ;

async function dashboard(req ,res ,next){
  console.log(req.userId , '*********');

  let scanResult = await Model.get(req._id);
  console.log(scanResult , 'dashboard');
  res.status(200).send(scanResult);
}

</code>```

答:
When you use res.redirect it will send a response to the client with redirect headers and then the client will initiate a new request, so all previous data will be lost at this time.

You could use app.set() method to set the data and get it in other routes.

Example.

```<code>router.post('/signin' , myAuth, signIn);
function signIn (req , res , next){
  app.set('userId', req.userId);
  console.log(req.userId, 'woooooooooooooorked');
  res.redirect(303 ,'/dashboard');
}
</code>```

```<code>router.get('/dashboard' , dashboard) ;

async function dashboard(req ,res ,next){
  console.log(req.userId , '*********');

  let scanResult = await Model.get(app.get('userId'));
  console.log(scanResult , 'dashboard');
  res.status(200).send(scanResult);
}
</code>```

Or you could use query strings to pass the data.

Example:

```<code>
router.post('/signin' , myAuth, signIn);
function signIn (req , res , next){
  console.log(req.userId, 'woooooooooooooorked');
  res.redirect(303 ,'/dashboard?userId=' + req.userId);
}

</code>```

```<code>router.get('/dashboard' , dashboard) ;

async function dashboard(req ,res ,next){
  console.log(req.userId , '*********');

  let scanResult = await Model.get(req.query.userId);
  console.log(scanResult , 'dashboard');
  res.status(200).send(scanResult);
}
</code>```

Body:
I'm trying to pass updated request (req.update), adding an object to it, but when redirecting from one route ('/') to another ('/dashboard') it does not hold the updates on the (req.update).

router.post('/signin' , myAuth, signIn);
function signIn (req , res , next){
  console.log(req.userId, 'woooooooooooooorked');
  // router.get('/dashboard');
  res.redirect(303 ,'/dashboard');
  // next(res.redirect('/dashboard'));
}

router.get('/dashboard' , dashboard) ;

async function dashboard(req ,res ,next){
  console.log(req.userId , '*********');

  let scanResult = await Model.get(req._id);
  console.log(scanResult , 'dashboard');
  res.status(200).send(scanResult);
}

Body:
When you use res.redirect it will send a response to the client with redirect headers and then the client will initiate a new request, so all previous data will be lost at this time.

You could use app.set() method to set the data and get it in other routes.

Example.

router.post('/signin' , myAuth, signIn);
function signIn (req , res , next){
  app.set('userId', req.userId);
  console.log(req.userId, 'woooooooooooooorked');
  res.redirect(303 ,'/dashboard');
}

router.get('/dashboard' , dashboard) ;

async function dashboard(req ,res ,next){
  console.log(req.userId , '*********');

  let scanResult = await Model.get(app.get('userId'));
  console.log(scanResult , 'dashboard');
  res.status(200).send(scanResult);
}

Or you could use query strings to pass the data.

Example:

router.post('/signin' , myAuth, signIn);
function signIn (req , res , next){
  console.log(req.userId, 'woooooooooooooorked');
  res.redirect(303 ,'/dashboard?userId=' + req.userId);
}

router.get('/dashboard' , dashboard) ;

async function dashboard(req ,res ,next){
  console.log(req.userId , '*********');

  let scanResult = await Model.get(req.query.userId);
  console.log(scanResult , 'dashboard');
  res.status(200).send(scanResult);
}


问:
Use mutate in purrr workflow
I got the following datasets:

```<code>dflist <- list(mtcars, mtcars)

dflist[[1]] %>%
  mutate(cyl2 = cyl * 2)
</code>```

This works!

```<code>dflist %>%
  map(.x, ~.x$cyl2 = .x$cyl * 2)

Error: unexpected '=' in:
"dflist %>%
  map(.x, ~x$cyl2 ="
</code>```

This results in an error. I tried other options, but the function does not except the = sign. What is wrong there?

Title: Use mutate in purrr workflow

Body:
I got the following datasets:

dflist <- list(mtcars, mtcars)

dflist[[1]] %>%
  mutate(cyl2 = cyl * 2)

This works!

dflist %>%
  map(.x, ~.x$cyl2 = .x$cyl * 2)

Error: unexpected '=' in:
"dflist %>%
  map(.x, ~x$cyl2 ="

This results in an error. I tried other options, but the function does not except the = sign. What is wrong there?

Body:
You can also try:

modify(dflist, ~ update_list(., cyl2 = ~ cyl * 2))

[[1]]
                   mpg cyl disp  hp drat    wt  qsec vs am gear carb cyl2
Mazda RX4         21.0   6  160 110 3.90 2.620 16.46  0  1    4    4   12
Mazda RX4 Wag     21.0   6  160 110 3.90 2.875 17.02  0  1    4    4   12
Datsun 710        22.8   4  108  93 3.85 2.320 18.61  1  1    4    1    8
Hornet 4 Drive    21.4   6  258 110 3.08 3.215 19.44  1  0    3    1   12
Hornet Sportabout 18.7   8  360 175 3.15 3.440 17.02  0  0    3    2   16

[[2]]
                   mpg cyl disp  hp drat    wt  qsec vs am gear carb cyl2
Mazda RX4         21.0   6  160 110 3.90 2.620 16.46  0  1    4    4   12
Mazda RX4 Wag     21.0   6  160 110 3.90 2.875 17.02  0  1    4    4   12
Datsun 710        22.8   4  108  93 3.85 2.320 18.61  1  1    4    1    8
Hornet 4 Drive    21.4   6  258 110 3.08 3.215 19.44  1  0    3    1   12
Hornet Sportabout 18.7   8  360 175 3.15 3.440 17.02  0  0    3    2   16


问:
Write a custom "editable" directive with angularjs
I'm studying angularjs, and I want to write a custom "editable" directive, which can make a normal html element "editable":

When user clicks it, it will show a text input or textarea to let user edit the content, and there is also a "update" and "cancel" button besides. User can click the "update" button or press "Ctrl+enter" to submit the modified content, or click "cancel" or press "escape" to cancel the modification.

The "editable" signature looks like:

```<code><div editable
     e-trigger="click|dblclick"       /* use click or dblclick to trigger the action */
     e-update-url="http://xxx/xxx"    /* when submitting, the data will PUT to this url */
     e-singleline="true|false"        /* if ture, use text input, otherwise textarea */
     ng-model="name">                 /* the corresponding model name */
{{name}}
</div>
</code>```

I've create a live demo here: http://jsfiddle.net/Freewind/KRduz/, you can just update it.

答:
use e-addYourDirectiveName

   ```

letters-input e-name="ValueAr" e-form="UniversityForm" onbeforesave="checkValue($data)">
                                        {{ university.ValueAr }}

Body:
I'm studying angularjs, and I want to write a custom "editable" directive, which can make a normal html element "editable":

When user clicks it, it will show a text input or textarea to let user edit the content, and there is also a "update" and "cancel" button besides. User can click the "update" button or press "Ctrl+enter" to submit the modified content, or click "cancel" or press "escape" to cancel the modification.

The "editable" signature looks like:

                 /* the corresponding model name */
{{name}}

I've create a live demo here: http://jsfiddle.net/Freewind/KRduz/, you can just update it.

Body:
use e-addYourDirectiveName

 <span editable-text="university.ValueAr" e-only-arabic-letters-input e-name="ValueAr" e-form="UniversityForm">  </span>

letters-input e-name="ValueAr" e-form="UniversityForm" onbeforesave="checkValue($data)">
                                        {{ university.ValueAr }}


问:
How to get predicates by specifying the number of arguments it should have?
Suppose I have these relations:

```<code>d(m, n).
d(x, y).
d(a, b, c).
d(i, j, k).
d(1, 2, 3, 4).
</code>```

How can I write a predicate mypred(Pred, NumArgs, Rel)?

Examples:

mypred(d, 2, Rel): Rel would be d(m, n), d(x, y), false.

mypred(d, 3, Rel): Rel would be d(a, b, c), d(i, j, k), false.

mypred(d, 4, Rel): Rel would be d(1, 2, 3, 4), false.

答:
```<code>mypred(F, A, Rel_0) :-
   functor(Rel_0, F, A),
   call(Rel_0).
</code>```

However, rather don't use such a definition.  Instead try to use call/N with N > 1.

Definitions as mypred/3, are very difficult to analyze.  Cross-referencing is practically impossible.  On the other hand, with call/N, N > 1 quite similar functionality is possible, cross-referencing stays intact. See meta-predicate for many uses.

Body:
Suppose I have these relations:

d(m, n).
d(x, y).
d(a, b, c).
d(i, j, k).
d(1, 2, 3, 4).

How can I write a predicate mypred(Pred, NumArgs, Rel)?

Examples:

mypred(d, 2, Rel): Rel would be d(m, n), d(x, y), false.

mypred(d, 3, Rel): Rel would be d(a, b, c), d(i, j, k), false.

mypred(d, 4, Rel): Rel would be d(1, 2, 3, 4), false.

Body:
mypred(F, A, Rel_0) :-
   functor(Rel_0, F, A),
   call(Rel_0).

However, rather don't use such a definition.  Instead try to use call/N with N > 1.

Definitions as mypred/3, are very difficult to analyze.  Cross-referencing is practically impossible.  On the other hand, with call/N, N > 1 quite similar functionality is possible, cross-referencing stays intact. See meta-predicate for many uses.


问:
Does tree object type in git internals point to the blob only or to trees as well?
I've explored a lot about the 3 commit model of the git internals and in the diagram,it's shown that tree object type is pointing to the other trees as well, but when I do
git cat-file -p 'sha-hash',
It tells that tree is pointing to the blobs only.
Please refer to the screenshot attached.
Please help me with a screenshot where tree is pointing to some other tree or tell me any use case which I may be missing.

答:
If a file's name is a/b/c/f.ext it will be stored in a commit as:

at the level of the commit: a tree containing a subtree named a

at the level of the subtree named a: a tree containing a subtree named b

at the level of the subtree named b: a tree containing a subtree named c

at the level of the subtree named c: a tree containing a blob named f.ext

Hence, from the top, we simply string together the names of each higher level tree to arrive at the file's actual name, a/b/c/f.ext.

None of this really matters while using the file, since the important version of the file is the one in the index, and that one is named a/b/c/f.ext (with slashes in the name).  It only matters when reading trees into the index (git read-tree), and when writing the index to a series of trees (git write-tree).


问:
Building a string representation of an object using a "mask" or user supplied Format String
I'm not really sure what tags should be on this sort of question so feel free to give me some suggestions if you think some others are more suited.

I have a dynamic object with an unknown number or properties on it, it's from a sort of dynamic self describing data model that lets the user build the data model at runtime. However because all of the fields holding relevant information to the user are in dynamic properties, it's difficult to determine what should be the human readable identifier, so it's left up to the administrator. (Don't think it matters but this is an ASP.NET MVC3 Application). To help during debugging I had started decorating some classes with DebuggerDisplayAttribute to make it easier to debug. This allow me to do things like

```<code>[DebuggerDisplay(@"\{Description = {Description}}")]
public class Group
</code>```

to get a better picture of what a specific instance of an object is. And this sort of setup would be perfect but I can't seem to find the implementation of this flexibility. This is especially useful on my dynamic objects because the string value of the DebuggerDisplayAttribute is resolved by the .NET framework and I have implementations of TryGetMember on my base object class to handle the dynamic aspect. But this only makes it easier for development. So I've added a field on what part of my object is still strongly typed and called it Title, and I'd like to let the administer set the implementation using their own format, so to speak. So for example they might build out a very simplistic rental tracking system to show rentals and they might specify a format string along the lines of

```<code>"{MovieTitle} (Due: {DueDate})"
</code>```

I would like that when they save the record to add some logic to first update the Title property by resolving the format string to substitute each place holder with the value of the appropriate property on the dynamic object. So this might resolve to a title of
"Inception (Due: May 21, 2011)", or a more realistic scenario of a format string of

```<code>"{LastName}, {FirstName}"
</code>```

I don't want the user to have to update the title of a record when they change the first name field or the last name field. I fully realize this will likely use reflection but I'm hoping some one out there can give me some pointers or even a working example to handle complex format strings that could be a mix if literal text and placeholders.

I've not had much luck looking for an implementation on the net that will do what I want since I'm not really sure what keywords would give me the most relevant search results?

答:
You need two things:

1) A syntax for formatting strings

You have already described a syntax where variables are surrounded by bracers, and if you want to use that you need to build a parser that can parse that. Perhaps you also want to add ways to specify say a date or a number format.

2) Rules for resolving variables

If there is a single context object you can use reflection and match variable names to properties but if your object model is more complex you can add conventions for searching say a hierarchy of objects.

If you are planning to base your model objects on dynamic chances are that you will find the Clay library on CodePlex interesting.

Body:
I'm not really sure what tags should be on this sort of question so feel free to give me some suggestions if you think some others are more suited.

I have a dynamic object with an unknown number or properties on it, it's from a sort of dynamic self describing data model that lets the user build the data model at runtime. However because all of the fields holding relevant information to the user are in dynamic properties, it's difficult to determine what should be the human readable identifier, so it's left up to the administrator. (Don't think it matters but this is an ASP.NET MVC3 Application). To help during debugging I had started decorating some classes with DebuggerDisplayAttribute to make it easier to debug. This allow me to do things like

[DebuggerDisplay(@"\{Description = {Description}}")]
public class Group

to get a better picture of what a specific instance of an object is. And this sort of setup would be perfect but I can't seem to find the implementation of this flexibility. This is especially useful on my dynamic objects because the string value of the DebuggerDisplayAttribute is resolved by the .NET framework and I have implementations of TryGetMember on my base object class to handle the dynamic aspect. But this only makes it easier for development. So I've added a field on what part of my object is still strongly typed and called it Title, and I'd like to let the administer set the implementation using their own format, so to speak. So for example they might build out a very simplistic rental tracking system to show rentals and they might specify a format string along the lines of

"{MovieTitle} (Due: {DueDate})"

I would like that when they save the record to add some logic to first update the Title property by resolving the format string to substitute each place holder with the value of the appropriate property on the dynamic object. So this might resolve to a title of
"Inception (Due: May 21, 2011)", or a more realistic scenario of a format string of

"{LastName}, {FirstName}"

I don't want the user to have to update the title of a record when they change the first name field or the last name field. I fully realize this will likely use reflection but I'm hoping some one out there can give me some pointers or even a working example to handle complex format strings that could be a mix if literal text and placeholders.

I've not had much luck looking for an implementation on the net that will do what I want since I'm not really sure what keywords would give me the most relevant search results?