问:
How can I prove irreflexivity of an inductively defined relation in Isabelle?
Consider as an example the following definition of inequality of natural numbers in Isabelle:

```<code>inductive unequal :: "nat ⇒ nat ⇒ bool" where
  zero_suc: "unequal 0 (Suc _)" |
  suc_zero: "unequal (Suc _) 0" |
  suc_suc:  "unequal n m ⟹ unequal (Suc n) (Suc m)"
</code>```

I want to prove irreflexivity of unequal, that is, ¬ unequal n n. For illustration purposes let me first prove the contrived lemma ¬ unequal (n + m) (n + m):

```<code>lemma "¬ unequal (n + m) (n + m)"
proof
  assume "unequal (n + m) (n + m)"
  then show False
  proof (induction "n + m" "n + m" arbitrary: n m)
    case zero_suc
    then show False by simp
  next
    case suc_zero
    then show False by simp
  next
    case suc_suc
    then show False by presburger
  qed
qed
</code>```

In the first two cases, False must be deduced from the assumptions 0 = n + m and Suc _ = n + m, which is trivial.

I would expect that the proof of ¬ unequal n n can be done in an analogous way, that is, according to the following pattern:

```<code>lemma "¬ unequal n n"
proof
  assume "unequal n n"
  then show False
  proof (induction n n arbitrary: n)
    case zero_suc
    then show False sorry
  next
    case suc_zero
    then show False sorry
  next
    case suc_suc
    then show False sorry
  qed
qed
</code>```

In particular, I would expect that in the first two cases, I get the assumptions 0 = n and Suc _ = n. However, I get no assumptions at all, meaning that I am asked to prove False from nothing. Why is this and how can I conduct the proof of inequality?

答:
The induction method handles variable instantiations and non-variable instantiations differently. A non-variable instantiation t is a shorthand for x ≡ t where x is a fresh variable. As a result, induction is done on x, and the context additionally contains the definition x ≡ t.

Therefore, (induction "n + m" "n + m" arbitrary: n m) in the first proof is equivalent to (induction k ≡ "n + m" l ≡ "n + m" arbitrary: n m) with the effect described above. To get this effect for the second proof, you have to replace (induction n n arbitrary: n) with (induction k ≡ n l ≡ n arbitrary: n). The assumptions will actually become so simple that the pre-simplifier, which is run by the induction method, can derive False from them. As a result, there will be no cases left to prove, and you can replace the whole inner proof–qed block with by (induction k ≡ n l ≡ n arbitrary: n).

Body:
Consider as an example the following definition of inequality of natural numbers in Isabelle:

inductive unequal :: "nat ⇒ nat ⇒ bool" where
  zero_suc: "unequal 0 (Suc _)" |
  suc_zero: "unequal (Suc _) 0" |
  suc_suc:  "unequal n m ⟹ unequal (Suc n) (Suc m)"

I want to prove irreflexivity of unequal, that is, ¬ unequal n n. For illustration purposes let me first prove the contrived lemma ¬ unequal (n + m) (n + m):

lemma "¬ unequal (n + m) (n + m)"
proof
  assume "unequal (n + m) (n + m)"
  then show False
  proof (induction "n + m" "n + m" arbitrary: n m)
    case zero_suc
    then show False by simp
  next
    case suc_zero
    then show False by simp
  next
    case suc_suc
    then show False by presburger
  qed
qed

In the first two cases, False must be deduced from the assumptions 0 = n + m and Suc _ = n + m, which is trivial.

I would expect that the proof of ¬ unequal n n can be done in an analogous way, that is, according to the following pattern:

lemma "¬ unequal n n"
proof
  assume "unequal n n"
  then show False
  proof (induction n n arbitrary: n)
    case zero_suc
    then show False sorry
  next
    case suc_zero
    then show False sorry
  next
    case suc_suc
    then show False sorry
  qed
qed

In particular, I would expect that in the first two cases, I get the assumptions 0 = n and Suc _ = n. However, I get no assumptions at all, meaning that I am asked to prove False from nothing. Why is this and how can I conduct the proof of inequality?


来源: stackexchange

问:
interval missing first item
I've written some js to the word displaying in #changingword loops through several different words. It mostly works however when it first loads it skips through the second word so it goes from 'design' straight to 'e-commerce solutions', without showing the 'development'. After the first loop it works correctly. My code is below.

The html:

```<code> <div class="col-lg-8 col-md-8 col-sm-8 col-xs-12">
    <h1>Creative Development</h1>
    <h2 id="changingword">Design</h2>
  </div>
</code>```

The JS:

```<code><script>
(function(){
    var words = [
        'Development',
        'E-commerce Solutions',
        'Optimisation',
        'Support',
        'Design'
        ], i = 0;
    setInterval(function(){
        $('#changingword').fadeOut(function(){
            $(this).html(words[i=(i+1)%words.length]).fadeIn("slow");
        });
    }, 1500);

})();
</script>
</code>```

Any ideas why this is happening?

答:
I think the issue is that on first pass through the words[i=(i+1)%words.length] will be equivalent to words[1] not words[0]. </p>

<p>You can increment but return the preincremented value by doing </p>

```<code>$('#changingword').fadeOut(function(){
            $(this).html(words[i++%words.length]).fadeIn("slow");
        });
</code>```

ContentLicense: CC BY-SA 3.0

Title: interval missing first item

Body:
I've written some js to the word displaying in #changingword loops through several different words. It mostly works however when it first loads it skips through the second word so it goes from 'design' straight to 'e-commerce solutions', without showing the 'development'. After the first loop it works correctly. My code is below.

The html:

Creative Development

Design

The JS:

Any ideas why this is happening?

Body:
I think the issue is that on first pass through the words[i=(i+1)%words.length] will be equivalent to words[1] not words[0].

You can increment but return the preincremented value by doing

$('#changingword').fadeOut(function(){
            $(this).html(words[i++%words.length]).fadeIn("slow");
        });


问:
How to delete Telegram message from certain chat members?
I have a Telegram bot, which is group admininstator and can handle all group messages. As I understand, when group member send message, it deliver to all group members (bot receive message too).

Can I delete group message from certain chat members, after they receive message?

答: No you can't. All Telegram operations are chat related and in case of group chat are applicable to all participants.</p>


问:
Use of getter-setter within class
Should one use under any circumstances getters-setters of a class within the class?</p>

答:
Getters setters are generally used from outside class from inside directly access the fields.
The main advantage/purpose is encapsulation of getter setters,

If your getters setters has some logical code then use it.

for example :

```<code>public void setValue(int val){
  if(val > 100)
    this.val = 0;
  else
    this.val = val;
  }
</code>```

Also see

why-use-getters-and-setters

More on getters and setters

ContentLicense: CC BY-SA 2.5

Title: Use of getter-setter within class

Body:
Getters setters are generally used from outside class from inside directly access the fields.
The main advantage/purpose is encapsulation of getter setters,

If your getters setters has some logical code then use it.

for example :

public void setValue(int val){
  if(val > 100)
    this.val = 0;
  else
    this.val = val;
  }

Also see

why-use-getters-and-setters

More on getters and setters


问:
I want to split the strings seperated with comma and save as new row in SQL Server
Table1:

```<code>Col1 | Col2
-----+-------------------
AAA  | BB1,KB2,YB3,BP4
</code>```

Table2:

```<code>Col1 | Col2
-----+--------
AAA  | BB1
AAA  | KB2
AAA  | YB3
AAA  | BP4
</code>```

Can someone help me split and save the results this way using SQL Server 2008 R2 or SSIS 2008 R2?

答:
Try this</p>

```<code>DECLARE @T TABLE
(
    Col1 VARCHAR(10),
    Col2 VARCHAR(100)
)

INSERT INTO @T
VALUES('AAA','BB1,KB2,YB3,BP4')

;WITH CTE
AS
(
    SELECT
    Col1,
    Col2_1 = SUBSTRING(Col2,CHARINDEX(',',Col2)+1,LEN(Col2)),
    Col2 = SUBSTRING(Col2,1,CHARINDEX(',',Col2)-1)
    FROM @T

    UNION ALL

    SELECT
        Col1,
        Col2_1 =
                CASE WHEN CHARINDEX(',',Col2_1) > 0
                            THEN SUBSTRING(Col2_1,CHARINDEX(',',Col2_1)+1,LEN(Col2_1))
                        ELSE NULL END,
        Col2 = CASE WHEN CHARINDEX(',',Col2_1) > 0
                            THEN SUBSTRING(Col2_1,1,CHARINDEX(',',Col2_1)-1)
                        ELSE Col2_1 END
        FROM CTE
            WHERE ISNULL(Col2_1,'')<>''

)
SELECT
Col1,
Col2
FROM CTE
</code>```

Body:
Table1:

Col1 | Col2
-----+-------------------
AAA  | BB1,KB2,YB3,BP4

Table2:

Col1 | Col2
-----+--------
AAA  | BB1
AAA  | KB2
AAA  | YB3
AAA  | BP4

Can someone help me split and save the results this way using SQL Server 2008 R2 or SSIS 2008 R2?

Body:
Try this

DECLARE @T TABLE
(
    Col1 VARCHAR(10),
    Col2 VARCHAR(100)
)

INSERT INTO @T
VALUES('AAA','BB1,KB2,YB3,BP4')

;WITH CTE
AS
(
    SELECT
    Col1,
    Col2_1 = SUBSTRING(Col2,CHARINDEX(',',Col2)+1,LEN(Col2)),
    Col2 = SUBSTRING(Col2,1,CHARINDEX(',',Col2)-1)
    FROM @T

    UNION ALL

    SELECT
        Col1,
        Col2_1 =
                CASE WHEN CHARINDEX(',',Col2_1) > 0
                            THEN SUBSTRING(Col2_1,CHARINDEX(',',Col2_1)+1,LEN(Col2_1))
                        ELSE NULL END,
        Col2 = CASE WHEN CHARINDEX(',',Col2_1) > 0
                            THEN SUBSTRING(Col2_1,1,CHARINDEX(',',Col2_1)-1)
                        ELSE Col2_1 END
        FROM CTE
            WHERE ISNULL(Col2_1,'')<>''

)
SELECT
Col1,
Col2
FROM CTE


问:
Widgets options is miss in my new created theme
I have created A new wordpress theme. but when I active this theme the widgets theme is missing .
My theme is just simple print "Hello World" in my theme body.
 I want to design my theme using widgets options. How can I add widgets options in my them.

please suggest me

Thanks in advance.

答:
You just need to register a widget area in your theme's functions.php</p>

```<code>function twentyfifteen_widgets_init() {
    register_sidebar( array(
        'name'          => __( 'Widget Area', 'twentyfifteen' ),
        'id'            => 'sidebar-1',
        'description'   => __( 'Add widgets here to appear in your sidebar.', 'twentyfifteen' ),
        'before_widget' => '<aside id="%1$s" class="widget %2$s">',
        'after_widget'  => '</aside>',
        'before_title'  => '<h2 class="widget-title">',
        'after_title'   => '</h2>',
    ) );
}
add_action( 'widgets_init', 'twentyfifteen_widgets_init' );
</code>```

Body:
You just need to register a widget area in your theme's functions.php

function twentyfifteen_widgets_init() {
    register_sidebar( array(
        'name'          => __( 'Widget Area', 'twentyfifteen' ),
        'id'            => 'sidebar-1',
        'description'   => __( 'Add widgets here to appear in your sidebar.', 'twentyfifteen' ),
        'before_widget' => '<aside id="%1$s" class="widget %2$s">',
        'after_widget'  => '</aside>',
        'before_title'  => '<h2 class="widget-title">',
        'after_title'   => '</h2>',
    ) );
}
add_action( 'widgets_init', 'twentyfifteen_widgets_init' );


问:
Ultimate image optimization solution
I am looking for an ultimate, final word solution for the image optimization issue. My goal is to get no comment from the Google PageSpeed Insight tool when analyzing my website. I know the trick that you can click on the 'download optimized images ...' link that the tool offers when you have unoptimized images, but I am looking for an ultimate solution for a wordpress web developer, that every image I upload to the media will be optimized 100% for the Google standards, no issues, no concerns. I am also ready to pay for a premium plugin if it really does the job.

I already tried:

- tinypng / tinyjpg

- wp-smushit

They don't please the gods.

答:
You can install WordPress Smush image plugin that will optimized images when you upload new images and for current images you have to do it manually.

There is a

Title: Ultimate image optimization solution


问:
Epic cannot be closed if Story is 'In Progress'
I need to find a way to restrict the EPIC from showing the Close transition if the stories in the Epic are in Open or In progress state.
I only have the script runner plugin.
The solution here: http://www.adaptavist.com/w/jira-genius-ensuring-that-epics-are-only-closed-when-stories-are-complete/
Doesn't work as it involves JMWE as well.

Thanks a mill.

答:
Where do you see that you need JMWE?

If you have your scripted condition, then all you have to do is:

Place the script as a condition on the transition(s) to Done for your workflow that is used by Epics and you will no longer experience Epics being closed before all Stories are complete.

(quoted from the link you provided)


问:
Why we don't need to provide initial value for local variables?
While I was learning suddenly I wondered myself:
why do we have to provide initial values for global(even beyond a class scope) variable but we do not have to do same step with local variables like this? Is there any reason?</p>

```<code>if importRequired {
    let deleteObjectCount: Int
}
</code>```

答:
It is allowed, because deleteObjectCount is never been used in your code. And - and this is the difference to global variables - this fact can be checked by the compiler.

You could even do something like:

```<code>let importRequired = true

if importRequired {
    let deleteObjectCount: Int
    deleteObjectCount = 5
    print (deleteObjectCount)
}
</code>```

(e.g. kind-of modify a constant let variable) because the compiler checks that the constant is written only once, and this is done before reading it's value.

In contrast, global variables must be initialized directly, because otherwise the compiler cannot guarantee that they have been so before being initialized (because the could be accessed from anywhere in your program).

Body:
While I was learning suddenly I wondered myself:
why do we have to provide initial values for global(even beyond a class scope) variable but we do not have to do same step with local variables like this? Is there any reason?

if importRequired {
    let deleteObjectCount: Int
}

Body:
It is allowed, because deleteObjectCount is never been used in your code. And - and this is the difference to global variables - this fact can be checked by the compiler.

You could even do something like:

let importRequired = true

if importRequired {
    let deleteObjectCount: Int
    deleteObjectCount = 5
    print (deleteObjectCount)
}

(e.g. kind-of modify a constant let variable) because the compiler checks that the constant is written only once, and this is done before reading it's value.

In contrast, global variables must be initialized directly, because otherwise the compiler cannot guarantee that they have been so before being initialized (because the could be accessed from anywhere in your program).


问:
How to calculate the value of an input that has a spinner so when the number changes, the result changes too?
I'm very new to Javascript and I need some help in a basic function that could calculate the value of an input that has a spinner and display the result in a second field.

My HTML :

```<code><form action="simulation_investment">

Nombre de vache(s):<br>

<input type="number" id= "cowsnumber" min="1" max="999"  onblur="calculate()">
<br>

Coût estimé du bétail:<br>
 <input type="numbers" id="cost">
 <br><br>
 </form>
</code>```

My Javascript :

```<code>calculate = function() {
    var cowsnumber = document.getElementById('cowsnumber').value;
    document.getElementById('cost').value = parseInt(cowsnumber) * 1500;
}
</code>```

I'm actually trying to make it work on JSFiddle but I get no result, nothing happens to the second input when I change the value of the first which has the spinner.

Thank you in advance ! :-)

答:
var a = document.getElementById('cowsnumber');
a.addEventListener("blur", function(){
document.getElementById('cost').value = parseInt(a.value) * 1500
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form action="simulation_investment">

Nombre de vache(s):<br>

<input type="number" id= "cowsnumber" min="1" max="999" >
<br>

Coût estimé du bétail:<br>
 <input type="numbers" id="cost">
 <br><br>
 </form></code>```

Body:
I'm very new to Javascript and I need some help in a basic function that could calculate the value of an input that has a spinner and display the result in a second field.

My HTML :

<form action="simulation_investment">

Nombre de vache(s):

<input type="number" id= "cowsnumber" min="1" max="999"  onblur="calculate()">

Coût estimé du bétail:

 <input type="numbers" id="cost">

 </form>

My Javascript :

calculate = function() {
    var cowsnumber = document.getElementById('cowsnumber').value;
    document.getElementById('cost').value = parseInt(cowsnumber) * 1500;
}

I'm actually trying to make it work on JSFiddle but I get no result, nothing happens to the second input when I change the value of the first which has the spinner.

Thank you in advance ! :-)

Body:
var a = document.getElementById('cowsnumber');
a.addEventListener("blur", function(){
document.getElementById('cost').value = parseInt(a.value) * 1500
})

<form action="simulation_investment">

Nombre de vache(s):<br>

<input type="number" id= "cowsnumber" min="1" max="999" >
<br>

Coût estimé du bétail:<br>
 <input type="numbers" id="cost">
 <br><br>
 </form>


问:
Difference between report and sub-report
What is a sub report and how is it different from a report?
Thanks
Furqan</p>

答: Subreport in Crystal Reports means a Report within a Report . When we want to show some additional information about the data in the Crystal Reports , we use the subreports to show the details. Subreports we show within the main Crystal Reports and also we can show it as On-Demand report , that means we put an Hyper link in the row, and when user click that hyper link then will get the subreport


问:
FIrebase iOS integration crash - caused by an invalid GOOGLE_APP_ID
I am trying to build my Cordova app with Firebase integrated using Xcode build, but I am getting this vague error, and I can't understand what's wrong. I have placed the GoogleService-Info.plist file in the project directory, but it still fails to build. Here is the stack trace

```<code>2017-05-17 09:56:43.610 MyAppz[824:13611] *** Terminating app due to uncaught exception 'com.firebase.core',
reason: 'Configuration fails. It may be caused by an invalid GOOGLE_APP_ID in GoogleService-Info.plist
or set in the customized options.'
    *** First throw call stack:
    (
        0   CoreFoundation                      0x00000001099cdb0b __exceptionPreprocess + 171
        1   libobjc.A.dylib                     0x0000000109409141 objc_exception_throw + 48
        2   CoreFoundation                      0x0000000109a36625 +[NSException raise:format:] + 197
        3   MyAppz                            0x0000000107280b70 +[FIRApp addAppToAppDictionary:] + 371
        4   MyAppz                            0x000000010728011b +[FIRApp configureDefaultAppWithOptions:sendingNotifications:] + 285
        5   MyAppz                            0x000000010727fe4f +[FIRApp configure] + 302
        6   MyAppz                            0x000000010721c59a -[AppDelegate(FirebasePlugin) application:swizzledDidFinishLaunchingWithOptions:] + 122
        7   UIKit                               0x000000010a804957 -[UIApplication _handleDelegateCallbacksWithOptions:isSuspended:restoreState:] + 299
        8   UIKit                               0x000000010a80623c -[UIApplication _callInitializationDelegatesForMainScene:transitionContext:] + 4119
        9   UIKit                               0x000000010a80c584 -[UIApplication _runWithMainScene:transitionContext:completion:] + 1709
        10  UIKit                               0x000000010a809793 -[UIApplication workspaceDidEndTransaction:] + 182
        11  FrontBoardServices                  0x000000010fce15f6 __FBSSERIALQUEUE_IS_CALLING_OUT_TO_A_BLOCK__ + 24
        12  FrontBoardServices                  0x000000010fce146d -[FBSSerialQueue _performNext] + 186
        13  FrontBoardServices                  0x000000010fce17f6 -[FBSSerialQueue _performNextFromRunLoopSource] + 45
        14  CoreFoundation                      0x0000000109973c01 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ + 17
        15  CoreFoundation                      0x00000001099590cf __CFRunLoopDoSources0 + 527
        16  CoreFoundation                      0x00000001099585ff __CFRunLoopRun + 911
        17  CoreFoundation                      0x0000000109958016 CFRunLoopRunSpecific + 406
        18  UIKit                               0x000000010a80802f -[UIApplication _run] + 468
        19  UIKit                               0x000000010a80e0d4 UIApplicationMain + 159
        20  MyAppz                            0x0000000107195df1 main + 65
        21  libdyld.dylib                       0x000000010cc3a65d start + 1
    )
    libc++abi.dylib: terminating with uncaught exception of type NSException
</code>```

What could be the problem, I don't know what else to show if it's needed, so please ask.

答:
In my case the problem was with the cordova copying GoogleService-Info.plist and corrupting it.

So the solution is you need to do it manually.
Just copy your GoogleService-Info.plist from your root folder then go to
platforms/ios/project-name/Resources and paste it there and then there is another Resources folder in it paste it there too.
platforms/ios/project-name/Resources/Resources

Then again try to make a build or run it in simulator and it'll be working fine.

Body:
I am trying to build my Cordova app with Firebase integrated using Xcode build, but I am getting this vague error, and I can't understand what's wrong. I have placed the GoogleService-Info.plist file in the project directory, but it still fails to build. Here is the stack trace

2017-05-17 09:56:43.610 MyAppz[824:13611] *** Terminating app due to uncaught exception 'com.firebase.core',
reason: 'Configuration fails. It may be caused by an invalid GOOGLE_APP_ID in GoogleService-Info.plist
or set in the customized options.'
    *** First throw call stack:
    (
        0   CoreFoundation                      0x00000001099cdb0b __exceptionPreprocess + 171
        1   libobjc.A.dylib                     0x0000000109409141 objc_exception_throw + 48
        2   CoreFoundation                      0x0000000109a36625 +[NSException raise:format:] + 197
        3   MyAppz                            0x0000000107280b70 +[FIRApp addAppToAppDictionary:] + 371
        4   MyAppz                            0x000000010728011b +[FIRApp configureDefaultAppWithOptions:sendingNotifications:] + 285
        5   MyAppz                            0x000000010727fe4f +[FIRApp configure] + 302
        6   MyAppz                            0x000000010721c59a -[AppDelegate(FirebasePlugin) application:swizzledDidFinishLaunchingWithOptions:] + 122
        7   UIKit                               0x000000010a804957 -[UIApplication _handleDelegateCallbacksWithOptions:isSuspended:restoreState:] + 299
        8   UIKit                               0x000000010a80623c -[UIApplication _callInitializationDelegatesForMainScene:transitionContext:] + 4119
        9   UIKit                               0x000000010a80c584 -[UIApplication _runWithMainScene:transitionContext:completion:] + 1709
        10  UIKit                               0x000000010a809793 -[UIApplication workspaceDidEndTransaction:] + 182
        11  FrontBoardServices                  0x000000010fce15f6 __FBSSERIALQUEUE_IS_CALLING_OUT_TO_A_BLOCK__ + 24
        12  FrontBoardServices                  0x000000010fce146d -[FBSSerialQueue _performNext] + 186
        13  FrontBoardServices                  0x000000010fce17f6 -[FBSSerialQueue _performNextFromRunLoopSource] + 45
        14  CoreFoundation                      0x0000000109973c01 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ + 17
        15  CoreFoundation                      0x00000001099590cf __CFRunLoopDoSources0 + 527
        16  CoreFoundation                      0x00000001099585ff __CFRunLoopRun + 911
        17  CoreFoundation                      0x0000000109958016 CFRunLoopRunSpecific + 406
        18  UIKit                               0x000000010a80802f -[UIApplication _run] + 468
        19  UIKit                               0x000000010a80e0d4 UIApplicationMain + 159
        20  MyAppz                            0x0000000107195df1 main + 65
        21  libdyld.dylib                       0x000000010cc3a65d start + 1
    )
    libc++abi.dylib: terminating with uncaught exception of type NSException

What could be the problem, I don't know what else to show if it's needed, so please ask.

ContentLicense: CC BY-SA 4.0


问:
docker-elk - how is it persisting elasticsearch index?
I'm just getting to grips with Docker and docker-compose, trying to create a development environment for Elasticsearch which I will deploy later.

I've been using docker-elk as a reference, and I've managed to create a working Elasticsearch container, seed it, and use it in my project.

As I understand it, Docker containers don't persist data, unless you use the Volumes API and create a volume outside the container that the container then accesses (read that here).

However docker-elk only uses Volumes to share a config yml file, but somehow my elastic indices are persisting when I bring the container down and up again.

From the docker-elk readme:

The data stored in Elasticsearch
  will be persisted after container reboot but not after container
  removal.

Can someone please explain what part of the below configuration is allowing the docker container to persist the index?

docker-compose.yml

```<code>version: '2'

services:
  elasticsearch:
    build:
      context: build/elasticsearch/
    volumes:
      - ./build/elasticsearch/config.yml:/usr/share/elasticsearch/config/elasticsearch.yml:ro
    ports:
      - "9200:9200"
      - "9300:9300"
    environment:
      ES_JAVA_OPTS: "-Xmx256m -Xms256m"
    networks:
      - elk

networks:
  elk:
    driver: bridge
</code>```

build/elasticsearch/Dockerfile

```<code>FROM docker.elastic.co/elasticsearch/elasticsearch-oss:6.0.0
</code>```

build/elasticsearch/config.yml

```<code>cluster.name: "docker-cluster"
network.host: 0.0.0.0
discovery.zen.minimum_master_nodes: 1
discovery.type: single-node
</code>```

答:
As you may know, a container is a sandbox. It has a filesystem with a structure very identical to a typical linux OS. The container only sees those files and folders that are in this filesystem.

The process running inside the container writes it data and config to files in this filesystem. This process is unaware that it is running in a container or on a VM. Thus the data is persisted in files and folder in this filesystem.

Now when you remove a container using docker rm ... those files are deleted with the container and thus you lose the data unless you use volumes which backup this data on the host.

On the other hand, stopping and starting the container does not remove the container files and thus the data is still there when you restart the container.

Body:
I'm just getting to grips with Docker and docker-compose, trying to create a development environment for Elasticsearch which I will deploy later.

I've been using docker-elk as a reference, and I've managed to create a working Elasticsearch container, seed it, and use it in my project.

As I understand it, Docker containers don't persist data, unless you use the Volumes API and create a volume outside the container that the container then accesses (read that here).

However docker-elk only uses Volumes to share a config yml file, but somehow my elastic indices are persisting when I bring the container down and up again.

From the docker-elk readme:

The data stored in Elasticsearch
  will be persisted after container reboot but not after container
  removal.

Can someone please explain what part of the below configuration is allowing the docker container to persist the index?

docker-compose.yml

version: '2'

services:
  elasticsearch:
    build:
      context: build/elasticsearch/
    volumes:
      - ./build/elasticsearch/config.yml:/usr/share/elasticsearch/config/elasticsearch.yml:ro
    ports:
      - "9200:9200"
      - "9300:9300"
    environment:
      ES_JAVA_OPTS: "-Xmx256m -Xms256m"
    networks:
      - elk

networks:
  elk:
    driver: bridge

build/elasticsearch/Dockerfile

FROM docker.elastic.co/elasticsearch/elasticsearch-oss:6.0.0

build/elasticsearch/config.yml

cluster.name: "docker-cluster"
network.host: 0.0.0.0
discovery.zen.minimum_master_nodes: 1
discovery.type: single-node


问:
Confused by asynchronous mechanism
I am confused by the fact that android is multi-threaded. If the code of a particular activity method is executing, can it be interrupted in the middle by onPause(), onStop() or onDestroy() or by another method like the onPostExecute() of an asynctask?

Edit 1

This question is not about activities life-cycle. What i am really asking is if the onPause() method can interrupt the onClick() method (just an example) and i would like to read more about how exactly android manages activities, calls their async methods etc...

Edit 2

Ok, it seems that i have found the relevant information i needed in the developer docs (don't know if it is explained better somewhere else): Threading Performance:

Internals

The main thread has a very simple design: Its only job is to take and
  execute blocks of work from a thread-safe work queue until its app is
  terminated. The framework generates some of these blocks of work from
  a variety of places. These places include callbacks associated with
  lifecycle information, user events such as input, or events coming
  from other apps and processes. In addition, app can explicitly enqueue
  blocks on their own, without using the framework.

It states that callbacks relative to activity lifecycle, user events such as input and other code are all managed using a "thread-safe work queue". This is central to understanding Android asynchronous programming. It explains a lots of things, such as why onClick() will be never be interrupted by activity onPause(), or why onClick() will be never be interrupted by a runnable posted using a Handler object (allocated in the main thread). So, for example, the onPostExecute() of an AsyncTask cannot interrupt the onClick() method (or onStart(), onResume(), onPause() etc...). As a novice android programmer, it was a bit confusing at first.

答:
According to your question, I think you need to understand basic about Android Application's life cycle.

Basically, the life cycle deals with the state of application in different different situation.
Like what will be state when application goes, in foreground or background and all that So These cycles state that you had mentioned like onPause(),onDestroy(), onStart(), onCreate().

Now talk for AsynchTask(), If you want to execute long running process like downloading image or listening musing or any other then we will use BackGround services. So don't get confusion between life cycle method and background services. .

Third, App will close only some rare condition like if memory is not sufficient or some other fatal issue occur in App then only it will terminate.

So, findings are that Thread is meant for long running process and Activity Life Cycles method are meant for various activity state

Please follow this tutorial and I hope you will get clarification

Title: Confused by asynchronous mechanism


问:
FileTransfer plugin, download not starting on iOS, no errors on callbacks
I’m trying to create an Ionic 3 App that downloads an image from internet and stores it in the device file system.
On an Android device all is working fine, on iOS the call to FileTransferObject.download(…) seems to hang doing nothing; I get no error callback and nothing is downloaded.
I created a sample repo you can check out at: https://github.com/andreabarani/TestFileTransferPlugin
You will find 2 branches in it:

‘master’ using version 1.6.3 of the plugin

‘file-transfer-plugin-1.7.0’ using version 1.7.0

Both versions produce same results on iOS while 1.7.0 makes Android build fail.

Any help is very appreciated, tnx in advance
Andrea

答:
I found the solution: my mistake was creating the FileTransferObject too soon, probably when platform wasn't yet ready; my code was like this:

```<code>    @Component({
      selector: 'page-home',
      templateUrl: 'home.html',
      providers: [FileTransfer, File]
    })
    export class HomePage {
      private fileTransfer: FileTransferObject = this.transfer.create(); // <-- here is too soon to create it
    ...
</code>```

This is instead the right way of doing it:

```<code>    @Component({
      selector: 'page-home',
      templateUrl: 'home.html',
      providers: [FileTransfer, File]
    })
    export class HomePage {
      private fileTransfer: FileTransferObject;
      ...
      ...

      constructor(public navCtrl: NavController, private transfer: FileTransfer, private file: File, private alertCtrl: AlertController, private platform: Platform) {
      }

      downloadFile() {
        // using a local constant is also a valid alternative,
        // the important thing is to instantiate the object at this time
        // const fileTransfer: FileTransferObject = this.transfer.create();
        this.fileTransfer = this.transfer.create();
</code>```

Regarding Android compilation problems with version 1.7.0 of the FileTransfer plugin, all was solved by updating Android Studio to version 3.0.1 from 2.3.3.

The complete working app is available here: https://github.com/andreabarani/TestFileTransferPlugin

Body:
I found the solution: my mistake was creating the FileTransferObject too soon, probably when platform wasn't yet ready; my code was like this:

    @Component({
      selector: 'page-home',
      templateUrl: 'home.html',
      providers: [FileTransfer, File]
    })
    export class HomePage {
      private fileTransfer: FileTransferObject = this.transfer.create(); // <-- here is too soon to create it
    ...

This is instead the right way of doing it:

    @Component({
      selector: 'page-home',
      templateUrl: 'home.html',
      providers: [FileTransfer, File]
    })
    export class HomePage {
      private fileTransfer: FileTransferObject;
      ...
      ...

      constructor(public navCtrl: NavController, private transfer: FileTransfer, private file: File, private alertCtrl: AlertController, private platform: Platform) {
      }

      downloadFile() {
        // using a local constant is also a valid alternative,
        // the important thing is to instantiate the object at this time
        // const fileTransfer: FileTransferObject = this.transfer.create();
        this.fileTransfer = this.transfer.create();

Regarding Android compilation problems with version 1.7.0 of the FileTransfer plugin, all was solved by updating Android Studio to version 3.0.1 from 2.3.3.

The complete working app is available here: https://github.com/andreabarani/TestFileTransferPlugin


问:
React.js create multiple tables from array
I have searched for a solution to my problem but nothing worked probably because of my lack of understanding.

I am trying to work with React.js to create tables of dynamic length.

I call an API in my project with the axios library that returns an array of JSON objects, We dont know the size of the returned array, but for each JSON object within the array I need to create a table and add its data. Here is an example of the API call return.

```<code>[

  {
        "feedbackID": 12,
        "posterID": "John",
        "comment": "shortcomment"
    },
    {
        "feedbackID": 23,
        "posterID": "billy",
        "comment": "long comment"
  }
]
</code>```

So with this return I will have to create 2 tables, one under the other as follows:

```<code>| Feedback ID | 12           |
| Poster ID   | John         |
| Comment     | shortcomment |

| Feedback ID | 23           |
| Poster ID   | billy        |
| Comment     | long comment |
</code>```

Here is my code so far:

```<code>   export class ViewFeedback extends Component {
  constructor(props) {
    super(props)
    this.state = {
      feedback: []
    }
  }

  componentDidMount() {
    var id = this.props.match.params.id;

    // this returns the JSON array like shown above
    getfeedback(id).then((response) => {

     this.setState({feedback:response})

    })

  }
</code>```

I have no clue at all how to make the tables, I tried the createElement and also Grid But I did it so wrong it wouldn't even compile the code.

答:
This should work:

```<code>renderTable = () => {
    return this.state.feedback.map(value => {
        return (
            <table>
            <tr>
                <td>Feedback ID</td>
                <td>{value.feedbackID}</td>
            </tr>
             <tr>
                <td>Poster ID</td>
                <td>{value.posterID}</td>
            </tr>
             <tr>
                <td>Comment</td>
                <td>{value.comment}</td>
            </tr>
        </table>
        )
    })
}

render () {
    return <div>{this.renderTable()}</div>;
}
</code>```

Render method is mainly a view, so moving the logic to a separate method is encouraged.

Body:
I have searched for a solution to my problem but nothing worked probably because of my lack of understanding.

I am trying to work with React.js to create tables of dynamic length.

I call an API in my project with the axios library that returns an array of JSON objects, We dont know the size of the returned array, but for each JSON object within the array I need to create a table and add its data. Here is an example of the API call return.

[

  {
        "feedbackID": 12,
        "posterID": "John",
        "comment": "shortcomment"
    },
    {
        "feedbackID": 23,
        "posterID": "billy",
        "comment": "long comment"
  }
]

So with this return I will have to create 2 tables, one under the other as follows:

| Feedback ID | 12           |
| Poster ID   | John         |
| Comment     | shortcomment |

| Feedback ID | 23           |
| Poster ID   | billy        |
| Comment     | long comment |

Here is my code so far:

   export class ViewFeedback extends Component {
  constructor(props) {
    super(props)
    this.state = {
      feedback: []
    }
  }

  componentDidMount() {
    var id = this.props.match.params.id;

    // this returns the JSON array like shown above
    getfeedback(id).then((response) => {

     this.setState({feedback:response})

    })

  }

I have no clue at all how to make the tables, I tried the createElement and also Grid But I did it so wrong it wouldn't even compile the code.

Body:
This should work:

renderTable = () => {
    return this.state.feedback.map(value => {
        return (
            <table>
            <tr>
                <td>Feedback ID</td>
                <td>{value.feedbackID}</td>
            </tr>
             <tr>
                <td>Poster ID</td>
                <td>{value.posterID}</td>
            </tr>
             <tr>
                <td>Comment</td>
                <td>{value.comment}</td>
            </tr>
        </table>
        )
    })
}

render () {
    return <div>{this.renderTable()}</div>;
}

Render method is mainly a view, so moving the logic to a separate method is encouraged.


问:
how to get value from html form and pass is to typescript in angular
Do anyone know how can I get value from HTML forms in typescript?

this is how my html page: login.component.html

```<code><form [formGroup]="loginForm" id="loginForm" (ngSubmit)="authUser()" #userForm="ngForm">
<div class="container">
  <div class="row">
    <div class="col-sm-6 col-sm-offset-3">
      <p><input type="email" formControlName="email" id="email" placeholder="Your email" [(ngModel)]="user.email" required></p>
    </div>
  </div>
  <div class="row">
    <div class="col-sm-6 col-sm-offset-3">
      <p><input type="password" formControlName="password" id="password" placeholder="Your password" [(ngModel)]="user.password" required></p>
    </div>
  </div>
   <div class="row">
    <div class="col-sm-6 col-sm-offset-3">
      <p><button class="btn btn-primary" type="submit" [disabled]="!bookForm.form.valid">Login</button> </p>
    </div>
  </div>
 </div>
</form>
<div *ngIf="edited" class="alert alert-success box-msg" role="alert">
        <strong>Successful Login!</strong>
</div>
</code>```

and this is my typescript: login.component.ts

```<code>import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup } from '@angular/forms';
import { Router } from '@angular/router';
import { Http } from '@angular/http';
import { PostsService } from '../posts.service';
@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {
  loginForm: FormGroup;
  login = false;
  users: any;

  user = {};
  constructor(private fb: FormBuilder, private http: Http, private router: Router, private postsService: PostsService) {
    this.postsService.getAllPosts().subscribe(users => {
      this.users = users;
    });

  }

  ngOnInit() {
    this.loginForm = this.fb.group({
      email: 'a@b.com',
      password: 'abc123.'

    });
  }
  authUser() {
    var i:number;
    var email:string = this.loginForm.value.email;
    var password:string = this.loginForm.value.password;
    var userType:string;
    var userEmail:string;
    for(i=0;i<this.users.length;i++){
      if(this.users[i].email == email && this.users[i].password == password){
         this.login = true
         userEmail = this.users[i].email;
         userType = this.users[i].accountType;
        }
    }
    if(this.login){
      console.log("Sucessful");
    }
    else{
      console.log("Unsucessful");

    }
  }

}
</code>```

I have tried a lot of methods but none of them seems to work for now my login the way my code words is that once the button is press it will not check whats in the html forms. but it will check againce var email:string = this.loginForm.value.email; and my database for the email and the value thats in var email:string = this.loginForm.value.email; have been hardcoded.

答:
You need the prevent default behavior of form. Use following code in your authUser method:

```<code>authUser(event) {
    event.preventDefault();
    //rest of code
  }
</code>```

and update your form tag:

```<code><form [formGroup]="loginForm" id="loginForm" (ngSubmit)="authUser($event)" #userForm="ngForm">
</code>```

Body:
Do anyone know how can I get value from HTML forms in typescript?

this is how my html page: login.component.html

<form [formGroup]="loginForm" id="loginForm" (ngSubmit)="authUser()" #userForm="ngForm">

<input type="email" formControlName="email" id="email" placeholder="Your email" [(ngModel)]="user.email" required>

<input type="password" formControlName="password" id="password" placeholder="Your password" [(ngModel)]="user.password" required>

<button class="btn btn-primary" type="submit" [disabled]="!bookForm.form.valid">Login</button>

</form>

        Successful Login!

and this is my typescript: login.component.ts

import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup } from '@angular/forms';
import { Router } from '@angular/router';
import { Http } from '@angular/http';
import { PostsService } from '../posts.service';
@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {
  loginForm: FormGroup;
  login = false;
  users: any;

  user = {};
  constructor(private fb: FormBuilder, private http: Http, private router: Router, private postsService: PostsService) {
    this.postsService.getAllPosts().subscribe(users => {
      this.users = users;
    });

  }

  ngOnInit() {
    this.loginForm = this.fb.group({
      email: 'a@b.com',
      password: 'abc123.'

    });
  }
  authUser() {
    var i:number;
    var email:string = this.loginForm.value.email;
    var password:string = this.loginForm.value.password;
    var userType:string;
    var userEmail:string;
    for(i=0;i<this.users.length;i++){
      if(this.users[i].email == email && this.users[i].password == password){
         this.login = true
         userEmail = this.users[i].email;
         userType = this.users[i].accountType;
        }
    }
    if(this.login){
      console.log("Sucessful");
    }
    else{
      console.log("Unsucessful");

    }
  }

}

I have tried a lot of methods but none of them seems to work for now my login the way my code words is that once the button is press it will not check whats in the html forms. but it will check againce var email:string = this.loginForm.value.email; and my database for the email and the value thats in var email:string = this.loginForm.value.email; have been hardcoded.

Body:
You need the prevent default behavior of form. Use following code in your authUser method:

authUser(event) {
    event.preventDefault();
    //rest of code
  }

and update your form tag:

<form [formGroup]="loginForm" id="loginForm" (ngSubmit)="authUser($event)" #userForm="ngForm">


问:
Flex menu, first element on whole row after line break
Responsive flex menu (code bellow) is on smaller viewports arranged like this:

```    |first item| |item| |item| |item| |item| |item|
                    |last item|```

Last item is on whole line in the middle.
Is it possible to do this? :

```                     |first item|
    |item| |item| |item| |item| |item| |last item|```

Looking for common solution. Menu can has any number of items.

* {
 box-sizing: border-box;
}

html {
 background:#a0522d;
}
ul {
 border:5px solid #a0522d;
 display:flex;
 flex-wrap:wrap;
 max-width:75em;
 padding:0;
 margin:20px auto;
 justify-content: center;
 align-items: center
}
ul li {
 list-style:none;
 flex-grow:1;
}
ul li a         {
 line-height:1.5;
 padding:8px 16px;
 display:block;
 text-align:center;
 border-radius:0.313em;
 background:PaleGoldenrod;
 margin:2px;
}
.last, .almostlast {
 max-width:320px;
}
    ```
<pre class="snippet-code-html lang-html prettyprint-override"><code> <ul>
     <li class="first">first item</li>
     <li>second item</li>
     <li>next item</li>
     <li>item</li>
     <li>pretty item</li>
     <li class="almostlast"><span>item</span></li>
     <li class="last">last item</li>
</ul></code>```

答:
Yes.

Set the first li to 100% width and the set the link inside to a centered in that li.

```<code>  .first {
    flex: 0 0 100%;
    text-align: center;
    display: flex;
    justify-content: center;
  }
</code>```

Result:

* {
  box-sizing: border-box;
}

html {
  background: #a0522d;
}

ul {
  border: 5px solid #a0522d;
  display: flex;
  flex-wrap: wrap;
  max-width: 75em;
  padding: 0;
  margin: 20px auto;
  justify-content: center;
  align-items: center
}

ul li {
  list-style: none;
  flex-grow: 1;
}

ul li a {
  line-height: 1.5;
  padding: 8px 16px;
  display: block;
  text-align: center;
  border-radius: 0.313em;
  background: PaleGoldenrod;
  margin: 2px;
}

.last,
.almostlast {
  max-width: 320px;
}

.first {
  flex: 0 0 100%;
  text-align: center;
  display: flex;
  justify-content: center;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul>
  <li class="first">first item</li>
  <li>second item</li>
  <li>next item</li>
  <li>item</li>
  <li>pretty item</li>
  <li class="almostlast"><span>item</span></li>
  <li class="last">last item</li>
</ul></code>```

Body:
Responsive flex menu (code bellow) is on smaller viewports arranged like this:

    |first item| |item| |item| |item| |item| |item|
                    |last item|

Last item is on whole line in the middle.
Is it possible to do this? :

                     |first item|
    |item| |item| |item| |item| |item| |last item|

Looking for common solution. Menu can has any number of items.

* {
 box-sizing: border-box;
}

html {
 background:#a0522d;
}
ul {
 border:5px solid #a0522d;
 display:flex;
 flex-wrap:wrap;
 max-width:75em;
 padding:0;
 margin:20px auto;
 justify-content: center;
 align-items: center
}
ul li {
 list-style:none;
 flex-grow:1;
}
ul li a         {
 line-height:1.5;
 padding:8px 16px;
 display:block;
 text-align:center;
 border-radius:0.313em;
 background:PaleGoldenrod;
 margin:2px;
}
.last, .almostlast {
 max-width:320px;
}

first item

second item

next item

item

pretty item

item

last item

Body:
Yes.

Set the first li to 100% width and the set the link inside to a centered in that li.

  .first {
    flex: 0 0 100%;
    text-align: center;
    display: flex;
    justify-content: center;
  }

Result:

* {
  box-sizing: border-box;
}

html {
  background: #a0522d;
}

ul {
  border: 5px solid #a0522d;
  display: flex;
  flex-wrap: wrap;
  max-width: 75em;
  padding: 0;
  margin: 20px auto;
  justify-content: center;
  align-items: center
}

ul li {
  list-style: none;
  flex-grow: 1;
}

ul li a {
  line-height: 1.5;
  padding: 8px 16px;
  display: block;
  text-align: center;
  border-radius: 0.313em;
  background: PaleGoldenrod;
  margin: 2px;
}

.last,
.almostlast {
  max-width: 320px;
}

.first {
  flex: 0 0 100%;
  text-align: center;
  display: flex;
  justify-content: center;
}

<ul>
  <li class="first"><a href="#">first item</a></li>
  <li><a href="#">second item</a></li>
  <li><a href="#">next item</a></li>
  <li><a href="#">item</a></li>
  <li><a href="#">pretty item</a></li>
  <li class="almostlast"><span><a href="#">item</a></span></li>
  <li class="last"><a href="#">last item</a></li>
</ul>


问:
Generics in Java - Why I am not allowed to do Comparable<? extends T> instead of Comparable<? super T>?
I have rewritten this ArrayIndexComparator class based on this answer of Jon Skeet so that it can support generic types: Get the indices of an array after sorting?

```<code>public class ArrayIndexComparator<T extends Comparable<? super T>> implements Comparator<Integer> {
    private final T[] array;

    public ArrayIndexComparator(T[] array) {
        this.array = array;
    }

    public Integer[] createIndexArray() {
        Integer[] indexes = new Integer[array.length];
        for (int i = 0; i < array.length; i++) {
            indexes[i] = i; // Autoboxing
        }
        return indexes;
    }

    @Override
    public int compare(Integer index1, Integer index2) {
        // Autounbox from Integer to int to use as array indexes
        return array[index2].compareTo(array[index1]);
    }
}
</code>```

And I can use this class as long as the T type or a supertype of T implements the Comparable interface (Comparable<? super T>).

If I write Comparable<? extends T> instead of Comparable<? super T>, the compiler gives me an error:

```<code>@Override
public int compare(Integer index1, Integer index2) {
    // Autounbox from Integer to int to use as array indexes
    return array[index2].compareTo(array[index1]); // ERROR -> compareTo (capture<? extends T>) in Comparable cannot be applied to (T)
}
</code>```

What does this compareTo (capture<? extends T>) in Comparable cannot be applied to (T) error mean?

I can assume that it does not make sense to define a class AClass which implements Comparable<AChildClassOfAClass>, but yet it is possible:

```<code>class AClass implements Comparable<AChildClassOfAClass> {

    @Override
    public int compareTo(AChildClassOfAClass o) {
        return 0;
    }
}

class AChildClassOfAClass extends AClass {
}
</code>```

In this strange scenario, I assume to be able to use ArrayIndexComparator if I have defined it as ArrayIndexComparator<T extends Comparable<? extends T>>, because in this case T is AClass which implements Comparable<AChildClassOfAClass> which turns out to be a subclass of AClass (therefore Comparable<? extends T> → Comparable<AChildClassOfAClass extends AClass>).

Of course, it makes more sense to use Comparable<? super T>, but I guess I should be able to do it anyway if I want to.

Why doesn't Java allow me to do this?

Thank you very much for your attention.

EDIT: after reading answer to the question Difference between <? super T> and <? extends T> in Java, here is what I understood and I hope I understood it correctly:

array[index1] is of type T but compareTo would expect a type <? extends T>, i.e. an unknown specific type of T (or T itself, but the compiler can't assure that).

Therefore the compiler can't safely cast T to the specific unknown type, whereas it could do it if we use <? super T> because in this case compareTo would expect an unknown supertype of T as a parameter, and as we are passing T, the compiler can safely cast the type T to its supertype as a type T is also a supertype of T (like when we say that an Integer is also a Number, but a Number is not necessarily an Integer).

In this Comparable<? extends T> case we are trying to consume array[index1] by passing it to the compareTo method, but the compiler can't safely cast the type T to the specific type required by compareTo(<? extends T>), which is unknown.

That's why I get the error.

Are this thoughts right?

答:
This kind of error generally means you're trying to encode a constraint that doesn't make sense.  In your case, we already know there's something that doesn't make sense:

in this case T is AClass which implements Comparable<AChildClassOfAClass>

This is the real issue.   Your classes allow you to do base.compareTo(child), but not child.compareTo(base).  You've tweaked the generic parameters to handle this, but you've merely pushed the problem elsewhere (and luckily the compiler is clever enough to spot it!).

What the error is actually saying

compareTo takes a ? extends T.  i.e. some specific yet unknown type that extends T.  The compiler is complaining because we're attempting to pass in a T - that won't be the same as (nor assignable to) the unknown type, in general.  The only thing we can pass into such a method is null.

Further reading

Why generic type is not applicable for argument extends super class for both? (a simpler variant of the same problem)

What is PECS? (a structured way to think about super vs. extends wildcards)

Body:
I have rewritten this ArrayIndexComparator class based on this answer of Jon Skeet so that it can support generic types: Get the indices of an array after sorting?

public class ArrayIndexComparator<T extends Comparable<? super T>> implements Comparator<Integer> {
    private final T[] array;

    public ArrayIndexComparator(T[] array) {
        this.array = array;
    }

    public Integer[] createIndexArray() {
        Integer[] indexes = new Integer[array.length];
        for (int i = 0; i < array.length; i++) {
            indexes[i] = i; // Autoboxing
        }
        return indexes;
    }

    @Override
    public int compare(Integer index1, Integer index2) {
        // Autounbox from Integer to int to use as array indexes
        return array[index2].compareTo(array[index1]);
    }
}

And I can use this class as long as the T type or a supertype of T implements the Comparable interface (Comparable<? super T>).

If I write Comparable<? extends T> instead of Comparable<? super T>, the compiler gives me an error:

@Override
public int compare(Integer index1, Integer index2) {
    // Autounbox from Integer to int to use as array indexes
    return array[index2].compareTo(array[index1]); // ERROR -> compareTo (capture<? extends T>) in Comparable cannot be applied to (T)
}

What does this compareTo (capture<? extends T>) in Comparable cannot be applied to (T) error mean?

I can assume that it does not make sense to define a class AClass which implements Comparable<AChildClassOfAClass>, but yet it is possible:

class AClass implements Comparable<AChildClassOfAClass> {

    @Override
    public int compareTo(AChildClassOfAClass o) {
        return 0;
    }
}

class AChildClassOfAClass extends AClass {
}

In this strange scenario, I assume to be able to use ArrayIndexComparator if I have defined it as ArrayIndexComparator<T extends Comparable<? extends T>>, because in this case T is AClass which implements Comparable<AChildClassOfAClass> which turns out to be a subclass of AClass (therefore Comparable<? extends T> → Comparable<AChildClassOfAClass extends AClass>).

Of course, it makes more sense to use Comparable<? super T>, but I guess I should be able to do it anyway if I want to.

Why doesn't Java allow me to do this?

Thank you very much for your attention.

EDIT: after reading answer to the question Difference between <? super T> and <? extends T> in Java, here is what I understood and I hope I understood it correctly:

array[index1] is of type T but compareTo would expect a type <? extends T>, i.e. an unknown specific type of T (or T itself, but the compiler can't assure that).

Therefore the compiler can't safely cast T to the specific unknown type, whereas it could do it if we use <? super T> because in this case compareTo would expect an unknown supertype of T as a parameter, and as we are passing T, the compiler can safely cast the type T to its supertype as a type T is also a supertype of T (like when we say that an Integer is also a Number, but a Number is not necessarily an Integer).

In this Comparable<? extends T> case we are trying to consume array[index1] by passing it to the compareTo method, but the compiler can't safely cast the type T to the specific type required by compareTo(<? extends T>), which is unknown.

That's why I get the error.

Are this thoughts right?


问:
Scanning classpath/modulepath in runtime in Java 9
I can't seem to find any info on whether scanning all available classes (for interfaces, annotations etc) is still possible in runtime, the way Spring, Reflections and many other frameworks and libraries currently do, in the face of Jigsaw related changes to the way classes are loaded.

EDIT:
This question is about scanning the real physical file paths looking for classes. The other question is about dynamically loading classes and resources. It's related but very much not a duplicate.

UPDATE: Jetty project has made a JEP proposal for a standardized API for this. If you have a way to help make this reality, please do. Otherwise, wait and hope.

UPDATE 2: Found this relevant sounding post. Quoting the code snippet for posterity:

If you are really just looking to get at the contents of the modules in
  the boot layer (the modules that are resolved at startup) then you'll do
  something like this:

```<code>  ModuleLayer.boot().configuration().modules().stream()
         .map(ResolvedModule::reference)
         .forEach(mref -> {
             System.out.println(mref.descriptor().name());
             try (ModuleReader reader = mref.open()) {
                 reader.list().forEach(System.out::println);
            } catch (IOException ioe) {
                 throw new UncheckedIOException(ioe);
             }
         });
</code>```

答:
The actual issue here is to find the paths to all jars and folders on the classpath. Once when you have them, you can scan.

What I did is the following:

get the current module descriptor for current class

get all requires modules

for each such module open resource of MANIFEST.MF

remove the MANIFEST.MF path from the resource url

what remains is the classpath of the module, i.e. to it's jar or folder.

I do the same for current module, to get the classpath for current code.

This way I collect classpath of a currently working module and all its required modules (1 step away). That was working for me - and my Java8 scanner was still being able to do the job. This approach does not require any additional VM flag etc.

I could extend this approach to get all required modules easily (not only the first level), but for now, I don't need that.

Code.

Body:
I can't seem to find any info on whether scanning all available classes (for interfaces, annotations etc) is still possible in runtime, the way Spring, Reflections and many other frameworks and libraries currently do, in the face of Jigsaw related changes to the way classes are loaded.

EDIT:
This question is about scanning the real physical file paths looking for classes. The other question is about dynamically loading classes and resources. It's related but very much not a duplicate.

UPDATE: Jetty project has made a JEP proposal for a standardized API for this. If you have a way to help make this reality, please do. Otherwise, wait and hope.

UPDATE 2: Found this relevant sounding post. Quoting the code snippet for posterity:

If you are really just looking to get at the contents of the modules in
  the boot layer (the modules that are resolved at startup) then you'll do
  something like this:

  ModuleLayer.boot().configuration().modules().stream()
         .map(ResolvedModule::reference)
         .forEach(mref -> {
             System.out.println(mref.descriptor().name());
             try (ModuleReader reader = mref.open()) {
                 reader.list().forEach(System.out::println);
            } catch (IOException ioe) {
                 throw new UncheckedIOException(ioe);
             }
         });


问:
Skipping headers and parsing xml to convert to json
I have a xml file like this:

```<code>  "HTTP/1.1 100 Continue
   HTTP/1.1 200 OK
   Expires: 0
   Buffer: false
   Pragma: No-cache
   Cache-Control: no-cache
   Server: Transaction_Server/4.1.0(zOS)
   Connection: close
   Content-Type: text/html
   Content-Length: 33842
   Date: Sat, 02 Aug 2014 09:27:02 GMT

 <?xml version=""1.0"" encoding=""UTF-8""?>
 <creditBureau xmlns=""http://www.transunion.com/namespace"" xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"">

 <document>response</document>
 <version>2.9</version>
 <transactionControl><userRefNumber>Credit Report Example</userRefNumber>
 <subscriber><industryCode>Z</industryCode></subscriber></transactionControl>
</code>```

This is just a part of the entire document. I want to convert this into json.
The problem is how to skip or delete the header part and start parsing from the real xml as in, starting from the <document> tag.

There are more than a million such files. I can't do it manually. How can I do it? Any help appreciated.

答:
You can read each file, remove the unwanted header using a concept as shown below.

```<code>import re

file = '''\
"HTTP/1.1 100 Continue
 HTTP/1.1 200 OK
 Expires: 0
 Buffer: false
 Pragma: No-cache
 Cache-Control: no-cache
 Server: Transaction_Server/4.1.0(zOS)
 Connection: close
 Content-Type: text/html
 Content-Length: 33842
 Date: Sat, 02 Aug 2014 09:27:02 GMT

<?xml version=""1.0"" encoding=""UTF-8""?>
<creditBureau xmlns=""http://www.transunion.com/namespace"" xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"">

<document>response</document>
<version>2.9</version>
<transactionControl><userRefNumber>Credit Report Example</userRefNumber>
<subscriber><industryCode>Z</industryCode></subscriber></transactionControl>'''

# list concept.
file_list = file.split('\n')
start = file_list.index('<?xml version=""1.0"" encoding=""UTF-8""?>')
new_list = file_list[start:]
print('joined from list:\n', '\n'.join(new_list), sep='')

# regexp concept.
new_string = re.sub(r'\A.*(<\?xml.*)\Z', r'\1', file, flags=re.S)
print('regexp:\n', new_string, sep='')
</code>```

The regexp might be quicker though you have plenty of files to test with.

Edit:

Use like this on test.xml:

```<code>import re

with open('test.xml') as r:
    file = r.read()

new_string = re.sub(r'\A.*(<\?xml.*)\Z', r'\1', file, flags=re.S)

print(new_string)
</code>```

Edit:

Another example showing bulk overwriting of xml files. Always test first before using on many files. Small test works fine for me.

```<code>import glob, re

for file in glob.iglob('*.xml'):
    with open(file) as r:
        current_string = r.read()

    new_string = re.sub(r'\A.*(<\?xml.*)\Z', r'\1', current_string, flags=re.S)

    with open(file, 'w') as w:
        w.write(new_string)
</code>```

Specify the codec for reading and writing may be needed.

Body:
I have a xml file like this:

  "HTTP/1.1 100 Continue
   HTTP/1.1 200 OK
   Expires: 0
   Buffer: false
   Pragma: No-cache
   Cache-Control: no-cache
   Server: Transaction_Server/4.1.0(zOS)
   Connection: close
   Content-Type: text/html
   Content-Length: 33842
   Date: Sat, 02 Aug 2014 09:27:02 GMT

 <?xml version=""1.0"" encoding=""UTF-8""?>
 <creditBureau xmlns=""http://www.transunion.com/namespace"" xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"">

 <document>response</document>
 <version>2.9</version>
 <transactionControl><userRefNumber>Credit Report Example</userRefNumber>
 <subscriber><industryCode>Z</industryCode></subscriber></transactionControl>

This is just a part of the entire document. I want to convert this into json.
The problem is how to skip or delete the header part and start parsing from the real xml as in, starting from the <document> tag.

There are more than a million such files. I can't do it manually. How can I do it? Any help appreciated.

Body:
You can read each file, remove the unwanted header using a concept as shown below.

import re

file = '''\
"HTTP/1.1 100 Continue
 HTTP/1.1 200 OK
 Expires: 0
 Buffer: false
 Pragma: No-cache
 Cache-Control: no-cache
 Server: Transaction_Server/4.1.0(zOS)
 Connection: close
 Content-Type: text/html
 Content-Length: 33842
 Date: Sat, 02 Aug 2014 09:27:02 GMT

<?xml version=""1.0"" encoding=""UTF-8""?>
<creditBureau xmlns=""http://www.transunion.com/namespace"" xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"">

<document>response</document>
<version>2.9</version>
<transactionControl><userRefNumber>Credit Report Example</userRefNumber>
<subscriber><industryCode>Z</industryCode></subscriber></transactionControl>'''

# list concept.
file_list = file.split('\n')
start = file_list.index('<?xml version=""1.0"" encoding=""UTF-8""?>')
new_list = file_list[start:]
print('joined from list:\n', '\n'.join(new_list), sep='')

# regexp concept.
new_string = re.sub(r'\A.*(<\?xml.*)\Z', r'\1', file, flags=re.S)
print('regexp:\n', new_string, sep='')

The regexp might be quicker though you have plenty of files to test with.

Edit:

Use like this on test.xml:

import re

with open('test.xml') as r:
    file = r.read()

new_string = re.sub(r'\A.*(<\?xml.*)\Z', r'\1', file, flags=re.S)

print(new_string)

Edit:

Another example showing bulk overwriting of xml files. Always test first before using on many files. Small test works fine for me.

import glob, re

for file in glob.iglob('*.xml'):
    with open(file) as r:
        current_string = r.read()

    new_string = re.sub(r'\A.*(<\?xml.*)\Z', r'\1', current_string, flags=re.S)

    with open(file, 'w') as w:
        w.write(new_string)

Specify the codec for reading and writing may be needed.


问:
Are all the classes containing business logic, domain objects?
So I have few doubts regarding calling something as domain object (and eventually placing the class under domain package) or not.

I have a micro-service whose responsibility is to do some calculations (without getting into actual business requirements, all it does is calculate some return of intereset based on given request). Now to achieve the calculations there are certain sub-calculations which need to take place and hence are composed in different classes respectively. But yes, these calculation do not need to be persisted in DB , and neither they have an ID (so definitely not an Entity or Aggregate). However these individual calculator classes (for the lack of terminology) do contain some complex business logic. Now, my question is, do these individual classes still qualify/classify as domain objects or should they be referred to as services ?

Feel free to ask for more clarifications around use case if need be.

Cheers !

答:
I would say that your calculations can fit well either in Value Objects or Domain Services.

How to differentiate? Well, I understand Domain Services as services (well, obvious) with business logic (such as your calculations) that require some kind of external dependency you need to inject in order to get your logic work.

On the other hand, if you can name that business logic as a business concept (i.e. CustomerFee, CustomerCommission, etc) and you don't need any injected dependency to make it work I would say it's a Value Object.

For instance, imagine that you want to calculate the price of a reservation which depends on the fee you will charge to the customer (among other params):

```<code>ReservationPrice(CustomerFee customerFee, ItemPrice ItemPrice)
</code>```

Now your CustomerFee is also calculated based on (say any variable) something.

This way you are modeling your calculations just with Value Objects which allows you to show in your code all the different business concepts they depend on. Also anyone looking at your code and files structure can get an idea about what you are calculating.

Body:
I would say that your calculations can fit well either in Value Objects or Domain Services.

How to differentiate? Well, I understand Domain Services as services (well, obvious) with business logic (such as your calculations) that require some kind of external dependency you need to inject in order to get your logic work.

On the other hand, if you can name that business logic as a business concept (i.e. CustomerFee, CustomerCommission, etc) and you don't need any injected dependency to make it work I would say it's a Value Object.

For instance, imagine that you want to calculate the price of a reservation which depends on the fee you will charge to the customer (among other params):

ReservationPrice(CustomerFee customerFee, ItemPrice ItemPrice)

Now your CustomerFee is also calculated based on (say any variable) something.

This way you are modeling your calculations just with Value Objects which allows you to show in your code all the different business concepts they depend on. Also anyone looking at your code and files structure can get an idea about what you are calculating.


问:
Rails - Named scopes
for my user's model I have:

```<code>class User < ActiveRecord::Base
  has_many :group_users, :class_name => "User", :finder_sql => 'select DISTINCT u.* from users u join permissions pp on pp.user_id=u.id join spaces p on pp.space_id=p.id where space_id in (select space_id from permissions pp2 where user_id=#{id}) and pp.user_id != #{id}'
</code>```

How can I access that in a scope like:

```<code>  scope :usersInMySpaces, lambda { |user|
      group_users
  }
</code>```

thanks

答: You can't and there's no point. has_many associations act like scopes in many cases but in this one the finder_sql is so complicated that it couldn't be combined with any other sql as a scope.

Title: Rails - Named scopes

Body:
for my user's model I have:

class User < ActiveRecord::Base
  has_many :group_users, :class_name => "User", :finder_sql => 'select DISTINCT u.* from users u join permissions pp on pp.user_id=u.id join spaces p on pp.space_id=p.id where space_id in (select space_id from permissions pp2 where user_id=#{id}) and pp.user_id != #{id}'

How can I access that in a scope like:

  scope :usersInMySpaces, lambda { |user|
      group_users
  }

thanks


问:
Equality check for two boolean expressions (TSQL)
I have two tables and I want to join two tables based on the sign of the related columns

I'm joining on the condition a<0 = b<0 but the equality sign gives me a syntax error. I don't want to do (a<0 AND b<0) OR (Not a<0 AND Not b<0) because it doesn't look clean

答:
You know what the answer is:

```<code>where (a < 0 and b < 0) or (a >= 0 and b >= 0)
</code>```

SQL Server doesn't treat boolean values as bona fide values, so you cannot treat them as regular values in other types of expressions.

You can express this using bitwise or ('^') if you really want:

```<code>where (case when a < 0 and b < 0 then 1 else 0 end) ^ (case when a >= 0 and b >= 0 then 1 else 0 end) = 1
</code>```

However, I find that rather inscrutable.

Body:
You know what the answer is:

where (a < 0 and b < 0) or (a >= 0 and b >= 0)

SQL Server doesn't treat boolean values as bona fide values, so you cannot treat them as regular values in other types of expressions.

You can express this using bitwise or ('^') if you really want:

where (case when a < 0 and b < 0 then 1 else 0 end) ^ (case when a >= 0 and b >= 0 then 1 else 0 end) = 1

However, I find that rather inscrutable.


问:
Chaining Promises In Loop
I am struggling to loop through the array periods whilst querying the DB and inserting data. The problem I am facing can be seen on the 5th from last line. The final db.queryPromise does not get invoked.

Please see comment 5 lines from the bottom for where the problem is.

```<code>// db.js

const mysql = require('mysql');

const connection = mysql.createConnection({
    host     : 'localhost',
    user     : ****,
    password : ****,
    database : ****,
});

module.exports = connection;

module.exports.queryPromise = function (args) {
  return new Promise((resolve, reject) => {
    connection.query(args, (err, rows, fields) => {
      if (err) return reject(err);
      resolve(rows);
    });
  });
};

module.exports.connectPromise = new Promise((resolve, reject) => {
  connection.connect(err => {
    if (err) reject(err);
    resolve();
  });
});

// app.js
const db = require('../config/db');

const periods = ['1h','12h','24h','1w','1m','3m','1y','all'];
const sqlCarIds = `SELECT id FROM car_models ORDER BY id DESC LIMIT 200;`;

return db.queryPromise(sqlCarIds)
.then((rows) => {
  const car_ids = [];
  for (let i = rows.length - 1; i >= 0; i--) {
    car_ids.push(rows[i].car_id);
  };

  for (let i = periods.length - 1; i >= 0; i--) {

    const sqlSnapshot = `SELECT price FROM car_models;`;

    db.queryPromise(sqlSnapshot)
    .then(([row]) => {
      if (!row) {
        throw new Error('API call found nothin');
      }

      const highPrice = row.high;
      const sqlInsert = `INSERT into price_cache (high) VALUES (` + highPrice` + )`;`

      console.log(sqlInsert); // logs correctly formed query
      db.queryPromise(sqlInsert)
      .then(() => {
        console.log('this should fire'); // doesn't fire
      });
    });
  }
});
</code>```

答:
The SQL syntax for the sqlInsert is invalid. You will need to write it like following example. You need to use the ${expression} literals to add the value of an expression into a "Template String". Your promise doesn't get resolved because there is an error which rejects it.

```<code>const sqlInsert = `INSERT into price_cache (high) VALUES (${highPrice})`;
</code>```

Title: Chaining Promises In Loop

Body:
I am struggling to loop through the array periods whilst querying the DB and inserting data. The problem I am facing can be seen on the 5th from last line. The final db.queryPromise does not get invoked.

Please see comment 5 lines from the bottom for where the problem is.

// db.js

const mysql = require('mysql');

const connection = mysql.createConnection({
    host     : 'localhost',
    user     : ****,
    password : ****,
    database : ****,
});

module.exports = connection;

module.exports.queryPromise = function (args) {
  return new Promise((resolve, reject) => {
    connection.query(args, (err, rows, fields) => {
      if (err) return reject(err);
      resolve(rows);
    });
  });
};

module.exports.connectPromise = new Promise((resolve, reject) => {
  connection.connect(err => {
    if (err) reject(err);
    resolve();
  });
});

// app.js
const db = require('../config/db');

const periods = ['1h','12h','24h','1w','1m','3m','1y','all'];
const sqlCarIds = `SELECT id FROM car_models ORDER BY id DESC LIMIT 200;`;

return db.queryPromise(sqlCarIds)
.then((rows) => {
  const car_ids = [];
  for (let i = rows.length - 1; i >= 0; i--) {
    car_ids.push(rows[i].car_id);
  };

  for (let i = periods.length - 1; i >= 0; i--) {

    const sqlSnapshot = `SELECT price FROM car_models;`;

    db.queryPromise(sqlSnapshot)
    .then(([row]) => {
      if (!row) {
        throw new Error('API call found nothin');
      }

      const highPrice = row.high;
      const sqlInsert = `INSERT into price_cache (high) VALUES (` + highPrice` + )`;`

      console.log(sqlInsert); // logs correctly formed query
      db.queryPromise(sqlInsert)
      .then(() => {
        console.log('this should fire'); // doesn't fire
      });
    });
  }
});

Body:
The SQL syntax for the sqlInsert is invalid. You will need to write it like following example. You need to use the ${expression} literals to add the value of an expression into a "Template String". Your promise doesn't get resolved because there is an error which rejects it.

const sqlInsert = `INSERT into price_cache (high) VALUES (${highPrice})`;


问:
Xamarin Forms PopModalAsync()
Working with Xamarin Forms, on iOS, pusing a modal using

```<code>  await Navigation.PushModalAsync(new mypage());
</code>```

When I call

```<code>  await Navigation.PopModalAsync();
</code>```

from mypage it pops all the way back to root instead of where I just called push from.   There's no code anywhere else interacting with the modally pushed page

答:
Maybe try pushing in this way: </p>

```<code>await ((MainPage)App.Current.MainPage).Detail.Navigation.PushAsync(new mypage());
</code>```

<p>And then call: </p>

```<code> Navigation.PopAsync();
</code>```

Title: Xamarin Forms PopModalAsync()

Body:
Working with Xamarin Forms, on iOS, pusing a modal using

  await Navigation.PushModalAsync(new mypage());

When I call

  await Navigation.PopModalAsync();

from mypage it pops all the way back to root instead of where I just called push from.   There's no code anywhere else interacting with the modally pushed page

Body:
Maybe try pushing in this way:

await ((MainPage)App.Current.MainPage).Detail.Navigation.PushAsync(new mypage());

And then call:

 Navigation.PopAsync();


问:
SAP HANA: Create a join with a max on date
I am busy with a SAP HANA development but ran into an issue with currency conversion.

On the left of a join, I have a projection with the Sales Order Number, Customer Requested Delivery Date and order value in Document Currency (from VBAK/VBAP).  On the right of the join, I have a projection containing the TCURR table (from SAP), filtered on MAER (monthly average exchange rate) and the "from currency" joined to document currency from the Sales Order.  I need to convert the value in document currency say to EUR but must select the latest exchange rate available in TCURR.   How do I do the join? So effectively, I need to join the date from the Sales Order to max( Exchange Rate Date) but must be less than or equal to the Sales Order date.

答:
Could you please check following HANA db SQLScript

I used multiple SQL CTE expressions on HANA SQLScript to get the most recent entry for each currency conversion to EUR
And then join this CTE tables (last one CTE3) to VBAK table

I actually did not do the amount convertion using the currency rate, I think you can handle it using multiplication or division, etc on the SELECT list

```<code>with cte as (
    select
        to_date( to_nvarchar(99999999 - gdatu) ) gdate,
        *
    from "SAPS4S".TCURR
    where tcurr = 'EUR'
), cte2 as (
    select
        row_number() over (partition by fcurr, YEAR(gdate), MONTH(gdate) order by gdate desc) as rn,
         YEAR(gdate) as gdate_year,
         MONTH(gdate) as gdate_month,
        *
    from cte
), cte3 as (
    select * from cte2 where rn = 1
)
select
    vbeln,
    erdat,
    netwr,
    waerk,
    cte3.*
from "SAPS4S".VBAK as vbak
left join cte3
    on
        vbak.waerk = cte3.fcurr and
        YEAR(vbak.erdat) = cte3.gdate_year and
        MONTH(vbak.erdat) = cte3.gdate_month;
</code>```

Hello Ernie,
According to your second comment, I changed the SQLScript query a bit as follows

```<code>with cte as (
    select
        to_date( to_nvarchar(99999999 - gdatu) ) gdate,
        *
    from "SAPABAP1".TCURR
    where tcurr = 'EUR'
), cte2 as (
select
    vbeln,
    erdat,
    netwr,
    waerk,
    sum(1) over (partition by vbeln order by gdate desc rows unbounded preceding) as rownum,
    cte.*
from "SAPABAP1".VBAK as vbak
left join cte
    on
        vbak.waerk = cte.fcurr and
        vbak.erdat >= cte.gdate
)
select *
from cte2
where ifnull(rownum,1) = 1
</code>```

I'll be happy if it works on your database and get your feedback

There are NULL records coming from TCURR table because there is no currency rate entry or the document currency is already defined as EUR (actually the rates should be then equal to 1)

Body:
Could you please check following HANA db SQLScript

I used multiple SQL CTE expressions on HANA SQLScript to get the most recent entry for each currency conversion to EUR
And then join this CTE tables (last one CTE3) to VBAK table

I actually did not do the amount convertion using the currency rate, I think you can handle it using multiplication or division, etc on the SELECT list

with cte as (
    select
        to_date( to_nvarchar(99999999 - gdatu) ) gdate,
        *
    from "SAPS4S".TCURR
    where tcurr = 'EUR'
), cte2 as (
    select
        row_number() over (partition by fcurr, YEAR(gdate), MONTH(gdate) order by gdate desc) as rn,
         YEAR(gdate) as gdate_year,
         MONTH(gdate) as gdate_month,
        *
    from cte
), cte3 as (
    select * from cte2 where rn = 1
)
select
    vbeln,
    erdat,
    netwr,
    waerk,
    cte3.*
from "SAPS4S".VBAK as vbak
left join cte3
    on
        vbak.waerk = cte3.fcurr and
        YEAR(vbak.erdat) = cte3.gdate_year and
        MONTH(vbak.erdat) = cte3.gdate_month;

Hello Ernie,
According to your second comment, I changed the SQLScript query a bit as follows

with cte as (
    select
        to_date( to_nvarchar(99999999 - gdatu) ) gdate,
        *
    from "SAPABAP1".TCURR
    where tcurr = 'EUR'
), cte2 as (
select
    vbeln,
    erdat,
    netwr,
    waerk,
    sum(1) over (partition by vbeln order by gdate desc rows unbounded preceding) as rownum,
    cte.*
from "SAPABAP1".VBAK as vbak
left join cte
    on
        vbak.waerk = cte.fcurr and
        vbak.erdat >= cte.gdate
)
select *
from cte2
where ifnull(rownum,1) = 1

I'll be happy if it works on your database and get your feedback

There are NULL records coming from TCURR table because there is no currency rate entry or the document currency is already defined as EUR (actually the rates should be then equal to 1)


问:
Getting java.sql.SQLException: XA error: XAResource.XAER_PROTO start() failed on resource error in weblogic 12c
I am getting below exception in the application log while getting a connection from data source. Though it is showing "caused by: cannot start a new transaction" in the exception, I am not starting new transaction anywhere.

I am facing this issue intermittently, it does not occur every time.

I am using web logic 12c (weblogic version 12.1.3.0.0) & using thin/XA driver.

I am facing this issue only on production environment other environment doesn't have the issue.

Using oracle 12.1.0.2.0 as a database

using ojdbc6.jar (Oracle jdbc driver version 12.1.0.2.0 JDBC 4.0 )

Exception I am getting,

```<code>cause:java.sql.SQLException: Unexpected exception while enlisting XAConnection java.sql.SQLException: XA error: XAResource.XAER_PROTO start() failed on resource 'myds': XAER_PROTO : Routine was invoked in an inproper context
    oracle.jdbc.xa.OracleXAException
        at oracle.jdbc.xa.OracleXAResource.checkError(OracleXAResource.java:1229)
        at oracle.jdbc.xa.client.OracleXAResource.start(OracleXAResource.java:246)
        at weblogic.jdbc.jta.DataSource.start(DataSource.java:830)
        at weblogic.transaction.internal.XAServerResourceInfo.start(XAServerResourceInfo.java:1311)
        at weblogic.transaction.internal.XAServerResourceInfo.xaStart(XAServerResourceInfo.java:1244)
        at weblogic.transaction.internal.XAServerResourceInfo.enlist(XAServerResourceInfo.java:292)
        at weblogic.transaction.internal.ServerTransactionImpl.enlistResource(ServerTransactionImpl.java:585)
        at weblogic.transaction.internal.ServerTransactionImpl.enlistResource(ServerTransactionImpl.java:490)
        at weblogic.jdbc.jta.DataSource.enlist(DataSource.java:1749)
        at weblogic.jdbc.jta.DataSource.refreshXAConnAndEnlist(DataSource.java:1651)
        at weblogic.jdbc.jta.DataSource.getConnectionInternal(DataSource.java:517)
        at weblogic.jdbc.jta.DataSource.getConnection(DataSource.java:494)
        at weblogic.jdbc.common.internal.RmiDataSource.getConnectionInternal(RmiDataSource.java:565)
        at weblogic.jdbc.common.internal.RmiDataSource.getConnection(RmiDataSource.java:545)
        at weblogic.jdbc.common.internal.RmiDataSource.getConnection(RmiDataSource.java:538)
    ....
    .....
    Caused by: java.sql.SQLException: ORA-24776: cannot start a new transaction
        at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:450)
        at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:392)
        at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:385)
        at oracle.jdbc.driver.T4CTTIfun.processError(T4CTTIfun.java:1018)
        at oracle.jdbc.driver.T4CTTIfun.receive(T4CTTIfun.java:522)
        at oracle.jdbc.driver.T4CTTIfun.doRPC(T4CTTIfun.java:257)
        at oracle.jdbc.driver.T4CTTIOtxse.doOTXSE(T4CTTIOtxse.java:164)
        at oracle.jdbc.driver.T4CXAResource.doStart(T4CXAResource.java:188)
        at oracle.jdbc.xa.client.OracleXAResource.start(OracleXAResource.java:241)
        ... 60 more
        at weblogic.jdbc.jta.DataSource.enlist(DataSource.java:1754)
        at weblogic.jdbc.jta.DataSource.refreshXAConnAndEnlist(DataSource.java:1651)
        at weblogic.jdbc.jta.DataSource.getConnectionInternal(DataSource.java:517)
        at weblogic.jdbc.jta.DataSource.getConnection(DataSource.java:494)
        at weblogic.jdbc.common.internal.RmiDataSource.getConnectionInternal(RmiDataSource.java:565)
        at weblogic.jdbc.common.internal.RmiDataSource.getConnection(RmiDataSource.java:545)
        at weblogic.jdbc.common.internal.RmiDataSource.getConnection(RmiDataSource.java:538)
</code>```

We are thinking it might be incompatible JDBC driver issue, but is it right finding or we may need to check something else?

答:
have you configured your db for xa by running initxa.sql script ? If not, then use the following :
[ be careful to replicate this environment to another machine other than production ]

```<code>$ sqlplus / a sysdba
SQL> @?/javavm/install/initxa.sql -- this file is located at $ORACLE_HOME/javavm/install directory.
</code>```

if you fail due to database's memory lackage, run the initjvm.sql script( located at the same directory ),

```<code>SQL> @?/javavm/install/initjvm.sql
</code>```

during execution it will indicate which parameters need to be adjusted.

Probably, it might tell you to increase java_pool_size & shared_pool_size, and do so in that case.

Body:
I am getting below exception in the application log while getting a connection from data source. Though it is showing "caused by: cannot start a new transaction" in the exception, I am not starting new transaction anywhere.

I am facing this issue intermittently, it does not occur every time.

I am using web logic 12c (weblogic version 12.1.3.0.0) & using thin/XA driver.

I am facing this issue only on production environment other environment doesn't have the issue.

Using oracle 12.1.0.2.0 as a database

using ojdbc6.jar (Oracle jdbc driver version 12.1.0.2.0 JDBC 4.0 )

Exception I am getting,

cause:java.sql.SQLException: Unexpected exception while enlisting XAConnection java.sql.SQLException: XA error: XAResource.XAER_PROTO start() failed on resource 'myds': XAER_PROTO : Routine was invoked in an inproper context
    oracle.jdbc.xa.OracleXAException
        at oracle.jdbc.xa.OracleXAResource.checkError(OracleXAResource.java:1229)
        at oracle.jdbc.xa.client.OracleXAResource.start(OracleXAResource.java:246)
        at weblogic.jdbc.jta.DataSource.start(DataSource.java:830)
        at weblogic.transaction.internal.XAServerResourceInfo.start(XAServerResourceInfo.java:1311)
        at weblogic.transaction.internal.XAServerResourceInfo.xaStart(XAServerResourceInfo.java:1244)
        at weblogic.transaction.internal.XAServerResourceInfo.enlist(XAServerResourceInfo.java:292)
        at weblogic.transaction.internal.ServerTransactionImpl.enlistResource(ServerTransactionImpl.java:585)
        at weblogic.transaction.internal.ServerTransactionImpl.enlistResource(ServerTransactionImpl.java:490)
        at weblogic.jdbc.jta.DataSource.enlist(DataSource.java:1749)
        at weblogic.jdbc.jta.DataSource.refreshXAConnAndEnlist(DataSource.java:1651)
        at weblogic.jdbc.jta.DataSource.getConnectionInternal(DataSource.java:517)
        at weblogic.jdbc.jta.DataSource.getConnection(DataSource.java:494)
        at weblogic.jdbc.common.internal.RmiDataSource.getConnectionInternal(RmiDataSource.java:565)
        at weblogic.jdbc.common.internal.RmiDataSource.getConnection(RmiDataSource.java:545)
        at weblogic.jdbc.common.internal.RmiDataSource.getConnection(RmiDataSource.java:538)
    ....
    .....
    Caused by: java.sql.SQLException: ORA-24776: cannot start a new transaction
        at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:450)
        at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:392)
        at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:385)
        at oracle.jdbc.driver.T4CTTIfun.processError(T4CTTIfun.java:1018)
        at oracle.jdbc.driver.T4CTTIfun.receive(T4CTTIfun.java:522)
        at oracle.jdbc.driver.T4CTTIfun.doRPC(T4CTTIfun.java:257)
        at oracle.jdbc.driver.T4CTTIOtxse.doOTXSE(T4CTTIOtxse.java:164)
        at oracle.jdbc.driver.T4CXAResource.doStart(T4CXAResource.java:188)
        at oracle.jdbc.xa.client.OracleXAResource.start(OracleXAResource.java:241)
        ... 60 more
        at weblogic.jdbc.jta.DataSource.enlist(DataSource.java:1754)
        at weblogic.jdbc.jta.DataSource.refreshXAConnAndEnlist(DataSource.java:1651)
        at weblogic.jdbc.jta.DataSource.getConnectionInternal(DataSource.java:517)
        at weblogic.jdbc.jta.DataSource.getConnection(DataSource.java:494)
        at weblogic.jdbc.common.internal.RmiDataSource.getConnectionInternal(RmiDataSource.java:565)
        at weblogic.jdbc.common.internal.RmiDataSource.getConnection(RmiDataSource.java:545)
        at weblogic.jdbc.common.internal.RmiDataSource.getConnection(RmiDataSource.java:538)

We are thinking it might be incompatible JDBC driver issue, but is it right finding or we may need to check something else?

Body:
have you configured your db for xa by running initxa.sql script ? If not, then use the following :
[ be careful to replicate this environment to another machine other than production ]

$ sqlplus / a sysdba
SQL> @?/javavm/install/initxa.sql -- this file is located at $ORACLE_HOME/javavm/install directory.

if you fail due to database's memory lackage, run the initjvm.sql script( located at the same directory ),

SQL> @?/javavm/install/initjvm.sql

during execution it will indicate which parameters need to be adjusted.

Probably, it might tell you to increase java_pool_size & shared_pool_size, and do so in that case.


问:
How to find maximum value in a list of arrays
I have a very large list of arrays that looks something like this:

```<code>'apples': array([1,2,3,4]), 'pears': array([1,2,10,11]),'oranges': array([1,10,10,3])
</code>```

I want to find the maximum value out of all the arrays. In my short example above it would be 11.

I am struggling to write something that would give me the maximum value for all arrays in the list. Any thoughts would be welcome.

答:
Your list is actually a dictionary, so you can do this:

```<code>arr = {'apples': [1,2,3,4], 'pears': [1,2,10,11],'oranges': [1,10,10,3]}
res = max(map(max, arr.values()))
print(res)
</code>```

Output:

```<code>11
</code>```

You can also do it using the chain function from itertools module:

```<code>from itertools import chain

arr = {'apples': [1,2,3,4], 'pears': [1,2,10,11],'oranges': [1,10,10,3]}
res = max(chain(max(i) for i in arr.values()))
print(res)
</code>```

Output:

```<code>11
</code>```

Body:
I have a very large list of arrays that looks something like this:

'apples': array([1,2,3,4]), 'pears': array([1,2,10,11]),'oranges': array([1,10,10,3])

I want to find the maximum value out of all the arrays. In my short example above it would be 11.

I am struggling to write something that would give me the maximum value for all arrays in the list. Any thoughts would be welcome.

Body:
Your list is actually a dictionary, so you can do this:

arr = {'apples': [1,2,3,4], 'pears': [1,2,10,11],'oranges': [1,10,10,3]}
res = max(map(max, arr.values()))
print(res)

Output:

11

You can also do it using the chain function from itertools module:

from itertools import chain

arr = {'apples': [1,2,3,4], 'pears': [1,2,10,11],'oranges': [1,10,10,3]}
res = max(chain(max(i) for i in arr.values()))
print(res)

Output:

11


问:
MySQL joining multiple sql results when all data is in one table
I have a table containing lots of data with several fields including:

```<code>day (Monday ~ Sunday)
City (NY, LA, FL, etc.)
</code>```

I would like to use php to make a table to display totals like this:

```<code>  --- Mon --- Tue --- Wed ...
NY    6       8       9
LA    7       5       3
FL    1       0       4
</code>```

But I am having trouble to write the SQL to make this work. I have used union but that appends the result at the bottom, so it seems I need to use inner join, or not even it. The two queries that I can get remotely close to what I want are:

select city, count(id) as 'Monday' from index where city = "NY" and day = 'Monday' group by city
union all
select city, count(id) as 'Monday' from index where city = 'LA' and day = 'Monday' group by city
union all
select city, count(id) as 'Monday' from index where city = 'FL' and day = 'Monday' group by city

This produces the following result

  --- Mon

  NY    6

  LA        7

  FL        1

The problem with this is I don't know how to add the rest of the days to the right of it

Another query I have tried is

select a.day, a.counts as 'NY', b.counts as 'LA' from
(select day, count(id) as counts from index where city='NY' GROUP BY DAY) as a
left join
(select day, count(id) as counts from index where city='LA' GROUP BY DAY) as b
on (a.day = b.day)
order by field (a.day, 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday')

This produces the following result

                 NY --- LA ---

  Monday      6        7

  Tuesday        8        5

And the problem with this one is the row and column should be swapped, also I don't know how to add another city (I have many cities).

All the data is in one table called "index". Could someone give me the guidance on how to write the SQL? I would also need the field to show 0 or Null when there is no record. The end goal is to produce the table with PHP.

Thank you for taking the time to read and answer.

答:
I don't have your schema so I'm taking a few liberties. You probably want something like this:

Ps: Depending on your db you may be able to replace the sum(case...) with the proper sumif function

```<code>SELECT
  city,
  sum(case when day = 'Monday' then 1 else 0 end) AS 'Monday',
  sum(case when day = 'Tuesday' then 1 else 0 end) AS 'Tuesday',
  sum(case when day = 'Wednesday' then 1 else 0 end) AS 'Wednesday',
  sum(case when day = 'Thursday' then 1 else 0 end) AS 'Thursday',
  sum(case when day = 'Friday' then 1 else 0 end) AS 'Friday',
  sum(case when day = 'Saturday' then 1 else 0 end) AS 'Saturday',
  sum(case when day = 'Sunday' then 1 else 0 end) AS 'Sunday'
FROM your_table
GROUP BY city
</code>```

Let me know if it helps

Body:
I have a table containing lots of data with several fields including:

day (Monday ~ Sunday)
City (NY, LA, FL, etc.)

I would like to use php to make a table to display totals like this:

  --- Mon --- Tue --- Wed ...
NY    6       8       9
LA    7       5       3
FL    1       0       4

But I am having trouble to write the SQL to make this work. I have used union but that appends the result at the bottom, so it seems I need to use inner join, or not even it. The two queries that I can get remotely close to what I want are:

select city, count(id) as 'Monday' from index where city = "NY" and day = 'Monday' group by city
union all
select city, count(id) as 'Monday' from index where city = 'LA' and day = 'Monday' group by city
union all
select city, count(id) as 'Monday' from index where city = 'FL' and day = 'Monday' group by city

This produces the following result

  --- Mon

  NY    6

  LA        7

  FL        1

The problem with this is I don't know how to add the rest of the days to the right of it

Another query I have tried is

select a.day, a.counts as 'NY', b.counts as 'LA' from
(select day, count(id) as counts from index where city='NY' GROUP BY DAY) as a
left join
(select day, count(id) as counts from index where city='LA' GROUP BY DAY) as b
on (a.day = b.day)
order by field (a.day, 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday')

This produces the following result

                 NY --- LA ---

  Monday      6        7

  Tuesday        8        5

And the problem with this one is the row and column should be swapped, also I don't know how to add another city (I have many cities).

All the data is in one table called "index". Could someone give me the guidance on how to write the SQL? I would also need the field to show 0 or Null when there is no record. The end goal is to produce the table with PHP.

Thank you for taking the time to read and answer.

Body:
I don't have your schema so I'm taking a few liberties. You probably want something like this:

Ps: Depending on your db you may be able to replace the sum(case...) with the proper sumif function

SELECT
  city,
  sum(case when day = 'Monday' then 1 else 0 end) AS 'Monday',
  sum(case when day = 'Tuesday' then 1 else 0 end) AS 'Tuesday',
  sum(case when day = 'Wednesday' then 1 else 0 end) AS 'Wednesday',
  sum(case when day = 'Thursday' then 1 else 0 end) AS 'Thursday',
  sum(case when day = 'Friday' then 1 else 0 end) AS 'Friday',
  sum(case when day = 'Saturday' then 1 else 0 end) AS 'Saturday',
  sum(case when day = 'Sunday' then 1 else 0 end) AS 'Sunday'
FROM your_table
GROUP BY city

Let me know if it helps