问:
Pandas - Selecting all columns but one in DataFrame while setting dtype
I want to do something using Pandas that seems to be quite difficult. I hope I'm wrong

I want to open a csv-file, set the dtype of every column as int with the exception of one column that I would like to drop.
I do not now the names and/or the number of columns present in advance.
The non-int column is always present at the same position, every other column consits only of intergers.

data:

```<code>foo.csv:
a   b       c   d   e   f  g ...
1   700592  a   23 ... ... ...
2   808295  b   24 ... ...
3   106796  c   25 ...
4   166438  d   26 ...
5   172594  e   27 ...
</code>```

what I would like to do:

```<code>df = pd.read_csv(foo.csv, usecols=[0,1,3, ...], dtype=int)
</code>```

I could read the complete file, drop the non-int column, and change the type globally but the data may be very large so speed and memory are to be considered.

答:
Before passing to pandas use np.loadtxt():

import numpy as np
f = np.loadtxt("foo.csv", usecols=[0,1,2,4], dtype="int32")
pd.DataFrame(f)

https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.loadtxt.html

Body:
I want to do something using Pandas that seems to be quite difficult. I hope I'm wrong

I want to open a csv-file, set the dtype of every column as int with the exception of one column that I would like to drop.
I do not now the names and/or the number of columns present in advance.
The non-int column is always present at the same position, every other column consits only of intergers.

data:

foo.csv:
a   b       c   d   e   f  g ...
1   700592  a   23 ... ... ...
2   808295  b   24 ... ...
3   106796  c   25 ...
4   166438  d   26 ...
5   172594  e   27 ...

what I would like to do:

df = pd.read_csv(foo.csv, usecols=[0,1,3, ...], dtype=int)

I could read the complete file, drop the non-int column, and change the type globally but the data may be very large so speed and memory are to be considered.


来源: stackexchange

问:
Row item of recycle view in Constraint layout collapse instead taking parent width
Recently, I started using Constraint layout but today encountered very strange behaviour using it. When I am using RelativeLayout as root instead of ConstraintLayout in fragment_holiday.xml output is as expected but I want to know what is wrong with ConstraintLayout. My code is as follows for fragment,item_row

And I am getting output with constraint layout as(And on scrolling it is showing different beheviour as you can see in screenshot I am sharing) ---

fragment_holiday.xml

```<code>    <android.support.constraint.ConstraintLayout 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"
    tools:context="com.thepsi.psidashboard.Fragments.HolidayFragment">

    <com.thepsi.psidashboard.CustomViews.CustomDatePicker
        android:id="@+id/customDatePicker_holiday"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:dateFormat="MONTH_YEAR"/>

    <android.support.v7.widget.RecyclerView
        android:id="@+id/recycle_view_holiday"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginTop="@dimen/general_margin_eight_dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/customDatePicker_holiday" />
</android.support.constraint.ConstraintLayout>
</code>```

item_holiday.xml

```<code>    <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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="wrap_content">

    <TextView
        android:id="@+id/textView25"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:text="24 - January - 2017"
        android:textColor="@color/colorPrimaryDark"
         />

    <TextView
        android:id="@+id/textView26"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginEnd="8dp"
        android:text="Saturday"
        android:layout_alignParentEnd="true"
        android:textColor="@color/colorPrimaryDark"
        />

    <TextView
        android:id="@+id/textView27"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@color/colorAccent"
        android:text="Mahavir Jayanti"
        android:textAlignment="center"
        android:textColor="@android:color/black"
        android:layout_below="@+id/textView25"
        />
</RelativeLayout>
</code>```

Expected Design -

Can someone tell me what I am missing here?

答:
Try following.</p>

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <TextView
        android:id="@+id/textView25"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:text="24 - January - 2017"
        android:textColor="@color/colorPrimaryDark"
        app:layout_constraintEnd_toStartOf="@+id/textView26"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <TextView
        android:id="@+id/textView26"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginEnd="8dp"
        android:gravity="right"
        android:text="Saturday"
        android:textColor="@color/colorPrimaryDark"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintLeft_toRightOf="@+id/textView25"
        app:layout_constraintTop_toTopOf="@+id/textView25" />

    <TextView
        android:id="@+id/textView27"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:background="@color/colorAccent"
        android:text="Mahavir Jayanti"
        android:textAlignment="center"
        android:textColor="@android:color/black"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textView25" />
</android.support.constraint.ConstraintLayout>
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Recently, I started using Constraint layout but today encountered very strange behaviour using it. When I am using RelativeLayout as root instead of ConstraintLayout in fragment_holiday.xml output is as expected but I want to know what is wrong with ConstraintLayout. My code is as follows for fragment,item_row

And I am getting output with constraint layout as(And on scrolling it is showing different beheviour as you can see in screenshot I am sharing) ---

fragment_holiday.xml

    <android.support.constraint.ConstraintLayout 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"
    tools:context="com.thepsi.psidashboard.Fragments.HolidayFragment">

    <com.thepsi.psidashboard.CustomViews.CustomDatePicker
        android:id="@+id/customDatePicker_holiday"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:dateFormat="MONTH_YEAR"/>

    <android.support.v7.widget.RecyclerView
        android:id="@+id/recycle_view_holiday"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginTop="@dimen/general_margin_eight_dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/customDatePicker_holiday" />
</android.support.constraint.ConstraintLayout>

item_holiday.xml

    <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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="wrap_content">

    <TextView
        android:id="@+id/textView25"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:text="24 - January - 2017"
        android:textColor="@color/colorPrimaryDark"
         />

    <TextView
        android:id="@+id/textView26"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginEnd="8dp"
        android:text="Saturday"
        android:layout_alignParentEnd="true"
        android:textColor="@color/colorPrimaryDark"
        />

    <TextView
        android:id="@+id/textView27"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@color/colorAccent"
        android:text="Mahavir Jayanti"
        android:textAlignment="center"
        android:textColor="@android:color/black"
        android:layout_below="@+id/textView25"
        />
</RelativeLayout>

Expected Design -

Can someone tell me what I am missing here?

Body:
Try following.

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <TextView
        android:id="@+id/textView25"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:text="24 - January - 2017"
        android:textColor="@color/colorPrimaryDark"
        app:layout_constraintEnd_toStartOf="@+id/textView26"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <TextView
        android:id="@+id/textView26"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginEnd="8dp"
        android:gravity="right"
        android:text="Saturday"
        android:textColor="@color/colorPrimaryDark"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintLeft_toRightOf="@+id/textView25"
        app:layout_constraintTop_toTopOf="@+id/textView25" />

    <TextView
        android:id="@+id/textView27"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:background="@color/colorAccent"
        android:text="Mahavir Jayanti"
        android:textAlignment="center"
        android:textColor="@android:color/black"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textView25" />
</android.support.constraint.ConstraintLayout>


问:
Execute method and webmethod async in webform
In my website login page, there is a section to showing news.in document.ready of this page, I call a webmethod by ajax request to show these news but it need some seconds to execute completely. Meanwhile if user click on login button, login process keep in waiting until news load completely, but I want to run login process async, there is any solution to solve this problem?
note that I add async in my function like this:

```<code>$(document).ready(async function () ...
</code>```

but news doesnt load any more.

答:
you can make async request for news as below </p>

```<code>  jQuery.ajax({
        url: 'http://example.com/',
        success: function (result) {
            if (result.isOk == false) alert(result.message);
        },
        async: true
    });
</code>```

Body:
In my website login page, there is a section to showing news.in document.ready of this page, I call a webmethod by ajax request to show these news but it need some seconds to execute completely. Meanwhile if user click on login button, login process keep in waiting until news load completely, but I want to run login process async, there is any solution to solve this problem?
note that I add async in my function like this:

$(document).ready(async function () ...

but news doesnt load any more.

Body:
you can make async request for news as below

  jQuery.ajax({
        url: 'http://example.com/',
        success: function (result) {
            if (result.isOk == false) alert(result.message);
        },
        async: true
    });


问:
TYPO3 8.7 - why is my typeNum page empty?
I have been stuck on this for about a day now. I recently upgraded from 7.6 to 8.7, and my Ajax feature no longer works. The problem: the page that I generate to host my plugin for the Ajax call is empty (always).

Here is the code that I use to generate the page:

```<code>ajaxselectlist_page = PAGE
ajaxselectlist_page {
    typeNum = 427590

    config {
        disableAllHeaderCode = 1
        additionalHeaders = Content-type:application/html
        xhtml_cleaning = 0
        debug = 0
        no_cache = 1
        admPanel = 0
    }

    10 < tt_content.list.20.extension_controller
}
</code>```

I have tested it, and the problem seems to be with the plugin generation, as I have no problem generating generic text on the page.

I did manage to get it working very briefly using the following code instead, though even this returned empty as soon as I made my first Ajax call.

```<code>10 = USER
10 {
    userFunc = TYPO3\CMS\Extbase\Core\Bootstrap->getInstance
    vendorName = HarryLaForge
    extensionName = Inventory
    pluginName = Item
    controller = Item
}
</code>```

One other point of information: when I updated to 8.7 I also removed the boostrap_package from my installation in lieu of simply creating my own templates. I don't think that this should have caused the problem, but I thought I would mention it none-the-less.

Thanks a million!

答:
As of TYPO3 8.x additionalHeaders is an array:</p>

```<code>additionalHeaders {
    10 {
        header = Content-Type: application/html
        replace = 1
    }
}
</code>```

Body:
I have been stuck on this for about a day now. I recently upgraded from 7.6 to 8.7, and my Ajax feature no longer works. The problem: the page that I generate to host my plugin for the Ajax call is empty (always).

Here is the code that I use to generate the page:

ajaxselectlist_page = PAGE
ajaxselectlist_page {
    typeNum = 427590

    config {
        disableAllHeaderCode = 1
        additionalHeaders = Content-type:application/html
        xhtml_cleaning = 0
        debug = 0
        no_cache = 1
        admPanel = 0
    }

    10 < tt_content.list.20.extension_controller
}

I have tested it, and the problem seems to be with the plugin generation, as I have no problem generating generic text on the page.

I did manage to get it working very briefly using the following code instead, though even this returned empty as soon as I made my first Ajax call.

10 = USER
10 {
    userFunc = TYPO3\CMS\Extbase\Core\Bootstrap->getInstance
    vendorName = HarryLaForge
    extensionName = Inventory
    pluginName = Item
    controller = Item
}

One other point of information: when I updated to 8.7 I also removed the boostrap_package from my installation in lieu of simply creating my own templates. I don't think that this should have caused the problem, but I thought I would mention it none-the-less.

Thanks a million!

Body:
As of TYPO3 8.x additionalHeaders is an array:

additionalHeaders {
    10 {
        header = Content-Type: application/html
        replace = 1
    }
}


问:
Bundle not working with rbenv
I'm trying to use bundler with rbenv. I has been working until today. The only thing I may have done to break it was gem pristine --all or gem cleanup ? When trying to install bundler i get the following error.

```<code>Antarrs-MacBook-Pro:some-app antarrbyrd$ sudo gem install bundler
Password:
Bundler gave the error "Could not find mail-2.5.4 in any of the sources" while processing "/Users/antarrbyrd/dev/some-app/Gemfile". Perhaps you forgot to run "bundle install"?
Successfully installed bundler-1.7.12
Parsing documentation for bundler-1.7.12
Done installing documentation for bundler after 3 seconds
1 gem installed
Antarrs-MacBook-Pro:some-app antarrbyrd$ bundle install
/Users/antarrbyrd/.rbenv/versions/2.1.2/lib/ruby/site_ruby/2.1.0/rubygems/dependency.rb:315:in `to_specs': Could not find 'bundler' (>= 0) among 8 total gem(s) (Gem::LoadError)
Checked in 'GEM_PATH=/Users/antarrbyrd/.gem', execute `gem env` for more information
    from /Users/antarrbyrd/.rbenv/versions/2.1.2/lib/ruby/site_ruby/2.1.0/rubygems/dependency.rb:324:in `to_spec'
    from /Users/antarrbyrd/.rbenv/versions/2.1.2/lib/ruby/site_ruby/2.1.0/rubygems/core_ext/kernel_gem.rb:64:in `gem'
    from /usr/local/bin/bundle:22:in `<main>'
</code>```

when i do rbenv rehash or rbenv bundler on it get this error

```<code>Bundler gave the error "Could not find mail-2.5.4 in any of the sources" while processing "/Users/antarrbyrd/dev/some-app/Gemfile". Perhaps you forgot to run "bundle install"?
</code>```

~/.bash_profile

```<code>export BUNDLER_EDITOR=atom
export PATH=$PATH:/usr/local/opt/android-sdk/build-tools/21.1.2
export HOMEBREW_GITHUB_API_TOKEN=...

export ANDROID_HOME=/usr/local/opt/android-sdk
export PATH="$HOME/.rbenv/bin:$PATH"
if which rbenv > /dev/null; then eval "$(rbenv init -)"; fi

# Allow local Gem Managment
# export GEM_HOME="$HOME/.gem"
# export GEM_PATH="$HOME/.gem"
# export PATH="$HOME/.gem/bin:$PATH"
</code>```

gem env

```<code>RubyGems Environment:
  - RUBYGEMS VERSION: 2.2.2
  - RUBY VERSION: 2.1.2 (2014-05-08 patchlevel 95) [x86_64-darwin14.0]
  - INSTALLATION DIRECTORY: /usr/local/var/rbenv/versions/2.1.2/lib/ruby/gems/2.1.0
  - RUBY EXECUTABLE: /usr/local/var/rbenv/versions/2.1.2/bin/ruby
  - EXECUTABLE DIRECTORY: /usr/local/var/rbenv/versions/2.1.2/bin
  - SPEC CACHE DIRECTORY: /Users/antarrbyrd/.gem/specs
  - RUBYGEMS PLATFORMS:
    - ruby
    - x86_64-darwin-14
  - GEM PATHS:
     - /usr/local/var/rbenv/versions/2.1.2/lib/ruby/gems/2.1.0
     - /Users/antarrbyrd/.gem/ruby/2.1.0
  - GEM CONFIGURATION:
     - :update_sources => true
     - :verbose => false
     - :backtrace => false
     - :bulk_threshold => 1000
     - "gem" => "-n/usr/local/bin"
  - REMOTE SOURCES:
     - https://rubygems.org/
  - SHELL PATH:
     - /usr/local/var/rbenv/versions/2.1.2/bin
     - /usr/local/Cellar/rbenv/0.4.0/libexec
     - /Users/antarrbyrd/.gem/bin
     - /usr/local/var/rbenv/shims
     - /usr/local/bin
     - /usr/bin
     - /bin
     - /usr/sbin
     - /sbin
     - /usr/local/var/rbenv/shims
     - /Users/antarrbyrd/.rbenv/bin
     - /Users/antarrbyrd/.rbenv/shims
     - /Users/antarrbyrd/.gem/bin
     - /usr/local/opt/android-sdk/build-tools/21.1.2
</code>```

update

I reinstalled rbenv via brew and now I get the following error when running bundle install.

```<code>The `bundle' command exists in these Ruby versions:
  2.1.5
</code>```

response to Joel

```<code>Antarrs-MacBook-Pro:myapp antarrbyrd$ command -v ruby
/usr/local/var/rbenv/shims/ruby
Antarrs-MacBook-Pro:myapp antarrbyrd$ command -v bundle
/usr/local/bin/bundle
Antarrs-MacBook-Pro:myapp antarrbyrd$ ruby -v
ruby 2.1.2p95 (2014-05-08 revision 45877) [x86_64-darwin14.0]
Antarrs-MacBook-Pro:myapp antarrbyrd$ bundle -v
Bundler version 1.7.12
Antarrs-MacBook-Pro:myapp antarrbyrd$
</code>```

答:
Try setting ruby globally</p>

```<code>rbenv global 2.3.1
</code>```

Title: Bundle not working with rbenv

Body:
I'm trying to use bundler with rbenv. I has been working until today. The only thing I may have done to break it was gem pristine --all or gem cleanup ? When trying to install bundler i get the following error.

Antarrs-MacBook-Pro:some-app antarrbyrd$ sudo gem install bundler
Password:
Bundler gave the error "Could not find mail-2.5.4 in any of the sources" while processing "/Users/antarrbyrd/dev/some-app/Gemfile". Perhaps you forgot to run "bundle install"?
Successfully installed bundler-1.7.12
Parsing documentation for bundler-1.7.12
Done installing documentation for bundler after 3 seconds
1 gem installed
Antarrs-MacBook-Pro:some-app antarrbyrd$ bundle install
/Users/antarrbyrd/.rbenv/versions/2.1.2/lib/ruby/site_ruby/2.1.0/rubygems/dependency.rb:315:in `to_specs': Could not find 'bundler' (>= 0) among 8 total gem(s) (Gem::LoadError)
Checked in 'GEM_PATH=/Users/antarrbyrd/.gem', execute `gem env` for more information
    from /Users/antarrbyrd/.rbenv/versions/2.1.2/lib/ruby/site_ruby/2.1.0/rubygems/dependency.rb:324:in `to_spec'
    from /Users/antarrbyrd/.rbenv/versions/2.1.2/lib/ruby/site_ruby/2.1.0/rubygems/core_ext/kernel_gem.rb:64:in `gem'
    from /usr/local/bin/bundle:22:in `'

when i do rbenv rehash or rbenv bundler on it get this error

Bundler gave the error "Could not find mail-2.5.4 in any of the sources" while processing "/Users/antarrbyrd/dev/some-app/Gemfile". Perhaps you forgot to run "bundle install"?

~/.bash_profile

export BUNDLER_EDITOR=atom
export PATH=$PATH:/usr/local/opt/android-sdk/build-tools/21.1.2
export HOMEBREW_GITHUB_API_TOKEN=...

export ANDROID_HOME=/usr/local/opt/android-sdk
export PATH="$HOME/.rbenv/bin:$PATH"
if which rbenv > /dev/null; then eval "$(rbenv init -)"; fi

# Allow local Gem Managment
# export GEM_HOME="$HOME/.gem"
# export GEM_PATH="$HOME/.gem"
# export PATH="$HOME/.gem/bin:$PATH"

gem env

RubyGems Environment:
  - RUBYGEMS VERSION: 2.2.2
  - RUBY VERSION: 2.1.2 (2014-05-08 patchlevel 95) [x86_64-darwin14.0]
  - INSTALLATION DIRECTORY: /usr/local/var/rbenv/versions/2.1.2/lib/ruby/gems/2.1.0
  - RUBY EXECUTABLE: /usr/local/var/rbenv/versions/2.1.2/bin/ruby
  - EXECUTABLE DIRECTORY: /usr/local/var/rbenv/versions/2.1.2/bin
  - SPEC CACHE DIRECTORY: /Users/antarrbyrd/.gem/specs
  - RUBYGEMS PLATFORMS:
    - ruby
    - x86_64-darwin-14
  - GEM PATHS:
     - /usr/local/var/rbenv/versions/2.1.2/lib/ruby/gems/2.1.0
     - /Users/antarrbyrd/.gem/ruby/2.1.0
  - GEM CONFIGURATION:
     - :update_sources => true
     - :verbose => false
     - :backtrace => false
     - :bulk_threshold => 1000
     - "gem" => "-n/usr/local/bin"
  - REMOTE SOURCES:
     - https://rubygems.org/
  - SHELL PATH:
     - /usr/local/var/rbenv/versions/2.1.2/bin
     - /usr/local/Cellar/rbenv/0.4.0/libexec
     - /Users/antarrbyrd/.gem/bin
     - /usr/local/var/rbenv/shims
     - /usr/local/bin
     - /usr/bin
     - /bin
     - /usr/sbin
     - /sbin
     - /usr/local/var/rbenv/shims
     - /Users/antarrbyrd/.rbenv/bin
     - /Users/antarrbyrd/.rbenv/shims
     - /Users/antarrbyrd/.gem/bin
     - /usr/local/opt/android-sdk/build-tools/21.1.2

update

I reinstalled rbenv via brew and now I get the following error when running bundle install.

The `bundle' command exists in these Ruby versions:
  2.1.5

response to Joel

Antarrs-MacBook-Pro:myapp antarrbyrd$ command -v ruby
/usr/local/var/rbenv/shims/ruby
Antarrs-MacBook-Pro:myapp antarrbyrd$ command -v bundle
/usr/local/bin/bundle
Antarrs-MacBook-Pro:myapp antarrbyrd$ ruby -v
ruby 2.1.2p95 (2014-05-08 revision 45877) [x86_64-darwin14.0]
Antarrs-MacBook-Pro:myapp antarrbyrd$ bundle -v
Bundler version 1.7.12
Antarrs-MacBook-Pro:myapp antarrbyrd$

Body:
Try setting ruby globally

rbenv global 2.3.1


问:
AWS Snowball GC overhead limit exceeded
I'm trying to send 5TB of data to S3 through AWS' snowball service.

I've received the snowball, and have connected to it through the snowball client okay. However, when I call the snowball cp command to copy files from the local server onto the snowball I hit issues. The cp command starts out fine but quickly chokes, followed by an error:

```<code>in thread "nioEventLoopGroup-2-45" Exception in thread "nioEventLoopGroup-2-12" Exception in thread "main" java.lang.OutOfMemoryError: GC overhead limit exceeded
</code>```

I'm connecting to the snowball on a linux machine and running the following command

```<code>bash snowball cp -r - f -l /path/to/the/archive/on/the/server s3://jobname/directory
</code>```

Thanks in advance.

答: An intensive background Java program was interfering with the transfer. After the program finished the cp command started working without throwing errors. </p>

Title: AWS Snowball GC overhead limit exceeded

Body:
I'm trying to send 5TB of data to S3 through AWS' snowball service.

I've received the snowball, and have connected to it through the snowball client okay. However, when I call the snowball cp command to copy files from the local server onto the snowball I hit issues. The cp command starts out fine but quickly chokes, followed by an error:

in thread "nioEventLoopGroup-2-45" Exception in thread "nioEventLoopGroup-2-12" Exception in thread "main" java.lang.OutOfMemoryError: GC overhead limit exceeded

I'm connecting to the snowball on a linux machine and running the following command

bash snowball cp -r - f -l /path/to/the/archive/on/the/server s3://jobname/directory

Thanks in advance.


问:
Django JQuery Autocomplete
I am trying to add an autocomplete field to my form. But I can't get t to work. I have tried almost every tutorial.
The request is sent out fine,I'm gettin a 200 response. In the developer tools pane when I click the request ,on the Response tab I see the whole HTML file. Shouldn't there be a json formated something..??
Here's the code:

models.py

```<code>class Signers(models.Model):
    uid = models.IntegerField(primary_key=True)
    firstName = models.CharField(max_length=255)
    lastName = models.CharField(max_length=255)
</code>```

views.py

```<code>def get_signers(request):
  if request.is_ajax():
    q = request.GET.get('term', '')
    signers = Signers.objects.filter(uid__icontains=q)[:20]
    results = []
    for s in signers:
      signer_json = {}
      signer_json['id'] = s.uid
      signer_json['label'] = s.uid
      signer_json['value'] = s.uid
      results.append(signer_json)
    data = json.dumps(results)
    print data
  else:
    data = 'fail'
  mimetype = 'application/json'
  return HttpResponse(data,mimetype)
</code>```

urls.py

```<code>url(r'^get_signers/', views.get_signers, name='get_signers'),
</code>```

praxis.html (my template)

```<code><script>

  $(function() {
    $("#id_signerIds").autocomplete({
      source: "get_signers/",
      minLength: 2,
    });
  });

</script>

<script>
$(document).ready(function() {

              $('#id_submissionTimestamp').hide();
              $('#id_issueDate').hide();
});
</script>

{% endblock page_head %}

{% block content %}

<form method="POST" class="post-form">{% csrf_token %}

<!--some other fields here... -->

<div class="ui-widget">
  <label for="id_signerIds">Signers: </label>
  <input id="id_signerIds">
</div>

<button type="submit" class="save btn btn-default">Save</button>

 </form>

{% endblock %}
</code>```

答:
First of all as you are using Django i suggest you type the urls by name, like this if you change an url of a view you will not need to change it everywhere in the comments so instead of source: "get_signers/", you can do source: "{% url 'get_signers' %}",.

Now returning to the question i suggest you change the code to:

```<code>signers = Signers.objects.filter(uid__icontains=q)[:20]
results = []
for signer in signers:
    signer_json = signer.name
    results.append(signer_json)
</code>```

To provide my working case i will give you my code:

views.py

```<code>def company_autocomplete(request):
    if request.is_ajax():
        query = request.GET.get("term", "")
        companies = Company.objects.filter(name__icontains=query)
        results = []
        for company in companies:
            place_json = company.name
            results.append(place_json)
        data = json.dumps(results)
    mimetype = "application/json"
    return HttpResponse(data, mimetype)
</code>```

urls.py

```<code>url(r'^api/company-autocomplete/', company_autocomplete, name='company-autocomplete'),
</code>```

add_company.html

```<code>...
<div class="form-group bmd-form-group">
  <label class="bmd-label-static"
         for="company_autocomplete_input">Cerca azienda</label>
  <input id="company_autocomplete_input" class="form-control"
         placeholder="Nome azienda" style="width:500px">
</div>
...
<button class="btn btn-raised btn-primary" type="submit"
        style="background-color:#1A88B9;">Aggiungi</button>
<script>
  $(function() {
    $("#company_autocomplete_input").autocomplete({
      source: "{% url 'company-autocomplete' %}",
      minLength: 1,
    });
  });
</script>
...
</code>```

And the most important thing:
be sure to add jQuery before of your autocomplete input

```<code><!-- jQuery !-->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"> </script>
<!-- jQuery UI !-->
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script>
</code>```

Title: Django JQuery Autocomplete

Body:
I am trying to add an autocomplete field to my form. But I can't get t to work. I have tried almost every tutorial.
The request is sent out fine,I'm gettin a 200 response. In the developer tools pane when I click the request ,on the Response tab I see the whole HTML file. Shouldn't there be a json formated something..??
Here's the code:

models.py

class Signers(models.Model):
    uid = models.IntegerField(primary_key=True)
    firstName = models.CharField(max_length=255)
    lastName = models.CharField(max_length=255)

views.py

def get_signers(request):
  if request.is_ajax():
    q = request.GET.get('term', '')
    signers = Signers.objects.filter(uid__icontains=q)[:20]
    results = []
    for s in signers:
      signer_json = {}
      signer_json['id'] = s.uid
      signer_json['label'] = s.uid
      signer_json['value'] = s.uid
      results.append(signer_json)
    data = json.dumps(results)
    print data
  else:
    data = 'fail'
  mimetype = 'application/json'
  return HttpResponse(data,mimetype)

urls.py

url(r'^get_signers/', views.get_signers, name='get_signers'),

praxis.html (my template)

{% endblock page_head %}

{% block content %}

<form method="POST" class="post-form">{% csrf_token %}

  Signers:
  <input id="id_signerIds">

<button type="submit" class="save btn btn-default">Save</button>

 </form>

{% endblock %}

Body:
First of all as you are using Django i suggest you type the urls by name, like this if you change an url of a view you will not need to change it everywhere in the comments so instead of source: "get_signers/", you can do source: "{% url 'get_signers' %}",.

Now returning to the question i suggest you change the code to:

signers = Signers.objects.filter(uid__icontains=q)[:20]
results = []
for signer in signers:
    signer_json = signer.name
    results.append(signer_json)

To provide my working case i will give you my code:

views.py

def company_autocomplete(request):
    if request.is_ajax():
        query = request.GET.get("term", "")
        companies = Company.objects.filter(name__icontains=query)
        results = []
        for company in companies:
            place_json = company.name
            results.append(place_json)
        data = json.dumps(results)
    mimetype = "application/json"
    return HttpResponse(data, mimetype)

urls.py

url(r'^api/company-autocomplete/', company_autocomplete, name='company-autocomplete'),

add_company.html

...
<div class="form-group bmd-form-group">
  <label class="bmd-label-static"
         for="company_autocomplete_input">Cerca azienda</label>
  <input id="company_autocomplete_input" class="form-control"
         placeholder="Nome azienda" style="width:500px">
</div>
...
<button class="btn btn-raised btn-primary" type="submit"
        style="background-color:#1A88B9;">Aggiungi</button>
<script>
  $(function() {
    $("#company_autocomplete_input").autocomplete({
      source: "{% url 'company-autocomplete' %}",
      minLength: 1,
    });
  });
</script>
...

And the most important thing:
be sure to add jQuery before of your autocomplete input

<!-- jQuery !-->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"> </script>
<!-- jQuery UI !-->
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script>


问:
Can't create two Types to same index elasticsearch & Kibana
I'm new in elasticsearch and kibana

I'm doing some exercices with elasticsearch (create index,types and documents..)

I created an index 'business' with type 'building'

```<code>put /business/building/217
{
  "adresse":"11 Pen Ave",
  "floors":5,
  "offices":7,
  "loc":{
    "lat":40.693479,
    "lon":-73.983854
  }
}
</code>```

it works funny but when I tried to create another type like this

```<code>put /business/employee/330
{
  "name":"Richard Bell",
  "title":"Senior Accountant",
  "salar_usd":115000.00,
  "hiredate":"Jan 19, 2013"
}
</code>```

then I got this error

```<code>{
  "error": {
    "root_cause": [
      {
        "type": "illegal_argument_exception",
        "reason": "Rejecting mapping update to [business] as the final mapping would have more than 1 type: [employee, building]"
      }
    ],
    "type": "illegal_argument_exception",
    "reason": "Rejecting mapping update to [business] as the final mapping would have more than 1 type: [employee, building]"
  },
  "status": 400
}
</code>```

答:
You're probably running Elasticsearch version 6 and as of that version ES doesn't allow you to create more than one type in any given index.

You need to store each of your document type inside a dedicated index, e.g.

```<code>PUT /business/building/217
{
  "adresse":"11 Pen Ave",
  "floors":5,
  "offices":7,
  "loc":{
    "lat":40.693479,
    "lon":-73.983854
  }
}

PUT /employees/employee/330
{
  "name":"Richard Bell",
  "title":"Senior Accountant",
  "salar_usd":115000.00,
  "hiredate":"Jan 19, 2013"
}
</code>```

Body:
I'm new in elasticsearch and kibana

I'm doing some exercices with elasticsearch (create index,types and documents..)

I created an index 'business' with type 'building'

put /business/building/217
{
  "adresse":"11 Pen Ave",
  "floors":5,
  "offices":7,
  "loc":{
    "lat":40.693479,
    "lon":-73.983854
  }
}

it works funny but when I tried to create another type like this

put /business/employee/330
{
  "name":"Richard Bell",
  "title":"Senior Accountant",
  "salar_usd":115000.00,
  "hiredate":"Jan 19, 2013"
}

then I got this error

{
  "error": {
    "root_cause": [
      {
        "type": "illegal_argument_exception",
        "reason": "Rejecting mapping update to [business] as the final mapping would have more than 1 type: [employee, building]"
      }
    ],
    "type": "illegal_argument_exception",
    "reason": "Rejecting mapping update to [business] as the final mapping would have more than 1 type: [employee, building]"
  },
  "status": 400
}

Body:
You're probably running Elasticsearch version 6 and as of that version ES doesn't allow you to create more than one type in any given index.

You need to store each of your document type inside a dedicated index, e.g.

PUT /business/building/217
{
  "adresse":"11 Pen Ave",
  "floors":5,
  "offices":7,
  "loc":{
    "lat":40.693479,
    "lon":-73.983854
  }
}

PUT /employees/employee/330
{
  "name":"Richard Bell",
  "title":"Senior Accountant",
  "salar_usd":115000.00,
  "hiredate":"Jan 19, 2013"
}


问:
Alter data in object of arrays
In a React app, I have this type of data:

```<code>const data = {
  open: [{
    id: 1,
    name: 'test 1'
  }, {
    id: 2,
    name: 'test 2'
  }],
  close: [{
    id: 3,
    name: 'test 3'
  }, {
    id: 4,
    name: 'test 4'
  }]
}
</code>```

I want to iterate over each object in the open and close arrays and return the existing data with additional type field. E.g.:

```<code>const data = {
  open: [{
    id: 1,
    name: 'test 1',
    type: 'alert'
  }, {...],
  close: [...]
}
</code>```

I'm trying something like this, but it returns undefined instead of the altered data:

```<code>const expandData = (data) => {
  return Object.keys(data).forEach((key) => {
    return data[key].map((item, idx) => ({
      ...item,
      type: 'alert'
    }))
  })
}

// call in another method
expandData(data) // the `data` above
</code>```

https://jsfiddle.net/x5aspec2/

答:
You just need to assign the new updated array from map to open and close properties instead of returning them.

Your whole code is correct and you need not change any method except that.

```<code>const expandData = (data) => {
  Object.keys(data).forEach((key) => {
    data[key] = data[key].map((item, idx) => ({
      ...item,
      type: 'alert'
    }))
  })
}

// call in another method
expandData(data);
console.log(data); //logs updated data
</code>```

If your data is immutable than you can return a new object instead of modifying the same data object.

```<code>const expandData = (data) => {
  var result = {};
  Object.keys(data).forEach((key) => {
    result[key] = data[key].map((item, idx) => ({
      ...item,
      type: 'alert'
    }))
  })
 return result;
}
expandData(data);
</code>```

Title: Alter data in object of arrays

Body:
In a React app, I have this type of data:

const data = {
  open: [{
    id: 1,
    name: 'test 1'
  }, {
    id: 2,
    name: 'test 2'
  }],
  close: [{
    id: 3,
    name: 'test 3'
  }, {
    id: 4,
    name: 'test 4'
  }]
}

I want to iterate over each object in the open and close arrays and return the existing data with additional type field. E.g.:

const data = {
  open: [{
    id: 1,
    name: 'test 1',
    type: 'alert'
  }, {...],
  close: [...]
}

I'm trying something like this, but it returns undefined instead of the altered data:

const expandData = (data) => {
  return Object.keys(data).forEach((key) => {
    return data[key].map((item, idx) => ({
      ...item,
      type: 'alert'
    }))
  })
}

// call in another method
expandData(data) // the `data` above

https://jsfiddle.net/x5aspec2/

Body:
You just need to assign the new updated array from map to open and close properties instead of returning them.

Your whole code is correct and you need not change any method except that.

const expandData = (data) => {
  Object.keys(data).forEach((key) => {
    data[key] = data[key].map((item, idx) => ({
      ...item,
      type: 'alert'
    }))
  })
}

// call in another method
expandData(data);
console.log(data); //logs updated data

If your data is immutable than you can return a new object instead of modifying the same data object.

const expandData = (data) => {
  var result = {};
  Object.keys(data).forEach((key) => {
    result[key] = data[key].map((item, idx) => ({
      ...item,
      type: 'alert'
    }))
  })
 return result;
}
expandData(data);


问:
JQuery not working for radio button
Group,

I have below code that isn't doing what I intend it to do. Not sure what am I missing. Can you please help? I would like an alert to flash as soon as radio button is clicked by the user. However, nothing is happening when the radio button is clicked.

```<code><HTML>
<head>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">

$('#amtopts input').on('change', function() {
   alert($('input[name=amount_r]:checked', '#amtopts').val());
});

var donateamt = document.getElementsByName('amount_r');
var donateamt_value;

function GetDonationAmt() {
    for(var i = 0; i < donateamt.length; i++){
        if(donateamt[i].checked){
            donateamt_value = donateamt[i].value;
            alert("Donation Amount is "+donameamt_value);
            break;
        }
    }
 }
 );
 </script>
 <body>
 <h1>Donate Now</h1>
 <p></p>
  Amount: Amount: <form id="amtopts"><input type="radio" id="amount_r" name="amount_r" value="50"> 50<input type="radio" id="amount_r" name="amount_r" value="75"> 75<input type="radio" id="amount_r" name="amount_r" value="100" > 100<input type="radio" id="amount_r" name="amount_r" value="150"> 150</form>

</body>
</html>
</code>```

答:
You Have to modify your script tag for j query API, you don't put your custom J query inside same script tag of j query API. see below code.

```<code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</code>```

And i minimize the code using of class instead of name/id please follow the code you will surely get the flash message.

HTML :

```<code>    <form id="amtopts">
  <input type="radio" id="amount_r" name="amount_r" class="amt" value="50"> 50
  <input type="radio" id="amount_r" name="amount_r" class="amt" value="75"> 75
  <input type="radio" id="amount_r" name="amount_r" class="amt" value="100" > 100
  <input type="radio" id="amount_r" name="amount_r" class="amt" value="150"> 150
  </form>
</code>```

J query :

```<code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<script>
 $(document).ready(function() {
    $('.amt').click(function() {
      alert($(this).val())
    })
 })
 </script>
</code>```

Title: JQuery not working for radio button

Body:
Group,

I have below code that isn't doing what I intend it to do. Not sure what am I missing. Can you please help? I would like an alert to flash as soon as radio button is clicked by the user. However, nothing is happening when the radio button is clicked.

Donate Now

  Amount: Amount: <form id="amtopts"><input type="radio" id="amount_r" name="amount_r" value="50"> 50<input type="radio" id="amount_r" name="amount_r" value="75"> 75<input type="radio" id="amount_r" name="amount_r" value="100" > 100<input type="radio" id="amount_r" name="amount_r" value="150"> 150</form>

Body:
You Have to modify your script tag for j query API, you don't put your custom J query inside same script tag of j query API. see below code.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

And i minimize the code using of class instead of name/id please follow the code you will surely get the flash message.

HTML :

    <form id="amtopts">
  <input type="radio" id="amount_r" name="amount_r" class="amt" value="50"> 50
  <input type="radio" id="amount_r" name="amount_r" class="amt" value="75"> 75
  <input type="radio" id="amount_r" name="amount_r" class="amt" value="100" > 100
  <input type="radio" id="amount_r" name="amount_r" class="amt" value="150"> 150
  </form>

J query :

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<script>
 $(document).ready(function() {
    $('.amt').click(function() {
      alert($(this).val())
    })
 })
 </script>


问:
Error:In <declare-styleable> ForegroundView, unable to find attribute foreground
I am the getting following errors while i execute paystack3.0.9 android code in android studio 3.

Error:In  ForegroundView, unable to find attribute foreground

Error:In  ForegroundView, unable to find attribute foregroundInsidePadding

Error:Execution failed for task ':paystack:processDebugResources'.
  com.android.ide.common.process.ProcessException: Failed to execute aapt

Application Gradle details:

```<code>buildscript {
    repositories {
        jcenter()
        maven {
            url 'https://maven.google.com/'
            name 'Google'
        }
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.2.0'
    }
}
</code>```

Module gradle details:

```<code>android {
    compileSdkVersion 26
    buildToolsVersion "26.0.3"
    aaptOptions {
        useNewCruncher false
    }

......

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    android {
        useLibrary 'org.apache.http.legacy'
    }

    compile 'com.flurry.android:analytics:6.3.1'
    compile 'com.braintreepayments.api:braintree:1.+'
    compile 'com.squareup.picasso:picasso:2.5.2'
    compile 'com.squareup.retrofit:retrofit:1.9.0'
    compile 'com.squareup.okhttp:okhttp:2.0.0'
    compile 'com.kbeanie:image-chooser-library:1.4.4@aar'
    compile 'com.sothree.slidinguppanel:library:3.1.1'
    compile 'com.google.code.gson:gson:2.5'
    compile 'co.paystack.android:paystack:3.0.9'
    compile 'com.android.support:support-v4:26.1.0'
    compile 'com.google.android.gms:play-services:7.0.0'
    compile 'com.android.support:appcompat-v7:26.1.0'
    compile 'com.android.support:design:26.1.0'
    compile 'com.facebook.android:facebook-android-sdk:3.19.0'
    compile 'com.android.support:multidex:1.0.0'
}
</code>```

}

After adding "compile 'co.paystack.android:paystack:3.0.9'", i am getting the above mentioned error. Please help me to fix this issue.

Thanks

答: I think this issue has been addressed on the issues page of that repo: https://github.com/PaystackHQ/paystack-android/issues/33</p>

Body:
I am the getting following errors while i execute paystack3.0.9 android code in android studio 3.

Error:In  ForegroundView, unable to find attribute foreground

Error:In  ForegroundView, unable to find attribute foregroundInsidePadding

Error:Execution failed for task ':paystack:processDebugResources'.
  com.android.ide.common.process.ProcessException: Failed to execute aapt

Application Gradle details:

buildscript {
    repositories {
        jcenter()
        maven {
            url 'https://maven.google.com/'
            name 'Google'
        }
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.2.0'
    }
}

Module gradle details:

android {
    compileSdkVersion 26
    buildToolsVersion "26.0.3"
    aaptOptions {
        useNewCruncher false
    }

......

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    android {
        useLibrary 'org.apache.http.legacy'
    }

    compile 'com.flurry.android:analytics:6.3.1'
    compile 'com.braintreepayments.api:braintree:1.+'
    compile 'com.squareup.picasso:picasso:2.5.2'
    compile 'com.squareup.retrofit:retrofit:1.9.0'
    compile 'com.squareup.okhttp:okhttp:2.0.0'
    compile 'com.kbeanie:image-chooser-library:1.4.4@aar'
    compile 'com.sothree.slidinguppanel:library:3.1.1'
    compile 'com.google.code.gson:gson:2.5'
    compile 'co.paystack.android:paystack:3.0.9'
    compile 'com.android.support:support-v4:26.1.0'
    compile 'com.google.android.gms:play-services:7.0.0'
    compile 'com.android.support:appcompat-v7:26.1.0'
    compile 'com.android.support:design:26.1.0'
    compile 'com.facebook.android:facebook-android-sdk:3.19.0'
    compile 'com.android.support:multidex:1.0.0'
}

}

After adding "compile 'co.paystack.android:paystack:3.0.9'", i am getting the above mentioned error. Please help me to fix this issue.

Thanks


问:
Kernel selection using yocto
I am building images for i.MX board using Yocto. My requirement is to build specific kernel for the board.

After downloading from Freescale Yocto repository site, I could see recipes for multiple kernels.

Can you guide me to understand how yocto will decide which kernel to build. I mean where Yocto configured to build specific kernel out of the available kernel recipes?

答:
Go to your meta-layer/conf/machine then open your selected-machine.conf file in and there you will find the macro variable

PREFERRED_PROVIDER_virtual/kernel

```<code>PREFERRED_VERSION_<bb_layer_name> ?= "<version>"
</code>```

the meta-layer developers written the default kernel & version here. If.

ContentLicense: CC BY-SA 4.0

Title: Kernel selection using yocto

Body:
Go to your meta-layer/conf/machine then open your selected-machine.conf file in and there you will find the macro variable

PREFERRED_PROVIDER_virtual/kernel

PREFERRED_VERSION_<bb_layer_name> ?= "<version>"

the meta-layer developers written the default kernel & version here. If.


问:
How to Do Growing Table / List

JS

```<code>var model = new JSONModel();
model.setData(data);
this.getView().byId("Table").setModel(model);
var table = this.getView().byId("Table");
table.bindItems({
    path: "/",
    template: new sap.m.ColumnListItem({
        cells: [
            new sap.m.Image({
                src: "{photo}"
            }),
            new sap.m.Text({
                text: "{name}"
            })
        ]
    })
});
</code>```

Here I have few data. Using above code I can list in table. Now I want to list only first 10 items in table and rest of the data will show after scroll down only. After scroll down mouse I need to call a function to get next 10 datas. How we can call a function after scroll down in sapUi5;

答: You need to set property growing to true. And also set property growingThreshold to 10.</p>

Title: How to Do Growing Table / List

Body:
JS

var model = new JSONModel();
model.setData(data);
this.getView().byId("Table").setModel(model);
var table = this.getView().byId("Table");
table.bindItems({
    path: "/",
    template: new sap.m.ColumnListItem({
        cells: [
            new sap.m.Image({
                src: "{photo}"
            }),
            new sap.m.Text({
                text: "{name}"
            })
        ]
    })
});

Here I have few data. Using above code I can list in table. Now I want to list only first 10 items in table and rest of the data will show after scroll down only. After scroll down mouse I need to call a function to get next 10 datas. How we can call a function after scroll down in sapUi5;


问:
Ansible - is it possible to register multiple variable?
I have a python script which is returning / print two lists.

test.py

```<code>def getHosts():
        Pool1=[x.x.x.x, x.x.x.x]
        Pool2=[x.x.x.x, x.x.x.x]
        Print pool1,pool2
        Return pool1,pool2

getHosts()
</code>```

My playbook looks like:

```<code>     -task:
      name: get the hosts
      command: /test.py
      register: result
</code>```

Now, is it possible to fetch out the pool1 and pool2 seperately from the registered variable result ? If yes, please show me an example.

Any help or suggestions will be highly appreciated.

答:
Produce JSON and feed it to Ansible. It will automatically create an appropriate data structure:

```<code>---
- hosts: localhost
  gather_facts: no
  connection: local
  tasks:
    - command: 'echo { \"Pool1\": \"[x.x.x.x, x.x.x.x]\", \"Pool2\": \"[x.x.x.x, x.x.x.x]\" }'
      register: my_output
    - set_fact:
        my_variable: "{{ my_output.stdout | from_json }}"
    - debug:
        msg: "Pool1 is {{ my_variable.Pool1 }} and Pool2 is {{ my_variable.Pool2 }}"
</code>```

Result:

```<code>ok: [localhost] => {
    "msg": "Pool1 is [x.x.x.x, x.x.x.x] and Pool2 is [x.x.x.x, x.x.x.x]"
}
</code>```

Depending on how you later use the variable, you might/might not need to from_json filter (see this).

Body:
I have a python script which is returning / print two lists.

test.py

def getHosts():
        Pool1=[x.x.x.x, x.x.x.x]
        Pool2=[x.x.x.x, x.x.x.x]
        Print pool1,pool2
        Return pool1,pool2

getHosts()

My playbook looks like:

     -task:
      name: get the hosts
      command: /test.py
      register: result

Now, is it possible to fetch out the pool1 and pool2 seperately from the registered variable result ? If yes, please show me an example.

Any help or suggestions will be highly appreciated.

Body:
Produce JSON and feed it to Ansible. It will automatically create an appropriate data structure:

---
- hosts: localhost
  gather_facts: no
  connection: local
  tasks:
    - command: 'echo { \"Pool1\": \"[x.x.x.x, x.x.x.x]\", \"Pool2\": \"[x.x.x.x, x.x.x.x]\" }'
      register: my_output
    - set_fact:
        my_variable: "{{ my_output.stdout | from_json }}"
    - debug:
        msg: "Pool1 is {{ my_variable.Pool1 }} and Pool2 is {{ my_variable.Pool2 }}"

Result:

ok: [localhost] => {
    "msg": "Pool1 is [x.x.x.x, x.x.x.x] and Pool2 is [x.x.x.x, x.x.x.x]"
}

Depending on how you later use the variable, you might/might not need to from_json filter (see this).


答:
You can do

const data = {
  open: [{
    id: 1,
    name: 'test 1'
  }, {
    id: 2,
    name: 'test 2'
  }],
  close: [{
    id: 3,
    name: 'test 3'
  }, {
    id: 4,
    name: 'test 4'
  }]
}

function expandData (data) {
  return Object.keys(data).reduce((a, b) => {
    a[b] = data[b].map(e => ({
      ...e,
      type: 'alert'
    }))
    return a;
  }, {});
}

const result = expandData(data)
console.log(result)```

Title: Alter data in object of arrays


问:
How to remove new line characters until each line has a specific number of instances of a specific character?
I have a real mess of a pipe-delimited file, which I need to load to a database. The file has 35 fields, and thus 34 pipes. One of the fields is comprised of HTML code which, for some records, includes multiple line breaks. Unfortunately there's no patter as to where the line breaks fall.

The solution I've come up with is to count the number of pipes in each line and until that number reaches 34, remove the new line character from that line. I'm not incredibly well-versed in Perl, but I think I'm close to achieving what I'm looking to do. Any suggestions?

```<code>#!/usr/local/bin/perl

use strict;

open (FILE, 'test.txt');

while (<FILE>) {
    chomp;
    my $line = $_;
    #remove null characters that are included in file
    $line =~ tr/\x00//;
    #count number of pipes
    my $count = ($line =~ tr/|//);
    #each line should have 34 pipes
    while ($count < 34) {
        #remove new lines until line has 34 pipes
        $line =~ tr/\r\n//;
        $count = ($line =~ tr/|//);
        print "$line\n";
    }
}
</code>```

答:
Twiddle with $/, the input record separator?

```<code>while (!eof(FILE)) {

    # assemble a row of data: 35 pipe separated fields, possibly over many lines
    my @fields = ();
    {
        # read 34 fields from FILE:
        local $/ = '|';
        for (1..34) {
            push @fields, scalar <FILE>;
        }
    }   # $/ is set back to original value ("\n") at the end of this block

    push @fields, scalar <FILE>;  # read last field, which ends with newline
    my $line = join '|', @fields;
    ... now you can process $line, and you already have the @fields ......
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I have a real mess of a pipe-delimited file, which I need to load to a database. The file has 35 fields, and thus 34 pipes. One of the fields is comprised of HTML code which, for some records, includes multiple line breaks. Unfortunately there's no patter as to where the line breaks fall.

The solution I've come up with is to count the number of pipes in each line and until that number reaches 34, remove the new line character from that line. I'm not incredibly well-versed in Perl, but I think I'm close to achieving what I'm looking to do. Any suggestions?

#!/usr/local/bin/perl

use strict;

open (FILE, 'test.txt');

while (<FILE>) {
    chomp;
    my $line = $_;
    #remove null characters that are included in file
    $line =~ tr/\x00//;
    #count number of pipes
    my $count = ($line =~ tr/|//);
    #each line should have 34 pipes
    while ($count < 34) {
        #remove new lines until line has 34 pipes
        $line =~ tr/\r\n//;
        $count = ($line =~ tr/|//);
        print "$line\n";
    }
}

Body:
Twiddle with $/, the input record separator?

while (!eof(FILE)) {

    # assemble a row of data: 35 pipe separated fields, possibly over many lines
    my @fields = ();
    {
        # read 34 fields from FILE:
        local $/ = '|';
        for (1..34) {
            push @fields, scalar <FILE>;
        }
    }   # $/ is set back to original value ("\n") at the end of this block

    push @fields, scalar <FILE>;  # read last field, which ends with newline
    my $line = join '|', @fields;
    ... now you can process $line, and you already have the @fields ......
}


问:
How to implement Server side pagination using angular 2
I am new in angular 2 so please help me.

I want to implement angular 2 and angular 4 to get data from database and apply server side pagination on it.

答:
There is a NPM package that handles this for you ngx-pagination

There are documents there that outline exactly how to get it working. You can see a live demo here, which includes a server side paging example with code


问:
Risks of using an Activity as a supplier of API
I am creating an application for Android which I want to turn into a library module and use its own logic as a common logic for several other application which differs in their UI. The library module got an Android service which can receive and send commands to a listener which is defined in the application itself (in my case in the main activity).

On the receiving side, The listener is the main activity of the application which then invokes callbacks according to the type of message from the service.

The issue is more with the sending commands to the service part. The API in question is the way of the application to send messages to the service. It simply gets the argument of the message to send and pass it along to the service.

The way I thought of doing it is making the library's main activity as the API which will allow both the sending and receiving events. The developer of a UI using this library will then simply need to make another module for the GUI alone, and make his main activity extend the library's main activity, thus being able to use the API and extend the listener's behavior.

What I want to know is possible technical issues, and not an opinion if the design itself is the best possible or not - Is there a problem with this design? For example issues with Android disposing of the activity? Any other issues?

答: The main risk with building your APIs based on the Activity is that you are basically tying your API to the activity lifecycle, I assume an API like that for messaging should be available on both the main and UI threads. I prefer using  interfaces for designing API's. Dagger is very helpful for creating singletons which can be injected anywhere.</p>


问:
Collection View Header not showing
I am currently implementing infinite scrolling using collectionView by following this link. But I got stuck when I have to add collectionView sectionheader. The header doesn't shows up when I am implemeting the above link custom flow layout, but if I use default UICollectionViewLayout it's been displayed.

Implemented the method : -

```<code>func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize
</code>```

答:
It works for me please try it hope helps to you

Set the UICollectionViewDelegateFlowLayout delegate

```<code>YourViewController : UIViewController <UICollectionViewDelegateFlowLayout>
</code>```

if You want scrolling then you can use this method in didLoad method

```<code>self.yourcollectionview.scrollDirection = UICollectionViewScrollDirectionHorizontal

self.yourcollectionview.scrollDirection = UICollectionViewScrollDirectionVertical
</code>```

Title: Collection View Header not showing

Body:
I am currently implementing infinite scrolling using collectionView by following this link. But I got stuck when I have to add collectionView sectionheader. The header doesn't shows up when I am implemeting the above link custom flow layout, but if I use default UICollectionViewLayout it's been displayed.

Implemented the method : -

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize

Body:
It works for me please try it hope helps to you

Set the UICollectionViewDelegateFlowLayout delegate

YourViewController : UIViewController <UICollectionViewDelegateFlowLayout>

if You want scrolling then you can use this method in didLoad method

self.yourcollectionview.scrollDirection = UICollectionViewScrollDirectionHorizontal

self.yourcollectionview.scrollDirection = UICollectionViewScrollDirectionVertical


问:
Multiple Where Linq Query
I am using linq c# to get the services ids selected by user OrderId

Since the user can have multiple OrderId I need to get the services of each id.

For this I am using foreach loop and getting the ServiceId from the database. This is taking long time to check for every OrderId, and ServiceId can be in list form.

Is there any method to get the result by calling database one time only?

Further the OrderId must be distinguishable for example how many services on each id.

Code

```<code>foreach (var ord in orderInfoDetailList)
{
    // this taking very long time if there are too many orderids
    long orderid = ord.orderObj.OrderID;
    var services = (from i in db.OrderServiceTBs
                    where i.OrderID == orderid
                    select i.ServiceID).ToList();
}
</code>```

答:
If you want all service-id's you should use this join approach (no foreach):

```<code>var allServiceIDs = from o in orderInfoDetailList
                    join i in db.OrderServiceTBs
                    on o.orderObj.OrderID equals i.OrderID
                    select i.ServiceID;
var list = allServiceIDs.ToList(); // if you get duplicates use Distinct() before ToList()
</code>```

But how will I distinguish which service on which orderid because
  this gives list?

Well, you haven't mentioned this anywehere in your question. However, you could use following query to create a dictionary, where the OrderId is the Key and the Value are all ServiceID:

```<code>var orderGroups = from o in orderInfoDetailList
                  join i in db.OrderServiceTBs
                  on o.orderObj.OrderID equals i.OrderID
                  group i by o.OrderID into orderGroup
                  select orderGroup;
var orderLookup = orderGroups.ToDictionary(g => g.Key, g => g.Select(x => x.ServiceID).ToList());
</code>```

Title: Multiple Where Linq Query

Body:
I am using linq c# to get the services ids selected by user OrderId

Since the user can have multiple OrderId I need to get the services of each id.

For this I am using foreach loop and getting the ServiceId from the database. This is taking long time to check for every OrderId, and ServiceId can be in list form.

Is there any method to get the result by calling database one time only?

Further the OrderId must be distinguishable for example how many services on each id.

Code

foreach (var ord in orderInfoDetailList)
{
    // this taking very long time if there are too many orderids
    long orderid = ord.orderObj.OrderID;
    var services = (from i in db.OrderServiceTBs
                    where i.OrderID == orderid
                    select i.ServiceID).ToList();
}

Body:
If you want all service-id's you should use this join approach (no foreach):

var allServiceIDs = from o in orderInfoDetailList
                    join i in db.OrderServiceTBs
                    on o.orderObj.OrderID equals i.OrderID
                    select i.ServiceID;
var list = allServiceIDs.ToList(); // if you get duplicates use Distinct() before ToList()

But how will I distinguish which service on which orderid because
  this gives list?

Well, you haven't mentioned this anywehere in your question. However, you could use following query to create a dictionary, where the OrderId is the Key and the Value are all ServiceID:

var orderGroups = from o in orderInfoDetailList
                  join i in db.OrderServiceTBs
                  on o.orderObj.OrderID equals i.OrderID
                  group i by o.OrderID into orderGroup
                  select orderGroup;
var orderLookup = orderGroups.ToDictionary(g => g.Key, g => g.Select(x => x.ServiceID).ToList());


问:
BndTools, How to add a non-OSGi JAR? Using plain JAR breaks the whole project. Missing requirement wiring package
I'm working on this BndTools based OSGi project: https://github.com/Jafre13/ISS-Product

My project though requires a non-OSGi based library (aliasi-lingpipe - https://mvnrepository.com/artifact/de.julielab/aliasi-lingpipe/4.1.0).

And here is where the problem starts. First I tried to add the JAR directly from the Maven repository, as BndTools is supposedly compatible with Maven repositories, but it doesn't seem to work from the "Repository Browser". Even when adding the Maven Central plugin to the build.bnd file as stated in http://bnd.bndtools.org/plugins/maven.html, still yields the same result.

Giving up on having Maven working, I tried to do it the most spartan way and download the JAR myself and add it as plain JAR as specified here: http://bndtools.org/faq.html (6 How Can I Depend on a Plain JAR File at Build Time?)

This time the JAR got recognised and I could start using it in the code. But once you launch the OSGi framework everything just crumbles again as it is trying to resolve the non-OSGi class paths, resulting in a wiring error like this:

could not resolve the bundles: [slf4j.api-1.7.25
  org.osgi.framework.BundleException: Unable to resolve slf4j.api [6](R
  6.0): missing requirement [slf4j.api [6](R 6.0)] osgi.wiring.package; (&(osgi.wiring.package=org.slf4j.impl)(version>=1.6.0)) Unresolved
  requirements: [[slf4j.api [6](R 6.0)] osgi.wiring.package;
  (&(osgi.wiring.package=org.slf4j.impl)(version>=1.6.0))] ,
  dk.sdu.sso.sred-0.0.0.201712041036 org.osgi.framework.BundleException:
  Unable to resolve dk.sdu.sso.sred [7](R 7.0): missing requirement
  [dk.sdu.sso.sred [7](R 7.0)] osgi.wiring.package;
  (osgi.wiring.package=com.aliasi.classify) Unresolved requirements:
  [[dk.sdu.sso.sred [7](R 7.0)] osgi.wiring.package;
  (osgi.wiring.package=com.aliasi.classify)] ]

So at this point I'm completely blocked and unable to proceed. I hope somebody with some OSGi experience could help here.

Greetings and thanks.

答:
By adding the jar at build time you are able to compile but not to run.

During the build bnd will see that you need the packages from the jar and create Import-Package statements for it. So in this state you would need to deploy a bundle that exports the packages. In fact this means you would have to create a bundle out of your jar.

The other option is to embed the jar into your own bundle. This can be done by adding the packages you need as private packages. Bnd will then automatically embed these. This approach works well if the jar is really only used internally.


问:
pip install returning invalid syntax
I've just installed python 3.6 which comes with pip

However, in Windows command prompt, when I do: 'pip install bs4' it returns 'SyntaxError: invalid syntax' under the install word.

Typing 'python' returns the version, which means it is installed correctly. What could be the problem?

答: You need to run pip install in the command prompt, outside from a python interpreter ! Try to exit python and re try :)</p>

Title: pip install returning invalid syntax


问:
Subquery returns more than 1 row. Using SQL select to update a different tables results
I am trying to update a column in the following table 'jobqueue' using the results from a SELECT query performed on the 'mdtinfo' table.

The column I am trying to update is called ignore and I need to set the value to 1 from its default of 0.

```<code>update jobqueue
set jobqueue.`ignore`= '1'
   where (SELECT JobQueue_job_queue_id
    FROM mdtinfo
    WHERE product_name  = 'Example')
</code>```

The above query returns the following error: SQL Error (1242): Subquery returns more than 1 row.

When running the select query on it's own it returns results successfully.

答:
In MySQL, a value of zero appearing in a WHERE clause means false.

So, UPDATE something SET col=val WHERE (SELECT colx FROM sometable) has the potential to be a valid query. If the inner SELECT gets just one row, and its colx column has the value 0, the update won't do anything. If the colx column has a nonzero value the query means UPDATE something SET col=val WHERE true. Accordingly, every row in sometable will be updated. I doubt that's what you want.

If the inner SELECT happens to return more than one row, the query isn't valid. You'll get the error 1242 you actually received.

(This business of interpreting numbers as Boolean values causes MySQL to accept some otherwise dodgy query syntax, like the syntax in your question.)

I guess you want to retrieve the job_queue_id values for the row or rows you actually want to update.  So try something like this.

```<code>update jobqueue
   set jobqueue.`ignore`= '1'
 where jobqueue.job_queue_id IN (SELECT JobQueue_job_queue_id
                                   FROM mdtinfo
                                  WHERE product_name  = 'Example')
</code>```

I guessed you have a column jobqueue.job_queue_id. You didn't tell us what columns you have in jobqueue.

Body:
I am trying to update a column in the following table 'jobqueue' using the results from a SELECT query performed on the 'mdtinfo' table.

The column I am trying to update is called ignore and I need to set the value to 1 from its default of 0.

update jobqueue
set jobqueue.`ignore`= '1'
   where (SELECT JobQueue_job_queue_id
    FROM mdtinfo
    WHERE product_name  = 'Example')

The above query returns the following error: SQL Error (1242): Subquery returns more than 1 row.

When running the select query on it's own it returns results successfully.

Body:
In MySQL, a value of zero appearing in a WHERE clause means false.

So, UPDATE something SET col=val WHERE (SELECT colx FROM sometable) has the potential to be a valid query. If the inner SELECT gets just one row, and its colx column has the value 0, the update won't do anything. If the colx column has a nonzero value the query means UPDATE something SET col=val WHERE true. Accordingly, every row in sometable will be updated. I doubt that's what you want.

If the inner SELECT happens to return more than one row, the query isn't valid. You'll get the error 1242 you actually received.

(This business of interpreting numbers as Boolean values causes MySQL to accept some otherwise dodgy query syntax, like the syntax in your question.)

I guess you want to retrieve the job_queue_id values for the row or rows you actually want to update.  So try something like this.

update jobqueue
   set jobqueue.`ignore`= '1'
 where jobqueue.job_queue_id IN (SELECT JobQueue_job_queue_id
                                   FROM mdtinfo
                                  WHERE product_name  = 'Example')

I guessed you have a column jobqueue.job_queue_id. You didn't tell us what columns you have in jobqueue.


问:
Mono cross platform build
Whats a good cross platform for Mono build tool. Is there some really nice that will gen build scripts for most, if not all Mono platforms. Cost may not be that important. </p>

答:
xbuild is Mono's version of MSBuild, so that's an option.

Also, I think NAnt ensures their system works with Mono.

Title: Mono cross platform build


问:
PHPJasperXML for PHP 7
As we already know, PHP 7 has been working in diferents plataforms now, I have been using PHPJasperXML to create different kinds of report with ireport for php, but mi reports stopped working after migrating my system to PHP 7.

Someone knows how to resolve this problem, or someone has been able to modify the phpjasperxml library for working in php 7?

答:
See
https://github.com/PHPJasper/phpjasper
has support to PHP 7

About

PHPJasper is the best solution to compile and process JasperReports (.jrxml & .jasper files) just using PHP, in short: to generate reports using PHP.

Notes:

PHPJasper Can be used regardless of your PHP Framework

For PHP versions less than 7.0 see: v1.16

Here are several examples of how to use PHPJasper

Title: PHPJasperXML for PHP 7


问:
Get Column name along with JSON response
I have three entity classes, I have written the query which includes join of two tables.

Table: ExpensesCategories

```<code>@Entity
@Table(name = "ExpensesCategories")
public class ExpensesCategories {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "category_id", unique = true)
    private int categoryId;

    @NotNull
    private String categoryName;

    @NotNull
    private String categoryCodeInBankStats;

    public int getCategoryId() {
        return categoryId;
    }

    public void setCategoryId(int categoryId) {
        this.categoryId = categoryId;
    }

    public String getCategoryName() {
        return categoryName;
    }

    public void setCategoryName(String categoryName) {
        this.categoryName = categoryName;
    }

    public String getCategoryCodeInBankStats() {
        return categoryCodeInBankStats;
    }

    public void setCategoryCodeInBankStats(String categoryCodeInBankStats) {
        this.categoryCodeInBankStats = categoryCodeInBankStats;
    }
}
</code>```

Table: Transactions

```<code>@Entity
@Table(name = "TransactionHistory")
public class TransactionHistory {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private int id;

    @Temporal(TemporalType.DATE)
    private Date dateOfTransaction;

    private String transactionType;

    private String refNo;

    private Date valueDate;

    private double withdrawalAmount;

    private double depositAmount;

    private double closingBalance;

    @ManyToOne
    @JoinColumn(name="userDetailsId", referencedColumnName="user_id")
    private UserDetails userDetails;

    @ManyToOne
    @JoinColumn(name="expenseCategoriesId", referencedColumnName="category_id")
    private ExpensesCategories expenseCategories;

    public TransactionHistory(int userId, Date dateOfTransaction, String transactionType, String refNo, Date valueDate,
            double withdrawalAmount, double depositAmount, double closingBalance) {
        this.dateOfTransaction = dateOfTransaction;
        this.transactionType = transactionType;
        this.refNo = refNo;
        this.valueDate = valueDate;
        this.withdrawalAmount = withdrawalAmount;
        this.depositAmount = depositAmount;
        this.closingBalance = closingBalance;
    }

    public TransactionHistory() {
    }

    public Date getDateOfTransaction() {
        return dateOfTransaction;
    }

    public void setDateOfTransaction(Date date) {
        this.dateOfTransaction = date;
    }

    public String getTransactionType() {
        return transactionType;
    }

    public void setTransactionType(String transactionType) {
        this.transactionType = transactionType;
    }

    public String getRefNo() {
        return refNo;
    }

    public void setRefNo(String refNo) {
        this.refNo = refNo;
    }

    public Date getValueDate() {
        return valueDate;
    }

    public void setValueDate(Date valueDate) {
        this.valueDate = valueDate;
    }

    public double getWithdrawalAmount() {
        return withdrawalAmount;
    }

    public void setWithdrawalAmount(double withdrawalAmount) {
        this.withdrawalAmount = withdrawalAmount;
    }

    public double getDepositAmount() {
        return depositAmount;
    }

    public void setDepositAmount(double depositAmount) {
        this.depositAmount = depositAmount;
    }

    public double getClosingBalance() {
        return closingBalance;
    }

    public void setClosingBalance(double closingBalance) {
        this.closingBalance = closingBalance;
    }

    public UserDetails getUserDetails() {
        return userDetails;
    }

    public void setUserDetails(UserDetails userDetails) {
        this.userDetails = userDetails;
    }

    public int getId() {
        return id;
    }

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

    public ExpensesCategories getExpenseCategories() {
        return expenseCategories;
    }

    public void setExpenseCategories(ExpensesCategories expenseCategories) {
        this.expenseCategories = expenseCategories;
    }
}
</code>```

Table: User Details

```<code>@Entity
@Table(name = "Employee")
public class UserDetails {

    @Id
    @Column(name = "user_id", unique = true)
    private int id;
    @NotNull
    private String firstname;
    @NotNull
    private String lastname;
    @Column(unique = true)
    @NotNull
    private String emailaddress;
    @NotNull
    private String role;

    public UserDetails(String firstname, String lastname, String emailaddress, String role) {
        this.firstname = firstname;
        this.lastname = lastname;
        this.emailaddress = emailaddress;
        this.role = role;
    }

    public int getId() {
        return id;
    }

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

    public UserDetails() {
    }

    public String getFirstname() {
        return firstname;
    }

    public void setFirstname(String firstname) {
        this.firstname = firstname;
    }

    public String getLastname() {
        return lastname;
    }

    public void setLastname(String lastname) {
        this.lastname = lastname;
    }

    public String getEmailaddress() {
        return emailaddress;
    }

    public void setEmailaddress(String emailaddress) {
        this.emailaddress = emailaddress;
    }

    public String getRole() {
        return role;
    }

    public void setRole(String role) {
        this.role = role;
    }

    @Override
    public String toString() {
        return "Employee [id=" + id + ", firstname=" + firstname + ", lastname=" + lastname + ", emailaddress="
                + emailaddress + ", role=" + role + "]";
    }
</code>```

I have written query like this in transaction entity.

```<code>    @Query( nativeQuery=true, value="SELECT a.expense_categories_id, a.Total_withdrawal_Amount, b.category_code_in_bank_stats, b.category_name FROM (SELECT expense_categories_id , SUM(withdrawal_amount) AS Total_withdrawal_Amount FROM transaction_history GROUP BY expense_categories_id) a join expenses_categories b on a.expense_categories_id = b.category_id

")
        List<Object[]> getCategorizedExpenses();
</code>```

My Json Response is like:

```<code>[
    [
        1,
        21,
        "UPI",
        "UPI Payments"
    ],
    [
        2,
        3733.59,
        "POS",
        "Shopping"
    ]
]
</code>```

But i want json response with column names as well:

```<code>[
    [
       expense_categories_id: 1,
       Total_withdrawal_Amount: 21,
       category_code_in_bank_stats: "UPI",
       category_name: "UPI Payments"
    ],
    [
        expense_categories_id: 2,
        Total_withdrawal_Amount: 3733.59,
        category_code_in_bank_stats: "POS",
        category_name: "Shopping"
    ]
]
</code>```

Please help me out..

答:
Your native query will give you an object[][] as an result. So, it actually a mxn rows.
So,
I think you should create a class names Response

```<code>public class Response{

   private Long expense_categories_id;
   private Double Total_withdrawal_Amount;
   private String category_code_in_bank_stats;
   private String category_name;

   //getters and setters for all attributes

}

List<Response> fillCategorizedExpenses(){
   List<Response> response_List = new ArrayList<>();
   Response response = null;
   Object[][] // fill each object with by accessing their index from
              //this array.
   for() //iterate the object array. {
       response = new Response();
       response.setExpense_categories_id(value); // set all attributes.
       ....
       ....
       ....
       response_List.add(response);
    }
     return response_List; //this will print as you need in your project.

}
</code>```

Thank You :) Hope this might help you out.

Body:
I have three entity classes, I have written the query which includes join of two tables.

Table: ExpensesCategories

@Entity
@Table(name = "ExpensesCategories")
public class ExpensesCategories {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "category_id", unique = true)
    private int categoryId;

    @NotNull
    private String categoryName;

    @NotNull
    private String categoryCodeInBankStats;

    public int getCategoryId() {
        return categoryId;
    }

    public void setCategoryId(int categoryId) {
        this.categoryId = categoryId;
    }

    public String getCategoryName() {
        return categoryName;
    }

    public void setCategoryName(String categoryName) {
        this.categoryName = categoryName;
    }

    public String getCategoryCodeInBankStats() {
        return categoryCodeInBankStats;
    }

    public void setCategoryCodeInBankStats(String categoryCodeInBankStats) {
        this.categoryCodeInBankStats = categoryCodeInBankStats;
    }
}

Table: Transactions

@Entity
@Table(name = "TransactionHistory")
public class TransactionHistory {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private int id;

    @Temporal(TemporalType.DATE)
    private Date dateOfTransaction;

    private String transactionType;

    private String refNo;

    private Date valueDate;

    private double withdrawalAmount;

    private double depositAmount;

    private double closingBalance;

    @ManyToOne
    @JoinColumn(name="userDetailsId", referencedColumnName="user_id")
    private UserDetails userDetails;

    @ManyToOne
    @JoinColumn(name="expenseCategoriesId", referencedColumnName="category_id")
    private ExpensesCategories expenseCategories;

    public TransactionHistory(int userId, Date dateOfTransaction, String transactionType, String refNo, Date valueDate,
            double withdrawalAmount, double depositAmount, double closingBalance) {
        this.dateOfTransaction = dateOfTransaction;
        this.transactionType = transactionType;
        this.refNo = refNo;
        this.valueDate = valueDate;
        this.withdrawalAmount = withdrawalAmount;
        this.depositAmount = depositAmount;
        this.closingBalance = closingBalance;
    }

    public TransactionHistory() {
    }

    public Date getDateOfTransaction() {
        return dateOfTransaction;
    }

    public void setDateOfTransaction(Date date) {
        this.dateOfTransaction = date;
    }

    public String getTransactionType() {
        return transactionType;
    }

    public void setTransactionType(String transactionType) {
        this.transactionType = transactionType;
    }

    public String getRefNo() {
        return refNo;
    }

    public void setRefNo(String refNo) {
        this.refNo = refNo;
    }

    public Date getValueDate() {
        return valueDate;
    }

    public void setValueDate(Date valueDate) {
        this.valueDate = valueDate;
    }

    public double getWithdrawalAmount() {
        return withdrawalAmount;
    }

    public void setWithdrawalAmount(double withdrawalAmount) {
        this.withdrawalAmount = withdrawalAmount;
    }

    public double getDepositAmount() {
        return depositAmount;
    }

    public void setDepositAmount(double depositAmount) {
        this.depositAmount = depositAmount;
    }

    public double getClosingBalance() {
        return closingBalance;
    }

    public void setClosingBalance(double closingBalance) {
        this.closingBalance = closingBalance;
    }

    public UserDetails getUserDetails() {
        return userDetails;
    }

    public void setUserDetails(UserDetails userDetails) {
        this.userDetails = userDetails;
    }

    public int getId() {
        return id;
    }

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

    public ExpensesCategories getExpenseCategories() {
        return expenseCategories;
    }

    public void setExpenseCategories(ExpensesCategories expenseCategories) {
        this.expenseCategories = expenseCategories;
    }
}

Table: User Details

@Entity
@Table(name = "Employee")
public class UserDetails {

    @Id
    @Column(name = "user_id", unique = true)
    private int id;
    @NotNull
    private String firstname;
    @NotNull
    private String lastname;
    @Column(unique = true)
    @NotNull
    private String emailaddress;
    @NotNull
    private String role;

    public UserDetails(String firstname, String lastname, String emailaddress, String role) {
        this.firstname = firstname;
        this.lastname = lastname;
        this.emailaddress = emailaddress;
        this.role = role;
    }

    public int getId() {
        return id;
    }

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

    public UserDetails() {
    }

    public String getFirstname() {
        return firstname;
    }

    public void setFirstname(String firstname) {
        this.firstname = firstname;
    }

    public String getLastname() {
        return lastname;
    }

    public void setLastname(String lastname) {
        this.lastname = lastname;
    }

    public String getEmailaddress() {
        return emailaddress;
    }

    public void setEmailaddress(String emailaddress) {
        this.emailaddress = emailaddress;
    }

    public String getRole() {
        return role;
    }

    public void setRole(String role) {
        this.role = role;
    }

    @Override
    public String toString() {
        return "Employee [id=" + id + ", firstname=" + firstname + ", lastname=" + lastname + ", emailaddress="
                + emailaddress + ", role=" + role + "]";
    }

I have written query like this in transaction entity.

    @Query( nativeQuery=true, value="SELECT a.expense_categories_id, a.Total_withdrawal_Amount, b.category_code_in_bank_stats, b.category_name FROM (SELECT expense_categories_id , SUM(withdrawal_amount) AS Total_withdrawal_Amount FROM transaction_history GROUP BY expense_categories_id) a join expenses_categories b on a.expense_categories_id = b.category_id

")
        List<Object[]> getCategorizedExpenses();

My Json Response is like:

[
    [
        1,
        21,
        "UPI",
        "UPI Payments"
    ],
    [
        2,
        3733.59,
        "POS",
        "Shopping"
    ]
]

But i want json response with column names as well:

[
    [
       expense_categories_id: 1,
       Total_withdrawal_Amount: 21,
       category_code_in_bank_stats: "UPI",
       category_name: "UPI Payments"
    ],
    [
        expense_categories_id: 2,
        Total_withdrawal_Amount: 3733.59,
        category_code_in_bank_stats: "POS",
        category_name: "Shopping"
    ]
]

Please help me out..

Body:
Your native query will give you an object[][] as an result. So, it actually a mxn rows.
So,
I think you should create a class names Response

public class Response{

   private Long expense_categories_id;
   private Double Total_withdrawal_Amount;
   private String category_code_in_bank_stats;
   private String category_name;

   //getters and setters for all attributes

}

List<Response> fillCategorizedExpenses(){
   List<Response> response_List = new ArrayList<>();
   Response response = null;
   Object[][] // fill each object with by accessing their index from
              //this array.
   for() //iterate the object array. {
       response = new Response();
       response.setExpense_categories_id(value); // set all attributes.
       ....
       ....
       ....
       response_List.add(response);
    }
     return response_List; //this will print as you need in your project.

}

Thank You :) Hope this might help you out.


问:
Alter data in object of arrays
In a React app, I have this type of data:

```<code>const data = {
  open: [{
    id: 1,
    name: 'test 1'
  }, {
    id: 2,
    name: 'test 2'
  }],
  close: [{
    id: 3,
    name: 'test 3'
  }, {
    id: 4,
    name: 'test 4'
  }]
}
</code>```

I want to iterate over each object in the open and close arrays and return the existing data with additional type field. E.g.:

```<code>const data = {
  open: [{
    id: 1,
    name: 'test 1',
    type: 'alert'
  }, {...],
  close: [...]
}
</code>```

I'm trying something like this, but it returns undefined instead of the altered data:

```<code>const expandData = (data) => {
  return Object.keys(data).forEach((key) => {
    return data[key].map((item, idx) => ({
      ...item,
      type: 'alert'
    }))
  })
}

// call in another method
expandData(data) // the `data` above
</code>```

https://jsfiddle.net/x5aspec2/

答:
This approach can also be followed:
If you need it smiple-

```<code>const data = {
  open: [{
    id: 1,
    name: 'test 1'
  }, {
    id: 2,
    name: 'test 2'
  }],
  close: [{
    id: 3,
    name: 'test 3'
  }, {
    id: 4,
    name: 'test 4'
  }]
}

function expandData (data) {
for(let key in data){
    if(data[key] instanceof Array){
    data[key].map(obj => {
    obj.type='alert'
  })
  }
}
return data
}

const result = expandData(data)
console.log(result)
</code>```

https://jsfiddle.net/Lspd8345/2/

Title: Alter data in object of arrays

Body:
In a React app, I have this type of data:

const data = {
  open: [{
    id: 1,
    name: 'test 1'
  }, {
    id: 2,
    name: 'test 2'
  }],
  close: [{
    id: 3,
    name: 'test 3'
  }, {
    id: 4,
    name: 'test 4'
  }]
}

I want to iterate over each object in the open and close arrays and return the existing data with additional type field. E.g.:

const data = {
  open: [{
    id: 1,
    name: 'test 1',
    type: 'alert'
  }, {...],
  close: [...]
}

I'm trying something like this, but it returns undefined instead of the altered data:

const expandData = (data) => {
  return Object.keys(data).forEach((key) => {
    return data[key].map((item, idx) => ({
      ...item,
      type: 'alert'
    }))
  })
}

// call in another method
expandData(data) // the `data` above

https://jsfiddle.net/x5aspec2/

Body:
This approach can also be followed:
If you need it smiple-

const data = {
  open: [{
    id: 1,
    name: 'test 1'
  }, {
    id: 2,
    name: 'test 2'
  }],
  close: [{
    id: 3,
    name: 'test 3'
  }, {
    id: 4,
    name: 'test 4'
  }]
}

function expandData (data) {
for(let key in data){
    if(data[key] instanceof Array){
    data[key].map(obj => {
    obj.type='alert'
  })
  }
}
return data
}

const result = expandData(data)
console.log(result)

https://jsfiddle.net/Lspd8345/2/


问:
Nopcommerce application restart stop visual studio 2017
When I restart nopCommerce 4.0 application from admin side it always stop visual studio and as well as application.

Same thing happening on Plugin install and uninstall time.
It's take too much time for build and run project every time on restart application and plugin install/uninstall moment.

There is any solution for that than let me know.

Thank You

答:
You need to select your project solution for run project instead of IIS.
Please check below image.


问:
Bash script: Turn on errors?
After designing a simple shell/bash based backup script on my Ubuntu engine and making it work, I've uploaded it to my Debian server, which outputs a number of errors while executing it.

What can I do to turn on "error handling" in my Ubuntu machine to make it easier to debug?

答:
Bash lets you turn on debugging selectively, or completely with the set command. Here is a good reference on how to debug bash scripts.

The command set -x will turn on debugging anywhere in your script. Likewise, set +x will turn it off again. This is useful if you only want to see debug output from parts of your script.

Title: Bash script: Turn on errors?