问:
How to get rid of extra space next to hamburger icon navigation drawer

I Have the layout shown as in this image and this is how my xml looks like :

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    app:contentInsetLeft="0dp"
    app:contentInsetStart="0dp"
    tools:context="pulsesecure.net.securewebbrowser.HomeActivity">

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:padding="0dp"
        android:theme="@style/AppTheme.AppBarOverlay"
        >

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            android:paddingTop="10dp"
            android:paddingBottom="5dp"
            app:popupTheme="@style/AppTheme.PopupOverlay">
            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:orientation="vertical">

                <LinearLayout
                    android:id="@+id/frag_toolbar"
                    android:layout_width="match_parent"
                    android:layout_height="0dp"
                    android:layout_weight="9"
                    android:orientation="horizontal"
                    android:visibility="gone">
                    <TextView
                        android:id="@+id/frag_title"
                        android:layout_width="0dp"
                        android:layout_weight="9"
                        android:layout_height="match_parent"
                        android:textColor="@android:color/white"
                        android:gravity="center_vertical"
                        android:textAppearance="?android:attr/textAppearanceMedium"
                        />

                    <ImageButton
                        android:id="@+id/add_tab_btn"
                        android:layout_width="0dp"
                        android:layout_weight="1"
                        android:layout_height="match_parent"
                        android:src="@mipmap/ic_add_white_24dp"
                        android:background="@color/colorPrimaryDark"
                        />
                </LinearLayout>
                <LinearLayout
                    android:id="@+id/urlBar"
                    android:layout_width="match_parent"
                    android:layout_height="0dp"
                    android:layout_weight="9"
                    android:orientation="horizontal"
                    android:visibility="gone"
                    android:background="@color/colorPrimaryDark"
                    android:focusableInTouchMode="true"
                    >
                    <EditText
                        android:id="@+id/searchET"
                        android:layout_width="0dp"
                        android:layout_weight="9"
                        android:layout_height="match_parent"
                        android:textColor="@android:color/darker_gray"
                        android:layout_gravity="center"
                        android:imeOptions="actionGo"
                        android:singleLine="true"
                        android:hint="@string/hint_url"
                        android:selectAllOnFocus="true"
                        android:background="@drawable/rounded_edit_text"
                       />

                    <ImageButton
                        android:id="@+id/delete_url"
                        android:layout_width="0dp"
                        android:layout_weight="1"
                        android:layout_height="match_parent"
                        android:layout_margin="5dp"
                        android:src="@mipmap/ic_clear_white_24dp"
                        android:background="@color/colorPrimaryDark"
                        />
                </LinearLayout>

                <LinearLayout
                    android:id="@+id/select_url_bar"
                    android:layout_width="match_parent"
                    android:layout_height="0dp"
                    android:layout_weight="9"
                    android:orientation="horizontal"
                    android:visibility="gone"
                    android:background="@color/colorPrimaryDark"
                    android:focusableInTouchMode="true"
                    >

                    <TextView
                        android:id="@+id/url_text"
                        android:layout_width="match_parent"
                        android:layout_height="match_parent"
                        android:layout_marginRight="5dp"
                        android:text="text view"
                        android:clickable="true"
                        android:singleLine="true"
                        android:gravity="center_vertical"
                        android:textColor="@android:color/black"
                        style="@style/PSFont"
                        android:background="@drawable/rounded_edit_text"/>

                </LinearLayout>

            </LinearLayout>

        </android.support.v7.widget.Toolbar>
        <ProgressBar
            android:id="@+id/page_load_progress"
            style="@android:style/Widget.ProgressBar.Horizontal"
            android:layout_width="match_parent"
            android:layout_height="3dp"
            android:progressTint="@color/colorAccent"
            android:visibility="invisible"
           />
    </android.support.design.widget.AppBarLayout>

    <include layout="@layout/content_home" />

</android.support.design.widget.CoordinatorLayout>
</code>```

I need to get rid of the space between hamburger icon and the Edittext (highlighted with orange arrow). I tried padding and inset, but no luck so far. Can someone give me pointers on this ? Thank you.

答:
Try to add below attribute in your <android.support.v7.widget.Toolbar>.

```<code>app:contentInsetStartWithNavigation="0dp"
</code>```

Adding this will work & if it is still not working then just add these two attributes as well

```<code>app:contentInsetLeft="0dp"
app:contentInsetStart="0dp"
</code>```

Body:
I Have the layout shown as in this image and this is how my xml looks like :

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    app:contentInsetLeft="0dp"
    app:contentInsetStart="0dp"
    tools:context="pulsesecure.net.securewebbrowser.HomeActivity">

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:padding="0dp"
        android:theme="@style/AppTheme.AppBarOverlay"
        >

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            android:paddingTop="10dp"
            android:paddingBottom="5dp"
            app:popupTheme="@style/AppTheme.PopupOverlay">
            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:orientation="vertical">

                <LinearLayout
                    android:id="@+id/frag_toolbar"
                    android:layout_width="match_parent"
                    android:layout_height="0dp"
                    android:layout_weight="9"
                    android:orientation="horizontal"
                    android:visibility="gone">
                    <TextView
                        android:id="@+id/frag_title"
                        android:layout_width="0dp"
                        android:layout_weight="9"
                        android:layout_height="match_parent"
                        android:textColor="@android:color/white"
                        android:gravity="center_vertical"
                        android:textAppearance="?android:attr/textAppearanceMedium"
                        />

                    <ImageButton
                        android:id="@+id/add_tab_btn"
                        android:layout_width="0dp"
                        android:layout_weight="1"
                        android:layout_height="match_parent"
                        android:src="@mipmap/ic_add_white_24dp"
                        android:background="@color/colorPrimaryDark"
                        />
                </LinearLayout>
                <LinearLayout
                    android:id="@+id/urlBar"
                    android:layout_width="match_parent"
                    android:layout_height="0dp"
                    android:layout_weight="9"
                    android:orientation="horizontal"
                    android:visibility="gone"
                    android:background="@color/colorPrimaryDark"
                    android:focusableInTouchMode="true"
                    >
                    <EditText
                        android:id="@+id/searchET"
                        android:layout_width="0dp"
                        android:layout_weight="9"
                        android:layout_height="match_parent"
                        android:textColor="@android:color/darker_gray"
                        android:layout_gravity="center"
                        android:imeOptions="actionGo"
                        android:singleLine="true"
                        android:hint="@string/hint_url"
                        android:selectAllOnFocus="true"
                        android:background="@drawable/rounded_edit_text"
                       />

                    <ImageButton
                        android:id="@+id/delete_url"
                        android:layout_width="0dp"
                        android:layout_weight="1"
                        android:layout_height="match_parent"
                        android:layout_margin="5dp"
                        android:src="@mipmap/ic_clear_white_24dp"
                        android:background="@color/colorPrimaryDark"
                        />
                </LinearLayout>

                <LinearLayout
                    android:id="@+id/select_url_bar"
                    android:layout_width="match_parent"
                    android:layout_height="0dp"
                    android:layout_weight="9"
                    android:orientation="horizontal"
                    android:visibility="gone"
                    android:background="@color/colorPrimaryDark"
                    android:focusableInTouchMode="true"
                    >

                    <TextView
                        android:id="@+id/url_text"
                        android:layout_width="match_parent"
                        android:layout_height="match_parent"
                        android:layout_marginRight="5dp"
                        android:text="text view"
                        android:clickable="true"
                        android:singleLine="true"
                        android:gravity="center_vertical"
                        android:textColor="@android:color/black"
                        style="@style/PSFont"
                        android:background="@drawable/rounded_edit_text"/>

                </LinearLayout>

            </LinearLayout>

        </android.support.v7.widget.Toolbar>
        <ProgressBar
            android:id="@+id/page_load_progress"
            style="@android:style/Widget.ProgressBar.Horizontal"
            android:layout_width="match_parent"
            android:layout_height="3dp"
            android:progressTint="@color/colorAccent"
            android:visibility="invisible"
           />
    </android.support.design.widget.AppBarLayout>

    <include layout="@layout/content_home" />

</android.support.design.widget.CoordinatorLayout>

I need to get rid of the space between hamburger icon and the Edittext (highlighted with orange arrow). I tried padding and inset, but no luck so far. Can someone give me pointers on this ? Thank you.

Body:
Try to add below attribute in your <android.support.v7.widget.Toolbar>.

app:contentInsetStartWithNavigation="0dp"

Adding this will work & if it is still not working then just add these two attributes as well

app:contentInsetLeft="0dp"
app:contentInsetStart="0dp"


来源: stackexchange

问:
How does data denormalization work with the Microservice Pattern?
I just read an article on Microservices and PaaS Architecture. In that article, about a third of the way down, the author states (under Denormalize like Crazy):

Refactor database schemas, and de-normalize everything, to allow complete separation and partitioning of data. That is, do not use underlying tables that serve multiple microservices. There should be no sharing of underlying tables that span multiple microservices, and no sharing of data. Instead, if several services need access to the same data, it should be shared via a service API (such as a published REST or a message service interface).

While this sounds great in theory, in practicality it has some serious hurdles to overcome. The biggest of which is that, often, databases are tightly coupled and every table has some foreign key relationship with at least one other table. Because of this it could be impossible to partition a database into n sub-databases controlled by n microservices.

So I ask: Given a database that consists entirely of related tables, how does one denormalize this into smaller fragments (groups of tables) so that the fragments can be controlled by separate microservices?

For instance, given the following (rather small, but exemplar) database:

```<code>[users] table
=============
user_id
user_first_name
user_last_name
user_email

[products] table
================
product_id
product_name
product_description
product_unit_price

[orders] table
==============
order_id
order_datetime
user_id

[products_x_orders] table (for line items in the order)
=======================================================
products_x_orders_id
product_id
order_id
quantity_ordered
</code>```

Don't spend too much time critiquing my design, I did this on the fly. The point is that, to me, it makes logical sense to split this database into 3 microservices:

UserService - for CRUDding users in the system; should ultimately manage the [users] table; and

ProductService - for CRUDding products in the system; should ultimately manage the [products] table; and

OrderService - for CRUDding orders in the system; should ultimately manage the [orders] and [products_x_orders] tables

However all of these tables have foreign key relationships with each other. If we denormalize them and treat them as monoliths, they lose all their semantic meaning:

```<code>[users] table
=============
user_id
user_first_name
user_last_name
user_email

[products] table
================
product_id
product_name
product_description
product_unit_price

[orders] table
==============
order_id
order_datetime

[products_x_orders] table (for line items in the order)
=======================================================
products_x_orders_id
quantity_ordered
</code>```

Now there's no way to know who ordered what, in which quantity, or when.

So is this article typical academic hullabaloo, or is there a real world practicality to this denormalization approach, and if so, what does it look like (bonus points for using my example in the answer)?

答:
It is indeed one of key problems in microservices which is quite conviniently omitted in most of articles. Fortunatelly there are solutions for this. As a basis for discussion let's have tables which you have provided in the question.

Image above shows how tables will look like in monolith. Just few tables with joins.

To refactor this to microservices we can use few strategies:

Api Join

In this strategy foreign keys between microservices are broken and microservice exposes an endpoint which mimics this key. For example: Product microservice will expose findProductById endpoint. Order microservice can use this endpoint instead of join.

It has an obvious downside. It is slower.

Read only views

In the second solution you can create copy of the table in the second database. Copy is read only. Each microservice can use mutable operations on its read/write tables. When it comes to read only tables which are copied from other databases they can (obviously) use only reads

High performance read

It is possible to achieve high performance read by introducing solutions such as redis/memcached on top of read only view solution. Both sides of join should be copied to flat structure optimized for reading. You can introduce completely new stateless microservice which can be used for reading from this storage. While it seems like a lot of hassle it is worth to note that it will have higher performance than monolithic solution on top of relational database.

There are few possible solutions. Ones which are simplest in implementation have lowest performance. High performance solutions will take few weeks to implement.

ContentLicense: CC BY-SA 3.0

Body:
I just read an article on Microservices and PaaS Architecture. In that article, about a third of the way down, the author states (under Denormalize like Crazy):

Refactor database schemas, and de-normalize everything, to allow complete separation and partitioning of data. That is, do not use underlying tables that serve multiple microservices. There should be no sharing of underlying tables that span multiple microservices, and no sharing of data. Instead, if several services need access to the same data, it should be shared via a service API (such as a published REST or a message service interface).

While this sounds great in theory, in practicality it has some serious hurdles to overcome. The biggest of which is that, often, databases are tightly coupled and every table has some foreign key relationship with at least one other table. Because of this it could be impossible to partition a database into n sub-databases controlled by n microservices.

So I ask: Given a database that consists entirely of related tables, how does one denormalize this into smaller fragments (groups of tables) so that the fragments can be controlled by separate microservices?

For instance, given the following (rather small, but exemplar) database:

[users] table
=============
user_id
user_first_name
user_last_name
user_email

[products] table
================
product_id
product_name
product_description
product_unit_price

[orders] table
==============
order_id
order_datetime
user_id

[products_x_orders] table (for line items in the order)
=======================================================
products_x_orders_id
product_id
order_id
quantity_ordered

Don't spend too much time critiquing my design, I did this on the fly. The point is that, to me, it makes logical sense to split this database into 3 microservices:

UserService - for CRUDding users in the system; should ultimately manage the [users] table; and

ProductService - for CRUDding products in the system; should ultimately manage the [products] table; and

OrderService - for CRUDding orders in the system; should ultimately manage the [orders] and [products_x_orders] tables

However all of these tables have foreign key relationships with each other. If we denormalize them and treat them as monoliths, they lose all their semantic meaning:

[users] table
=============
user_id
user_first_name
user_last_name
user_email

[products] table
================
product_id
product_name
product_description
product_unit_price

[orders] table
==============
order_id
order_datetime

[products_x_orders] table (for line items in the order)
=======================================================
products_x_orders_id
quantity_ordered

Now there's no way to know who ordered what, in which quantity, or when.

So is this article typical academic hullabaloo, or is there a real world practicality to this denormalization approach, and if so, what does it look like (bonus points for using my example in the answer)?


问:
Move elements passed into a component using a slot
I'm just starting out with VueJS and I was trying to port over a simple jQuery read more plugin I had.

I've got everything working except I don't know how to get access to the contents of the slot. What I would like to do is move some elements  passed into the slot to right above the div.readmore__wrapper.

Can this be done simply in the template, or am I going to have to do it some other way?

Here's my component so far...

```<code><template>
    <div class="readmore">

        <!-- SOME ELEMENTS PASSED TO SLOT TO GO HERE! -->

        <div class="readmore__wrapper" :class="{ 'active': open }">
            <slot></slot>
        </div>
        <a href="#!" @click.prevent="toggle" class="readmore__button">Read {{ open ? lessLabel : moreLabel }}</a>
    </div>
</template>
<script>
    export default {
        name: 'read-more',
        data() {
            return {
                open: false,
                moreLabel: 'more',
                lessLabel: 'less'
            };
        },
        methods: {
            toggle() {
                this.open = !this.open;
            }
        },
    }
</script>
</code>```

答:
You can certainly do what you describe. Manipulating the DOM in a component is typically done in the mounted hook. If you expect the content of the slot to be updated at some point, you might need to do the same thing in the updated hook, although in playing with it, simply having some interpolated content change didn't require it.

new Vue({
  el: '#app',
  components: {
    readMore: {
      template: '#read-more-template',
      data() {
        return {
          open: false,
          moreLabel: 'more',
          lessLabel: 'less'
        };
      },
      methods: {
        toggle() {
          this.open = !this.open;
        }
      },
      mounted() {
        const readmoreEl = this.$el.querySelector('.readmore__wrapper');
        const firstEl = readmoreEl.querySelector('*');

        this.$el.insertBefore(firstEl, readmoreEl);
      }
    }
  }
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.readmore__wrapper {
  display: none;
}

.readmore__wrapper.active {
  display: block;
}</code>```

  Hi there.
  <read-more>

First div inside

Another div of content

  </read-more>

<template id="read-more-template">

            <slot></slot>

        Read {{ open ? lessLabel : moreLabel }}

</template>```

Body:
I'm just starting out with VueJS and I was trying to port over a simple jQuery read more plugin I had.

I've got everything working except I don't know how to get access to the contents of the slot. What I would like to do is move some elements  passed into the slot to right above the div.readmore__wrapper.

Can this be done simply in the template, or am I going to have to do it some other way?

Here's my component so far...

<template>

            <slot></slot>

        Read {{ open ? lessLabel : moreLabel }}

</template>

Body:
You can certainly do what you describe. Manipulating the DOM in a component is typically done in the mounted hook. If you expect the content of the slot to be updated at some point, you might need to do the same thing in the updated hook, although in playing with it, simply having some interpolated content change didn't require it.

new Vue({
  el: '#app',
  components: {
    readMore: {
      template: '#read-more-template',
      data() {
        return {
          open: false,
          moreLabel: 'more',
          lessLabel: 'less'
        };
      },
      methods: {
        toggle() {
          this.open = !this.open;
        }
      },
      mounted() {
        const readmoreEl = this.$el.querySelector('.readmore__wrapper');
        const firstEl = readmoreEl.querySelector('*');

        this.$el.insertBefore(firstEl, readmoreEl);
      }
    }
  }
});

.readmore__wrapper {
  display: none;
}

.readmore__wrapper.active {
  display: block;
}

<script src="//cdnjs.cloudflare.com/ajax/libs/vue/2.4.2/vue.min.js"></script>
<div id='app'>
  Hi there.
  <read-more>
    <div>First div inside</div>
    <div>Another div of content</div>
  </read-more>
</div>
<template id="read-more-template">
    <div class="readmore">

        <!-- SOME ELEMENTS PASSED TO SLOT TO GO HERE! -->

        <div class="readmore__wrapper" :class="{ 'active': open }">
            <slot></slot>
        </div>
        <a href="#!" @click.prevent="toggle" class="readmore__button">Read {{ open ? lessLabel : moreLabel }}</a>
    </div>
</template>

ContentLicense: CC BY-SA 4.0


问:
manipulation of csv format in python files
I have combined two lists using zip syntax. When I saved it in csv format, whole data are stayed in one cell of excell. what's that i want is: each element of zipped file should be stay on each row.

This is my code:

```<code>list_of_first_column=["banana","cat","brown"]
list_of_second_column=["fruit","animal","color"]

graph_zip_file=zip(list_of_first_column,list_of_second_column)
with open('graph.csv', 'w') as csv_file:
    writer = csv.writer(csv_file)
    writer.writerow(graph_zip_file)
</code>```

what I want in csv format:

```<code>banana,fruit
cat,animal
brown,color
</code>```

答:
You've got two ways of doing this, assuming that you're using the csv module. You can either use writer.writerows:

```<code>list_of_first_column = ["banana", "cat", "brown"]
list_of_second_column = ["fruit", "animal", "color"]

graph_zip_file = zip(list_of_first_column, list_of_second_column)
with open('graph.csv', 'w') as csv_file:
    writer = csv.writer(csv_file)
    writer.writerows(graph_zip_file)
</code>```

Or, you can use writer.writerow and a for-loop:

```<code>list_of_first_column = ["banana", "cat", "brown"]
list_of_second_column = ["fruit", "animal", "color"]

graph_zip_file = zip(list_of_first_column, list_of_second_column)
with open('graph.csv', 'w') as csv_file:
    writer = csv.writer(csv_file)
    for row in graph_zip_file
        writer.writerow(row)
</code>```

They both should return the same thing, which is what you've indicated as your desired output.

I hope this proves useful.

Body:
I have combined two lists using zip syntax. When I saved it in csv format, whole data are stayed in one cell of excell. what's that i want is: each element of zipped file should be stay on each row.

This is my code:

list_of_first_column=["banana","cat","brown"]
list_of_second_column=["fruit","animal","color"]

graph_zip_file=zip(list_of_first_column,list_of_second_column)
with open('graph.csv', 'w') as csv_file:
    writer = csv.writer(csv_file)
    writer.writerow(graph_zip_file)

what I want in csv format:

banana,fruit
cat,animal
brown,color

Body:
You've got two ways of doing this, assuming that you're using the csv module. You can either use writer.writerows:

list_of_first_column = ["banana", "cat", "brown"]
list_of_second_column = ["fruit", "animal", "color"]

graph_zip_file = zip(list_of_first_column, list_of_second_column)
with open('graph.csv', 'w') as csv_file:
    writer = csv.writer(csv_file)
    writer.writerows(graph_zip_file)

Or, you can use writer.writerow and a for-loop:

list_of_first_column = ["banana", "cat", "brown"]
list_of_second_column = ["fruit", "animal", "color"]

graph_zip_file = zip(list_of_first_column, list_of_second_column)
with open('graph.csv', 'w') as csv_file:
    writer = csv.writer(csv_file)
    for row in graph_zip_file
        writer.writerow(row)

They both should return the same thing, which is what you've indicated as your desired output.

I hope this proves useful.


问:
Mysql self join with aggregate is slow and optimized differently than intended
I've a query which performs slow (~20s) and after doing a fair amount of reading and digging I can't seem to figure out a solution.

The query is:

```<code>EXPLAIN EXTENDED
SELECT t1.*
FROM   tire_transaction AS t1
       INNER JOIN (SELECT license_plate,
                          Max(transaction_date) AS `last_checkin`
                   FROM   tire_transaction
                   GROUP  BY license_plate) AS t2
               ON t1.license_plate = t2.license_plate
                  AND t1.transaction_date = t2.last_checkin
WHERE  ( t1.client_id = '1' )
       AND ( t1.deleted = 0 )
</code>```

The result is:

```<code>id  select_type  table             type    possible_keys                                                              key                  key_len  ref                                 rows  filtered  Extra
 1  PRIMARY      <derived2>        ALL     (NULL)                                                                     (NULL)               (NULL)   (NULL)                             69121    100.00
 1  PRIMARY      t1                ref     client_id,license_plate,tire_transaction_date,deleted,license__trans_date  license__trans_date  67       t2.last_checkin,t2.license_plate       1    100.00  Using where
 2  DERIVED      tire_transaction  index   (NULL)                                                                     license_plate        63       (NULL)                            366423    100.00
</code>```

The table is:

```<code>CREATE TABLE `tire_transaction` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `entity_id` int(11) DEFAULT NULL,
  `client_id` int(11) NOT NULL,
  `company_id` int(11) NOT NULL,
  `parent_id` int(11) DEFAULT NULL,
  `transaction_type` tinyint(1) DEFAULT '0',
  `transaction_date` date DEFAULT NULL,
  `transaction_status` int(11) DEFAULT NULL,
  `transaction_urgent` tinyint(1) NOT NULL DEFAULT '0',
  `license_plate` varchar(20) DEFAULT NULL,
  `license_plate_country` varchar(2) DEFAULT 'NL',
  `chassis_number` varchar(40) DEFAULT NULL,
  `brand` varchar(255) DEFAULT NULL,
  `brand_type` varchar(255) DEFAULT NULL,
  `client_name` varchar(255) DEFAULT NULL,
  `client_salutation` varchar(255) DEFAULT NULL,
  `client_company` varchar(255) DEFAULT NULL,
  `client_street` varchar(255) DEFAULT NULL,
  `client_number` varchar(255) DEFAULT NULL,
  `client_postalcode` varchar(255) DEFAULT NULL,
  `client_city` varchar(255) DEFAULT NULL,
  `client_phone` varchar(255) DEFAULT NULL,
  `client_phone_alt` varchar(255) DEFAULT NULL,
  `client_email` varchar(255) DEFAULT NULL,
  `tire_type` tinyint(1) DEFAULT '0',
  `set_price` int(11) DEFAULT NULL,
  `rim_material` tinyint(1) DEFAULT '0',
  `notes` text,
  `created` datetime DEFAULT NULL,
  `deleted` tinyint(1) NOT NULL DEFAULT '0',
  PRIMARY KEY (`id`),
  KEY `client_id` (`client_id`) USING BTREE,
  KEY `company_id` (`company_id`) USING BTREE,
  KEY `license_plate` (`license_plate`) USING BTREE,
  KEY `client_name` (`client_name`) USING BTREE,
  KEY `tire_transaction_entityId` (`entity_id`) USING BTREE,
  KEY `tire_transaction_parentId` (`parent_id`) USING BTREE,
  KEY `tire_transaction_date` (`transaction_date`),
  KEY `deleted` (`deleted`),
  KEY `license__trans_date` (`transaction_date`,`license_plate`)
) ENGINE=InnoDB AUTO_INCREMENT=418618 DEFAULT CHARSET=utf8
</code>```

There are like 400K rows. Mysql is optimizing the query and rewriting the ON statement as a WHERE statement which I think is where the slowness comes from.

Any thoughts on this one? Thanks!

答:
One area where you might be able to improve your performance is the subquery which involves a GROUP BY aggregation (aliased as t2).  Consider adding a composite index on license_plate and transaction_date:

```<code>CREATE INDEX tire_idx on tire_transaction(license_plate, transaction_date);
</code>```

If you peruse the MySQL documentation on optimizing GROUP BY queries, the above index should allow MySQL to do the aggregation via a loose index scan.  If the above works, then you should see Using index for group-by in the Extra column of when you run EXPLAIN.

Body:
I've a query which performs slow (~20s) and after doing a fair amount of reading and digging I can't seem to figure out a solution.

The query is:

EXPLAIN EXTENDED
SELECT t1.*
FROM   tire_transaction AS t1
       INNER JOIN (SELECT license_plate,
                          Max(transaction_date) AS `last_checkin`
                   FROM   tire_transaction
                   GROUP  BY license_plate) AS t2
               ON t1.license_plate = t2.license_plate
                  AND t1.transaction_date = t2.last_checkin
WHERE  ( t1.client_id = '1' )
       AND ( t1.deleted = 0 )

The result is:

id  select_type  table             type    possible_keys                                                              key                  key_len  ref                                 rows  filtered  Extra
 1  PRIMARY      <derived2>        ALL     (NULL)                                                                     (NULL)               (NULL)   (NULL)                             69121    100.00
 1  PRIMARY      t1                ref     client_id,license_plate,tire_transaction_date,deleted,license__trans_date  license__trans_date  67       t2.last_checkin,t2.license_plate       1    100.00  Using where
 2  DERIVED      tire_transaction  index   (NULL)                                                                     license_plate        63       (NULL)                            366423    100.00

The table is:

CREATE TABLE `tire_transaction` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `entity_id` int(11) DEFAULT NULL,
  `client_id` int(11) NOT NULL,
  `company_id` int(11) NOT NULL,
  `parent_id` int(11) DEFAULT NULL,
  `transaction_type` tinyint(1) DEFAULT '0',
  `transaction_date` date DEFAULT NULL,
  `transaction_status` int(11) DEFAULT NULL,
  `transaction_urgent` tinyint(1) NOT NULL DEFAULT '0',
  `license_plate` varchar(20) DEFAULT NULL,
  `license_plate_country` varchar(2) DEFAULT 'NL',
  `chassis_number` varchar(40) DEFAULT NULL,
  `brand` varchar(255) DEFAULT NULL,
  `brand_type` varchar(255) DEFAULT NULL,
  `client_name` varchar(255) DEFAULT NULL,
  `client_salutation` varchar(255) DEFAULT NULL,
  `client_company` varchar(255) DEFAULT NULL,
  `client_street` varchar(255) DEFAULT NULL,
  `client_number` varchar(255) DEFAULT NULL,
  `client_postalcode` varchar(255) DEFAULT NULL,
  `client_city` varchar(255) DEFAULT NULL,
  `client_phone` varchar(255) DEFAULT NULL,
  `client_phone_alt` varchar(255) DEFAULT NULL,
  `client_email` varchar(255) DEFAULT NULL,
  `tire_type` tinyint(1) DEFAULT '0',
  `set_price` int(11) DEFAULT NULL,
  `rim_material` tinyint(1) DEFAULT '0',
  `notes` text,
  `created` datetime DEFAULT NULL,
  `deleted` tinyint(1) NOT NULL DEFAULT '0',
  PRIMARY KEY (`id`),
  KEY `client_id` (`client_id`) USING BTREE,
  KEY `company_id` (`company_id`) USING BTREE,
  KEY `license_plate` (`license_plate`) USING BTREE,
  KEY `client_name` (`client_name`) USING BTREE,
  KEY `tire_transaction_entityId` (`entity_id`) USING BTREE,
  KEY `tire_transaction_parentId` (`parent_id`) USING BTREE,
  KEY `tire_transaction_date` (`transaction_date`),
  KEY `deleted` (`deleted`),
  KEY `license__trans_date` (`transaction_date`,`license_plate`)
) ENGINE=InnoDB AUTO_INCREMENT=418618 DEFAULT CHARSET=utf8

There are like 400K rows. Mysql is optimizing the query and rewriting the ON statement as a WHERE statement which I think is where the slowness comes from.

Any thoughts on this one? Thanks!

Body:
One area where you might be able to improve your performance is the subquery which involves a GROUP BY aggregation (aliased as t2).  Consider adding a composite index on license_plate and transaction_date:

CREATE INDEX tire_idx on tire_transaction(license_plate, transaction_date);

If you peruse the MySQL documentation on optimizing GROUP BY queries, the above index should allow MySQL to do the aggregation via a loose index scan.  If the above works, then you should see Using index for group-by in the Extra column of when you run EXPLAIN.


问:
Input field and button side by side in center
I have an input field and a button that I want to have horizontally and vertically centered (without transform) side by side in the middle. I can easily fix the centering part, but to place the input field and the button side by side has proven to be much harder. For whatever reason, the button is placed lower than the input field.

The HTML and CSS:

body {
  background: #000;
  text-align: center;
 }
.hd {
  font-size: 3.9rem;
  font-family: Open Sans,Segoe UI,Arial,Verdana,Tahoma,sans-serif;
  color: rgb(250, 250, 250);
  margin-bottom: 30px;
 }
.content {
  margin: 0;
  position: relative;
    margin-top: 20vh;
 }
.form-control, .btn {
  display: inline-block;
  padding: 10px 25px;
  font-size: 1rem;
  font-family: Open Sans,Segoe UI,Arial,Verdana,Tahoma,sans-serif;
  border-radius: 0;
  -webkit-appearance: none;
 }
.form-group {
  display: inline-block;
 }
.form-control {
  border: 0;
  float: left;
  width: 250px;
 }
*:focus {
  outline: none;
 }
.form-controlt:focus{
  outline: none;
 }
.btn {
  background-color: lightgreen;
  border: 0;
  background-color: #ff8e41;
  -o-transition: all .3s;
  transition: all .3s;
  font-family: Open Sans,Segoe UI,Arial,Verdana,Tahoma,sans-serif;
  font-style: normal;
  font-weight: 600;
  position: relative;
  border: 0;
  box-sizing: border-box;
  color: #fff;
  text-align: center;
  margin: 0 auto;
  -webkit-appearance: button;
  cursor: pointer;
 }
.btn::-moz-focus-inner {
  border: 0;
 }
.btn[type=submit]:active {
  background: #ed7a18;
  box-shadow: 0 1px 0 0 hsla(0,0%,100%,.27),inset 0 1px 0 0 #bc5f10;
 }
.btn[type=submit]:hover {
  background-color: #ffa353;
  -o-transition: all .3s;
  transition: all .3s;
 }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="content">

  <div class="hd">Text</div>

 <form action="8dy9s8hsd9.php" method="POST">

  <div id="name-group" class="form-group">
   <input type="text" class="form-control">
  </div>

  <button type="submit" class="btn btn-success">Submit<span class="fa fa-arrow-right"></span></button>

 </form>
</div></code>```

答:
Put the input and the button elements inside the same div with .form-group class.

body {
  background: #000;
  text-align: center;
 }
.hd {
  font-size: 3.9rem;
  font-family: Open Sans,Segoe UI,Arial,Verdana,Tahoma,sans-serif;
  color: rgb(250, 250, 250);
  margin-bottom: 30px;
 }
.content {
  margin: 0;
  position: relative;
    margin-top: 20vh;
 }
.form-control, .btn {
  display: inline-block;
  padding: 10px 25px;
  font-size: 1rem;
  font-family: Open Sans,Segoe UI,Arial,Verdana,Tahoma,sans-serif;
  border-radius: 0;
  -webkit-appearance: none;
 }
.form-group {
  display: inline-block;
 }
.form-control {
  border: 0;
  float: left;
  width: 250px;
 }
*:focus {
  outline: none;
 }
.form-controlt:focus{
  outline: none;
 }
.btn {
  background-color: lightgreen;
  border: 0;
  background-color: #ff8e41;
  -o-transition: all .3s;
  transition: all .3s;
  font-family: Open Sans,Segoe UI,Arial,Verdana,Tahoma,sans-serif;
  font-style: normal;
  font-weight: 600;
  position: relative;
  border: 0;
  box-sizing: border-box;
  color: #fff;
  text-align: center;
  margin: 0 auto;
  -webkit-appearance: button;
  cursor: pointer;
 }
.btn::-moz-focus-inner {
  border: 0;
 }
.btn[type=submit]:active {
  background: #ed7a18;
  box-shadow: 0 1px 0 0 hsla(0,0%,100%,.27),inset 0 1px 0 0 #bc5f10;
 }
.btn[type=submit]:hover {
  background-color: #ffa353;
  -o-transition: all .3s;
  transition: all .3s;
 }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="content">

  <div class="hd">Text</div>

 <form action="8dy9s8hsd9.php" method="POST">

  <div id="name-group" class="form-group">
   <input type="text" class="form-control">
      <button type="submit" class="btn btn-success">Submit<span class="fa fa-arrow-right"></span></button>
  </div>

 </form>
</div></code>```

Body:
I have an input field and a button that I want to have horizontally and vertically centered (without transform) side by side in the middle. I can easily fix the centering part, but to place the input field and the button side by side has proven to be much harder. For whatever reason, the button is placed lower than the input field.

The HTML and CSS:

body {
  background: #000;
  text-align: center;
 }
.hd {
  font-size: 3.9rem;
  font-family: Open Sans,Segoe UI,Arial,Verdana,Tahoma,sans-serif;
  color: rgb(250, 250, 250);
  margin-bottom: 30px;
 }
.content {
  margin: 0;
  position: relative;
    margin-top: 20vh;
 }
.form-control, .btn {
  display: inline-block;
  padding: 10px 25px;
  font-size: 1rem;
  font-family: Open Sans,Segoe UI,Arial,Verdana,Tahoma,sans-serif;
  border-radius: 0;
  -webkit-appearance: none;
 }
.form-group {
  display: inline-block;
 }
.form-control {
  border: 0;
  float: left;
  width: 250px;
 }
*:focus {
  outline: none;
 }
.form-controlt:focus{
  outline: none;
 }
.btn {
  background-color: lightgreen;
  border: 0;
  background-color: #ff8e41;
  -o-transition: all .3s;
  transition: all .3s;
  font-family: Open Sans,Segoe UI,Arial,Verdana,Tahoma,sans-serif;
  font-style: normal;
  font-weight: 600;
  position: relative;
  border: 0;
  box-sizing: border-box;
  color: #fff;
  text-align: center;
  margin: 0 auto;
  -webkit-appearance: button;
  cursor: pointer;
 }
.btn::-moz-focus-inner {
  border: 0;
 }
.btn[type=submit]:active {
  background: #ed7a18;
  box-shadow: 0 1px 0 0 hsla(0,0%,100%,.27),inset 0 1px 0 0 #bc5f10;
 }
.btn[type=submit]:hover {
  background-color: #ffa353;
  -o-transition: all .3s;
  transition: all .3s;
 }

Text

 <form action="8dy9s8hsd9.php" method="POST">

   <input type="text" class="form-control">

  <button type="submit" class="btn btn-success">Submit</button>

 </form>

Body:
Put the input and the button elements inside the same div with .form-group class.

body {
  background: #000;
  text-align: center;
 }
.hd {
  font-size: 3.9rem;
  font-family: Open Sans,Segoe UI,Arial,Verdana,Tahoma,sans-serif;
  color: rgb(250, 250, 250);
  margin-bottom: 30px;
 }
.content {
  margin: 0;
  position: relative;
    margin-top: 20vh;
 }
.form-control, .btn {
  display: inline-block;
  padding: 10px 25px;
  font-size: 1rem;
  font-family: Open Sans,Segoe UI,Arial,Verdana,Tahoma,sans-serif;
  border-radius: 0;
  -webkit-appearance: none;
 }
.form-group {
  display: inline-block;
 }
.form-control {
  border: 0;
  float: left;
  width: 250px;
 }
*:focus {
  outline: none;
 }
.form-controlt:focus{
  outline: none;
 }
.btn {
  background-color: lightgreen;
  border: 0;
  background-color: #ff8e41;
  -o-transition: all .3s;
  transition: all .3s;
  font-family: Open Sans,Segoe UI,Arial,Verdana,Tahoma,sans-serif;
  font-style: normal;
  font-weight: 600;
  position: relative;
  border: 0;
  box-sizing: border-box;
  color: #fff;
  text-align: center;
  margin: 0 auto;
  -webkit-appearance: button;
  cursor: pointer;
 }
.btn::-moz-focus-inner {
  border: 0;
 }
.btn[type=submit]:active {
  background: #ed7a18;
  box-shadow: 0 1px 0 0 hsla(0,0%,100%,.27),inset 0 1px 0 0 #bc5f10;
 }
.btn[type=submit]:hover {
  background-color: #ffa353;
  -o-transition: all .3s;
  transition: all .3s;
 }

<div class="content">

  <div class="hd">Text</div>

 <form action="8dy9s8hsd9.php" method="POST">

  <div id="name-group" class="form-group">
   <input type="text" class="form-control">
      <button type="submit" class="btn btn-success">Submit<span class="fa fa-arrow-right"></span></button>
  </div>

 </form>
</div>


问:
How to search and display items through php,html and from database (cpanel)
I want to create a form which allows the user to type in a search and have it pick up the values from a database and display them, for some reason I can't get my query to work it just displays "could not search" even after i type in the search criteria. The include("global.php") is what i use to connect to the database. For my other codes to connect to the database, i uses these:

```<code>include("global.php");

session_start();
$userid = ($_SESSION['userid']);
if (isset($_SESSION['userid']) == false)
{
    header("Location: login.php");
}

$mysqli = new mysqli(spf, dbuser, dbpw, db);
$stmt = $mysqli->prepare("SELECT name, position FROM profiles WHERE userid=?");
$stmt->bind_param("s", $userid);
$stmt->execute();
$stmt->bind_result($name, $position);
$stmt->fetch();
$stmt->close();
$mysqli->close();
?>
</code>```

Below is the issue i am facing. Above is an example of how i normally connect to the database and retrieve datas i want. But i do not knw how to apply it to codes below.

```<code><form action ="search.php" method = "post">

      <input name="search" type="text" size="30" />

      <input type="submit" value="Search"/>

</form>

<?php
include("global.php");
error_reporting(E_ERROR);

 $output = '';

if(isset($_POST['search'])) {
$search = $_POST['search'];
$search = preg_replace("#[^0-9a-z]i#","", $search);

$mysqli_query = new mysqli(spf, dbuser, dbpw, db);
$query = mysqli_query("SELECT * FROM items WHERE userid LIKE '%$search%'") or die ("Could not search");
$count = mysqli_num_rows($query);

if($count == 0){
  $output = "There was no search results!";

}else{

  while ($row = mysqli_fetch_array($query)) {

    $userid = $row ['userid'];
    $carno = $row ['carno'];
    $cost = $row ['cost'];
    $area = $row ['area'];
    $receipt = $row ['receipt'];

    $output .='<div> '.$userid.' '.$carno.' '.$cost.''.$area.' '.receipt.'</div>';

  }

}
}

?>
</code>```

Preview:

database

答:
Let me explain the following query:

$query = mysqli_query("SELECT * FROM items WHERE userid LIKE '%$search%'") or die ("Could not search");

You are searching userid LIKE '%search%'. Currently you are searching exactly '%search%' as text, while $search should contain $_POST data like 'Ronnie Oosting'. But i understand you want to have a variable which contains information you want to search on. This means you need to 'split' text and php. So a working query should be something like:

$query = mysqli_query("SELECT * FROM items WHERE userid LIKE %'" . $search . "'%") or die ("Could not search");

note: I didnt test this, so let me know if you get results, or not.

$search is a variable now, so you need to have $search set with data which can be hard coded, or in your case filled with $_POST data. Something like (which is not save): $search = $_POST['something'];

In your case this should work:

```<code>if(isset($_POST['search'])) {
$search = $_POST['search'];
$search = preg_replace("#[^0-9a-z]i#","", $search);

$mysqli_query = new mysqli('spf', 'dbuser', 'dbpw', 'db');
$query = mysqli_query("SELECT * FROM items WHERE userid = '" . $search . "'");
$count = mysqli_num_rows($query);
</code>```

Another note:

You are using $mysqli = new mysqli(spf, dbuser, dbpw, db);. Which should be $mysqli = new mysqli('spf', 'dbuser', 'dbpw', 'db');

Body:
I want to create a form which allows the user to type in a search and have it pick up the values from a database and display them, for some reason I can't get my query to work it just displays "could not search" even after i type in the search criteria. The include("global.php") is what i use to connect to the database. For my other codes to connect to the database, i uses these:

include("global.php");

session_start();
$userid = ($_SESSION['userid']);
if (isset($_SESSION['userid']) == false)
{
    header("Location: login.php");
}

$mysqli = new mysqli(spf, dbuser, dbpw, db);
$stmt = $mysqli->prepare("SELECT name, position FROM profiles WHERE userid=?");
$stmt->bind_param("s", $userid);
$stmt->execute();
$stmt->bind_result($name, $position);
$stmt->fetch();
$stmt->close();
$mysqli->close();
?>

Below is the issue i am facing. Above is an example of how i normally connect to the database and retrieve datas i want. But i do not knw how to apply it to codes below.

<form action ="search.php" method = "post">

      <input name="search" type="text" size="30" />

      <input type="submit" value="Search"/>

</form>

<?php
include("global.php");
error_reporting(E_ERROR);

 $output = '';

if(isset($_POST['search'])) {
$search = $_POST['search'];
$search = preg_replace("#[^0-9a-z]i#","", $search);

$mysqli_query = new mysqli(spf, dbuser, dbpw, db);
$query = mysqli_query("SELECT * FROM items WHERE userid LIKE '%$search%'") or die ("Could not search");
$count = mysqli_num_rows($query);

if($count == 0){
  $output = "There was no search results!";

}else{

  while ($row = mysqli_fetch_array($query)) {

    $userid = $row ['userid'];
    $carno = $row ['carno'];
    $cost = $row ['cost'];
    $area = $row ['area'];
    $receipt = $row ['receipt'];

    $output .='
 '.$userid.' '.$carno.' '.$cost.''.$area.' '.receipt.'
';

  }

}
}

?>

Preview:

database

Body:
Let me explain the following query:

$query = mysqli_query("SELECT * FROM items WHERE userid LIKE '%$search%'") or die ("Could not search");

You are searching userid LIKE '%search%'. Currently you are searching exactly '%search%' as text, while $search should contain $_POST data like 'Ronnie Oosting'. But i understand you want to have a variable which contains information you want to search on. This means you need to 'split' text and php. So a working query should be something like:

$query = mysqli_query("SELECT * FROM items WHERE userid LIKE %'" . $search . "'%") or die ("Could not search");

note: I didnt test this, so let me know if you get results, or not.

$search is a variable now, so you need to have $search set with data which can be hard coded, or in your case filled with $_POST data. Something like (which is not save): $search = $_POST['something'];

In your case this should work:

if(isset($_POST['search'])) {
$search = $_POST['search'];
$search = preg_replace("#[^0-9a-z]i#","", $search);

$mysqli_query = new mysqli('spf', 'dbuser', 'dbpw', 'db');
$query = mysqli_query("SELECT * FROM items WHERE userid = '" . $search . "'");
$count = mysqli_num_rows($query);

Another note:

You are using $mysqli = new mysqli(spf, dbuser, dbpw, db);. Which should be $mysqli = new mysqli('spf', 'dbuser', 'dbpw', 'db');


问:
Sequence number Equivalent in sybase ase
I have an existing sybase ase table which is using IDENTITY as its primary key. Now i need to recreate this table but i want to start the PK from next value of IDENTITY PK in prod env. e.g. If currently PK = 231 then after re-creating i want it to start from 232 onwards or any other INTEGER value > 231.

In oracle its easy to configure a sequence number and we can give start with but in sybase ase as we dont have sequence available so i tried using newid() function but it gives binary(16) values whereas i want  integer values.

Can anyone suggest something ?

答:
select next_identity('tablename') will return the identity value of the next insert for a table with an identity column so you know which ID will be allocated next.

Select @@identity immediately after an insert will return the ID which was just given to the row inserted.

However you need to be careful as identity columns are not the same as sequences and should not be relied upon if you want a sequence with no gaps because you will get a gap (albeit small sometimes) if the database crashes or is shutdown with nowait. For these a number fountain/insert trigger type generation of IDs is a better option. Using 'identity insert' is only really for when you want to bulk-load a whole table - you should not be setting that with every insert or you will defeat the whole purpose of an identity column, which is fast generation of new key values.


问:
pull apache beam from github compile error
I am new to Apache beam, I download latest source code from github and compile runner module under path :

../beam/runners

with command : mvn package and it prints the exception like this :
enter image description here

 Apache Beam :: Runners :: Core Construction Java ... FAILURE

Does anyone have some ideas with this ? thanks!

答:
@Balajee Venkatesh
Here are my compile steps:

cd beam-master

mvn compile

wait compile finish

The first time I execute mvn compile command and met the exception shown above was under path beam-master/runners. After I changing compiling path to beam-master everything goes well .

And may I ask are you trying to compile the whole project to load it to your IDE ?
If so , I  suggest using IDEA with 'File'->'import from existing source'  instead of executing 'mvn compile' command .

If you try to use IDEA import beam , you can just remove/comment error messages in ${project_loc:beam-parent/pom.xml}  like ：

```<code>  <!-- <plugin>
    <groupId>org.codehaus.mojo</groupId>
    <artifactId>versions-maven-plugin</artifactId>
    <version>2.3</version>
    <reportSets>
      <reportSet>
        <reports>
          <report>dependency-updates-report</report>
          <report>plugin-updates-report</report>
        </reports>
      </reportSet>
    </reportSets>
  </plugin>-->
</code>```

and, replace this maven plugins version the same as your mvn -version .

```<code>  <!-- Rename the artifact produced by the Apache parent's
         source release. -->
     <plugin>
      <groupId>org.apache.maven.plugins</groupId>
      <artifactId>maven-assembly-plugin</artifactId>
      <version>**3.3.3**</version>
      <executions>
        <execution>
          <id>source-release-assembly</id>
          <configuration>
            <finalName>apache-beam-${project.version}</finalName>
          </configuration>
        </execution>
      </executions>
    </plugin>
</code>```

By the way , my maven version is 3.3.3 . You can also check out if the pom.xml's  maven version incompatible with your local mvn -version .

Here is my mvn compile path :

enter image description here

Body:
@Balajee Venkatesh
Here are my compile steps:

cd beam-master

mvn compile

wait compile finish

The first time I execute mvn compile command and met the exception shown above was under path beam-master/runners. After I changing compiling path to beam-master everything goes well .

And may I ask are you trying to compile the whole project to load it to your IDE ?
If so , I  suggest using IDEA with 'File'->'import from existing source'  instead of executing 'mvn compile' command .

If you try to use IDEA import beam , you can just remove/comment error messages in ${project_loc:beam-parent/pom.xml}  like ：

  <!-- <plugin>
    <groupId>org.codehaus.mojo</groupId>
    <artifactId>versions-maven-plugin</artifactId>
    <version>2.3</version>
    <reportSets>
      <reportSet>
        <reports>
          <report>dependency-updates-report</report>
          <report>plugin-updates-report</report>
        </reports>
      </reportSet>
    </reportSets>
  </plugin>-->

and, replace this maven plugins version the same as your mvn -version .

  <!-- Rename the artifact produced by the Apache parent's
         source release. -->
     <plugin>
      <groupId>org.apache.maven.plugins</groupId>
      <artifactId>maven-assembly-plugin</artifactId>
      <version>**3.3.3**</version>
      <executions>
        <execution>
          <id>source-release-assembly</id>
          <configuration>
            <finalName>apache-beam-${project.version}</finalName>
          </configuration>
        </execution>
      </executions>
    </plugin>

By the way , my maven version is 3.3.3 . You can also check out if the pom.xml's  maven version incompatible with your local mvn -version .

Here is my mvn compile path :

enter image description here


问:
ES6 Map key to be either string or number
I have a ES6 Map , where keys are number. Some time the key is number and some time the key is string which represents a number. The map will never have duplicate key at runtime for me. Example I will never have key "1" and 1 .

While retrieving from map I need a simple one liner code which will negate whether if the key is a string or a number.

```<code>var map = new Map();
undefined
map.set('1', 'string one');
map.set(2, 'number tow')
Map(2) {"1" => "string one", 2 => "number tow"}
map.get(1)
undefined
map.get('1')
"string one"
</code>```

答:
For starters, I would recommend that you will sanitize your keys (e.g use only strings or only numbers) and by this you will make your life easier.

If you still insist on using both type of keys you could create a wrapper function like this :

```<code>function getFromMap(map, key){
    var stringKey = key.toString();
    var integerKey = parseInt(key);
    return map.get(stringKey) || map.get(integerKey);
}
</code>```

As a side note :
It seems that in your case you could easily use an ordinary object (Using brackets for object assignment will automatically convert the numbers to strings) :

```<code>var o = {};
o[1] = 'First value';
console.log(o[1] === o['1']); // true
</code>```

For furthor reading about the advantages/disadvantages of using Map vs Objects you are invited to read the following SA question .

Body:
I have a ES6 Map , where keys are number. Some time the key is number and some time the key is string which represents a number. The map will never have duplicate key at runtime for me. Example I will never have key "1" and 1 .

While retrieving from map I need a simple one liner code which will negate whether if the key is a string or a number.

var map = new Map();
undefined
map.set('1', 'string one');
map.set(2, 'number tow')
Map(2) {"1" => "string one", 2 => "number tow"}
map.get(1)
undefined
map.get('1')
"string one"

Body:
For starters, I would recommend that you will sanitize your keys (e.g use only strings or only numbers) and by this you will make your life easier.

If you still insist on using both type of keys you could create a wrapper function like this :

function getFromMap(map, key){
    var stringKey = key.toString();
    var integerKey = parseInt(key);
    return map.get(stringKey) || map.get(integerKey);
}

As a side note :
It seems that in your case you could easily use an ordinary object (Using brackets for object assignment will automatically convert the numbers to strings) :

var o = {};
o[1] = 'First value';
console.log(o[1] === o['1']); // true

For furthor reading about the advantages/disadvantages of using Map vs Objects you are invited to read the following SA question .


问:
Pascal results window
I have written a programme which merges two 1D arrays containing names. I print the list of arr1, arr2 and arr3.

I am using Lazarus Free Pascal v. 1.0.14 . I was wondering if anyone knows how to break the results in the dos-like window because the list is so long that I can only see the last few names in the returned results. The rest go by too fast to read.

I know I can save the resuls to file and I also use the delay command, but would like to know if there is a way to somehow break the results or slow them down or even edit the output console?

I appreciate your help.

答:
You can change the code of your loop in the following way:

say you print the results by the followng loop:

```<code>for i:=0 to 250 do
  WriteLn(ArrUnited[i]);
</code>```

you can replace it with:

```<code>for i:=0 to 250 do
  begin
    WriteLn(ArrUnited[i]);
    if (i mod 25) = 24 then //the code will wait for the user pressing Enter every 25 rows
      ReadLn;
  end;
</code>```

For the future please! post MCVE in your questions otherwise everyone has to guess what your code is.

Title: Pascal results window

Body:
You can change the code of your loop in the following way:

say you print the results by the followng loop:

for i:=0 to 250 do
  WriteLn(ArrUnited[i]);

you can replace it with:

for i:=0 to 250 do
  begin
    WriteLn(ArrUnited[i]);
    if (i mod 25) = 24 then //the code will wait for the user pressing Enter every 25 rows
      ReadLn;
  end;

For the future please! post MCVE in your questions otherwise everyone has to guess what your code is.


问:
Can I write a select function run on different db tables in lambda or Entityframework
I am new to EntityFramework and want to know If it is possible to write a Select statement works on different table. As following.

```<code>public IList<ent_customer> getCustomer()
{
    return db.Customers.Select(a=>new ent_Customers{
         first_name=a.first_name,
         last_name=a.last_Name
    }).ToList();
}
public IList<ent_vendors> getVendors()
{
    return db.Vendors.Select(a=>new ent_vendors{
         first_name=a.first_name,
         last_name=a.last_Name,
         mobile=a.mobile,
         email=a.email
    }).ToList();
}
</code>```

Before I was using one Select,Insert,Update,Delete function for all tables and avoided rewriting of same code in normal 3 tier project.

I tried a lot and google, unfortunately not found any suggestion

Update

Before in general 3tier One SQLEngine Class maintain SQL Queries and Dynamically generates Select,Delete,Edit etc.
If I have a class dal_Product and I need to get product list then Only I was calling

```<code>objProduct.Select();// All Productions
objCustomer.Select();//All Customer No need to write two different queries
obj

on above examle .. SQLEngine were automatically generate two queries
 1- "select *from Product"
 2- "Select *from Customer"

So I was avoiding rewriting for similar queries and functions.
</code>```

Hop know you people understand that I want SQLEngine type of central queries generator based on condition.

Thanks and Advance

答:
Not sure what exactly you mean by "works on different table", but let me suggest:

1. Use Repository Pattern as @Jordy van Eijk suggest.

2. Use .Include() / .Load() if you need to work on different but related tables  Link

Body:
I am new to EntityFramework and want to know If it is possible to write a Select statement works on different table. As following.

public IList<ent_customer> getCustomer()
{
    return db.Customers.Select(a=>new ent_Customers{
         first_name=a.first_name,
         last_name=a.last_Name
    }).ToList();
}
public IList<ent_vendors> getVendors()
{
    return db.Vendors.Select(a=>new ent_vendors{
         first_name=a.first_name,
         last_name=a.last_Name,
         mobile=a.mobile,
         email=a.email
    }).ToList();
}

Before I was using one Select,Insert,Update,Delete function for all tables and avoided rewriting of same code in normal 3 tier project.

I tried a lot and google, unfortunately not found any suggestion

Update

Before in general 3tier One SQLEngine Class maintain SQL Queries and Dynamically generates Select,Delete,Edit etc.
If I have a class dal_Product and I need to get product list then Only I was calling

objProduct.Select();// All Productions
objCustomer.Select();//All Customer No need to write two different queries
obj

on above examle .. SQLEngine were automatically generate two queries
 1- "select *from Product"
 2- "Select *from Customer"

So I was avoiding rewriting for similar queries and functions.

Hop know you people understand that I want SQLEngine type of central queries generator based on condition.

Thanks and Advance


问:
MS SQL combine selects into one, char separator string
Hey all this is my query here:

```<code>SELECT
    uT.employeeID + '|' + uT.lastFirstMiddle + '|' + uT.ntName + '|' +
    uT.email + '|' + uT.firstName + '|' + uT.lastName + '|' + uT.active,
    (
        SELECT
            ',' + uP.type
        FROM
            usersPermissions AS uP
        WHERE
            ',' + uT.userPerms + ','
        LIKE
            '%,' + cast(uP.id AS nvarchar(20)) + ',%'
        FOR
            XML PATH(''), TYPE
    ).value('substring(text()[1], 2)', 'varchar(max)') AS userPerms,
    (
        SELECT
            ',' + uP.name
        FROM
            pagePermissions AS uP
        WHERE
            ',' + uT.userPerms + ','
        LIKE
            '%,' + cast(uP.id AS nvarchar(20)) + ',%'
        FOR
            XML PATH(''), TYPE
    ).value('substring(text()[1], 2)', 'varchar(max)') AS userPermPages
FROM
    usersTbl as uT
WHERE
    uT.id = '1';
</code>```

And what I am looking to do is combine all those into just one output.

So instead of this:

```<code>(No Column Name)                                                       |userPerms         |userPermsPages
-----------------------------------------------------------------------+------------------+-----------------------------
R98T92C48|Barker, Bob|bbarker|bbarker@priceisright.com|Bob|Barker|true |Read,Upload,Admin |ANP Index,BOM import,BOM line
</code>```

I would like something more along the lines of this:

```<code>(No Column Name)
-----------------------------------------------------------------------------------------------------------------------
R98T92C48|Barker, Bob|bbarker|bbarker@priceisright.com|Bob|Barker|true|Read|Upload|Admin|ANP Index|BOM import|BOM line
</code>```

So how would the query look in order to output it like the above example?

答:
Have you tried to wrap that query in a CTE or Derived table and select from it</p>

```<code>SELECT X.firstCol + X.userPerms + X.userPermPages
FROM
(
    SELECT
        uT.employeeID + '|' + uT.lastFirstMiddle + '|' + uT.ntName + '|' +
        uT.email + '|' + uT.firstName + '|' + uT.lastName + '|' + uT.active AS firstCol,
        (
            SELECT
                ',' + uP.type
            FROM
                usersPermissions AS uP
            WHERE
                ',' + uT.userPerms + ','
            LIKE
                '%,' + cast(uP.id AS nvarchar(20)) + ',%'
            FOR
                XML PATH(''), TYPE
        ).value('substring(text()[1], 2)', 'varchar(max)') AS userPerms,
        (
            SELECT
                ',' + uP.name
            FROM
                pagePermissions AS uP
            WHERE
                ',' + uT.userPerms + ','
            LIKE
                '%,' + cast(uP.id AS nvarchar(20)) + ',%'
            FOR
                XML PATH(''), TYPE
        ).value('substring(text()[1], 2)', 'varchar(max)') AS userPermPages
    FROM
        usersTbl as uT
    WHERE
        uT.id = '1'
) X ;
</code>```

Body:
Hey all this is my query here:

SELECT
    uT.employeeID + '|' + uT.lastFirstMiddle + '|' + uT.ntName + '|' +
    uT.email + '|' + uT.firstName + '|' + uT.lastName + '|' + uT.active,
    (
        SELECT
            ',' + uP.type
        FROM
            usersPermissions AS uP
        WHERE
            ',' + uT.userPerms + ','
        LIKE
            '%,' + cast(uP.id AS nvarchar(20)) + ',%'
        FOR
            XML PATH(''), TYPE
    ).value('substring(text()[1], 2)', 'varchar(max)') AS userPerms,
    (
        SELECT
            ',' + uP.name
        FROM
            pagePermissions AS uP
        WHERE
            ',' + uT.userPerms + ','
        LIKE
            '%,' + cast(uP.id AS nvarchar(20)) + ',%'
        FOR
            XML PATH(''), TYPE
    ).value('substring(text()[1], 2)', 'varchar(max)') AS userPermPages
FROM
    usersTbl as uT
WHERE
    uT.id = '1';

And what I am looking to do is combine all those into just one output.

So instead of this:

(No Column Name)                                                       |userPerms         |userPermsPages
-----------------------------------------------------------------------+------------------+-----------------------------
R98T92C48|Barker, Bob|bbarker|bbarker@priceisright.com|Bob|Barker|true |Read,Upload,Admin |ANP Index,BOM import,BOM line

I would like something more along the lines of this:

(No Column Name)
-----------------------------------------------------------------------------------------------------------------------
R98T92C48|Barker, Bob|bbarker|bbarker@priceisright.com|Bob|Barker|true|Read|Upload|Admin|ANP Index|BOM import|BOM line

So how would the query look in order to output it like the above example?

Body:
Have you tried to wrap that query in a CTE or Derived table and select from it

SELECT X.firstCol + X.userPerms + X.userPermPages
FROM
(
    SELECT
        uT.employeeID + '|' + uT.lastFirstMiddle + '|' + uT.ntName + '|' +
        uT.email + '|' + uT.firstName + '|' + uT.lastName + '|' + uT.active AS firstCol,
        (
            SELECT
                ',' + uP.type
            FROM
                usersPermissions AS uP
            WHERE
                ',' + uT.userPerms + ','
            LIKE
                '%,' + cast(uP.id AS nvarchar(20)) + ',%'
            FOR
                XML PATH(''), TYPE
        ).value('substring(text()[1], 2)', 'varchar(max)') AS userPerms,
        (
            SELECT
                ',' + uP.name
            FROM
                pagePermissions AS uP
            WHERE
                ',' + uT.userPerms + ','
            LIKE
                '%,' + cast(uP.id AS nvarchar(20)) + ',%'
            FOR
                XML PATH(''), TYPE
        ).value('substring(text()[1], 2)', 'varchar(max)') AS userPermPages
    FROM
        usersTbl as uT
    WHERE
        uT.id = '1'
) X ;


问:
jQuery slider value save
I have an input and jQuery slider next to it.

```<code><div id="slider_value_1" class="slider"></div> <input type="text" name="value_1" value="<?php echo get_option('value_1'); ?>" />
</code>```

The slider settings are:

```<code> $(".slider").slider({
        slide: function(event, ui) {
            $(this).next().val(ui.value);
        }
    });

 $("#slider_value_1").slider({ min: 1, max: 2000, step: 100  });
</code>```

So when I move the slider to the very right - it shows 2000 in the input next to it and when I move the slider to the left - it shows 1.

The problem is I'm saving my form and it saves input's value perfectly but I want to save slider's position also? How to do that?

I guess:

```<code><div id="slider_value_1" class="slider" value="<?php echo get_option('value_1'); ?>"></div>
</code>```

Won't work?

答:
Given that your input has the correct value, perhaps you can put something like the following in your slider init</p>

```<code>$("#slider_value_1").slider({ min: 1, max: 2000, step: 100, value: $("input[name='value_1']").val() });
</code>```

ContentLicense: CC BY-SA 2.5

Title: jQuery slider value save

Body:
I have an input and jQuery slider next to it.

 <input type="text" name="value_1" value="<?php echo get_option('value_1'); ?>" />

The slider settings are:

 $(".slider").slider({
        slide: function(event, ui) {
            $(this).next().val(ui.value);
        }
    });

 $("#slider_value_1").slider({ min: 1, max: 2000, step: 100  });

So when I move the slider to the very right - it shows 2000 in the input next to it and when I move the slider to the left - it shows 1.

The problem is I'm saving my form and it saves input's value perfectly but I want to save slider's position also? How to do that?

I guess:

<div id="slider_value_1" class="slider" value="<?php echo get_option('value_1'); ?>">

Won't work?

Body:
Given that your input has the correct value, perhaps you can put something like the following in your slider init

$("#slider_value_1").slider({ min: 1, max: 2000, step: 100, value: $("input[name='value_1']").val() });


问:
error:Connection reset (Gradle sync failed: Connection reset)
I am importing constraint-layout-start to android studio 3.0. I have kept in androidstudioproject folder that's the the path where all my android studio projects are stored. after importing its showing connection reset error. Here is the log file link: https://drive.google.com/file/d/1W1mGmIc67baZb4C5nGGecWm15ggB0Wp5/view?usp=sharing

i have all the SDK installed. tried to manually change the sdk verion to 21 which was running perfectly for my other projects, but here it didn't work.

i checked all the files are okay, i am not getting why this error occurs.
images of gradle page are given below.

build.gradle

gradle

答:
For Android studio 3.0.0

required Gradle version: 4.1

File > Project Structure > Project

required Build Tools 26.0.2


问:
Why am I getting this syntax error: keyword can't be an expression
```<code>def multiply():
    number_1 = int (input ("Please insert the first number for multiplication:"))
    number_2 = int (input ("Please insert the second number for multiplication:"))
    result = str (number_1*number_2)
    return print (number_1*number_2=result)
multiply()
</code>```

I am getting the Following error when trying to execute the following function.

```<code>    return print (number_1*number_2=result)
                 ^
SyntaxError: keyword can't be an expression
</code>```

答:
Why am I getting this syntax error: keyword can't be an expression

Because what you write in parentheses after a function name (including print in python3) are arguments of the function. Any argument written in the form keyword=value is a keyword argument. You cannot use an expression (here a product) as a keyword.

Body:
def multiply():
    number_1 = int (input ("Please insert the first number for multiplication:"))
    number_2 = int (input ("Please insert the second number for multiplication:"))
    result = str (number_1*number_2)
    return print (number_1*number_2=result)
multiply()

I am getting the Following error when trying to execute the following function.

    return print (number_1*number_2=result)
                 ^
SyntaxError: keyword can't be an expression


答:
You are defining a keyword argument by using =:

```<code>...(number_1*number_2=result)
                     ^
</code>```

That makes everything before the = a Python expression, namely number_1 * number_2. Python doesn't allow this.

If you wanted to print out a nicely formatted expression, you'll have to use separate string arguments:

```<code>print(number_1, '*', number_2, '=', result)
</code>```

Python writes out separate arguments with a space to separate them (but you can use sep='...' to set a different string to separate them, including the empty string to have no separation at all).

Note that you don't actually have to convert result to a string here, the print() function converts all arguments to strings before writing them to the console.

You could also learn about Python string formatting, which gives you a bit more control over the whitespace handling, as well as alignment end value formatting, for example.

The following would print out your numbers and the result as part of a format string with the same amount of spaces:

```<code>print('{} * {} = {}'.format(number_1, number_2, result))
</code>```

Each {} placeholder is then filled with the next argument you passed into the str.format() method. You can remove the spaces here too if you wanted to.

Last, but not least, the print() function always returns None. You don't have to return that from your function, remove the return. Your actual use of the multiply function doesn't use the returned value anyway:

```<code>def multiply():
    number_1 = int(input("Please insert the first number for multiplication:"))
    number_2 = int(input("Please insert the second number for multiplication:"))
    result = number_1 * number_2
    print(number_1, '*', number_2, '=', result)

multiply()
</code>```

Title: Why am I getting this syntax error: keyword can't be an expression

Body:
You are defining a keyword argument by using =:

...(number_1*number_2=result)
                     ^

That makes everything before the = a Python expression, namely number_1 * number_2. Python doesn't allow this.

If you wanted to print out a nicely formatted expression, you'll have to use separate string arguments:

print(number_1, '*', number_2, '=', result)

Python writes out separate arguments with a space to separate them (but you can use sep='...' to set a different string to separate them, including the empty string to have no separation at all).

Note that you don't actually have to convert result to a string here, the print() function converts all arguments to strings before writing them to the console.

You could also learn about Python string formatting, which gives you a bit more control over the whitespace handling, as well as alignment end value formatting, for example.

The following would print out your numbers and the result as part of a format string with the same amount of spaces:

print('{} * {} = {}'.format(number_1, number_2, result))

Each {} placeholder is then filled with the next argument you passed into the str.format() method. You can remove the spaces here too if you wanted to.

Last, but not least, the print() function always returns None. You don't have to return that from your function, remove the return. Your actual use of the multiply function doesn't use the returned value anyway:

def multiply():
    number_1 = int(input("Please insert the first number for multiplication:"))
    number_2 = int(input("Please insert the second number for multiplication:"))
    result = number_1 * number_2
    print(number_1, '*', number_2, '=', result)

multiply()


问:
scp a bunch of files via bash script: there must be a better way
I currently have the following bash script:

```<code>for a in `seq 16 75`;
do scp doneill@server:/mnt/device/folder/numbered_file$a.txt ./;
done;
</code>```

while this does work, it is very slow.  Each file, the request to the sever takes about 4-7 seconds, then sending the file takes another 3 or so seconds.

Is there a way to do this that involves only 1 command sent to the server (to minimize the time my VPN spends sending receiving each individual command)?  Normally, I would do something like scp doneill@server:/mnt/device/folder/numbered_file* but there are many thousands of files in the folder that I don't want to copy.  I need to get only those few (defined by the sequence).

答:
rsync should do the trick: http://www.manpagez.com/man/1/rsync/

You may have to fiddle a bit with the parameters, but done right, it's probably the fastest way of transferring files over ssh.

Body:
I currently have the following bash script:

for a in `seq 16 75`;
do scp doneill@server:/mnt/device/folder/numbered_file$a.txt ./;
done;

while this does work, it is very slow.  Each file, the request to the sever takes about 4-7 seconds, then sending the file takes another 3 or so seconds.

Is there a way to do this that involves only 1 command sent to the server (to minimize the time my VPN spends sending receiving each individual command)?  Normally, I would do something like scp doneill@server:/mnt/device/folder/numbered_file* but there are many thousands of files in the folder that I don't want to copy.  I need to get only those few (defined by the sequence).


问:
Spring, Java - run many scheduled-tasks in parallel
I try to run many scheduled-tasks in parallel with scheduler, but only one starts.
my beans configuration in spring-scheduler.xml</p>

```<code><?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:p="http://www.springframework.org/schema/p"
    xmlns:task="http://www.springframework.org/schema/task"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
            http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
            http://www.springframework.org/schema/task
            http://www.springframework.org/schema/task/spring-task-3.2.xsd">

    <task:executor id="executor" pool-size="5"/>
    <task:scheduler id="scheduler" pool-size="10"/>

    <bean id="UpdateScheduler" class="org.ws.scheduled.UpdateScheduler" />
    <bean id="PatchData" class="org.ws.scheduled.PatchData" />

    <task:scheduled-tasks>
        <task:scheduled ref="UpdateScheduler" method="start" fixed-delay="1000" />
        <task:scheduled ref="PatchData" method="start" fixed-delay="5000" />
    </task:scheduled-tasks>

    <task:annotation-driven scheduler="scheduler" executor="executor" />

</beans>
</code>```

答:
Thank you all !
I started to use with this config and it's working fine from here https://docs.spring.io/spring/docs/current/spring-framework-reference/integration.html#scheduling-task-namespace-scheduled-tasks

```<code><task:scheduled-tasks scheduler="myScheduler">
    <task:scheduled ref="beanA" method="methodA" fixed-delay="5000" initial-delay="1000"/>
    <task:scheduled ref="beanB" method="methodB" fixed-rate="5000"/>
    <task:scheduled ref="beanC" method="methodC" cron="*/5 * * * * MON-FRI"/>
</code>```

Body:
I try to run many scheduled-tasks in parallel with scheduler, but only one starts.
my beans configuration in spring-scheduler.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:p="http://www.springframework.org/schema/p"
    xmlns:task="http://www.springframework.org/schema/task"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
            http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
            http://www.springframework.org/schema/task
            http://www.springframework.org/schema/task/spring-task-3.2.xsd">

    <task:executor id="executor" pool-size="5"/>
    <task:scheduler id="scheduler" pool-size="10"/>

    <bean id="UpdateScheduler" class="org.ws.scheduled.UpdateScheduler" />
    <bean id="PatchData" class="org.ws.scheduled.PatchData" />

    <task:scheduled-tasks>
        <task:scheduled ref="UpdateScheduler" method="start" fixed-delay="1000" />
        <task:scheduled ref="PatchData" method="start" fixed-delay="5000" />
    </task:scheduled-tasks>

    <task:annotation-driven scheduler="scheduler" executor="executor" />

</beans>

Body:
Thank you all !
I started to use with this config and it's working fine from here https://docs.spring.io/spring/docs/current/spring-framework-reference/integration.html#scheduling-task-namespace-scheduled-tasks

<task:scheduled-tasks scheduler="myScheduler">
    <task:scheduled ref="beanA" method="methodA" fixed-delay="5000" initial-delay="1000"/>
    <task:scheduled ref="beanB" method="methodB" fixed-rate="5000"/>
    <task:scheduled ref="beanC" method="methodC" cron="*/5 * * * * MON-FRI"/>


答:
I assume you want output like

```<code>number_1*number2 = 6
</code>```

The first part of this is some fixed text you want printed. Thus you need to put in in a string and print that. You can print multiple things like print(a, b). This should be enough for you to figure out

Body:
I assume you want output like

number_1*number2 = 6

The first part of this is some fixed text you want printed. Thus you need to put in in a string and print that. You can print multiple things like print(a, b). This should be enough for you to figure out


问:
Java 8 example for if else with Optional
I have a method which returns Optional. Basically, it gets value from DB and if the value from DB is present and if the value is before 20 years, it returns currentDate-20 years or else return as it is.

```<code>Optional<Instant> getJoinDate(final Instant instant) {

        final Optional<Employee> joinTime = empService.retrieveById(1);

        if (joinTime.isPresent()) {

            final Instant joinDate = joinTime.get().getJoinTime().toInstant();

            if (joinDate.isBefore(instant.minus(20,ChronoUnit.YEARS))) {
                return Optional.of(instant.minus(20, ChronoUnit.YEARS));
            }
            else {
                return Optional.of(joinDate);
            }
        }

        return Optional.empty();
    }
</code>```

Is there any simple way to do this with Java 8 without if else?

Thanks

答:
You can use flatMap:

```<code>Optional<Instant> getJoinDate(final Instant instant) {
    final Optional<Employee> joinTime = empService.retrieveById(1);
    return joinTime.flatMap (emp -> {
        final Instant joinDate = emp.getJoinTime().toInstant();
        if (joinDate.isBefore(instant.minus(20,ChronoUnit.YEARS))) {
            return Optional.of(instant.minus(20, ChronoUnit.YEARS));
        }
        else {
            return Optional.of(joinDate);
        }
    });
}
</code>```

of course you can replace the inner if-else with ternary conditional expression:

```<code>Optional<Instant> getJoinDate(final Instant instant) {
    final Optional<Employee> joinTime = empService.retrieveById(1);
    return joinTime.flatMap (emp -> {
        final Instant joinDate = emp.getJoinTime().toInstant();
        return joinDate.isBefore(instant.minus(20,ChronoUnit.YEARS)) ?
            Optional.of(instant.minus(20, ChronoUnit.YEARS)) :
            Optional.of(joinDate);
    });
}
</code>```

or even shorter:

```<code>Optional<Instant> getJoinDate(final Instant instant) {
    return empService.retrieveById(1).flatMap (emp ->
            emp.getJoinTime().toInstant().isBefore(instant.minus(20,ChronoUnit.YEARS)) ?
            Optional.of(instant.minus(20, ChronoUnit.YEARS)) :
            Optional.of(emp.getJoinTime().toInstant()));
}
</code>```

However, this has the disadvantage of calling emp.getJoinTime().toInstant() twice.

Body:
I have a method which returns Optional. Basically, it gets value from DB and if the value from DB is present and if the value is before 20 years, it returns currentDate-20 years or else return as it is.

Optional<Instant> getJoinDate(final Instant instant) {

        final Optional<Employee> joinTime = empService.retrieveById(1);

        if (joinTime.isPresent()) {

            final Instant joinDate = joinTime.get().getJoinTime().toInstant();

            if (joinDate.isBefore(instant.minus(20,ChronoUnit.YEARS))) {
                return Optional.of(instant.minus(20, ChronoUnit.YEARS));
            }
            else {
                return Optional.of(joinDate);
            }
        }

        return Optional.empty();
    }

Is there any simple way to do this with Java 8 without if else?

Thanks

Body:
You can use flatMap:

Optional<Instant> getJoinDate(final Instant instant) {
    final Optional<Employee> joinTime = empService.retrieveById(1);
    return joinTime.flatMap (emp -> {
        final Instant joinDate = emp.getJoinTime().toInstant();
        if (joinDate.isBefore(instant.minus(20,ChronoUnit.YEARS))) {
            return Optional.of(instant.minus(20, ChronoUnit.YEARS));
        }
        else {
            return Optional.of(joinDate);
        }
    });
}

of course you can replace the inner if-else with ternary conditional expression:

Optional<Instant> getJoinDate(final Instant instant) {
    final Optional<Employee> joinTime = empService.retrieveById(1);
    return joinTime.flatMap (emp -> {
        final Instant joinDate = emp.getJoinTime().toInstant();
        return joinDate.isBefore(instant.minus(20,ChronoUnit.YEARS)) ?
            Optional.of(instant.minus(20, ChronoUnit.YEARS)) :
            Optional.of(joinDate);
    });
}

or even shorter:

Optional<Instant> getJoinDate(final Instant instant) {
    return empService.retrieveById(1).flatMap (emp ->
            emp.getJoinTime().toInstant().isBefore(instant.minus(20,ChronoUnit.YEARS)) ?
            Optional.of(instant.minus(20, ChronoUnit.YEARS)) :
            Optional.of(emp.getJoinTime().toInstant()));
}

However, this has the disadvantage of calling emp.getJoinTime().toInstant() twice.


问:
Grep Two Dimensional Array
Since this is not a question directly covered here, thought best I ask and answer it.

I had an issue where I wanted to add a node name to a list only if the same node doesn't already exist. The array was built using:

```<code>push (@fin_nodes, [$node, $hindex, $e->{$hip}->{FREQ}]);
</code>```

So given when given array (@fin_nodes) that looks like:

```<code>$VAR1 = [
      'first-node',
      '4',
      3
    ];
$VAR2 = [
      'second-node',
      '1',
      3
    ];
$VAR3 = [
      'another-node',
      '1',
      5
    ];
$VAR4 = [
      'some-node',
      '0',
      5
    ];
</code>```

To do a grep on this the following works:

```<code>my @match = grep { grep { $_ =~ $node } @$_ } @fin_nodes;
</code>```

So given a $node "second-node" the above statement will return @match as:

```<code>$VAR1 = [
  'second-node',
  '1',
  3
];
</code>```

答:
I would say "don't" and instead:

```<code>my %fin_nodes;
$fin_nodes{$node} = [$hindex, $e->{$hip}->{FREQ}]);
</code>```

And then you can simply if ($fin_nodes{$node}) {

Failing that though - you don't need to grep every element, as your node name is always first.

So:

```<code> my @matches = grep { $_ -> [0] eq $node } @fin_nodes;
</code>```

eq is probably a better choice than =~ here, because the latter will substring match. (And worse, can potentially do some quite unexpected things if you've metacharacters in there, since you're not quoting or escaping them)

E.g. in your example - if you look for a node called "node" you'll get multiple hits.

Note - if you're only looking for one match, you can do something like:

```<code>my ( $first_match ) =  grep { $_ -> [0] eq $node } @fin_nodes;
</code>```

This will just get you the first result, and the rest will be discarded. (Which isn't too efficient, because grep will continue to iterate the whole list).

Title: Grep Two Dimensional Array

Body:
Since this is not a question directly covered here, thought best I ask and answer it.

I had an issue where I wanted to add a node name to a list only if the same node doesn't already exist. The array was built using:

push (@fin_nodes, [$node, $hindex, $e->{$hip}->{FREQ}]);

So given when given array (@fin_nodes) that looks like:

$VAR1 = [
      'first-node',
      '4',
      3
    ];
$VAR2 = [
      'second-node',
      '1',
      3
    ];
$VAR3 = [
      'another-node',
      '1',
      5
    ];
$VAR4 = [
      'some-node',
      '0',
      5
    ];

To do a grep on this the following works:

my @match = grep { grep { $_ =~ $node } @$_ } @fin_nodes;

So given a $node "second-node" the above statement will return @match as:

$VAR1 = [
  'second-node',
  '1',
  3
];

Body:
I would say "don't" and instead:

my %fin_nodes;
$fin_nodes{$node} = [$hindex, $e->{$hip}->{FREQ}]);

And then you can simply if ($fin_nodes{$node}) {

Failing that though - you don't need to grep every element, as your node name is always first.

So:

 my @matches = grep { $_ -> [0] eq $node } @fin_nodes;

eq is probably a better choice than =~ here, because the latter will substring match. (And worse, can potentially do some quite unexpected things if you've metacharacters in there, since you're not quoting or escaping them)

E.g. in your example - if you look for a node called "node" you'll get multiple hits.

Note - if you're only looking for one match, you can do something like:

my ( $first_match ) =  grep { $_ -> [0] eq $node } @fin_nodes;

This will just get you the first result, and the rest will be discarded. (Which isn't too efficient, because grep will continue to iterate the whole list).


问:
java Object copying,Array index out of bound
I have a class "schedule".

```<code>public class schedule {
    public int P;
    public int K;
    Vector<Vector<element>> r;

    public schedule(int p, int k) {
    this.P = p;
    this.K = k;
    r = new Vector<Vector<element>>(5 * P);
    for (int i = 0; i < 5 * p; i++) {
        Vector<element> v = new Vector<element>();
        r.add(v);
    }
}

schedule(schedule s){
    P = s.P;
    K = s.K;
    r = s.r;
}

public ArrayList<schedule> getSuccessors() {
    ArrayList<schedule> routine;
    routine = new ArrayList<schedule>();
    schedule temp= new schedule(this);

    for (int i = 0; i < r.size(); i++) {
        for (int j = 0; j < r.get(i).size(); j++) {
            for (int k = 1; k < r.size(); k++) {
                //System.out.println(r.elementAt(i).size());
                //System.out.println(r.elementAt(j).size());
                //System.out.println("credit "+ r.elementAt(i).elementAt(j).credit);
                if (!r.elementAt(k).contains(r.elementAt(i).elementAt(j))) {
                    temp.r = r;
                    temp.r.elementAt(k).add(r.elementAt(i).elementAt(j));
                    temp.r.get(i).remove(j);
                }
            }
        }
        routine.add(temp);
    }
    return routine;
}
}
</code>```

Whenever  the code is executed i get java.lang.ArrayIndexOutOfBoundsException: 0 >= 0 error message at getSuccessors() method.Any help is greatly welcome.

答:
You are removing elements of the arrays while doing the loop. That is always a bad idea, since your contract of the index being valid might not hold anymore after you removed the element.

If you want to remove elements while iterating, you should use Iterator and its remove() method. And if you're inside a nested collection and you're removing an elements from the external collection while you're in the internal collection, delay it until after you've finished the external loop (either by using break or by setting a toRemove flag and then deleting the element after you're done with the internal loop).

Body:
I have a class "schedule".

public class schedule {
    public int P;
    public int K;
    Vector<Vector<element>> r;

    public schedule(int p, int k) {
    this.P = p;
    this.K = k;
    r = new Vector<Vector<element>>(5 * P);
    for (int i = 0; i < 5 * p; i++) {
        Vector<element> v = new Vector<element>();
        r.add(v);
    }
}

schedule(schedule s){
    P = s.P;
    K = s.K;
    r = s.r;
}

public ArrayList<schedule> getSuccessors() {
    ArrayList<schedule> routine;
    routine = new ArrayList<schedule>();
    schedule temp= new schedule(this);

    for (int i = 0; i < r.size(); i++) {
        for (int j = 0; j < r.get(i).size(); j++) {
            for (int k = 1; k < r.size(); k++) {
                //System.out.println(r.elementAt(i).size());
                //System.out.println(r.elementAt(j).size());
                //System.out.println("credit "+ r.elementAt(i).elementAt(j).credit);
                if (!r.elementAt(k).contains(r.elementAt(i).elementAt(j))) {
                    temp.r = r;
                    temp.r.elementAt(k).add(r.elementAt(i).elementAt(j));
                    temp.r.get(i).remove(j);
                }
            }
        }
        routine.add(temp);
    }
    return routine;
}
}

Whenever  the code is executed i get java.lang.ArrayIndexOutOfBoundsException: 0 >= 0 error message at getSuccessors() method.Any help is greatly welcome.


问:
redirect to error on exceeding fileupload size
I am trying to direct user to a error page when maximum fileupload size excedds.For this iam doing the following thing:

```<code>public void Init(HttpApplication application)
    {
        application.BeginRequest += new EventHandler(application_BeginRequest);
    }

    void application_BeginRequest(object sender, EventArgs e)
    {
        HttpApplication application = (HttpApplication)sender;
        HttpContext context = application.Context;
        if (context.Request.ContentLength > 4096000)
        {
            context.Response.Redirect("~/Error.aspx");
        }
    }
    public void Dispose()
    {
    }
</code>```

But on uploading file with size more than the max filesize it is showing "connection reset" error.
How should i do this.

答: Use Transfer.Redirect()</p>

Body:
I am trying to direct user to a error page when maximum fileupload size excedds.For this iam doing the following thing:

public void Init(HttpApplication application)
    {
        application.BeginRequest += new EventHandler(application_BeginRequest);
    }

    void application_BeginRequest(object sender, EventArgs e)
    {
        HttpApplication application = (HttpApplication)sender;
        HttpContext context = application.Context;
        if (context.Request.ContentLength > 4096000)
        {
            context.Response.Redirect("~/Error.aspx");
        }
    }
    public void Dispose()
    {
    }

But on uploading file with size more than the max filesize it is showing "connection reset" error.
How should i do this.

Body: Use Transfer.Redirect()


问:
What we have to check when upgrate jboss server version
I want to upgrade jboss server version from 4.2.0 to 4.2.3. What i need to look or see documents to do the upgradation? Please give me points i need to consider, documents to verify to upgrade any server version?
This information will be useful to upgrate any version? Currenlty i am doing for 4.2.0 to 4.2.3?

Thank you for your time.

答:
Hm, seems that upgrading from 4.2.0 to 4.2.3 you can manage without any reading... The difference between these servers are just bugs fixed.

This is the 3rd bug fixing release of the JBoss Application Server v4.2 series.

well, just deploy there your application, change configuration (the way you did for 4.2.0, if you did), and it should work.

Added: you will need to study some wikis, articles, APIs when you are going to migrate to JBoss 5.x or 6.x - it will take some time (I managed migrating from 4.2.3 to 6.0 for 1 week). Starting from 5.x they changed architecture of server a bit, folders where you put libraries (actually it was improved), there are deprecated APIs (e.g. in Hibernate), so you need to change API you use etc. But not in your current case, 4.2.0 -> 4.2.3 = that's easy :)