问:
Prevent @RabbitListener in spring-rabbit from trying to connect to server during integration test
I want to run some acceptance tests for my services that are using rabbitMq but I want to ignore all that require inter-service communication (amqp).

The problem however is that Spring tries to connect to the (non-exisiting) rabbit host on startup so it can register its consumers. It does that for each method that is annotated with @RabbitListener which can get quite annoying with the long timeout this has if I have more than one listener in my service.

How can I reduce this timeout or even prevent @RabbitListener connection all together?

Our (simplified) Rabbit Config:

```<code>@Configuration
@EnableRabbit
public class RabbitMqConfig {

    public RabbitMqConfig(
            @Value("${rabbitmq.host}") String rabbitHost,
            @Value("${rabbitmq.port}") int rabbitPort,
            @Value("${exchange.name}") String exchange) {
        this.rabbitHost = rabbitHost;
        this.rabbitPort = rabbitPort;
        this.exchange= exchange;
    }

  @Bean
  DirectExchange directExchangeBean() {
    return new DirectExchange(this.exchange, true, false);
  }

  @Bean
  public ConnectionFactory connectionFactory() {
    CachingConnectionFactory connectionFactory = new CachingConnectionFactory(rabbitHost);
    connectionFactory.setPort(rabbitPort);
    return connectionFactory;
  }

  @Bean
  public RabbitTemplate rabbitTemplate() {
    return new RabbitTemplate(connectionFactory());
  }

  @Bean
  public Queue itemDoneQueue() {
    return new Queue(ITEM_DONE_QUEUENAME, true);
  }

  @Bean
  Binding itemDoneBinding() {
    return BindingBuilder.bind(itemDoneQueue()).to(directExchangeBean()).with(ITEM_DONE_KEY);
  }

}
</code>```

Properties

```<code>rabbitmq.host=192.168.42.100
rabbitmq.port=5672
exchange.name=myExchange
</code>```

The Listener:

```<code>  @RabbitListener(queues = ITEM_DONE_QUEUENAME)
  public void receiveMessageFromItemDoneQueue(String message) {
    // do the work
  }
</code>```

The Test:

```<code>@RunWith(SpringRunner.class)
@SpringBootTest(classes = {Application.class})
public abstract class RabbitTest {
</code>```

Really nothing special here. Obviously during testing the rabbit host is unavailable. That is fine. I want to ignore the fact. And quickly.

I've tried

```<code>spring.rabbitmq.connection-timeout=1
</code>```

But that didn't change anything.

Using

```<code>spring.rabbitmq.listener.simple.auto-startup=false
</code>```

neither does anything.

Using

```<code>spring.autoconfigure.exclude:org.springframework.boot.autoconfigure.amqp.RabbitAutoConfiguration
</code>```

just kills my application context loading with spring complaining about a NoSuchBeanDefinitionException: No bean named 'rabbitListenerContainerFactory' available

Any ideas?
Thanks!

答:
I would expect the spring.rabbitmq.listener.simple.auto-startup=false to work - are you sure you're not trying to connect to Rabbit with some other code? Can you provide a DEBUG log to show the problem when that is set to false?

You can use the JUnit BrokerRunning @Rule to skip any tests that need a real RabbitMQ broker.

Body:
I want to run some acceptance tests for my services that are using rabbitMq but I want to ignore all that require inter-service communication (amqp).

The problem however is that Spring tries to connect to the (non-exisiting) rabbit host on startup so it can register its consumers. It does that for each method that is annotated with @RabbitListener which can get quite annoying with the long timeout this has if I have more than one listener in my service.

How can I reduce this timeout or even prevent @RabbitListener connection all together?

Our (simplified) Rabbit Config:

@Configuration
@EnableRabbit
public class RabbitMqConfig {

    public RabbitMqConfig(
            @Value("${rabbitmq.host}") String rabbitHost,
            @Value("${rabbitmq.port}") int rabbitPort,
            @Value("${exchange.name}") String exchange) {
        this.rabbitHost = rabbitHost;
        this.rabbitPort = rabbitPort;
        this.exchange= exchange;
    }

  @Bean
  DirectExchange directExchangeBean() {
    return new DirectExchange(this.exchange, true, false);
  }

  @Bean
  public ConnectionFactory connectionFactory() {
    CachingConnectionFactory connectionFactory = new CachingConnectionFactory(rabbitHost);
    connectionFactory.setPort(rabbitPort);
    return connectionFactory;
  }

  @Bean
  public RabbitTemplate rabbitTemplate() {
    return new RabbitTemplate(connectionFactory());
  }

  @Bean
  public Queue itemDoneQueue() {
    return new Queue(ITEM_DONE_QUEUENAME, true);
  }

  @Bean
  Binding itemDoneBinding() {
    return BindingBuilder.bind(itemDoneQueue()).to(directExchangeBean()).with(ITEM_DONE_KEY);
  }

}

Properties

rabbitmq.host=192.168.42.100
rabbitmq.port=5672
exchange.name=myExchange

The Listener:

  @RabbitListener(queues = ITEM_DONE_QUEUENAME)
  public void receiveMessageFromItemDoneQueue(String message) {
    // do the work
  }

The Test:

@RunWith(SpringRunner.class)
@SpringBootTest(classes = {Application.class})
public abstract class RabbitTest {

Really nothing special here. Obviously during testing the rabbit host is unavailable. That is fine. I want to ignore the fact. And quickly.

I've tried

spring.rabbitmq.connection-timeout=1

But that didn't change anything.

Using

spring.rabbitmq.listener.simple.auto-startup=false

neither does anything.

Using

spring.autoconfigure.exclude:org.springframework.boot.autoconfigure.amqp.RabbitAutoConfiguration

just kills my application context loading with spring complaining about a NoSuchBeanDefinitionException: No bean named 'rabbitListenerContainerFactory' available

Any ideas?
Thanks!


来源: stackexchange

问:
MDX filter one dimension by multiple criteria using "like"
I'm new on MDX, and please help me with an example of how can I build an MDX query that will have a filter equivalent with the following SQL:

select *

from [dbo].[FactPurchase]

where Artikelnummer like 'E75%'

or Artikelnummer like 'S241%%NA'

or Artikelnummer like 'S241%%SW'

or Artikelnummer like 'S241%%PL'

Thanks.

答:
I find an answer that works for my needs here:
http://sqljason.com/2010/04/searching-substrings-in-mdx.html</p>

ContentLicense: CC BY-SA 3.0


问:
zfs send warning: snapshot does not exist (it exists)
I have the next 'zfs pool' in the machine A:

```<code>root@machineA:/ # zfs list -t all
NAME                                            USED  AVAIL  REFER  MOUNTPOINT
tank                                           7.44M  28.8G    20K  /tank
tank/test                                        92K  28.8G    19K  /tank/test
tank/test@SNAP_2017-June-30_10:00:00              9K      -    19K  -
tank/test@SNAP_2017-July-01_10:00:00              9K      -    19K  -
tank/test@SNAP_2017-July-02_10:00:00              9K      -    19K  -
tank/test@SNAP_2017-July-03_10:00:00              9K      -    19K  -
tank/test@SNAP_2017-July-04_10:00:00               0      -    19K  -
tank/test@BACKUP_from_2017-June-30                 0      -    19K  -
tank/test/exe                                    37K  28.8G    19K  /tank/test/exe
tank/test/exe@EXE_2017-June-29_13:58:49           9K      -    19K  -
tank/test/exe@EXE_2017-July-03_10:00:00           9K      -    19K  -
tank/test/exe@EXE_2017-July-04_10:00:00            0      -    19K  -
tank/test/exe@BACKUP_from_2017-June-29
</code>```

And I want to send a snapshot to the machine B:

```<code>root@machineB:/ # zfs list -t all
NAME   USED  AVAIL  REFER  MOUNTPOINT
tank  6.04M  28.8G    23K  /tank
</code>```

With the netcat I can send the snapshots but the system returns me an error very unusual...

If I do:

```<code>B: nc -w 5 -l 7766 | zfs recv tank/test/exe
A: zfs send -R tank/test/exe@EXE_2017-July-04_10:00:00 | nc -w 5 192.168.99.2 7766
</code>```

All it's ok, but if I do:

```<code>B: nc -w 5 -l 7766 | zfs recv tank/test
A: zfs send -R tank/test@SNAP_2017-July-04_10:00:00 | nc -w 5 192.168.99.2 7766
</code>```

The stream of snapshots is sent but in the source side I can show:

```<code>root@machineA:/ # zfs send -R tank/test@SNAP_2017-July-04_10:00:00 | nc -w 5 192.168.99.2 7766
WARNING: could not send tank/test/exe@SNAP_2017-July-04_10:00:00: does not exist
WARNING: could not send tank/test/exe@SNAP_2017-July-04_10:00:00: does not exist
</code>```

Why ZFS takes the dataset tank/test/exe? Any suggestions?

答:
Actually, the snapshots it's complaining about don't exist on the source system -- tank/test/exe only has @EXE_<date> snapshots, while you're trying to send tank/test/exe@SNAP_<date>. This warning is appearing because you're sending with -R (recursive) from the top-level tank/test filesystem, which sends the specified snapshot on the parent filesystem first, and then searches the children for the same snapshot name to try to send those as well. Usually, this only does what you are expecting when you've taken a snapshot on the parent filesystem with -R -- on your system, you only snapshotted the parent without snapshotting the child at the same time.

On the sending system, you probably want to change your command to be:

zfs send -R tank/test/snap@SNAP_2017-July-04_10:00:00 | nc -w 5 192.168.99.2 7766

Body:
I have the next 'zfs pool' in the machine A:

root@machineA:/ # zfs list -t all
NAME                                            USED  AVAIL  REFER  MOUNTPOINT
tank                                           7.44M  28.8G    20K  /tank
tank/test                                        92K  28.8G    19K  /tank/test
tank/test@SNAP_2017-June-30_10:00:00              9K      -    19K  -
tank/test@SNAP_2017-July-01_10:00:00              9K      -    19K  -
tank/test@SNAP_2017-July-02_10:00:00              9K      -    19K  -
tank/test@SNAP_2017-July-03_10:00:00              9K      -    19K  -
tank/test@SNAP_2017-July-04_10:00:00               0      -    19K  -
tank/test@BACKUP_from_2017-June-30                 0      -    19K  -
tank/test/exe                                    37K  28.8G    19K  /tank/test/exe
tank/test/exe@EXE_2017-June-29_13:58:49           9K      -    19K  -
tank/test/exe@EXE_2017-July-03_10:00:00           9K      -    19K  -
tank/test/exe@EXE_2017-July-04_10:00:00            0      -    19K  -
tank/test/exe@BACKUP_from_2017-June-29

And I want to send a snapshot to the machine B:

root@machineB:/ # zfs list -t all
NAME   USED  AVAIL  REFER  MOUNTPOINT
tank  6.04M  28.8G    23K  /tank

With the netcat I can send the snapshots but the system returns me an error very unusual...

If I do:

B: nc -w 5 -l 7766 | zfs recv tank/test/exe
A: zfs send -R tank/test/exe@EXE_2017-July-04_10:00:00 | nc -w 5 192.168.99.2 7766

All it's ok, but if I do:

B: nc -w 5 -l 7766 | zfs recv tank/test
A: zfs send -R tank/test@SNAP_2017-July-04_10:00:00 | nc -w 5 192.168.99.2 7766

The stream of snapshots is sent but in the source side I can show:

root@machineA:/ # zfs send -R tank/test@SNAP_2017-July-04_10:00:00 | nc -w 5 192.168.99.2 7766
WARNING: could not send tank/test/exe@SNAP_2017-July-04_10:00:00: does not exist
WARNING: could not send tank/test/exe@SNAP_2017-July-04_10:00:00: does not exist

Why ZFS takes the dataset tank/test/exe? Any suggestions?


问:
RDP automatic log off after 15 minutes
I am having an issue when I connect to a server via RDP. The server is a Windows Server 2016 Standard; and after 15 minutes of inactivity from my side, it seems to close the session, closing all the applications I had open etc...

This is extremely irritating, especially when I am writing code in ‘sql server management studio’, or if I am moving files… I then re-connect via RDP, and it successfully loads a new session.

I have tried this solution, but did not fix it:

Browse to Computer Configuration --> Administrative Templates --> Windows Components --> Remote Desktop Services --> Remote Desktop Session Host --> Session Time Limits.
Enable the "Set time limit for disconnected sessions" and set it to Never

答:
You can try to enable RDP keep alive functionnality in the registry:

In regedit.exe as admin:

```<code>Go to the location HKLM\SYSTEM\CurrentControlSet\Control\Terminal Server
Create or edit the DWORD value of KeepAliveEnable
Set it to 1.
Save and quit
</code>```

see https://superuser.com/a/1144885/745652

Title: RDP automatic log off after 15 minutes

Body:
You can try to enable RDP keep alive functionnality in the registry:

In regedit.exe as admin:

Go to the location HKLM\SYSTEM\CurrentControlSet\Control\Terminal Server
Create or edit the DWORD value of KeepAliveEnable
Set it to 1.
Save and quit

see https://superuser.com/a/1144885/745652


问:
How to convert mySQL Query to Laravel 5.4 Query Builder
Please someone should help me convert this SQL Query to Laravel 5.4 Query Builder syntax. I have searched for solutions and found some but not exactly as I wanted.

I have 3 tables:

Feeds:
   - feed_id
   - user_id
   - feed_title

Users:
   - id
   - username

Commments:
   - comment_id
   - feed_id
   - text
   - user_id

On my view returned, I want to see the feed title, user's user name, and a count of all comments to each feed. Like what you see on facebook: displaying the amount of comments on each post displayed. Please I really need this to be done:

This is the SQL code I tried in MySQL Database, it kinda works there but returns an error when I try to implement the same in Laravel

```<code>select *, count(comments.comment_id) as comment_count
from `feeds`
inner join `users` on
`feeds`.`user_id` = `users`.`id`
inner join `comments` on
`feeds`.`feed_id` = `comments`.`comment_feed_id`
group by `comments`.`comment_feed_id`
</code>```

答:
This should do it, assuming the name of your model is "Feed":</p>

```<code>Feed::selectRaw('feeds.*, count(comments.comment_id) as comment_count')
->join('users', 'users.id', '=', 'feeds.user_id')
->join('comments', 'feeds.feed_id', '=', 'comments.comment_feed_id')
->groupBy('comments.comment_feed_id')->get();
</code>```

Body:
Please someone should help me convert this SQL Query to Laravel 5.4 Query Builder syntax. I have searched for solutions and found some but not exactly as I wanted.

I have 3 tables:

Feeds:
   - feed_id
   - user_id
   - feed_title

Users:
   - id
   - username

Commments:
   - comment_id
   - feed_id
   - text
   - user_id

On my view returned, I want to see the feed title, user's user name, and a count of all comments to each feed. Like what you see on facebook: displaying the amount of comments on each post displayed. Please I really need this to be done:

This is the SQL code I tried in MySQL Database, it kinda works there but returns an error when I try to implement the same in Laravel

select *, count(comments.comment_id) as comment_count
from `feeds`
inner join `users` on
`feeds`.`user_id` = `users`.`id`
inner join `comments` on
`feeds`.`feed_id` = `comments`.`comment_feed_id`
group by `comments`.`comment_feed_id`

Body:
This should do it, assuming the name of your model is "Feed":

Feed::selectRaw('feeds.*, count(comments.comment_id) as comment_count')
->join('users', 'users.id', '=', 'feeds.user_id')
->join('comments', 'feeds.feed_id', '=', 'comments.comment_feed_id')
->groupBy('comments.comment_feed_id')->get();


问:
Using column-count together with ::before
In a small experiment I tried to replace the default bullets in a list by custom ones using a ::before pseudo-element. This works in both Chrome 50 as well as Firefox 46.

But when I try to combine that with column-count it breaks in Chrome. Firefox, however, displays like I intended it.

So is this a bug in Chrome (respective Blink) I should report or did I miss something here and Firefox is just able to deal with my crappy code?

Fiddle

ul#test {
  -webkit-column-count: 3;
  -moz-column-count: 3;
  column-count: 3;
}
li {
  list-style-type: none;
}
li::before {
  content: '*';
  width: 0.7em;
  height: 0.7em;
  margin-right: -0.7em;
  display: inline-block;
  position: relative;
  left: -1em;
  background-color: blue;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul>
  <li>1</li>
  <li>2</li>
  <li>3</li>
  <li>4</li>
  <li>5</li>
  <li>6</li>
</ul>
<ul id="test">
  <li>1</li>
  <li>2</li>
  <li>3</li>
  <li>4</li>
  <li>5</li>
  <li>6</li>
</ul></code>```

答:
I ran into the same problem today and my solution is to simply float the ::before-Element. Beside that I added some handy improvements:

Fiddle

li {
  list-style-type: none;
  margin-left: 1.5em;
  line-height: 1.25em;
  break-inside: avoid;
}
li:before {
  content: '';
  width: 0.7em;
  height: 0.7em;
  display: block;
  float: left;
  margin: 0 .5em 0 -1.3em;
  background-color: #BBB;
  position: relative;
  top: .25em;
}

ul#withColumCountAndBefore {
  -webkit-column-count: 3;
  -moz-column-count: 3;
  column-count: 3;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><h2>ul without column count</h2>
<ul>
  <li>1</li>
  <li>2</li>
  <li>3</li>
  <li>4</li>
  <li>5</li>
  <li>6</li>
</ul>
<h2>ul with column count (using :before and float)</h2>
<ul id="withColumCountAndBefore">
  <li>1</li>
  <li>2 with a very long tail to cause a line break</li>
  <li>3</li>
  <li>4</li>
  <li>5</li>
  <li>6</li>
</ul></code>```

Body:
In a small experiment I tried to replace the default bullets in a list by custom ones using a ::before pseudo-element. This works in both Chrome 50 as well as Firefox 46.

But when I try to combine that with column-count it breaks in Chrome. Firefox, however, displays like I intended it.

So is this a bug in Chrome (respective Blink) I should report or did I miss something here and Firefox is just able to deal with my crappy code?

Fiddle

ul#test {
  -webkit-column-count: 3;
  -moz-column-count: 3;
  column-count: 3;
}
li {
  list-style-type: none;
}
li::before {
  content: '*';
  width: 0.7em;
  height: 0.7em;
  margin-right: -0.7em;
  display: inline-block;
  position: relative;
  left: -1em;
  background-color: blue;
}

1

2

3

4

5

6

1

2

3

4

5

6

Body:
I ran into the same problem today and my solution is to simply float the ::before-Element. Beside that I added some handy improvements:

Fiddle

li {
  list-style-type: none;
  margin-left: 1.5em;
  line-height: 1.25em;
  break-inside: avoid;
}
li:before {
  content: '';
  width: 0.7em;
  height: 0.7em;
  display: block;
  float: left;
  margin: 0 .5em 0 -1.3em;
  background-color: #BBB;
  position: relative;
  top: .25em;
}

ul#withColumCountAndBefore {
  -webkit-column-count: 3;
  -moz-column-count: 3;
  column-count: 3;
}

<h2>ul without column count</h2>
<ul>
  <li>1</li>
  <li>2</li>
  <li>3</li>
  <li>4</li>
  <li>5</li>
  <li>6</li>
</ul>
<h2>ul with column count (using :before and float)</h2>
<ul id="withColumCountAndBefore">
  <li>1</li>
  <li>2 with a very long tail to cause a line break</li>
  <li>3</li>
  <li>4</li>
  <li>5</li>
  <li>6</li>
</ul>


问:
Identify multiple regex matches in a single string and get substring for each match
I would like to find strings with regex pattern.
For example:

```<code># header ## smaller header
</code>```

I would like to find two string set as follows.

```<code># header
## smaller header
</code>```

So I make the regex pattern as follows.

```<code>pattern = re.compile("(?:^#+|\s#+)\s")
</code>```

With this pattern, I can find # header.

```<code># header
</code>```

But I can't find the string such as ## smaller header

How can I make the regex so that find two set of strings?

答:
```<code>       import re
       pattern = re.compile("#+[\s\w]+")
       a = re.findall(pattern,'# header ## smaller header')
       print (*a,sep="\n")
</code>```

Body:
I would like to find strings with regex pattern.
For example:

# header ## smaller header

I would like to find two string set as follows.

# header
## smaller header

So I make the regex pattern as follows.

pattern = re.compile("(?:^#+|\s#+)\s")

With this pattern, I can find # header.

# header

But I can't find the string such as ## smaller header

How can I make the regex so that find two set of strings?


问:
UI buttons and images are cruppted after upgrading project to unity 5 on ios

Im facing a problem after upgrading my project  on unity5 on ios platform.

 it's working fine on Android and the editor but on is in real device all sprite images and hi buttons are cruppted.
Screen shot:

https://i.stack.imgur.com/McxvL.jpg

I need help to fix this issue.

Thanks alot

答: Reset the image from the inspector was the solution</p>


问:
How can I create the necessary out-directories for targets with make?
Say, in a Makefile, I have the following targets:

```<code>EXES=dir1/subdir1/abc dir1/subdir1/def dir1/subdir2/ghi dir1/subdir2/jkl dir2/subdir3/mno dir2/subdir3/pqr
</code>```

Each item in $(EXES) represents a binary to be created. I want to make sure that the necessary directories (in the example: dir1/subdir1, dir1/subdir2, dir2/subdir3) are created if they are not existent.

How would I achieve this with gnu-make?

答:
I finally found a solution with $(dir ...)

```<code>EXE_DIRS=$(dir $(EXES))

EXE_DIRS_UNIQUE=$(shell for DIR in $(EXE_DIRS); do echo $$DIR; done | sort | uniq)

$(shell for DIR in $(EXE_DIRS_UNIQUE); do if [ ! -d $$DIR ]; then mkdir -p $$DIR; fi; done)

all: $(EXES)
</code>```

Body:
Say, in a Makefile, I have the following targets:

EXES=dir1/subdir1/abc dir1/subdir1/def dir1/subdir2/ghi dir1/subdir2/jkl dir2/subdir3/mno dir2/subdir3/pqr

Each item in $(EXES) represents a binary to be created. I want to make sure that the necessary directories (in the example: dir1/subdir1, dir1/subdir2, dir2/subdir3) are created if they are not existent.

How would I achieve this with gnu-make?

Body:
I finally found a solution with $(dir ...)

EXE_DIRS=$(dir $(EXES))

EXE_DIRS_UNIQUE=$(shell for DIR in $(EXE_DIRS); do echo $$DIR; done | sort | uniq)

$(shell for DIR in $(EXE_DIRS_UNIQUE); do if [ ! -d $$DIR ]; then mkdir -p $$DIR; fi; done)

all: $(EXES)


问:
Remove some part of URL using javascript
I have a URL which will be something like below

```<code>http://localhost:22306/NESSPATH/VSAT/I-HP-AAMB-ENB-0003_C1//Panaromic//120.jpg
</code>```

I want URL which will be something like this

```<code>NESSPATH/VSAT/I-HP-AAMB-ENB-0003_C1//Panaromic//120.jpg
</code>```

Here is what I get in variable

```<code>VSATSaving.PANAROMIC_120 = document.getElementById('ImgPanaromic120').src;
</code>```

how to get that using javascript. Tried with lastIndexOf but it is not working

答:
You can create a new URL object and use the pathname property to extract the data.

const myUrl = new URL(document.getElementById('ImgPanaromic120').src);

console.log(myUrl.pathname);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><img id="ImgPanaromic120" src="http://localhost:22306/NESSPATH/VSAT/I-HP-AAMB-ENB-0003_C1//Panaromic//120.jpg"/></code>```

Body:
I have a URL which will be something like below

http://localhost:22306/NESSPATH/VSAT/I-HP-AAMB-ENB-0003_C1//Panaromic//120.jpg

I want URL which will be something like this

NESSPATH/VSAT/I-HP-AAMB-ENB-0003_C1//Panaromic//120.jpg

Here is what I get in variable

VSATSaving.PANAROMIC_120 = document.getElementById('ImgPanaromic120').src;

how to get that using javascript. Tried with lastIndexOf but it is not working

Body:
You can create a new URL object and use the pathname property to extract the data.

const myUrl = new URL(document.getElementById('ImgPanaromic120').src);

console.log(myUrl.pathname);

<img id="ImgPanaromic120" src="http://localhost:22306/NESSPATH/VSAT/I-HP-AAMB-ENB-0003_C1//Panaromic//120.jpg"/>


问:
how to group by and filter a dataframe based on different conditions for each group
i have the following data frame:

```<code>user_id var  gp         95_q
147     1   -75.19  529.3280
20395   2   -109.11 609.0675
32035   2   36.00   609.0675
33725   2   120.98  609.0675
47808   1   -17.89  529.3280
48633   1   -19.49  529.3280
110330  1   800     529.3280
117277  2   271.80  609.0675
1122081 2   7123.78 609.0675
129120  2   21.00   609.0675
131222  2   -4.95   609.0675
131480  1   18.58   529.3280
</code>```

i need to create a new dataframe where for each group( var=1 and var=2) rows where gp is more that 95_q are filtered, as you can see 95_q is different for each group.

i took the following approach:

```<code>df.groupby('var').filter(lambda x: (x['gross_profit'] > x['95_q']))
</code>```

but it returns the following error:

```<code>filter function returned a Series, but expected a scalar bool
</code>```

when i convert the code to :

```<code>df.groupby('var').filter(lambda x: (x['gross_profit'] > x['95_q']).any())
</code>```

i still get a dataframe that still has values more than 95_q

答:
as @Scott Boston mentioned boolean indexing is enough:</p>

```<code>  df[df['gp'] < df['95_q']]
</code>```

Body:
i have the following data frame:

user_id var  gp         95_q
147     1   -75.19  529.3280
20395   2   -109.11 609.0675
32035   2   36.00   609.0675
33725   2   120.98  609.0675
47808   1   -17.89  529.3280
48633   1   -19.49  529.3280
110330  1   800     529.3280
117277  2   271.80  609.0675
1122081 2   7123.78 609.0675
129120  2   21.00   609.0675
131222  2   -4.95   609.0675
131480  1   18.58   529.3280

i need to create a new dataframe where for each group( var=1 and var=2) rows where gp is more that 95_q are filtered, as you can see 95_q is different for each group.

i took the following approach:

df.groupby('var').filter(lambda x: (x['gross_profit'] > x['95_q']))

but it returns the following error:

filter function returned a Series, but expected a scalar bool

when i convert the code to :

df.groupby('var').filter(lambda x: (x['gross_profit'] > x['95_q']).any())

i still get a dataframe that still has values more than 95_q

Body:
as @Scott Boston mentioned boolean indexing is enough:

  df[df['gp'] < df['95_q']]


问:
Send Emails From AppEngine Locally
The subject of the post says it all: I want to be able to send emails from AppEngine when it is running locally. As far as I understood from this post:

to send emails from Google appengine

I have to setup a mail server. Can anyone tells me some easy steps to install a mail server locally and use it with Google AppEngine?

答:
Why do you want to send mail from AppEngine while running locally? If it's just for testing purposes, Python comes with a built-in SMTP server that will log to the console for you:

python -m smtpd -n -c DebuggingServer localhost:1025

ContentLicense: CC BY-SA 2.5

Title: Send Emails From AppEngine Locally


问:
Parse JSON file with Python
I trying to import a nested JSON file. I am using Python 3.0
The JSON file looks like this

```<code> "funds": [
    {
      "branch": "****",
      "controlDigits": "**",
      "accountNumber": "7605390244",
      "balance": {
        "amount": "71.1",
        "currency": "EUR"
      },
      "fundName": "Eurobits Funds 0",
      "webAlias": "Eurobits Funds 0",
      "performance": "4.41",
      "performanceDescription": "",
      "yield": {
        "amount": "0.0",
        "currency": "EUR"
      },
      "quantity": "10.00",
      "valueDate": "30/03/2017",
      "transactions": [
        {
          "operationType": "1",
          "operationDescription": "MOVILIZACION HACIA DENTRO",
          "operationDate": "30/03/2017",
          "fundName": "B EVOLUCION PRUDEN",
          "quantity": "-809.27",
          "unitPrice": "7.98",
          "operationAmount": {
            "amount": "-6457.97",
            "currency": "EUR"
          }
        }
      ]
    }
  ]
</code>```

I am using this code:

```<code>from pandas.io.json import json_normalize
data_json = open("prueba.json",mode='r', encoding="utf8").read().replace('\n', '').replace('\t', '')
data_python = json.loads(data_json)

json_normalize(data_python['funds'])
</code>```

this code works fine but field transaction is not expanded

In order to expand transactions I have tried this:

```<code>json_normalize(data_python,['funds','transactions'])
</code>```

The information from transactions is expanded but I loose the other information
Besides that, the field amount looks like this:

{'amount': '1.00', 'currency': ''}

and I am not able to get it into separate fields

My question is how can I combine all the information into a single dataframe?

答: Try d['funds'][0]['transactions'] instead, where d is the name of your dictionary.

Title: Parse JSON file with Python

Body:
I trying to import a nested JSON file. I am using Python 3.0
The JSON file looks like this

 "funds": [
    {
      "branch": "****",
      "controlDigits": "**",
      "accountNumber": "7605390244",
      "balance": {
        "amount": "71.1",
        "currency": "EUR"
      },
      "fundName": "Eurobits Funds 0",
      "webAlias": "Eurobits Funds 0",
      "performance": "4.41",
      "performanceDescription": "",
      "yield": {
        "amount": "0.0",
        "currency": "EUR"
      },
      "quantity": "10.00",
      "valueDate": "30/03/2017",
      "transactions": [
        {
          "operationType": "1",
          "operationDescription": "MOVILIZACION HACIA DENTRO",
          "operationDate": "30/03/2017",
          "fundName": "B EVOLUCION PRUDEN",
          "quantity": "-809.27",
          "unitPrice": "7.98",
          "operationAmount": {
            "amount": "-6457.97",
            "currency": "EUR"
          }
        }
      ]
    }
  ]

I am using this code:

from pandas.io.json import json_normalize
data_json = open("prueba.json",mode='r', encoding="utf8").read().replace('\n', '').replace('\t', '')
data_python = json.loads(data_json)

json_normalize(data_python['funds'])

this code works fine but field transaction is not expanded

In order to expand transactions I have tried this:

json_normalize(data_python,['funds','transactions'])

The information from transactions is expanded but I loose the other information
Besides that, the field amount looks like this:

{'amount': '1.00', 'currency': ''}

and I am not able to get it into separate fields

My question is how can I combine all the information into a single dataframe?


问:
Get property with highest value from key value pair
In MongoDB, I have documents with a structure like this:

```<code>{
    _id: "123456...", // an ObjectId
    name: "foobar",
    classification: {
        class_1: 0.45,
        class_2: 0.11,
        class_3: 0.44
    }
}
</code>```

Using the aggregation pipeline, is it possible to give me an object that contains the highest classification? So, given the above, I would like something like this as result:

```<code>{
    _id: "123456...", // an ObjectId
    name: "foobar",
    classification: "class_1"
}
</code>```

I thought I could use $unwind but the classification property is not an array.

For what it's worth: I know there will always be three properties in classification, so it's ok to hard-code the keys in the query.

答:
You should probably note here that every technique applied is essentially based on "coercion" of the "key/value" pairs into an "array" format for comparison and extraction. So the real lesson to learn is is that your document "should" in fact store this as an "array" instead. But onto the techniques.

If you have MongoDB 3.4 then you can use $objectToArray to turn the "keys" into an array so you can get the value:

Dynamic

```<code>db.collection.aggregate([
   { "$addFields": {
     "classification": {
       "$arrayElemAt": [
           { "$map": {
             "input": {
               "$filter": {
                 "input": { "$objectToArray": "$classification" },
                 "as": "c",
                 "cond": {
                   "$eq": [
                     "$$c.v",
                     { "$max": {
                       "$map": {
                         "input": { "$objectToArray": "$classification" },
                         "as": "c",
                         "in": "$$c.v"
                       }
                     }}
                   ]
                 }
               }
             },
             "as": "c",
             "in": "$$c.k",
           }},
           0
       ]
     }
   }}
])
</code>```

Otherwise just to the transformation as you iterate the cursor if you do not really need it for further aggregation. As a basic JavaScript example:

```<code> db.collection.find().map(d => Object.assign(
   d,
   { classification: Object.keys(d.classification)
       .filter(k => d.classification[k] === Math.max.apply(null,
         Object.keys(d.classification).map(k => d.classification[k])
       ))[0]
   }
 ));
</code>```

And that's also the same basic logic that you apply using mapReduce if you were actually aggregating something.

Both produce:

```<code>/* 1 */
{
    "_id" : "123456...",
    "name" : "foobar",
    "classification" : "class_1"
}
</code>```

HardCoding

On the "hardcoding" case which you say is okay. Then you can construct like this with $switch by supplying  $max with each of the values:

```<code>db.collection.aggregate([
  { "$addFields": {
    "classification": {
      "$let": {
        "vars": {
          "max": {
            "$max": [
              "$classification.class_1",
              "$classification.class_2",
              "$classification.class_3"
            ]
          }
        },
        "in": {
          "$switch": {
            "branches": [
              { "case": { "$eq": [ "$classification.class_1", "$$max" ] }, "then": "class_1" },
              { "case": { "$eq": [ "$classification.class_2", "$$max" ] }, "then": "class_2" },
              { "case": { "$eq": [ "$classification.class_3", "$$max" ] }, "then": "class_3" },
            ]
          }
        }
      }
    }
  }}
])
</code>```

Which gives rise to then actually being able to write that out longer using $cond, and then the only real constraint is the change in $max for MongoDB 3.2, which allowed an array of arguments as opposed to it's previous role as an "accumulator only":

```<code>db.collection.aggregate([
  { "$addFields": {
    "classification": {
      "$let": {
        "vars": {
          "max": {
            "$max": [
              "$classification.class_1",
              "$classification.class_2",
              "$classification.class_3"
            ]
          }
        },
        "in": {
          "$cond": {
            "if": { "$eq": [ "$classification.class_1", "$$max" ] },
            "then": "class_1",
            "else": {
              "$cond": {
                "if": { "$eq": [ "$classification.class_2", "$$max" ] },
                "then": "class_2",
                "else": "class_3"
              }
            }
          }
        }
      }
    }
  }}
])
</code>```

If you were "really" constrained then you could "force" the "max" through a separate pipeline stage using $map and $unwind on the array then $group again. This would make the operations compatible with MongoDB 2.6:

```<code>db.collection.aggregate([
  { "$project": {
    "name": 1,
    "classification": 1,
    "max": {
      "$map": {
        "input": [1,2,3],
        "as": "e",
        "in": {
          "$cond": {
            "if": { "$eq": [ "$$e", 1 ] },
            "then": "$classification.class_1",
            "else": {
              "$cond": {
                "if": { "$eq": [ "$$e", 2 ] },
                "then": "$classification.class_2",
                "else": "$classification.class_3"
              }
            }
          }
        }
      }
    }
  }},
  { "$unwind": "$max" },
  { "$group": {
    "_id": "$_id",
    "name": { "$first": "$name" },
    "classification": { "$first": "$classification" },
    "max": { "$max": "$max" }
  }},
  { "$project": {
    "name": 1,
    "classification": {
      "$cond": {
        "if": { "$eq": [ "$classification.class_1", "$max" ] },
        "then": "class_1",
        "else": {
          "$cond": {
            "if": { "$eq": [ "$classification.class_2", "$max" ] },
            "then": "class_2",
            "else": "class_3"
          }
        }
      }
    }
  }}
])
</code>```

And going really ancient, then we can instead $unwind from $const, which was (and still is) a "hidden" and undocumented operator equal in function to $literal (which is technically aliased to it) in modern versions, but also with the alternate syntax to $cond as an "array" ternary operation this then becomes compatible with all versions since the aggregation framework existed:

```<code>db.collection.aggregate([
  { "$project": {
    "name": 1,
    "classification": 1,
    "temp": { "$const": [1,2,3] }
  }},
  { "$unwind": "$temp" },
  { "$group": {
    "_id": "$_id",
    "name": { "$first": "$name" },
    "classification": { "$first": "$classification" },
    "max": {
      "$max": {
        "$cond": [
          { "$eq": [ "$temp", 1 ] },
          "$classification.class_1",
          { "$cond": [
            { "$eq": [ "$temp", 2 ] },
            "$classification.class_2",
            "$classification.class_3"
          ]}
        ]
      }
    }
  }},
  { "$project": {
    "name": 1,
    "classification": {
      "$cond": [
        { "$eq": [ "$max", "$classification.class_1" ] },
        "class_1",
        { "$cond": [
          { "$eq": [ "$max", "$classification.class_2" ] },
          "class_2",
          "class_3"
        ]}
      ]
    }
  }}
])
</code>```

But it is of course possible, even if extremely messy.

Body:
In MongoDB, I have documents with a structure like this:

{
    _id: "123456...", // an ObjectId
    name: "foobar",
    classification: {
        class_1: 0.45,
        class_2: 0.11,
        class_3: 0.44
    }
}

Using the aggregation pipeline, is it possible to give me an object that contains the highest classification? So, given the above, I would like something like this as result:

{
    _id: "123456...", // an ObjectId
    name: "foobar",
    classification: "class_1"
}

I thought I could use $unwind but the classification property is not an array.

For what it's worth: I know there will always be three properties in classification, so it's ok to hard-code the keys in the query.

Body:
You should probably note here that every technique applied is essentially based on "coercion" of the "key/value" pairs into an "array" format for comparison and extraction. So the real lesson to learn is is that your document "should" in fact store this as an "array" instead. But onto the techniques.

If you have MongoDB 3.4 then you can use $objectToArray to turn the "keys" into an array so you can get the value:

Dynamic

db.collection.aggregate([
   { "$addFields": {
     "classification": {
       "$arrayElemAt": [
           { "$map": {
             "input": {
               "$filter": {
                 "input": { "$objectToArray": "$classification" },
                 "as": "c",
                 "cond": {
                   "$eq": [
                     "$$c.v",
                     { "$max": {
                       "$map": {
                         "input": { "$objectToArray": "$classification" },
                         "as": "c",
                         "in": "$$c.v"
                       }
                     }}
                   ]
                 }
               }
             },
             "as": "c",
             "in": "$$c.k",
           }},
           0
       ]
     }
   }}
])

Otherwise just to the transformation as you iterate the cursor if you do not really need it for further aggregation. As a basic JavaScript example:

 db.collection.find().map(d => Object.assign(
   d,
   { classification: Object.keys(d.classification)
       .filter(k => d.classification[k] === Math.max.apply(null,
         Object.keys(d.classification).map(k => d.classification[k])
       ))[0]
   }
 ));

And that's also the same basic logic that you apply using mapReduce if you were actually aggregating something.

Both produce:

/* 1 */
{
    "_id" : "123456...",
    "name" : "foobar",
    "classification" : "class_1"
}

HardCoding

On the "hardcoding" case which you say is okay. Then you can construct like this with $switch by supplying  $max with each of the values:

db.collection.aggregate([
  { "$addFields": {
    "classification": {
      "$let": {
        "vars": {
          "max": {
            "$max": [
              "$classification.class_1",
              "$classification.class_2",
              "$classification.class_3"
            ]
          }
        },
        "in": {
          "$switch": {
            "branches": [
              { "case": { "$eq": [ "$classification.class_1", "$$max" ] }, "then": "class_1" },
              { "case": { "$eq": [ "$classification.class_2", "$$max" ] }, "then": "class_2" },
              { "case": { "$eq": [ "$classification.class_3", "$$max" ] }, "then": "class_3" },
            ]
          }
        }
      }
    }
  }}
])

Which gives rise to then actually being able to write that out longer using $cond, and then the only real constraint is the change in $max for MongoDB 3.2, which allowed an array of arguments as opposed to it's previous role as an "accumulator only":

db.collection.aggregate([
  { "$addFields": {
    "classification": {
      "$let": {
        "vars": {
          "max": {
            "$max": [
              "$classification.class_1",
              "$classification.class_2",
              "$classification.class_3"
            ]
          }
        },
        "in": {
          "$cond": {
            "if": { "$eq": [ "$classification.class_1", "$$max" ] },
            "then": "class_1",
            "else": {
              "$cond": {
                "if": { "$eq": [ "$classification.class_2", "$$max" ] },
                "then": "class_2",
                "else": "class_3"
              }
            }
          }
        }
      }
    }
  }}
])

If you were "really" constrained then you could "force" the "max" through a separate pipeline stage using $map and $unwind on the array then $group again. This would make the operations compatible with MongoDB 2.6:

db.collection.aggregate([
  { "$project": {
    "name": 1,
    "classification": 1,
    "max": {
      "$map": {
        "input": [1,2,3],
        "as": "e",
        "in": {
          "$cond": {
            "if": { "$eq": [ "$$e", 1 ] },
            "then": "$classification.class_1",
            "else": {
              "$cond": {
                "if": { "$eq": [ "$$e", 2 ] },
                "then": "$classification.class_2",
                "else": "$classification.class_3"
              }
            }
          }
        }
      }
    }
  }},
  { "$unwind": "$max" },
  { "$group": {
    "_id": "$_id",
    "name": { "$first": "$name" },
    "classification": { "$first": "$classification" },
    "max": { "$max": "$max" }
  }},
  { "$project": {
    "name": 1,
    "classification": {
      "$cond": {
        "if": { "$eq": [ "$classification.class_1", "$max" ] },
        "then": "class_1",
        "else": {
          "$cond": {
            "if": { "$eq": [ "$classification.class_2", "$max" ] },
            "then": "class_2",
            "else": "class_3"
          }
        }
      }
    }
  }}
])

And going really ancient, then we can instead $unwind from $const, which was (and still is) a "hidden" and undocumented operator equal in function to $literal (which is technically aliased to it) in modern versions, but also with the alternate syntax to $cond as an "array" ternary operation this then becomes compatible with all versions since the aggregation framework existed:

db.collection.aggregate([
  { "$project": {
    "name": 1,
    "classification": 1,
    "temp": { "$const": [1,2,3] }
  }},
  { "$unwind": "$temp" },
  { "$group": {
    "_id": "$_id",
    "name": { "$first": "$name" },
    "classification": { "$first": "$classification" },
    "max": {
      "$max": {
        "$cond": [
          { "$eq": [ "$temp", 1 ] },
          "$classification.class_1",
          { "$cond": [
            { "$eq": [ "$temp", 2 ] },
            "$classification.class_2",
            "$classification.class_3"
          ]}
        ]
      }
    }
  }},
  { "$project": {
    "name": 1,
    "classification": {
      "$cond": [
        { "$eq": [ "$max", "$classification.class_1" ] },
        "class_1",
        { "$cond": [
          { "$eq": [ "$max", "$classification.class_2" ] },
          "class_2",
          "class_3"
        ]}
      ]
    }
  }}
])

But it is of course possible, even if extremely messy.


问:
Postgres group by expressions evaluation
When "group by" expression evaluated? When Postgres decides, that two expressions actually the same?

Example:

```<code>db=> \timing
Timing is on.

db=> select pg_sleep(1) group by pg_sleep(1)::varchar;
 pg_sleep
----------

(1 row)

Time: 2002.416 ms

db=> select pg_sleep(1)::varchar group by pg_sleep(1)::varchar;
 pg_sleep
----------

(1 row)

Time: 1001.367 ms
</code>```

Because of possible overhead, is it aliases in "group by" performed better than expressions? For example, will it be better than version with "group by" using expressions:

```<code>db=> select pg_sleep(1)::varchar as e group by e;
 e
---

(1 row)

Time: 1001.688 ms
</code>```

Even if ASTs are different, expression will not be re-evaluated:

```<code>db=> select pg_sleep(1 + 0.5)::varchar group by pg_sleep(0.5 + 1)::varchar;
 pg_sleep
----------

(1 row)

Time: 1500.971 ms
</code>```

答:
I'm not sure I understand the question, so maybe answering the wrong one. Yet - here it is. It groups result after getting it. I was surprised pg_sleep was not re executed with same cast. Smart planner is smart. Aggregation method does not seem to change it. And regarding aliasing - if planner understood that expression is same and no need to execute function again it did it without help of alias, so probably alias wont change anything.

```<code>so=# explain analyze select pg_sleep(1) group by pg_sleep(1)::varchar;
                                           QUERY PLAN
-------------------------------------------------------------------------------------------------
 HashAggregate  (cost=0.02..0.04 rows=1 width=0) (actual time=2002.201..2002.203 rows=1 loops=1)
   ->  Result  (cost=0.00..0.02 rows=1 width=0) (actual time=1001.093..1001.093 rows=1 loops=1)
 Total runtime: 2002.236 ms
(3 rows)

Time: 2002.779 ms

so=# set enable_hashagg to off;
SET

so=# explain analyze select pg_sleep(1)::text group by pg_sleep(1)::varchar;
                                              QUERY PLAN
------------------------------------------------------------------------------------------------------
 Group  (cost=0.03..0.05 rows=1 width=0) (actual time=2002.219..2002.220 rows=1 loops=1)
   ->  Sort  (cost=0.03..0.03 rows=1 width=0) (actual time=1001.111..1001.112 rows=1 loops=1)
         Sort Key: ((pg_sleep(1::double precision))::character varying)
         Sort Method: quicksort  Memory: 25kB
         ->  Result  (cost=0.00..0.02 rows=1 width=0) (actual time=1001.100..1001.100 rows=1 loops=1)
 Total runtime: 2002.245 ms
(6 rows)

Time: 2002.564 ms
so=# explain analyze select pg_sleep(1)::varchar as e group by e;
                                              QUERY PLAN
------------------------------------------------------------------------------------------------------
 Group  (cost=0.03..0.04 rows=1 width=0) (actual time=1001.109..1001.110 rows=1 loops=1)
   ->  Sort  (cost=0.03..0.03 rows=1 width=0) (actual time=1001.107..1001.108 rows=1 loops=1)
         Sort Key: ((pg_sleep(1::double precision))::character varying)
         Sort Method: quicksort  Memory: 25kB
         ->  Result  (cost=0.00..0.02 rows=1 width=0) (actual time=1001.098..1001.099 rows=1 loops=1)
 Total runtime: 1001.132 ms
(6 rows)

Time: 1001.470 ms
</code>```

Finally I'm not sure such behaviour is intuitive:

```<code>so=# explain analyze select pg_sleep(random())::text group by pg_sleep(random())::varchar;
                                            QUERY PLAN
--------------------------------------------------------------------------------------------------
 Group  (cost=0.03..0.06 rows=1 width=0) (actual time=742.928..742.930 rows=1 loops=1)
   ->  Sort  (cost=0.03..0.04 rows=1 width=0) (actual time=53.152..53.153 rows=1 loops=1)
         Sort Key: ((pg_sleep(random()))::character varying)
         Sort Method: quicksort  Memory: 25kB
         ->  Result  (cost=0.00..0.02 rows=1 width=0) (actual time=53.143..53.143 rows=1 loops=1)
 Total runtime: 742.958 ms
(6 rows)

Time: 743.271 ms
so=# explain analyze select pg_sleep(random())::text group by pg_sleep(random())::text;
                                             QUERY PLAN
----------------------------------------------------------------------------------------------------
 Group  (cost=0.03..0.05 rows=1 width=0) (actual time=963.075..963.076 rows=1 loops=1)
   ->  Sort  (cost=0.03..0.04 rows=1 width=0) (actual time=963.073..963.073 rows=1 loops=1)
         Sort Key: ((pg_sleep(random()))::text)
         Sort Method: quicksort  Memory: 25kB
         ->  Result  (cost=0.00..0.02 rows=1 width=0) (actual time=963.063..963.065 rows=1 loops=1)
 Total runtime: 963.099 ms
(6 rows)

Time: 963.419 ms
</code>```

I would expect explain analyze select pg_sleep(random())::text group by pg_sleep(random())::text; to reexecute pg_sleep in group by

Body:
When "group by" expression evaluated? When Postgres decides, that two expressions actually the same?

Example:

db=> \timing
Timing is on.

db=> select pg_sleep(1) group by pg_sleep(1)::varchar;
 pg_sleep
----------

(1 row)

Time: 2002.416 ms

db=> select pg_sleep(1)::varchar group by pg_sleep(1)::varchar;
 pg_sleep
----------

(1 row)

Time: 1001.367 ms

Because of possible overhead, is it aliases in "group by" performed better than expressions? For example, will it be better than version with "group by" using expressions:

db=> select pg_sleep(1)::varchar as e group by e;
 e
---

(1 row)

Time: 1001.688 ms

Even if ASTs are different, expression will not be re-evaluated:

db=> select pg_sleep(1 + 0.5)::varchar group by pg_sleep(0.5 + 1)::varchar;
 pg_sleep
----------

(1 row)

Time: 1500.971 ms

Body:
I'm not sure I understand the question, so maybe answering the wrong one. Yet - here it is. It groups result after getting it. I was surprised pg_sleep was not re executed with same cast. Smart planner is smart. Aggregation method does not seem to change it. And regarding aliasing - if planner understood that expression is same and no need to execute function again it did it without help of alias, so probably alias wont change anything.

so=# explain analyze select pg_sleep(1) group by pg_sleep(1)::varchar;
                                           QUERY PLAN
-------------------------------------------------------------------------------------------------
 HashAggregate  (cost=0.02..0.04 rows=1 width=0) (actual time=2002.201..2002.203 rows=1 loops=1)
   ->  Result  (cost=0.00..0.02 rows=1 width=0) (actual time=1001.093..1001.093 rows=1 loops=1)
 Total runtime: 2002.236 ms
(3 rows)

Time: 2002.779 ms

so=# set enable_hashagg to off;
SET

so=# explain analyze select pg_sleep(1)::text group by pg_sleep(1)::varchar;
                                              QUERY PLAN
------------------------------------------------------------------------------------------------------
 Group  (cost=0.03..0.05 rows=1 width=0) (actual time=2002.219..2002.220 rows=1 loops=1)
   ->  Sort  (cost=0.03..0.03 rows=1 width=0) (actual time=1001.111..1001.112 rows=1 loops=1)
         Sort Key: ((pg_sleep(1::double precision))::character varying)
         Sort Method: quicksort  Memory: 25kB
         ->  Result  (cost=0.00..0.02 rows=1 width=0) (actual time=1001.100..1001.100 rows=1 loops=1)
 Total runtime: 2002.245 ms
(6 rows)

Time: 2002.564 ms
so=# explain analyze select pg_sleep(1)::varchar as e group by e;
                                              QUERY PLAN
------------------------------------------------------------------------------------------------------
 Group  (cost=0.03..0.04 rows=1 width=0) (actual time=1001.109..1001.110 rows=1 loops=1)
   ->  Sort  (cost=0.03..0.03 rows=1 width=0) (actual time=1001.107..1001.108 rows=1 loops=1)
         Sort Key: ((pg_sleep(1::double precision))::character varying)
         Sort Method: quicksort  Memory: 25kB
         ->  Result  (cost=0.00..0.02 rows=1 width=0) (actual time=1001.098..1001.099 rows=1 loops=1)
 Total runtime: 1001.132 ms
(6 rows)

Time: 1001.470 ms

Finally I'm not sure such behaviour is intuitive:

so=# explain analyze select pg_sleep(random())::text group by pg_sleep(random())::varchar;
                                            QUERY PLAN
--------------------------------------------------------------------------------------------------
 Group  (cost=0.03..0.06 rows=1 width=0) (actual time=742.928..742.930 rows=1 loops=1)
   ->  Sort  (cost=0.03..0.04 rows=1 width=0) (actual time=53.152..53.153 rows=1 loops=1)
         Sort Key: ((pg_sleep(random()))::character varying)
         Sort Method: quicksort  Memory: 25kB
         ->  Result  (cost=0.00..0.02 rows=1 width=0) (actual time=53.143..53.143 rows=1 loops=1)
 Total runtime: 742.958 ms
(6 rows)

Time: 743.271 ms
so=# explain analyze select pg_sleep(random())::text group by pg_sleep(random())::text;
                                             QUERY PLAN
----------------------------------------------------------------------------------------------------
 Group  (cost=0.03..0.05 rows=1 width=0) (actual time=963.075..963.076 rows=1 loops=1)
   ->  Sort  (cost=0.03..0.04 rows=1 width=0) (actual time=963.073..963.073 rows=1 loops=1)
         Sort Key: ((pg_sleep(random()))::text)
         Sort Method: quicksort  Memory: 25kB
         ->  Result  (cost=0.00..0.02 rows=1 width=0) (actual time=963.063..963.065 rows=1 loops=1)
 Total runtime: 963.099 ms
(6 rows)

Time: 963.419 ms

I would expect explain analyze select pg_sleep(random())::text group by pg_sleep(random())::text; to reexecute pg_sleep in group by


问:
How can i hold a first letter of `h1` content after pressing backspace
How can i hold a first letter of h1 content after pressing backspace. Here i used keyup function but its not allowing to write in h1. Can someone know how to do it?

Here is the link: https://jsfiddle.net/5brr7sj1/3/

CODE:

$(document).ready(function(){

var txt = $('.editor').text();
var splitTxt = txt.split('');

 $('.editor').keyup(function(){
 $(this).text(splitTxt[1]);
 });

});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.editor {
  border:1px solid #d9d9d9;
  height:40px;
  line-height:40px;
  padding:0 15px;
}</code>```

    Click here to edit content

```

答:
Try to use the keyCode

```<code>$('.editor').keyup(function(event){

     if(event.keyCode == 8){
         $(this).text(splitTxt[1]);
     }

  });
</code>```

Body:
How can i hold a first letter of h1 content after pressing backspace. Here i used keyup function but its not allowing to write in h1. Can someone know how to do it?

Here is the link: https://jsfiddle.net/5brr7sj1/3/

CODE:

$(document).ready(function(){

var txt = $('.editor').text();
var splitTxt = txt.split('');

 $('.editor').keyup(function(){
 $(this).text(splitTxt[1]);
 });

});

.editor {
  border:1px solid #d9d9d9;
  height:40px;
  line-height:40px;
  padding:0 15px;
}

    Click here to edit content

Body:
Try to use the keyCode

$('.editor').keyup(function(event){

     if(event.keyCode == 8){
         $(this).text(splitTxt[1]);
     }

  });


问:
Could not find com.google.firebase:firebase-core:11.0.0 when i try to add mobile-center-push to React Native project
I want integrate the push notification to my React Native project follow the guide
https://mobile.azure.com/orgs/....../push/setup
and when i run

```<code>react-native run-android
</code>```

i got an error:

```<code>-> % react-native run-android
Scanning 744 folders for symlinks in /Users/kalaliu/temp/RNBase/node_modules (5ms)
JS server already running.
Building and installing the app on the device (cd android && ./gradlew installDebug)...
File /Users/kalaliu/.android/repositories.cfg could not be loaded.

FAILURE: Build failed with an exception.

* What went wrong:
A problem occurred configuring project ':app'.
> Could not resolve all dependencies for configuration ':app:_debugApk'.
   > A problem occurred configuring project ':mobile-center-push'.
      > Could not resolve all dependencies for configuration ':mobile-center-push:_debugPublishCopy'.
         > Could not find com.google.firebase:firebase-core:11.0.0.
           Required by:
               RNBase:mobile-center-push:unspecified > com.microsoft.azure.mobile:mobile-center-push:0.10.0
         > Could not find com.google.firebase:firebase-messaging:11.0.0.
           Required by:
               RNBase:mobile-center-push:unspecified > com.microsoft.azure.mobile:mobile-center-push:0.10.0

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.

BUILD FAILED
</code>```

it looks like that i need upgrade my android SDK in my RN project?
any idea about this?
my android configuration

```<code> compileSdkVersion 23
    buildToolsVersion "23.0.1"

    defaultConfig {
        applicationId "com.rnbase"
        minSdkVersion 16
        targetSdkVersion 22
        versionCode 1
        versionName "1.0.1"
        ndk {
            abiFilters "armeabi-v7a"
        }
        vectorDrawables.useSupportLibrary = true
    }
</code>```

my package.json

```<code>"mobile-center": "^0.6.0",
"mobile-center-analytics": "^0.6.0"
"mobile-center-crashes": "^0.6.0",
"mobile-center-push": "^0.7.0",
"react": "16.0.0-alpha.12",
"react-native": "^0.45.1",
</code>```

PS:
i find the firebase tips:

答:
Looks like you are missing a step related to Firebase. Please make sure that you have completed all steps of the instructions.

From the documentation:

Before using Mobile Center Push service, you need to add Firebase to your application.

Body:
I want integrate the push notification to my React Native project follow the guide
https://mobile.azure.com/orgs/....../push/setup
and when i run

react-native run-android

i got an error:

-> % react-native run-android
Scanning 744 folders for symlinks in /Users/kalaliu/temp/RNBase/node_modules (5ms)
JS server already running.
Building and installing the app on the device (cd android && ./gradlew installDebug)...
File /Users/kalaliu/.android/repositories.cfg could not be loaded.

FAILURE: Build failed with an exception.

* What went wrong:
A problem occurred configuring project ':app'.
> Could not resolve all dependencies for configuration ':app:_debugApk'.
   > A problem occurred configuring project ':mobile-center-push'.
      > Could not resolve all dependencies for configuration ':mobile-center-push:_debugPublishCopy'.
         > Could not find com.google.firebase:firebase-core:11.0.0.
           Required by:
               RNBase:mobile-center-push:unspecified > com.microsoft.azure.mobile:mobile-center-push:0.10.0
         > Could not find com.google.firebase:firebase-messaging:11.0.0.
           Required by:
               RNBase:mobile-center-push:unspecified > com.microsoft.azure.mobile:mobile-center-push:0.10.0

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.

BUILD FAILED

it looks like that i need upgrade my android SDK in my RN project?
any idea about this?
my android configuration

 compileSdkVersion 23
    buildToolsVersion "23.0.1"

    defaultConfig {
        applicationId "com.rnbase"
        minSdkVersion 16
        targetSdkVersion 22
        versionCode 1
        versionName "1.0.1"
        ndk {
            abiFilters "armeabi-v7a"
        }
        vectorDrawables.useSupportLibrary = true
    }

my package.json

"mobile-center": "^0.6.0",
"mobile-center-analytics": "^0.6.0"
"mobile-center-crashes": "^0.6.0",
"mobile-center-push": "^0.7.0",
"react": "16.0.0-alpha.12",
"react-native": "^0.45.1",

PS:
i find the firebase tips:


问:
Backbone Model listenTo self
I am trying to do a listenTo binding in my model to itself and cannot get it to work. I'm not sure what I am doing wrong:</p>

```<code>initialize: function() {
  this.listenTo(this, "change:projectData", this.processData);
}

setProject: function(id) {
  //do async call and get someData variable
  this.set('projectData', someData);
}

processData: function(data) {
  debugger; //not triggering
}
</code>```

答:
You need to trigger the event change:projectData

So this code:

```<code>setProject: function(id) {
  //do async call and get someData variable
  this.set('projectData', someData);
}
</code>```

Should be something like this:

```<code>setProject: function(id) {
   //do async call and get someData variable
   this.trigger('change:projectData', someData);
   //or Backbone.trigger(...)
}
</code>```

Documentation: http://backbonejs.org/#Events-trigger

Title: Backbone Model listenTo self

Body:
I am trying to do a listenTo binding in my model to itself and cannot get it to work. I'm not sure what I am doing wrong:

initialize: function() {
  this.listenTo(this, "change:projectData", this.processData);
}

setProject: function(id) {
  //do async call and get someData variable
  this.set('projectData', someData);
}

processData: function(data) {
  debugger; //not triggering
}

Body:
You need to trigger the event change:projectData

So this code:

setProject: function(id) {
  //do async call and get someData variable
  this.set('projectData', someData);
}

Should be something like this:

setProject: function(id) {
   //do async call and get someData variable
   this.trigger('change:projectData', someData);
   //or Backbone.trigger(...)
}

Documentation: http://backbonejs.org/#Events-trigger


问:
How to multiply in Javascript? problems with decimals
i've the following code in Javascript:

```<code>var m1 = 2232.00;
var percent = (10/100);
var total = percent*m1;
alert(total);
</code>```

The problem is that the variable "total" gives me "223.20000000000002" and it should be "223.2", what should i do to get the correct value?

答:
This can be done well with an external library called decimal.js that provides a Decimal type for JavaScript. It's also available for Node on npm. Below is an example that replicates the original example from gustavomanolo using decimal.js.

// Decimal type provided by decimal.js (http://mikemcl.github.io/decimal.js/)
var m1 = new Decimal( 2232.00 );
var percent = new Decimal( 10/100 );
var total = m1.mul(percent);
console.log( 'Total:', total );```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/decimal.js/7.2.3/decimal.min.js"></script></code>```

Body:
i've the following code in Javascript:

var m1 = 2232.00;
var percent = (10/100);
var total = percent*m1;
alert(total);

The problem is that the variable "total" gives me "223.20000000000002" and it should be "223.2", what should i do to get the correct value?

Body:
This can be done well with an external library called decimal.js that provides a Decimal type for JavaScript. It's also available for Node on npm. Below is an example that replicates the original example from gustavomanolo using decimal.js.

// Decimal type provided by decimal.js (http://mikemcl.github.io/decimal.js/)
var m1 = new Decimal( 2232.00 );
var percent = new Decimal( 10/100 );
var total = m1.mul(percent);
console.log( 'Total:', total );

<script src="https://cdnjs.cloudflare.com/ajax/libs/decimal.js/7.2.3/decimal.min.js"></script>


问:
Why the switch statement and not if-else?
I've been wondering this for some time now.  I'm by far not a hardcore programmer, mainly small Python scripts and I've written a couple molecular dynamics simulations.  For the real question:  What is the point of the switch statement?  Why can't you just use the if-else statement?

Thanks for your answer and if this has been asked before please point me to the link.

EDIT

S.Lott has pointed out that this may be a duplicate of questions If/Else vs. Switch.  If you want to close then do so.  I'll leave it open for further discussion.

答:
For expressiveness, the switch/case statement allows you to group multiple cases together, for example:

```<code>case 1,2,3: do(this); break;
case 4,5,6: do(that); break;
</code>```

For performance, compilers can sometimes optimize switch statements into jump tables.

OwnerDisplayName: Casey

LastEditorDisplayName: Casey

Body:
For expressiveness, the switch/case statement allows you to group multiple cases together, for example:

case 1,2,3: do(this); break;
case 4,5,6: do(that); break;

For performance, compilers can sometimes optimize switch statements into jump tables.

OwnerDisplayName: jdigital


问:
How to refresh a part of the page view without refreshing the entire page in angular on a click event?
I am building a chat application using Angular. I have two components for the chat. One for each user. I am using a radio button component which creates a new message as radio button. The user selects an option. Once the user clicks on submit button the radio button message is edited and a new message is printed with the option selected by the user.

You can see the demonstration in the plunker below. If user1 creates the radio message and submits the option in the same view, it works as expected. But if user1 creates the radio message and user2 submits the option, then the radio button message is not edited but only generates a new message with the option selected.

The problem I am facing here is that I am unable to refresh the view on the click event. This will display the edited radio button message by removing the options to select.

There is an API available in Angular: ChangeDetection.
It goes something like this: ANGULAR CHANGE DETECTION

edit(message: Message): void {
        let result = JSON.stringify(message);
        if (!result) {
            return;
        }
        this.appService.update(this.message)
            .then(() => {
                return null;
            });
    }```

But I am unable to use this API on click event.

Plunker for the same is attached: Angular chat application

Is there any other way or work around to get this working?
Feel free to fork the plunker code and edit if needed.

答:
Remove setMessage and getMessage methods from AppService.

By using these methods you hold object in shared service. And as object and  array are mutable you will get a lot of problem with such implementation.

I would use @Input property for Radio component

app.component.html home.component.html

```<code><mm-radio-message [message]="message" ...></mm-radio-message>
</code>```

radio.component.ts

```<code>@Input() message: Message;
</code>```

Forked Plunker

Body:
I am building a chat application using Angular. I have two components for the chat. One for each user. I am using a radio button component which creates a new message as radio button. The user selects an option. Once the user clicks on submit button the radio button message is edited and a new message is printed with the option selected by the user.

You can see the demonstration in the plunker below. If user1 creates the radio message and submits the option in the same view, it works as expected. But if user1 creates the radio message and user2 submits the option, then the radio button message is not edited but only generates a new message with the option selected.

The problem I am facing here is that I am unable to refresh the view on the click event. This will display the edited radio button message by removing the options to select.

There is an API available in Angular: ChangeDetection.
It goes something like this: ANGULAR CHANGE DETECTION

edit(message: Message): void {
        let result = JSON.stringify(message);
        if (!result) {
            return;
        }
        this.appService.update(this.message)
            .then(() => {
                return null;
            });
    }

But I am unable to use this API on click event.

Plunker for the same is attached: Angular chat application

Is there any other way or work around to get this working?
Feel free to fork the plunker code and edit if needed.

Body:
Remove setMessage and getMessage methods from AppService.

By using these methods you hold object in shared service. And as object and  array are mutable you will get a lot of problem with such implementation.

I would use @Input property for Radio component

app.component.html home.component.html

<mm-radio-message [message]="message" ...></mm-radio-message>

radio.component.ts

@Input() message: Message;

Forked Plunker


问:
Creating and Updating User Table With PHP/MySql Script
I am reading a book on PHP, MYSQL, JAVASCRIPT and JQUERY.  While reading, I do type the code and see how it worked.  I have the following script which I ran to create a table named: "users', and subsequently update the table with two users.  When I ran the script in my browser, it only created the new table but failed to update it with the new users.  I do not receive any error.  Below is the entire script.

```<code><?php // setup_users.php

require_once 'login.php';

$connection = new mysqli($hn, $un, $pw, $db);
if ($connection->connect_error) die($connection->connect_error);

$query = "CREATE TABLE users (

    forename VARCHAR(32) NOT NULL,
    surname  VARCHAR(32) NOT NULL,
    username VARCHAR(32) NOT NULL UNIQUE,
    password VARCHAR(32) NOT NULL
    )";

$result = $connection->query($query);

if (!$result) die($connection->error);

$salt1 = "qm&g";
$salt2 = "ph!@";

$forename = 'Baban';
$surname = 'Sadik';
$username = 'bsadik';
$password = 'babansadik1';
$token = hash('ripemd128', "$salt1$password$salt2");

add_user($connection, $forename, $surname, $username, $token);

$forename = 'Abdullah';
$surname = 'Abubakar';
$username = 'aabubakar';
$password = 'abakar1';
$token = hash('ripemd128', "$salt1$password$salt2");

add_user($connection, $forename, $surname, $username, $token);

function add_user($connection, $fn, $sn, $un, $pw) {

    $query = "INSERT INTO users VALUES('$forename', '$surname', '$username', '$token')";
    $result = $connection->query($query);
    if (!$result) die($connection->error);

}

?>
</code>```

Where did go wrong please?

答:
You just missed to put column names in the insertion query in add_user function and you are passing undefined variables
Do like this </p>

```<code>$query = "INSERT INTO users(forename, surname, username, password)
        VALUES('$fn', '$sn', '$un', '$pw')";
</code>```

Body:
I am reading a book on PHP, MYSQL, JAVASCRIPT and JQUERY.  While reading, I do type the code and see how it worked.  I have the following script which I ran to create a table named: "users', and subsequently update the table with two users.  When I ran the script in my browser, it only created the new table but failed to update it with the new users.  I do not receive any error.  Below is the entire script.

<?php // setup_users.php

require_once 'login.php';

$connection = new mysqli($hn, $un, $pw, $db);
if ($connection->connect_error) die($connection->connect_error);

$query = "CREATE TABLE users (

    forename VARCHAR(32) NOT NULL,
    surname  VARCHAR(32) NOT NULL,
    username VARCHAR(32) NOT NULL UNIQUE,
    password VARCHAR(32) NOT NULL
    )";

$result = $connection->query($query);

if (!$result) die($connection->error);

$salt1 = "qm&g";
$salt2 = "ph!@";

$forename = 'Baban';
$surname = 'Sadik';
$username = 'bsadik';
$password = 'babansadik1';
$token = hash('ripemd128', "$salt1$password$salt2");

add_user($connection, $forename, $surname, $username, $token);

$forename = 'Abdullah';
$surname = 'Abubakar';
$username = 'aabubakar';
$password = 'abakar1';
$token = hash('ripemd128', "$salt1$password$salt2");

add_user($connection, $forename, $surname, $username, $token);

function add_user($connection, $fn, $sn, $un, $pw) {

    $query = "INSERT INTO users VALUES('$forename', '$surname', '$username', '$token')";
    $result = $connection->query($query);
    if (!$result) die($connection->error);

}

?>

Where did go wrong please?

Body:
You just missed to put column names in the insertion query in add_user function and you are passing undefined variables
Do like this

$query = "INSERT INTO users(forename, surname, username, password)
        VALUES('$fn', '$sn', '$un', '$pw')";


问:
Build Tables with relationships
I'm trying to build table on my website. Right now it's working fine:

```<code><table id="objects" class="table">
    <thead>
        <tr>
            <th>#</th>
            <th>Object Name</th>
            <th>Object Relation Names</th>
            <th>Object Relation Types</th>
        </tr>
    </thead>
    <tbody>
        @forelse($objects as $object)
            <tr>
                <td>{{ $object->id }}</td>
                <td>{{ $object->name }}</td>
                <td>
                    @foreach($object->relations as $relation)
                        {{ $relation->name }}
                    @endforeach
                </td>
                <td>
                    @foreach($object->relations as $relation)
                        {{ $relation->type }}
                    @endforeach
                </td>
            </tr>
        @empty
            <tr>
                <td colspan="4" class="text-center">No results.</td>
            </tr>
        @endforelse
    </tbody>
</table>
</code>```

Result:

```<code>--------------------------------------
|#|Name  |Relation Name|Relation Type|
--------------------------------------
| |      |Relation 1   |      1      |
|1|Name 1|Relation 2   |      2      |
| |      |Relation 3   |      1      |
--------------------------------------
| |      |Relation 1   |      1      |
|2|Name 2|Relation 2   |      1      |
</code>```

But I'm thinking if it's possible to make only one foreach loop and inside it make . Something like that:

```<code><table id="objects" class="table">
    <thead>
        <tr>
            <th>#</th>
            <th>Object Name</th>
            <th>Object Relation Names</th>
            <th>Object Relation Types</th>
        </tr>
    </thead>
    <tbody>
        @forelse($objects as $object)
            <tr>
                <td>{{ $object->id }}</td>
                <td>{{ $object->name }}</td>
                @foreach($object->relations as $relation)
                    <td>{{ $relation->name }}</td>
                    <td>{{ $relation->type }}</td>
                @endforeach
            </tr>
        @empty
            <tr>
                <td colspan="4" class="text-center">No results.</td>
            </tr>
        @endforelse
    </tbody>
</table>
</code>```

In this case I'm getting something like this:

```<code>--------------------------------------
|#|Name  |Relation Name|Relation Type|
--------------------------------------
|1|Name 1|Relation 1   |      1      |Relation 2   |      2      |Relation 3   |      1      |
--------------------------------------
|2|Name 2|Relation 1   |      1      |Relation 2   |      1      |
</code>```

答:
You have to make something like this

```<code>        1   @forelse($objects as $object)
        2    <tr>
        3   <td>{{ $object->id }}</td>
        4   <td>{{ $object->name }}</td>
        5   @foreach($object->relations as $relation)
        6       <td>{{ $relation->name }}</td>
        7       <td>{{ $relation->type }}</td>
        8   @endforeach
        9 </tr>
</code>```

after line no. 7 add a break line tag to avoid this problem.

or try this. I have not tried it because I am not a home.

```<code>        1   @forelse($objects as $object)
        2    @foreach($object->relations as $relation)
        3    <tr>
        4   <td>{{ $object->id }}</td>
        5   <td>{{ $object->name }}</td>
        6       <td>{{ $relation->name }}</td>
        7       <td>{{ $relation->type }}</td>
        8   @endforeach
        9 </tr>
</code>```

Title: Build Tables with relationships

Body:
I'm trying to build table on my website. Right now it's working fine:

            #
            Object Name
            Object Relation Names
            Object Relation Types

        @forelse($objects as $object)

                {{ $object->id }}
                {{ $object->name }}

                    @foreach($object->relations as $relation)
                        {{ $relation->name }}
                    @endforeach

                    @foreach($object->relations as $relation)
                        {{ $relation->type }}
                    @endforeach

        @empty

                No results.

        @endforelse

Result:

--------------------------------------
|#|Name  |Relation Name|Relation Type|
--------------------------------------
| |      |Relation 1   |      1      |
|1|Name 1|Relation 2   |      2      |
| |      |Relation 3   |      1      |
--------------------------------------
| |      |Relation 1   |      1      |
|2|Name 2|Relation 2   |      1      |

But I'm thinking if it's possible to make only one foreach loop and inside it make . Something like that:

            #
            Object Name
            Object Relation Names
            Object Relation Types

        @forelse($objects as $object)

                {{ $object->id }}
                {{ $object->name }}
                @foreach($object->relations as $relation)
                    {{ $relation->name }}
                    {{ $relation->type }}
                @endforeach

        @empty

                No results.

        @endforelse

In this case I'm getting something like this:

--------------------------------------
|#|Name  |Relation Name|Relation Type|
--------------------------------------
|1|Name 1|Relation 1   |      1      |Relation 2   |      2      |Relation 3   |      1      |
--------------------------------------
|2|Name 2|Relation 1   |      1      |Relation 2   |      1      |

Body:
You have to make something like this

        1   @forelse($objects as $object)
        2    <tr>
        3   <td>{{ $object->id }}</td>
        4   <td>{{ $object->name }}</td>
        5   @foreach($object->relations as $relation)
        6       <td>{{ $relation->name }}</td>
        7       <td>{{ $relation->type }}</td>
        8   @endforeach
        9 </tr>

after line no. 7 add a break line tag to avoid this problem.

or try this. I have not tried it because I am not a home.

        1   @forelse($objects as $object)
        2    @foreach($object->relations as $relation)
        3    <tr>
        4   <td>{{ $object->id }}</td>
        5   <td>{{ $object->name }}</td>
        6       <td>{{ $relation->name }}</td>
        7       <td>{{ $relation->type }}</td>
        8   @endforeach
        9 </tr>


问:
Silverlight context menu: how to determine which menu was clicked?
I have the following context menu:

```<code>                <ListBox x:Name="sectionList" Margin="56,8,15,0" FontSize="64" SelectionChanged="SectionList_SelectionChanged">
                    <ListBox.ItemTemplate>
                        <DataTemplate>
                            <StackPanel>
                                <toolkit:ContextMenuService.ContextMenu>
                                    <toolkit:ContextMenu>
                                        <toolkit:MenuItem Header="Hide this section from this list" Click="ContextMenuItem_Click" />
                                    </toolkit:ContextMenu>
                                </toolkit:ContextMenuService.ContextMenu>
                                <TextBlock Text="{Binding DisplayName}" />
                            </StackPanel>
                        </DataTemplate>
                    </ListBox.ItemTemplate>
                </ListBox>
</code>```

As you can see, each displayed item has its own context menu. Each context menu is hooked up to the same event handler:

```<code>    private void ContextMenuItem_Click(object sender, RoutedEventArgs e)
    {

    }
</code>```

From this method, how can I tell which context menu was clicked? I want to know what the DataContext for the corresponding DataTemplate is.

答: If you use <StackPanel Tag="{Binding}"> then ((FrameworkElement)sender).Tag will return the DataContext object (you'll have to cast it before use, of course).

Body:
I have the following context menu:

                <ListBox x:Name="sectionList" Margin="56,8,15,0" FontSize="64" SelectionChanged="SectionList_SelectionChanged">
                    <ListBox.ItemTemplate>
                        <DataTemplate>
                            <StackPanel>
                                <toolkit:ContextMenuService.ContextMenu>
                                    <toolkit:ContextMenu>
                                        <toolkit:MenuItem Header="Hide this section from this list" Click="ContextMenuItem_Click" />
                                    </toolkit:ContextMenu>
                                </toolkit:ContextMenuService.ContextMenu>
                                <TextBlock Text="{Binding DisplayName}" />
                            </StackPanel>
                        </DataTemplate>
                    </ListBox.ItemTemplate>
                </ListBox>

As you can see, each displayed item has its own context menu. Each context menu is hooked up to the same event handler:

    private void ContextMenuItem_Click(object sender, RoutedEventArgs e)
    {

    }

From this method, how can I tell which context menu was clicked? I want to know what the DataContext for the corresponding DataTemplate is.


问:
Reading the remaining content of the serial buffer Matlab
I have a program that involves continuous reading of the serial port and then doing some processing. Due to the processing, I have some delay in reading the values (I read line by line). Once the user presses stop, the reading stops and I wan't to make sure that the buffer is fully read. I know that there will be some data in the buffer and I don't want to loose it once the comport is closed. is there a way to read the content of the whole buffer at once?

I tried fscanf(comport) but it only read one element.

I know fread reads the whole buffer, but I don't know how to convert the binary to string and get my useful data.

Thanks

答:
If you can read all by fread, then it is just a matter of formatting. You could fread all as number, and convert to char:

```<code>u8 = fread(comport, comport.BytesAvailable); % uchar, but in double
ch = char(u8);
</code>```

This should give you all in buffer as string.

Body:
If you can read all by fread, then it is just a matter of formatting. You could fread all as number, and convert to char:

u8 = fread(comport, comport.BytesAvailable); % uchar, but in double
ch = char(u8);

This should give you all in buffer as string.


问:
Oracle Golden Gate with Cassandra
I am pretty new to Oracle Golden Gate, wanted to understand if it possible to create a bidirectional sync between Oracle 12x and Cassandra(DSE) using Oracle Golden Gate? Searched several places in internet but most examples are replicating data between Oracle databases. I started wondering if it is even possible to do so. Can anyone help me with any documentation? </p>

答:
There is a separate module called Oracle GoldenGate for BigData. It supports many NoSQL replication targets.
One of the supported BigData databases is also Apache Cassandra.

There is a separate manual explaining how to use it.

There is no separate module that allows you to connect Apache Cassandra as the source of your replication. If you need such replication you need to provide some intermediate step. The source of replication for Oracle GoldenGate can only be a database (Oracle, TimesTen, DB2, Informix, MySQL, MS SQL Server, NonStop SQL/MX, SAP/Sybase ASE, Teradata) or a JMS queue.

Title: Oracle Golden Gate with Cassandra


问:
unique records by one column
I have been working on this for a long time now and cant get the answer.
I have a table with 4 columns. I need to return two of these columns, A and B.
However I need the data to be filtered by the first column A. A is not a primary key. How can I achieve this? If I can return all the columns its also ok, as long as the data is only filtered by column A.

```<code>A  B  C  D
1  e  f  r
1  e  f  r
1  e  k  t
2  c  f  r
2  c  f  r
3  l  f  r
</code>```

This should return

```<code>A  B  C  D
1  e  f  r
2  c  f  r
3  l  f  r
</code>```

Which query wil give me this result? Until now I have this but it does not work well:

```<code>SELECT DISTINCT A, B, FROM myTable WHERE C=f
</code>```

答:
use this </p>

```<code>with cte as
(
select * , row_Number() over (Partition by A order by A) as aa from myTable
)
select * from cte where aa = 1
</code>```

Title: unique records by one column

Body:
I have been working on this for a long time now and cant get the answer.
I have a table with 4 columns. I need to return two of these columns, A and B.
However I need the data to be filtered by the first column A. A is not a primary key. How can I achieve this? If I can return all the columns its also ok, as long as the data is only filtered by column A.

A  B  C  D
1  e  f  r
1  e  f  r
1  e  k  t
2  c  f  r
2  c  f  r
3  l  f  r

This should return

A  B  C  D
1  e  f  r
2  c  f  r
3  l  f  r

Which query wil give me this result? Until now I have this but it does not work well:

SELECT DISTINCT A, B, FROM myTable WHERE C=f

Body:
use this

with cte as
(
select * , row_Number() over (Partition by A order by A) as aa from myTable
)
select * from cte where aa = 1


问:
Android: How to set password property in an edit text?
I need to create a login form with 'username' 'password' fields and two buttons 'login' and 'cancel' in my android application.

I am using an alert dialog with edittext inside that.

This is the code I used to create password edittext..

```<code>     final EditText Password = new EditText(this);
     Password.setGravity(Gravity.CENTER);
     Password.setHint("Password");
     Password.setWidth(200);

     Password.setTransformationMethod(new PasswordTransformationMethod());
     login_alert.addView(Password);
</code>```

My issue is that, plain text is shown instead of 'dots' when i open a softkeypad to edit the password. (It is shown as dots when not in softkeypad mode)

Can anyone suggest a solution?

答:
To set password enabled in EditText, We will have to set an "inputType" attribute in xml file.If we are using only EditText then we will have set input type in EditText as given in below code.

```<code>                    <EditText
                    android:id="@+id/password_Edit"
                    android:focusable="true"
                    android:focusableInTouchMode="true"
                    android:hint="password"
                    android:imeOptions="actionNext"
                    android:inputType="textPassword"
                    android:maxLength="100"
                    android:nextFocusDown="@+id/next"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent" />
</code>```

Password enable attribute is

```<code> android:inputType="textPassword"
</code>```

But if we are implementing Password EditText with Material Design (With Design support library) then we will have write code as given bellow.

```<code><android.support.design.widget.TextInputLayout
                xmlns:app="http://schemas.android.com/apk/res-auto"
                android:id="@+id/txtInput_currentPassword"
                android:layout_width="match_parent"
                app:passwordToggleEnabled="false"
                android:layout_height="wrap_content">

                <EditText
                    android:id="@+id/password_Edit"
                    android:focusable="true"
                    android:focusableInTouchMode="true"
                    android:hint="@string/hint_currentpassword"
                    android:imeOptions="actionNext"
                    android:inputType="textPassword"
                    android:maxLength="100"
                    android:nextFocusDown="@+id/next"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent" />
            </android.support.design.widget.TextInputLayout>
</code>```

@Note: - In Android SDK 24 and above, "passwordToggleEnabled" is by default true. So if we have the customs handling of show/hide feature in the password EditText then we will have to set it false in code as given above in .

```<code>app:passwordToggleEnabled="true"
</code>```

To add above line, we will have to add below line in root layout.

```<code>xmlns:app="http://schemas.android.com/apk/res-auto"
</code>```

Body:
I need to create a login form with 'username' 'password' fields and two buttons 'login' and 'cancel' in my android application.

I am using an alert dialog with edittext inside that.

This is the code I used to create password edittext..

     final EditText Password = new EditText(this);
     Password.setGravity(Gravity.CENTER);
     Password.setHint("Password");
     Password.setWidth(200);

     Password.setTransformationMethod(new PasswordTransformationMethod());
     login_alert.addView(Password);

My issue is that, plain text is shown instead of 'dots' when i open a softkeypad to edit the password. (It is shown as dots when not in softkeypad mode)

Can anyone suggest a solution?

Body:
To set password enabled in EditText, We will have to set an "inputType" attribute in xml file.If we are using only EditText then we will have set input type in EditText as given in below code.

                    <EditText
                    android:id="@+id/password_Edit"
                    android:focusable="true"
                    android:focusableInTouchMode="true"
                    android:hint="password"
                    android:imeOptions="actionNext"
                    android:inputType="textPassword"
                    android:maxLength="100"
                    android:nextFocusDown="@+id/next"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent" />

Password enable attribute is

 android:inputType="textPassword"

But if we are implementing Password EditText with Material Design (With Design support library) then we will have write code as given bellow.

<android.support.design.widget.TextInputLayout
                xmlns:app="http://schemas.android.com/apk/res-auto"
                android:id="@+id/txtInput_currentPassword"
                android:layout_width="match_parent"
                app:passwordToggleEnabled="false"
                android:layout_height="wrap_content">

                <EditText
                    android:id="@+id/password_Edit"
                    android:focusable="true"
                    android:focusableInTouchMode="true"
                    android:hint="@string/hint_currentpassword"
                    android:imeOptions="actionNext"
                    android:inputType="textPassword"
                    android:maxLength="100"
                    android:nextFocusDown="@+id/next"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent" />
            </android.support.design.widget.TextInputLayout>

@Note: - In Android SDK 24 and above, "passwordToggleEnabled" is by default true. So if we have the customs handling of show/hide feature in the password EditText then we will have to set it false in code as given above in .

app:passwordToggleEnabled="true"

To add above line, we will have to add below line in root layout.

xmlns:app="http://schemas.android.com/apk/res-auto"


答:
You could change your function to:</p>

```<code>$(document).ready(function(){
  function split(text){
    var splitTxt = text.split('');
    var first_letter = splitTxt[1];
  }

  $('.editor').keyup(function(){
    split($(this).text());
  });
});
</code>```

Title: How can i hold a first letter of `h1` content after pressing backspace

Body:
How can i hold a first letter of h1 content after pressing backspace. Here i used keyup function but its not allowing to write in h1. Can someone know how to do it?

Here is the link: https://jsfiddle.net/5brr7sj1/3/

CODE:

$(document).ready(function(){

var txt = $('.editor').text();
var splitTxt = txt.split('');

 $('.editor').keyup(function(){
 $(this).text(splitTxt[1]);
 });

});

.editor {
  border:1px solid #d9d9d9;
  height:40px;
  line-height:40px;
  padding:0 15px;
}

    Click here to edit content

Body:
You could change your function to:

$(document).ready(function(){
  function split(text){
    var splitTxt = text.split('');
    var first_letter = splitTxt[1];
  }

  $('.editor').keyup(function(){
    split($(this).text());
  });
});


问:
Remove some part of URL using javascript
I have a URL which will be something like below

```<code>http://localhost:22306/NESSPATH/VSAT/I-HP-AAMB-ENB-0003_C1//Panaromic//120.jpg
</code>```

I want URL which will be something like this

```<code>NESSPATH/VSAT/I-HP-AAMB-ENB-0003_C1//Panaromic//120.jpg
</code>```

Here is what I get in variable

```<code>VSATSaving.PANAROMIC_120 = document.getElementById('ImgPanaromic120').src;
</code>```

how to get that using javascript. Tried with lastIndexOf but it is not working

答:
You can simply use window.location.pathname since this is a url.

For other strings, you can use indexOf, split, substring and many of the other string functions.

//example using `split`
var str = "http://localhost:22306/NESSPATH/VSAT/I-HP-AAMB-ENB-0003_C1//Panaromic//120.jpg";
var paths = str.split("http://localhost:22306/")
console.log(paths[1]);```

Body:
I have a URL which will be something like below

http://localhost:22306/NESSPATH/VSAT/I-HP-AAMB-ENB-0003_C1//Panaromic//120.jpg

I want URL which will be something like this

NESSPATH/VSAT/I-HP-AAMB-ENB-0003_C1//Panaromic//120.jpg

Here is what I get in variable

VSATSaving.PANAROMIC_120 = document.getElementById('ImgPanaromic120').src;

how to get that using javascript. Tried with lastIndexOf but it is not working