问:
Why does setBounds() method not work even after setting setLayout() as null?
Usually setBounds() method positions the called object in the specified location and in specified size..right?
I created a JFrame class and demonstrated its working on a button with setting setLayout(null).
Then I created a class which extends JPanel and put some components in it.
The Bounds for these components are set inside a method.
An object of this class is included in a class which extends JFrame.
Then this object calls setBound() method.
But the result does not show the components in JPanel extended class.
the cde fragment is given below.</p>

```<code>class Administrator extends JFrame implements ActionListener
{
  public Administrator()
  {
    setTitle("Administration");
    setSize(500,500);
    setDefaultCloseOperation(EXIT_ON_CLOSE);
    setLayout(null);
    JButton newbutton=new JButton(" New.. ");
    newbutton.addActionListener(this);
    add(newbutton);
    newbutton.setBounds(100,100,100,25);
    setVisible(true);

    public static void main(String arg[])
    {
      new Administrator();
    }

    public void actionPerformed(ActionEvent ae)
  {
    String act=(String)ae.getActionCommand();
    if(act.equals("New Registry..")||act.equals(" New.. "))
     {
        regPanel rgpnl=new regPanel();

        Dimension sz;
        sz=rgpnl.getPreferredSize();
        rgpnl.setBounds(800,800,sz.width,sz.height);
        rgpnl.arrangeComponents();
        add(rgpnl);

        repaint();
        setVisible(true);
     }
}
class regPanel extends JPanel
{
  Label namelab;
  JTextField name;
  JButton do_register;
  public regPanel()
  {
    //Container   = get ();
    setLayout(null);

    namelab=new Label("Name :");
    name=new JTextField(20);
    add(namelab);
    add(name);
    add(do_register);
   }
   public void arrangeComponents()
  {
    Dimension size;

    size=namelab.getPreferredSize();
    namelab.setBounds(20,10,size.width,size.height);
    name.getPreferredSize();
    name.setBounds(150,10,size.width,size.height);
    do_register.setBounds(10,10,size.width,size.height);

    repaint();

  }
}
</code>```

答: Apart from some questionable parts of your code -- like missing curly brackets, null pointers and such errors -- your code creates components at (800,800) while the interface is only 500x500 px in size. This will put the components out-of-view. Put the components at a smaller offset from the window origin and they will show. (I tested this, along with some modifications to your code, like the order in which calls are made with respect to setLayout(null). This call should seemingly occur at the right time, otherwise the components wouldn't show for me.)

Body:
Usually setBounds() method positions the called object in the specified location and in specified size..right?
I created a JFrame class and demonstrated its working on a button with setting setLayout(null).
Then I created a class which extends JPanel and put some components in it.
The Bounds for these components are set inside a method.
An object of this class is included in a class which extends JFrame.
Then this object calls setBound() method.
But the result does not show the components in JPanel extended class.
the cde fragment is given below.

class Administrator extends JFrame implements ActionListener
{
  public Administrator()
  {
    setTitle("Administration");
    setSize(500,500);
    setDefaultCloseOperation(EXIT_ON_CLOSE);
    setLayout(null);
    JButton newbutton=new JButton(" New.. ");
    newbutton.addActionListener(this);
    add(newbutton);
    newbutton.setBounds(100,100,100,25);
    setVisible(true);

    public static void main(String arg[])
    {
      new Administrator();
    }

    public void actionPerformed(ActionEvent ae)
  {
    String act=(String)ae.getActionCommand();
    if(act.equals("New Registry..")||act.equals(" New.. "))
     {
        regPanel rgpnl=new regPanel();

        Dimension sz;
        sz=rgpnl.getPreferredSize();
        rgpnl.setBounds(800,800,sz.width,sz.height);
        rgpnl.arrangeComponents();
        add(rgpnl);

        repaint();
        setVisible(true);
     }
}
class regPanel extends JPanel
{
  Label namelab;
  JTextField name;
  JButton do_register;
  public regPanel()
  {
    //Container   = get ();
    setLayout(null);

    namelab=new Label("Name :");
    name=new JTextField(20);
    add(namelab);
    add(name);
    add(do_register);
   }
   public void arrangeComponents()
  {
    Dimension size;

    size=namelab.getPreferredSize();
    namelab.setBounds(20,10,size.width,size.height);
    name.getPreferredSize();
    name.setBounds(150,10,size.width,size.height);
    do_register.setBounds(10,10,size.width,size.height);

    repaint();

  }
}

ContentLicense: CC BY-SA 2.5


来源: stackexchange

问:
lodash pick: set value if key not set
I have the following two arrays:

```<code>var headerKeys = ["title","name","address"]
var resultsArr = [
    { title:"test 1", name: "test1", unrelatedKey: "blah" },
    { title:"test 2", name: "test2" }
]
</code>```

I'd like to clean up resultsArr such that it only has the keys found in headerKeys.
My desired output looks like this:

```<code>[
    { title:"test 1", name: "test1", address: "" },
    { title:"test 2", name: "test2", address: "" }
]
</code>```

This is the code I'm currently using:

```<code>_.chain(resultsArr).map(function(item){
    return _.chain(item).pick(headerKeys).value()
}).value()
</code>```

This outputs:

```<code>[
    { title:"test 1", name: "test1" },
    { title:"test 2", name: "test2" }
]
</code>```

It's pretty close to what I want, but it will not show address since it isn't set. Is there anyway to force it to show the key even if it has no value?

Also, if you have suggestions on how to improve my lodash chain, that would be great.

答:
You can use _.defaults() to add the missing keys:

var headerKeys = ["title","name","address"]
var resultsArr = [
    { title:"test 1", name: "test1", unrelatedKey: "blah" },
    { title:"test 2", name: "test2" }
];

/** create once the defaults object from the headerKeys **/
var defaultsObj = _(headerKeys)
  .mapKeys()
  .mapValues(function() { return ""; })
  .value();

var result = resultsArr.map(function(obj) {
  return _(obj)
    .pick(headerKeys)
    .defaults(defaultsObj) // apply the defaults
    .value();
});

console.log(result);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script></code>```

ContentLicense: CC BY-SA 3.0

Title: lodash pick: set value if key not set

Body:
I have the following two arrays:

var headerKeys = ["title","name","address"]
var resultsArr = [
    { title:"test 1", name: "test1", unrelatedKey: "blah" },
    { title:"test 2", name: "test2" }
]

I'd like to clean up resultsArr such that it only has the keys found in headerKeys.
My desired output looks like this:

[
    { title:"test 1", name: "test1", address: "" },
    { title:"test 2", name: "test2", address: "" }
]

This is the code I'm currently using:

_.chain(resultsArr).map(function(item){
    return _.chain(item).pick(headerKeys).value()
}).value()

This outputs:

[
    { title:"test 1", name: "test1" },
    { title:"test 2", name: "test2" }
]

It's pretty close to what I want, but it will not show address since it isn't set. Is there anyway to force it to show the key even if it has no value?

Also, if you have suggestions on how to improve my lodash chain, that would be great.

Body:
You can use _.defaults() to add the missing keys:

var headerKeys = ["title","name","address"]
var resultsArr = [
    { title:"test 1", name: "test1", unrelatedKey: "blah" },
    { title:"test 2", name: "test2" }
];

/** create once the defaults object from the headerKeys **/
var defaultsObj = _(headerKeys)
  .mapKeys()
  .mapValues(function() { return ""; })
  .value();

var result = resultsArr.map(function(obj) {
  return _(obj)
    .pick(headerKeys)
    .defaults(defaultsObj) // apply the defaults
    .value();
});

console.log(result);

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


问:
Trouble with string mining from rvest results
I'm mining species data from this page which offers no API or downloadable list:

```<code>    library(rvest)
      moltres<-1:30
     for (i in moltres){
      temphtml<-read_html(paste0("http://checklist.aou.org/taxa/",i)) %>%
      html_node("section") %>%
      html_text()
      pidgey<-rbind(pidgey, temphtml)
      }
</code>```

Outcome comes like this, for each item on the list:

```<code>"\n  \n      species: \n      Chen canagica (Emperor Goose, Oie empereur)\n  \n\n\n\nNOTE: This is an invalidated taxon. It is a 'synonym' for 12681, which has superseded it.\n\n\n\n\t\n  Compare AOU treatments of \n    \n        Chen canagica,\n in Avibase\n     (1886 to present).\n  \n\n\tSearch for \n    \n        Chen canagica\n at Cornell Birds of North America.\n  \n\n\n\n\n    Annotation: Monotypic.\n\n\n\n\n\n\n\n\n\t"
</code>```

I'm trying to extract the code 12681 in every "It is a 'synonym' for 12681"
(these are the up-to-date names of the species)

I tried with:

```<code>pidgey$sub<-sub(".*synonim (.*?)\\,.*", "\\1", pidgey)
</code>```

but it makes a big mess with the original list I 'rvested, and at the end there's a column which doesn't contain what I want, I think it has to do with the text format,
I appreciate your help enormously

答:
I'm not sure if the text changes due to locale, but this will match "synonym" or "synonim" and get the # you desire:</p>

```<code>library(rvest)
library(dplyr)
library(purrr)
library(stringi)

moltres <- 1:30

pb <- progress_estimated(length(moltres))
map_df(moltres, ~{

  pb$tick()$print()

  Sys.sleep(sample(1:5, 1)) # be kind, you have time and the resource is free

  pg <- read_html(sprintf("http://checklist.aou.org/taxa/%s", .x))

  data_frame(
    res = .x,
    txt = html_node(pg, "section") %>% html_text()
  )

}) -> xdf

xdf$synon <- stri_match_first_regex(xdf$txt, "'synon[yi]m' for ([[:digit:]]+)")[,2]

select(xdf, synon) %>%
  print(n=30)
## # A tibble: 30 x 1
##    synon
##    <chr>
##  1  <NA>
##  2  <NA>
##  3  <NA>
##  4  <NA>
##  5  <NA>
##  6  <NA>
##  7  <NA>
##  8  <NA>
##  9  <NA>
## 10  <NA>
## 11  <NA>
## 12  <NA>
## 13  <NA>
## 14  <NA>
## 15  <NA>
## 16 12681
## 17 12691
## 18 12701
## 19  <NA>
## 20  <NA>
## 21  <NA>
## 22  <NA>
## 23  <NA>
## 24  <NA>
## 25  <NA>
## 26  <NA>
## 27  <NA>
## 28  <NA>
## 29  <NA>
## 30  <NA>
</code>```

Body:
I'm mining species data from this page which offers no API or downloadable list:

    library(rvest)
      moltres<-1:30
     for (i in moltres){
      temphtml<-read_html(paste0("http://checklist.aou.org/taxa/",i)) %>%
      html_node("section") %>%
      html_text()
      pidgey<-rbind(pidgey, temphtml)
      }

Outcome comes like this, for each item on the list:

"\n  \n      species: \n      Chen canagica (Emperor Goose, Oie empereur)\n  \n\n\n\nNOTE: This is an invalidated taxon. It is a 'synonym' for 12681, which has superseded it.\n\n\n\n\t\n  Compare AOU treatments of \n    \n        Chen canagica,\n in Avibase\n     (1886 to present).\n  \n\n\tSearch for \n    \n        Chen canagica\n at Cornell Birds of North America.\n  \n\n\n\n\n    Annotation: Monotypic.\n\n\n\n\n\n\n\n\n\t"

I'm trying to extract the code 12681 in every "It is a 'synonym' for 12681"
(these are the up-to-date names of the species)

I tried with:

pidgey$sub<-sub(".*synonim (.*?)\\,.*", "\\1", pidgey)

but it makes a big mess with the original list I 'rvested, and at the end there's a column which doesn't contain what I want, I think it has to do with the text format,
I appreciate your help enormously

Body:
I'm not sure if the text changes due to locale, but this will match "synonym" or "synonim" and get the # you desire:

library(rvest)
library(dplyr)
library(purrr)
library(stringi)

moltres <- 1:30

pb <- progress_estimated(length(moltres))
map_df(moltres, ~{

  pb$tick()$print()

  Sys.sleep(sample(1:5, 1)) # be kind, you have time and the resource is free

  pg <- read_html(sprintf("http://checklist.aou.org/taxa/%s", .x))

  data_frame(
    res = .x,
    txt = html_node(pg, "section") %>% html_text()
  )

}) -> xdf

xdf$synon <- stri_match_first_regex(xdf$txt, "'synon[yi]m' for ([[:digit:]]+)")[,2]

select(xdf, synon) %>%
  print(n=30)
## # A tibble: 30 x 1
##    synon
##    <chr>
##  1  <NA>
##  2  <NA>
##  3  <NA>
##  4  <NA>
##  5  <NA>
##  6  <NA>
##  7  <NA>
##  8  <NA>
##  9  <NA>
## 10  <NA>
## 11  <NA>
## 12  <NA>
## 13  <NA>
## 14  <NA>
## 15  <NA>
## 16 12681
## 17 12691
## 18 12701
## 19  <NA>
## 20  <NA>
## 21  <NA>
## 22  <NA>
## 23  <NA>
## 24  <NA>
## 25  <NA>
## 26  <NA>
## 27  <NA>
## 28  <NA>
## 29  <NA>
## 30  <NA>


问:
Redirect HTTP to HTTPS:PORT in Tomcat
I have a running tomcat application that already have the following redirection rule from HTTP to HTTPs:

<Connector executor="tomcatThreadPool"
           port="80"
           protocol="HTTP/1.1"
           connectionTimeout="20000"
           redirectPort="443" />
```

Is it possible to add an exception/rule, that a specific HTTPrequest (http://www.example.com), will be redirected to another specific address , with a port specified (say https://www.example.com:8443/test), without changing/removing the above Connector ?

答:
You can do it to every app deployed to tomcat by adding this to the end of tomcat_dir/conf/web.xml:

<security-constraint>
    <web-resource-collection>
        <web-resource-name>Entire Application</web-resource-name>
        <url-pattern>/*</url-pattern>
    </web-resource-collection>

    <user-data-constraint>
        <transport-guarantee>CONFIDENTIAL</transport-guarantee>
    </user-data-constraint>
</security-constraint>
```
<p>So you don't have to change it on the web.xml of your webapp.</p>
<p>That should work, <strong>assuming you already have https working in another port (usually 443)</strong>. If you don't, make sure your <code>tomcat_dir/conf/server.xml</code> looks like this:</p>
<pre class="lang-xml prettyprint-override"><code><!-- Default tomcat connector, changed the redirectPort from 8443 to 443 -->
<Connector port="8080" protocol="HTTP/1.1"
               connectionTimeout="20000"
               redirectPort="443" />

<!-- To make https work on port 443 -->
<Connector port="443" protocol="org.apache.coyote.http11.Http11NioProtocol"
        maxThreads="150" SSLEnabled="true">
    <UpgradeProtocol className="org.apache.coyote.http2.Http2Protocol"/>
    <SSLHostConfig>
        <Certificate certificateKeyFile="/your/own/privkey.pem"
            certificateFile="/eyour/own/cert.pem"
            certificateChainFile="/your/own/chain.pem"
            type="RSA" />
    </SSLHostConfig>
</Connector>
</code>```

ContentLicense: CC BY-SA 4.0

Title: Redirect HTTP to HTTPS:PORT in Tomcat

Body:
I have a running tomcat application that already have the following redirection rule from HTTP to HTTPs:

<Connector executor="tomcatThreadPool"
           port="80"
           protocol="HTTP/1.1"
           connectionTimeout="20000"
           redirectPort="443" />

Is it possible to add an exception/rule, that a specific HTTPrequest (http://www.example.com), will be redirected to another specific address , with a port specified (say https://www.example.com:8443/test), without changing/removing the above Connector ?

Body:
You can do it to every app deployed to tomcat by adding this to the end of tomcat_dir/conf/web.xml:

<security-constraint>
    <web-resource-collection>
        <web-resource-name>Entire Application</web-resource-name>
        <url-pattern>/*</url-pattern>
    </web-resource-collection>
    <!-- auth-constraint goes here if you requre authentication -->
    <user-data-constraint>
        <transport-guarantee>CONFIDENTIAL</transport-guarantee>
    </user-data-constraint>
</security-constraint>

So you don't have to change it on the web.xml of your webapp.

That should work, assuming you already have https working in another port (usually 443). If you don't, make sure your tomcat_dir/conf/server.xml looks like this:

<!-- Default tomcat connector, changed the redirectPort from 8443 to 443 -->
<Connector port="8080" protocol="HTTP/1.1"
               connectionTimeout="20000"
               redirectPort="443" />

<!-- To make https work on port 443 -->
<Connector port="443" protocol="org.apache.coyote.http11.Http11NioProtocol"
        maxThreads="150" SSLEnabled="true">
    <UpgradeProtocol className="org.apache.coyote.http2.Http2Protocol"/>
    <SSLHostConfig>
        <Certificate certificateKeyFile="/your/own/privkey.pem"
            certificateFile="/eyour/own/cert.pem"
            certificateChainFile="/your/own/chain.pem"
            type="RSA" />
    </SSLHostConfig>
</Connector>


问:
Prevent FAB from going down when scrolling in RecyclerView in fragment
I'm new to android development and recently learning about fragments.

I have a recyclerview inside fragment, and I want it to be attached to the toolbar, I tried put app:layout_behavior="@string/appbar_scrolling_view_behavior"
inside the container layout but whenever the toolbar shows the FAB moves down below the navigation bar as you can see here.

activity_main.XML

```<code>    <?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout
    android:id="@+id/main_screen"
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.atar.mango.MainActivity">

    <android.support.design.widget.CoordinatorLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <android.support.design.widget.AppBarLayout
            android:id="@+id/app_bar"
            android:orientation="vertical"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

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

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

        <FrameLayout
            android:id="@+id/container"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            app:layout_behavior="@string/appbar_scrolling_view_behavior"/>

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

    <android.support.design.widget.NavigationView
        android:id="@+id/nav_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        app:headerLayout="@layout/logo_header"
        app:menu="@menu/menu_for_navigation_view"/>

</android.support.v4.widget.DrawerLayout>
</code>```

home_fragment.XML

```<code>    <android.support.design.widget.CoordinatorLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.atar.mango.HomeFragment"
    android:background="@color/background">

    <TextView
        android:id="@+id/empty"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:text="@string/empty"
        android:gravity="center"
        android:textSize="90sp"
        android:textColor="#32000000"/>

    <android.support.v7.widget.RecyclerView
        android:id="@+id/notes"
        app:backgroundTint="@color/background"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:scrollbars="none"
        android:overScrollMode="never">

    </android.support.v7.widget.RecyclerView>

    <android.support.design.widget.FloatingActionButton
        android:id="@+id/add_note"
        app:backgroundTint="@color/options"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom|end"
        android:layout_marginRight="@dimen/fab_margin_right"
        android:layout_marginEnd="@dimen/fab_margin_right"
        app:layout_anchorGravity="bottom|right|end"
        android:layout_marginBottom="16dp"
        android:src="@mipmap/add_note"
        app:borderWidth="0dp"
        android:elevation="6dp"
        app:pressedTranslationZ="12dp"
        app:fabSize="normal"/>

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

Thanks.

答:
I think you must specify your layout target,
in this way:</p>

```<code><android.support.design.widget.FloatingActionButton
 ...
    android:layout_gravity="bottom|end|right"
    app:layout_anchor="@id/notes"
    app:layout_anchorGravity="bottom|right|end"
/>
</code>```

Body:
I'm new to android development and recently learning about fragments.

I have a recyclerview inside fragment, and I want it to be attached to the toolbar, I tried put app:layout_behavior="@string/appbar_scrolling_view_behavior"
inside the container layout but whenever the toolbar shows the FAB moves down below the navigation bar as you can see here.

activity_main.XML

    <?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout
    android:id="@+id/main_screen"
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.atar.mango.MainActivity">

    <android.support.design.widget.CoordinatorLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <android.support.design.widget.AppBarLayout
            android:id="@+id/app_bar"
            android:orientation="vertical"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

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

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

        <FrameLayout
            android:id="@+id/container"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            app:layout_behavior="@string/appbar_scrolling_view_behavior"/>

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

    <android.support.design.widget.NavigationView
        android:id="@+id/nav_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        app:headerLayout="@layout/logo_header"
        app:menu="@menu/menu_for_navigation_view"/>

</android.support.v4.widget.DrawerLayout>

home_fragment.XML

    <android.support.design.widget.CoordinatorLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.atar.mango.HomeFragment"
    android:background="@color/background">

    <TextView
        android:id="@+id/empty"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:text="@string/empty"
        android:gravity="center"
        android:textSize="90sp"
        android:textColor="#32000000"/>

    <android.support.v7.widget.RecyclerView
        android:id="@+id/notes"
        app:backgroundTint="@color/background"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:scrollbars="none"
        android:overScrollMode="never">

    </android.support.v7.widget.RecyclerView>

    <android.support.design.widget.FloatingActionButton
        android:id="@+id/add_note"
        app:backgroundTint="@color/options"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom|end"
        android:layout_marginRight="@dimen/fab_margin_right"
        android:layout_marginEnd="@dimen/fab_margin_right"
        app:layout_anchorGravity="bottom|right|end"
        android:layout_marginBottom="16dp"
        android:src="@mipmap/add_note"
        app:borderWidth="0dp"
        android:elevation="6dp"
        app:pressedTranslationZ="12dp"
        app:fabSize="normal"/>

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

Thanks.

Body:
I think you must specify your layout target,
in this way:

<android.support.design.widget.FloatingActionButton
 ...
    android:layout_gravity="bottom|end|right"
    app:layout_anchor="@id/notes"
    app:layout_anchorGravity="bottom|right|end"
/>


问:
WPF pre-render a list w/o actually showing it
Is there a way to "pre-render" a list in WPF without actually showing it to the user? I have a list that renders fairly slowly ( a few seconds ) the first time it is displayed to the user.

I'd like to pre-render/pre-draw the list so that the few seconds it takes to display the list to the users is not noticeable. I'd like this to happen while the app is starting up - while my splash screen is displayed.

What is the best way to accomplish this?

EDIT:

Here is my list item style. As you can see the target type is a Button. The button also has a RoutedEvent (Command) set on it.

```<code><Style x:Key="Button_ProductFinder_Item" TargetType="Button">
    <Setter Property="Control.Template">
        <Setter.Value>
            <ControlTemplate TargetType="Button">

                <Grid Width="690" Height="181"   >

                    <Image Name="Up" Source="{StaticResource Img_ProductFinder_FriendUp}" Stretch="Uniform"/>
                    <Image Name="Down" Source="{StaticResource Img_ProductFinder_FriendDn}" Visibility="Hidden" Stretch="Uniform"/>

                    <Canvas Name="Clip" ClipToBounds="True" Height="162" Width="175" HorizontalAlignment="Left" Margin="0,10,0,0" >
                        <Image Name="DynamicFriend"  Stretch="UniformToFill" Canvas.Left="16" Canvas.Top="-10" HorizontalAlignment="Left"  Source="{Binding ImageSource}" Height="162" Width="162" />
                        <Canvas.RenderTransform>
                            <TransformGroup>
                                <TranslateTransform />
                            </TransformGroup>
                        </Canvas.RenderTransform>
                    </Canvas>

                    <TextBlock Name="DynamicName" Margin="210,69,0,0"  Style="{StaticResource ButtonFriend_Textstyle}"
                                   TextWrapping="Wrap" HorizontalAlignment="Left" Width="440" VerticalAlignment="Stretch" Height="Auto"
                                   Text="{Binding ProductName}"  />
                </Grid>

                <ControlTemplate.Triggers>
                    <Trigger Property="IsPressed" Value="True">
                        <Setter TargetName="Up" Property="Visibility" Value="Hidden"/>
                        <Setter TargetName="Down" Property="Visibility" Value="Visible"/>
                        <Setter TargetName="Clip" Property="RenderTransform">
                            <Setter.Value>
                                <TransformGroup>
                                    <TranslateTransform Y="2"/>
                                </TransformGroup>
                            </Setter.Value>
                        </Setter>
                        <Setter TargetName="DynamicName" Property="RenderTransform">
                            <Setter.Value>
                                <TransformGroup>
                                    <TranslateTransform Y="2"/>
                                </TransformGroup>
                            </Setter.Value>
                        </Setter>
                        <Setter TargetName="DynamicName" Property="Foreground" Value="#FFFFFF"/>
                        <Trigger.EnterActions>
                            <ctrls:ButtonSoundPlayerAction SoundFile="buttonclick.wav"/>
                        </Trigger.EnterActions>
                    </Trigger>
                </ControlTemplate.Triggers>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>
</code>```

答:
You could always set the list (or the whole window the list is contained in) to collapsed in it's initial state, and then un-collapse it when you get word back from your data retrieval thread that it is done.

I have done that with a couple of my other programs and it works pretty well.

User executes the program, splash screen displays, and main window loads collapsed.

Data retrieval thread executes, gets data, reports it is finished.

Splash screen disappears, main window displays and list is populated.


问:
Big model table view solution Swift
I have a question about what in your opinion is the best way to handle my problem.

The case is, I have models that are really big and contain lots of data. These are stored in a database and sent to the client. Now I would like to show this data in way of table views. Showing the data is not the problem but the best way to access it is.

My question is: What is a smart way to handle big data models in table view cells

So to give an example I have model that contains say 30 variables.
Now I have a page view controller with a table view in there where on the first page I would like to show variable 1,2,5,6,7,9,10 and the next page 1,2,21,23,24,22 (of 100 objects) and above the page there is a little indicator what the number or string means.

So I thought of a solution with Swift 4

```<code>typealias listTypeObject = (name: String, minSize: Int, object: KeyPath<Any, Any>)
</code>```

A problem here is that you can not convert key path types so it can not accept my key paths. So this will not work not in this state at least. If someone knows a solution for this that would be amazing!

The other solution would be creating every list by hand with the header and content separate. This will cost me a lot of lines of code that I would imagine could be much smaller.

I hope someone can show me a better way or just tell me that the best way is by hand.

Thanks a lot!

Update 1:
code example// This is the list with the pages

```<code>enum listTypes {
    case player
    case playerPoints
    case team
}

// I have a base model
class BaseModel {

    var id: Int = 0
    let updated: Date = Date()

    init(id: Int) {
        self.id = id
    }
}

// I have multiple final models like this but bigger
final class PlayerModel: BaseModel {
    var firstName: String = "John"
    var surname: String = "Doe"

    var pointsInFootball: Int = 60
    var pointsInBasketball: Int = 23

    init(id: Int, firstName: String, surname: String, pointsInFootball: Int, pointsInBasketball: Int) {
        super.init(id: id)

        self.firstName = firstName
        self.surname = surname

        self.pointsInFootball = pointsInFootball
        self.pointsInBasketball = pointsInBasketball
    }
}

final class TeamModel: BaseModel {
    var name: String = "TeamTest"
}

// Lets create the example
var dataArray: [BaseModel] = []

// Add some test objects to the array
for i in 0..<10 {
    let object = PlayerModel(id: i, firstName: "John\(i)", surname: "Doe\(i)", pointsInFootball: 10 * i, pointsInBasketball: 5 * i)
    dataArray.append(object)
}

// So now in the list I would like to say what is accessible for the table view
// listTypes.player = PlayerModel: firstName - surname - age
// listTypes.playerPoints = PlayerModel: firstName - pointsInFootball - pointsInBasketball - pointsInSkiing
// But list type team should be
// listTypes.team = TeamModel: name
</code>```

答: From what i understand, I think you should use enums. By using an array of enums, it can isolate the variables you want to present, and you won't have to create unique tableViews in order to accomplish this. You just pass an array to the tableView delegate/datasouce functions. Without a code example / further information, this is all I can deduce. </p>

Title: Big model table view solution Swift

Body:
I have a question about what in your opinion is the best way to handle my problem.

The case is, I have models that are really big and contain lots of data. These are stored in a database and sent to the client. Now I would like to show this data in way of table views. Showing the data is not the problem but the best way to access it is.

My question is: What is a smart way to handle big data models in table view cells

So to give an example I have model that contains say 30 variables.
Now I have a page view controller with a table view in there where on the first page I would like to show variable 1,2,5,6,7,9,10 and the next page 1,2,21,23,24,22 (of 100 objects) and above the page there is a little indicator what the number or string means.

So I thought of a solution with Swift 4

typealias listTypeObject = (name: String, minSize: Int, object: KeyPath<Any, Any>)

A problem here is that you can not convert key path types so it can not accept my key paths. So this will not work not in this state at least. If someone knows a solution for this that would be amazing!

The other solution would be creating every list by hand with the header and content separate. This will cost me a lot of lines of code that I would imagine could be much smaller.

I hope someone can show me a better way or just tell me that the best way is by hand.

Thanks a lot!

Update 1:
code example// This is the list with the pages

enum listTypes {
    case player
    case playerPoints
    case team
}

// I have a base model
class BaseModel {

    var id: Int = 0
    let updated: Date = Date()

    init(id: Int) {
        self.id = id
    }
}

// I have multiple final models like this but bigger
final class PlayerModel: BaseModel {
    var firstName: String = "John"
    var surname: String = "Doe"

    var pointsInFootball: Int = 60
    var pointsInBasketball: Int = 23

    init(id: Int, firstName: String, surname: String, pointsInFootball: Int, pointsInBasketball: Int) {
        super.init(id: id)

        self.firstName = firstName
        self.surname = surname

        self.pointsInFootball = pointsInFootball
        self.pointsInBasketball = pointsInBasketball
    }
}

final class TeamModel: BaseModel {
    var name: String = "TeamTest"
}

// Lets create the example
var dataArray: [BaseModel] = []

// Add some test objects to the array
for i in 0..<10 {
    let object = PlayerModel(id: i, firstName: "John\(i)", surname: "Doe\(i)", pointsInFootball: 10 * i, pointsInBasketball: 5 * i)
    dataArray.append(object)
}

// So now in the list I would like to say what is accessible for the table view
// listTypes.player = PlayerModel: firstName - surname - age
// listTypes.playerPoints = PlayerModel: firstName - pointsInFootball - pointsInBasketball - pointsInSkiing
// But list type team should be
// listTypes.team = TeamModel: name


问:
Why my jquery hide and show methods are not working for online offline link
I have small app that displays twitchTV channels and users. When I click on "online" link, only online users are display. and the same goes when I click on
"offline" link. (navigation var) the problem is I don't see the the logic taking effect on the page. What am I missing? thanks

var status;
var names = ["ESL_SC2", "OgamingSC2", "cretetion", "freecodecamp", "storbeck", "habathcx", "RobotCaleb", "noobs2ninjas"]
var url = "https://wind-bow.gomix.me/twitch-api/";

$(document).ready(function() {
  $("#allusers").click(function() {
    $("#onlineuser").show();
    $("#offlineuser").show();
  });
  $("#online").click(function() {
    $("#onlineuser").show();
    $("#offlineuser").hide();

  });
  $("#offline").click(function() {
    $("#offlineuser").show();
    $("#onlineuser").hide();
  });
  getData();
});

function getData() {
  //for every single stream/channel a url need build
  for (var i = 0; i < names.length; i++) {
    getStreams(url, "streams", names[i]);
    getChannel(url, "channels", names[i]);
  }
}

//getting stream status json data
function getStreams(url, type, name) {
  url += '/' + type + '/' + name + '?callback=?';
  // console.log(url);
  $.getJSON(url, function(data) {
    console.log(data);
    if (data.stream !== null) {
      status = "online";
      // console.log(data);
    } else {
      status = "offline";
    }
  });
}

//getting channel json data
function getChannel(url, type, name) {
  url += type + '/' + name + '?callback=?';
  // console.log(url);
  $.getJSON(url, function(data) {
    // console.log(data);
    var output = document.getElementById("output");
    var logo = data.logo;
    var title = data.status;
    var channel = data.url;
    // console.log(logo +", "+title+", "+channel);
    //formatting individual channels

    output.innerHTML += '

' + name + '

' + status + '

' + ((title.length > 40) ? title.substring(0, 40).concat("...") : title) + '

';
  });
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
  background-color: #445f44;
}

.user-data {
  padding-top: 10px;
  padding-left: 5px;
  padding-right: 5px;
  color: black;
  font-size: 17px;
  background-color: white;
  opacity: 0.5;
  margin-bottom: 5px;
}

#header {
  background-color: #333854
}

#user {
  font-size: 20px;
  padding-left: 10px;
  padding-right: 10px;
}

img {
  width: 50px;
  height: 50px;
  border-radius: 300px;
  border-color: green;
  border-width: 1px;
  border-style: solid;
}

.border {
  border-style: solid;
  border-width: 1px;
  color: white;
}</code>```

TwitchTV Streamers

All Users

Online

Offline

```

答:
Seems like you are trying to use an id to target multiple elements, try using classes instead.

ex:

$("#online").click(function(){
  $(".onlineuser").show();
  $(".offlineuser").hide();
});

output.innerHTML += '

'+name+'

'+status+'

'+((title.length > 40) ? title.substring(0, 40).concat("...") : title)+'

'; ```

Link to a codepen with these changes: https://codepen.io/anon/pen/awKBEM

Body:
I have small app that displays twitchTV channels and users. When I click on "online" link, only online users are display. and the same goes when I click on
"offline" link. (navigation var) the problem is I don't see the the logic taking effect on the page. What am I missing? thanks

var status;
var names = ["ESL_SC2", "OgamingSC2", "cretetion", "freecodecamp", "storbeck", "habathcx", "RobotCaleb", "noobs2ninjas"]
var url = "https://wind-bow.gomix.me/twitch-api/";

$(document).ready(function() {
  $("#allusers").click(function() {
    $("#onlineuser").show();
    $("#offlineuser").show();
  });
  $("#online").click(function() {
    $("#onlineuser").show();
    $("#offlineuser").hide();

  });
  $("#offline").click(function() {
    $("#offlineuser").show();
    $("#onlineuser").hide();
  });
  getData();
});

function getData() {
  //for every single stream/channel a url need build
  for (var i = 0; i < names.length; i++) {
    getStreams(url, "streams", names[i]);
    getChannel(url, "channels", names[i]);
  }
}

//getting stream status json data
function getStreams(url, type, name) {
  url += '/' + type + '/' + name + '?callback=?';
  // console.log(url);
  $.getJSON(url, function(data) {
    console.log(data);
    if (data.stream !== null) {
      status = "online";
      // console.log(data);
    } else {
      status = "offline";
    }
  });
}

//getting channel json data
function getChannel(url, type, name) {
  url += type + '/' + name + '?callback=?';
  // console.log(url);
  $.getJSON(url, function(data) {
    // console.log(data);
    var output = document.getElementById("output");
    var logo = data.logo;
    var title = data.status;
    var channel = data.url;
    // console.log(logo +", "+title+", "+channel);
    //formatting individual channels

    output.innerHTML += '

' + name + '

' + status + '

' + ((title.length > 40) ? title.substring(0, 40).concat("...") : title) + '

';
  });
}

body {
  background-color: #445f44;
}

.user-data {
  padding-top: 10px;
  padding-left: 5px;
  padding-right: 5px;
  color: black;
  font-size: 17px;
  background-color: white;
  opacity: 0.5;
  margin-bottom: 5px;
}

#header {
  background-color: #333854
}

#user {
  font-size: 20px;
  padding-left: 10px;
  padding-right: 10px;
}

img {
  width: 50px;
  height: 50px;
  border-radius: 300px;
  border-color: green;
  border-width: 1px;
  border-style: solid;
}

.border {
  border-style: solid;
  border-width: 1px;
  color: white;
}

TwitchTV Streamers

All Users

Online

Offline

Body:
Seems like you are trying to use an id to target multiple elements, try using classes instead.

ex:

$("#online").click(function(){
  $(".onlineuser").show();
  $(".offlineuser").hide();
});

output.innerHTML += '<div class="'+status+'user channel row user-data"><div ><img id="logo" src="'+logo+'"></div><a href="'+channel+'" target="_blank"><h5 id="user">'+name+'</h5></a><div class="col-md-2 user-data"><strong>'+status+'</strong></div><div id="title" class="col-md-5 user-data">'+((title.length > 40) ? title.substring(0, 40).concat("...") : title)+'</div></div>';

Link to a codepen with these changes: https://codepen.io/anon/pen/awKBEM


问:
Java RMI server to client communication not working
I'm developing a game which use server communication with socket and RMI. I'm quite new to RMI and i'm encountering some problems while trying to communicate between a server and a client which are not on the same PC.
In localhost it work flawlessy, otherwise communication don't work as expected.
Here some code snippets:

```<code>public RMIServer (ServerInterface mainServer){
    this.mainServer = mainServer;
}

public void startServer() throws IOException {
    Registry registry  = createOrLoadRegistry(Server.RMIPORT);
    try {
        System.out.println("Insert server ip address: ");
        Scanner in = new Scanner(System.in);
        String address = in.nextLine();
        in.close();
        System.setProperty("java.rmi.server.hostname", address);
        registry.bind("RMIServerInterface", this);
        UnicastRemoteObject.exportObject(this, Server.RMIPORT+1);
    } catch (RemoteException | AlreadyBoundException e) {
        System.err.println(e.getMessage());
    }
}

private Registry createOrLoadRegistry(int port) throws IOException{
    try {
        System.out.println("creating register.. ");
        return LocateRegistry.createRegistry(port);
    } catch (RemoteException e) {
        System.err.println(e.getMessage());
    }
    try {
        return LocateRegistry.getRegistry(port);
    } catch (RemoteException e) {
        System.err.println(e.getMessage());
    }
    return null;
}
</code>```

Socket works very good instead.

EDIT:
To let RMI work in first place I was forced to use:

```<code>System.setProperty("java.rmi.server.hostname")

enter code here
</code>```

because server IP was randomly set to 127.0.1.1 (loopback).
I printed the stack track on server side and this was the result:

```<code>    creating register..
Insert server ip address:
192.168.1.73
Socket server is ready
Recieved RMI client connection
create first room..
cchvo has been added to room
Number of players: 1
java.rmi.ConnectException: Connection refused to host: 127.0.1.1; nested exception is:
  java.net.ConnectException: Connessione rifiutata (Connection refused)
  at sun.rmi.transport.tcp.TCPEndpoint.newSocket(TCPEndpoint.java:619)
  at sun.rmi.transport.tcp.TCPChannel.createConnection(TCPChannel.java:216)
  at sun.rmi.transport.tcp.TCPChannel.newConnection(TCPChannel.java:202)
  at sun.rmi.server.UnicastRef.invoke(UnicastRef.java:130)
  at java.rmi.server.RemoteObjectInvocationHandler.invokeRemoteMethod(RemoteObjectInvocationHandler.java:227)
  at java.rmi.server.RemoteObjectInvocationHandler.invoke(RemoteObjectInvocationHandler.java:179)
  at com.sun.proxy.$Proxy1.notifyNewPlayer(Unknown Source)
  at server.RMIPlayer.notifyNewPlayer(RMIPlayer.java:28)
  at server.Room.notifyNewPlayer(Room.java:147)
  at server.Room.addPlayer(Room.java:106)
  at server.Server.createRoom(Server.java:98)
  at server.Server.addPlayerFirstAvailableRoom(Server.java:119)
  at server.RMIServer.addRoom(RMIServer.java:82)
  at server.RMIServer.loginPlayer(RMIServer.java:75)
  at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
  at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
  at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
  at java.lang.reflect.Method.invoke(Method.java:498)
  at sun.rmi.server.UnicastServerRef.dispatch(UnicastServerRef.java:346)
  at sun.rmi.transport.Transport$1.run(Transport.java:200)
  at sun.rmi.transport.Transport$1.run(Transport.java:197)
  at java.security.AccessController.doPrivileged(Native Method)
  at sun.rmi.transport.Transport.serviceCall(Transport.java:196)
  at sun.rmi.transport.tcp.TCPTransport.handleMessages(TCPTransport.java:568)
  at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run0(TCPTransport.java:826)
  at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.lambda$run$0(TCPTransport.java:683)
  at java.security.AccessController.doPrivileged(Native Method)
  at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run(TCPTransport.java:682)
  at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
  at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
  at java.lang.Thread.run(Thread.java:748)
Caused by: java.net.ConnectException: Connessione rifiutata (Connection refused)
  at java.net.PlainSocketImpl.socketConnect(Native Method)
  at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:350)
  at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:206)
  at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:188)
  at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
  at java.net.Socket.connect(Socket.java:589)
  at java.net.Socket.connect(Socket.java:538)
  at java.net.Socket.<init>(Socket.java:434)
  at java.net.Socket.<init>(Socket.java:211)
  at sun.rmi.transport.proxy.RMIDirectSocketFactory.createSocket(RMIDirectSocketFactory.java:40)
  at sun.rmi.transport.proxy.RMIMasterSocketFactory.createSocket(RMIMasterSocketFactory.java:148)
  at sun.rmi.transport.tcp.TCPEndpoint.newSocket(TCPEndpoint.java:613)
  ... 30 more
</code>```

答:
You're doing everything in the wrong order.

Set java.rmi.server.hostname.

Export the remote object.

Create the Registry.

Bind the remote object to the Registry.

Body:
I'm developing a game which use server communication with socket and RMI. I'm quite new to RMI and i'm encountering some problems while trying to communicate between a server and a client which are not on the same PC.
In localhost it work flawlessy, otherwise communication don't work as expected.
Here some code snippets:

public RMIServer (ServerInterface mainServer){
    this.mainServer = mainServer;
}

public void startServer() throws IOException {
    Registry registry  = createOrLoadRegistry(Server.RMIPORT);
    try {
        System.out.println("Insert server ip address: ");
        Scanner in = new Scanner(System.in);
        String address = in.nextLine();
        in.close();
        System.setProperty("java.rmi.server.hostname", address);
        registry.bind("RMIServerInterface", this);
        UnicastRemoteObject.exportObject(this, Server.RMIPORT+1);
    } catch (RemoteException | AlreadyBoundException e) {
        System.err.println(e.getMessage());
    }
}

private Registry createOrLoadRegistry(int port) throws IOException{
    try {
        System.out.println("creating register.. ");
        return LocateRegistry.createRegistry(port);
    } catch (RemoteException e) {
        System.err.println(e.getMessage());
    }
    try {
        return LocateRegistry.getRegistry(port);
    } catch (RemoteException e) {
        System.err.println(e.getMessage());
    }
    return null;
}

Socket works very good instead.

EDIT:
To let RMI work in first place I was forced to use:

System.setProperty("java.rmi.server.hostname")

enter code here

because server IP was randomly set to 127.0.1.1 (loopback).
I printed the stack track on server side and this was the result:

    creating register..
Insert server ip address:
192.168.1.73
Socket server is ready
Recieved RMI client connection
create first room..
cchvo has been added to room
Number of players: 1
java.rmi.ConnectException: Connection refused to host: 127.0.1.1; nested exception is:
  java.net.ConnectException: Connessione rifiutata (Connection refused)
  at sun.rmi.transport.tcp.TCPEndpoint.newSocket(TCPEndpoint.java:619)
  at sun.rmi.transport.tcp.TCPChannel.createConnection(TCPChannel.java:216)
  at sun.rmi.transport.tcp.TCPChannel.newConnection(TCPChannel.java:202)
  at sun.rmi.server.UnicastRef.invoke(UnicastRef.java:130)
  at java.rmi.server.RemoteObjectInvocationHandler.invokeRemoteMethod(RemoteObjectInvocationHandler.java:227)
  at java.rmi.server.RemoteObjectInvocationHandler.invoke(RemoteObjectInvocationHandler.java:179)
  at com.sun.proxy.$Proxy1.notifyNewPlayer(Unknown Source)
  at server.RMIPlayer.notifyNewPlayer(RMIPlayer.java:28)
  at server.Room.notifyNewPlayer(Room.java:147)
  at server.Room.addPlayer(Room.java:106)
  at server.Server.createRoom(Server.java:98)
  at server.Server.addPlayerFirstAvailableRoom(Server.java:119)
  at server.RMIServer.addRoom(RMIServer.java:82)
  at server.RMIServer.loginPlayer(RMIServer.java:75)
  at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
  at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
  at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
  at java.lang.reflect.Method.invoke(Method.java:498)
  at sun.rmi.server.UnicastServerRef.dispatch(UnicastServerRef.java:346)
  at sun.rmi.transport.Transport$1.run(Transport.java:200)
  at sun.rmi.transport.Transport$1.run(Transport.java:197)
  at java.security.AccessController.doPrivileged(Native Method)
  at sun.rmi.transport.Transport.serviceCall(Transport.java:196)
  at sun.rmi.transport.tcp.TCPTransport.handleMessages(TCPTransport.java:568)
  at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run0(TCPTransport.java:826)
  at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.lambda$run$0(TCPTransport.java:683)
  at java.security.AccessController.doPrivileged(Native Method)
  at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run(TCPTransport.java:682)
  at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
  at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
  at java.lang.Thread.run(Thread.java:748)
Caused by: java.net.ConnectException: Connessione rifiutata (Connection refused)
  at java.net.PlainSocketImpl.socketConnect(Native Method)
  at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:350)
  at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:206)
  at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:188)
  at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
  at java.net.Socket.connect(Socket.java:589)
  at java.net.Socket.connect(Socket.java:538)
  at java.net.Socket.<init>(Socket.java:434)
  at java.net.Socket.<init>(Socket.java:211)
  at sun.rmi.transport.proxy.RMIDirectSocketFactory.createSocket(RMIDirectSocketFactory.java:40)
  at sun.rmi.transport.proxy.RMIMasterSocketFactory.createSocket(RMIMasterSocketFactory.java:148)
  at sun.rmi.transport.tcp.TCPEndpoint.newSocket(TCPEndpoint.java:613)
  ... 30 more


问:
Exception Load Errors, for files that exist (even in multiple places?)
I am finding these errors (via debug) and don't understand why I'm getting them.   I'm not sure if I have duplicate files for a reason either.  I'm using .rvm and it has a gems directory with a ruby directory inside of it, but there is also .rvm/rubies/ruby-'version' directory.  I was trying to find some info about the ruby and gem folder structure but so far haven't had much luck.

In other words maybe it's possible I have multiple versions of Ruby or something isn't right?

Example rubygems.rb

```<code>Exception `LoadError' at /home/vagrant/.rvm/rubies/ruby-2.4.1/lib/ruby/site_ruby/2.4.0/rubygems.rb:1346 - cannot load such file -- rubygems
defaults/operating_system

**Yet I did a find the file**
./vagrant/.rvm/rubies/ruby-2.4.1/lib/ruby/2.4.0/rubygems.rb
./vagrant/.rvm/rubies/ruby-2.4.1/lib/ruby/site_ruby/2.4.0/rubygems.rb
./vagrant/.rvm/rubies/ruby-2.4.1/lib/ruby/gems/2.4.0/gems/bundler-1.15.0/lib/bundler/plugin/installer/rubygems.rb
./vagrant/.rvm/rubies/ruby-2.4.1/lib/ruby/gems/2.4.0/gems/bundler-1.15.0/lib/bundler/source/rubygems.rb
./vagrant/.rvm/gems/ruby-2.4.1/gems/bundler-1.15.1/lib/bundler/plugin/installer/rubygems.rb
./vagrant/.rvm/gems/ruby-2.4.1/gems/bundler-1.15.1/lib/bundler/source/rubygems.rb
./vagrant/.rvm/gems/ruby-2.4.1/gems/rubygems-update-2.6.12/bundler/lib/bundler/plugin/installer/rubygems.rb
./vagrant/.rvm/gems/ruby-2.4.1/gems/rubygems-update-2.6.12/bundler/lib/bundler/source/rubygems.rb
./vagrant/.rvm/gems/ruby-2.4.1/gems/rubygems-update-2.6.12/lib/rubygems.rb
vagrant@vagrant:/home$
</code>```

Here is one for kernel_require.rb

```<code>Exception `LoadError' at /home/vagrant/.rvm/rubies/ruby-2.4.1/lib/ruby/site_ruby/2.4.0/rubygems/core_ext/kernel_require.rb:55 - cannot load
such file -- sinatra
</code>```

Yet Sinatra was running

here are the kernel_requires

```<code>./vagrant/.rvm/rubies/ruby-2.4.1/lib/ruby/2.4.0/rubygems/core_ext/kernel_require.rb
./vagrant/.rvm/rubies/ruby-2.4.1/lib/ruby/site_ruby/2.4.0/rubygems/core_ext/kernel_require.rb
./vagrant/.rvm/gems/ruby-2.4.1/gems/rubygems-update-2.6.12/lib/rubygems/core_ext/kernel_require.rb
</code>```

答:
At first I thought there was another Ruby -v not being managed however I went through the RVM structure and see no discrepancies.

Anyone interested in seeing the directory structure (it wasn't on RVM site), I found it here.

It then came down to my load errors.  I found a post in Ruby trunk issues that said load error, no file found for rubygems.rb was normal, if you are running debug.  I believe it is looking at outside sources of rubygems?.

The last issue was syntax errors for /forwardable/impl.rb.  This was because, again debug was set.  Now I'm not entirely sure what the message means, but the line referenced, 6, is 'resue SyntaxError'.

So I learned a bit more using RVM , gems and some on bundler.  Side note, I was able to use bundle exec on the Sinatra app.

Body:
I am finding these errors (via debug) and don't understand why I'm getting them.   I'm not sure if I have duplicate files for a reason either.  I'm using .rvm and it has a gems directory with a ruby directory inside of it, but there is also .rvm/rubies/ruby-'version' directory.  I was trying to find some info about the ruby and gem folder structure but so far haven't had much luck.

In other words maybe it's possible I have multiple versions of Ruby or something isn't right?

Example rubygems.rb

Exception `LoadError' at /home/vagrant/.rvm/rubies/ruby-2.4.1/lib/ruby/site_ruby/2.4.0/rubygems.rb:1346 - cannot load such file -- rubygems
defaults/operating_system

**Yet I did a find the file**
./vagrant/.rvm/rubies/ruby-2.4.1/lib/ruby/2.4.0/rubygems.rb
./vagrant/.rvm/rubies/ruby-2.4.1/lib/ruby/site_ruby/2.4.0/rubygems.rb
./vagrant/.rvm/rubies/ruby-2.4.1/lib/ruby/gems/2.4.0/gems/bundler-1.15.0/lib/bundler/plugin/installer/rubygems.rb
./vagrant/.rvm/rubies/ruby-2.4.1/lib/ruby/gems/2.4.0/gems/bundler-1.15.0/lib/bundler/source/rubygems.rb
./vagrant/.rvm/gems/ruby-2.4.1/gems/bundler-1.15.1/lib/bundler/plugin/installer/rubygems.rb
./vagrant/.rvm/gems/ruby-2.4.1/gems/bundler-1.15.1/lib/bundler/source/rubygems.rb
./vagrant/.rvm/gems/ruby-2.4.1/gems/rubygems-update-2.6.12/bundler/lib/bundler/plugin/installer/rubygems.rb
./vagrant/.rvm/gems/ruby-2.4.1/gems/rubygems-update-2.6.12/bundler/lib/bundler/source/rubygems.rb
./vagrant/.rvm/gems/ruby-2.4.1/gems/rubygems-update-2.6.12/lib/rubygems.rb
vagrant@vagrant:/home$

Here is one for kernel_require.rb

Exception `LoadError' at /home/vagrant/.rvm/rubies/ruby-2.4.1/lib/ruby/site_ruby/2.4.0/rubygems/core_ext/kernel_require.rb:55 - cannot load
such file -- sinatra

Yet Sinatra was running

here are the kernel_requires

./vagrant/.rvm/rubies/ruby-2.4.1/lib/ruby/2.4.0/rubygems/core_ext/kernel_require.rb
./vagrant/.rvm/rubies/ruby-2.4.1/lib/ruby/site_ruby/2.4.0/rubygems/core_ext/kernel_require.rb
./vagrant/.rvm/gems/ruby-2.4.1/gems/rubygems-update-2.6.12/lib/rubygems/core_ext/kernel_require.rb


答:
TABLE ACCESS BY INDEX ROWID - we should know two things about it

The rowid of a row specifies the data file and data block containing the row and the location of the row in that block. Locating a row by specifying its rowid is the fastest way to retrieve a single row because it specifies the exact location of the row in the database.

Searching the index is a fast and an efficient operation for Oracle and when Oracle finds the desired value it is looking for, it can also find out the rowid of the record in some other table. Oracle can then use this rowid to fetch further information if requested in query

Title: Does "TABLE ACCESS BY INDEX ROWID" means optimizer using index or table?

Body:
I have query that join two very big tables and ran explain plan on that it showing like this..

      ----------------------------------------------------------------------------------------------------------------
        | Id  | Operation                        | Name                        | Rows  | Bytes | Cost (%CPU)| Time     |
        ----------------------------------------------------------------------------------------------------------------
        |   0 | SELECT STATEMENT                 |                             |     1 |    31 |     7   (0)| 00:00:01 |
        |   1 |  PX COORDINATOR                  |                             |       |       |            |          |
        |   2 |   PX SEND QC (RANDOM)            | :TQ10000                    |       |       |            |          |
        |   3 |    NESTED LOOPS                  |                             |       |       |            |          |
        |   4 |     NESTED LOOPS                 |                             |     1 |    31 |     7   (0)| 00:00:01 |
        |   5 |      PX PARTITION HASH ALL       |                             |     1 |    17 |     5   (0)| 00:00:01 |
        |   6 |       TABLE ACCESS BY INDEX ROWID| Tab1                        |     1 |    17 |     5   (0)| 00:00:01 |
        |*  7 |        INDEX RANGE SCAN          | Tab1_PK                     |     1 |       |     4   (0)| 00:00:01 |
        |*  8 |      INDEX UNIQUE SCAN           | tab2_PK                     |     1 |       |     1   (0)| 00:00:01 |
        |*  9 |     TABLE ACCESS BY INDEX ROWID  | Tab2                        |     1 |    14 |     2   (0)| 00:00:01 |
        ----------------------------------------------------------------------------------------------------------------

Query:

select t2.colC,t2,colD,t1.colX
from tab2 t2
join tab1 t1 on t2.colA=t1.colA
and t1.colB=2345
and t2.colC in (123,456,789);

Does TABLE ACCESS BY INDEX ROWID mean Optimizer is accessing rowid in Index or scanning table to get the rowids?

Currently Query is finishing in few secs. But in the plan says its not using any index, both tables has appropriate indexes.


问:
MPI create MPI_Datatype from struct containing structs with structs and typedef
I have a quite complex program which I have to parallel with MPI. I use MPICH3 for this.

I know the way to make a new MPI_Datatype as:

```<code>  typedef struct{
    float x;
    float y;
    int centroid;
} point;
typedef struct{
    int csize;//the current size
    int tsize;//the total size
    point * data;//the data carried
} ArrayList;

const int nfields=3;
MPI_Aint disps[nfields];
int blocklens[] = {1,1,1};
MPI_Datatype types[] = {MPI_FLOAT, MPI_FLOAT, MPI_INT};

disps[0] = offsetof( point, x );
disps[1] = offsetof( point, y );
disps[2] = offsetof( point, centroid );

MPI_Datatype istruct, pstruct;
MPI_Type_create_struct(nfields, blocklens, disps, types, &istruct );
MPI_Type_create_resized( istruct, 0, (char *)&(points[1]) - (char *)(&points[0]), &pstruct );
MPI_Type_commit(&pstruct);
</code>```

But I have to do a MPI_Datatype of the following struct BigInteger:

```<code>struct mylimb
{
  int x;
};
typedef struct mylimb limb;
typedef enum eBoolean
{
  FALSE = 0,
  TRUE,
} boolean;

enum eSign
{
  SIGN_POSITIVE = 0,
  SIGN_NEGATIVE,
};

typedef struct BigInteger
{
  limb limbs[1000];
  int nbrLimbs;
  enum eSign sign;
} BigInteger;
</code>```

The struct is widely used in the code so I can not simply change it to a easier way. So can anybody tell my how I can do a MPI_Datatype from the BigInteger?
My main problem is the limb which is a mylimb  how can I concat this into my MPI_Datatype

Thanks in advance!
chrigi

答:
Derived MPI datatypes can be freely nested in order to create even more complex ones. Nothing prevents you from creating an MPI datatype that matches struct mylimb and then using it in the creation of the datatype that matches struct BigInteger:

MPI_Datatype dt_limb_temp, dt_limb;
disps[0] = offsetof(limb, x);
blocklens[0] = 0;
types[0] = MPI_INT;
MPI_Type_create_struct(1, blocklens, disps, types, &dt_limb_temp);
MPI_Type_create_resized(dt_limb_temp, 0, sizeof limb, &dt_limb);
MPI_Type_free(dt_limb_temp);

MPI_Datatype dt_biginteger;
disps[0] = offsetof(BigInteger, limbs);
disps[1] = offsetof(BigInteger, nbrLimbs);
disps[2] = offsetof(BigInteger, sign);
blocklens[0] = 1000;
blocklens[1] = blocklens[2] = 1;
types[0] = dt_limbs;
types[1] = MPI_INT;
types[2] = dt_esign;
MPI_Type_create_struct(3, blocklens, disps, types, &dt_biginteger);
MPI_Type_commit(&dt_biginteger);
```

This will work even if you add other members to struct mylib. The tricky part is to get the datatype dt_esign that matches enum eSign. The C standard only states that enums are either char or an (unsigned) integer type and leaves it to the implementation to select an integer of a particular size. Therefore, sizeof enum eSign might differ depending on the compiler, which means that fixing the type as e.g. MPI_INT won't work. Fortran users are lucky as one can use MPI_Type_match_size to obtain a matching predefined MPI integer datatype given its size in bytes. In C one has to iterate over MPI_CHAR, MPI_SHORT, MPI_INT, etc. and compare their size (as returned by MPI_Type_size) to sizeof enum eSign. As the values of the enum are non-negative, the type will most likely be unsigned, i.e. MPI_UNSIGNED_SHORT, MPI_UNSIGNED, etc. It might be tricky (impossible?) to find out whether an unsigned type is used or not. This last part is only relevant for truly portable MPI programs that should run in heterogeneous environments, where type conversion to and from some external representation could be performed by MPI. In a homogeneous environment the enum can be treated as an array of bytes as suggested by Gilles.

Body:
I have a quite complex program which I have to parallel with MPI. I use MPICH3 for this.

I know the way to make a new MPI_Datatype as:

  typedef struct{
    float x;
    float y;
    int centroid;
} point;
typedef struct{
    int csize;//the current size
    int tsize;//the total size
    point * data;//the data carried
} ArrayList;

const int nfields=3;
MPI_Aint disps[nfields];
int blocklens[] = {1,1,1};
MPI_Datatype types[] = {MPI_FLOAT, MPI_FLOAT, MPI_INT};

disps[0] = offsetof( point, x );
disps[1] = offsetof( point, y );
disps[2] = offsetof( point, centroid );

MPI_Datatype istruct, pstruct;
MPI_Type_create_struct(nfields, blocklens, disps, types, &istruct );
MPI_Type_create_resized( istruct, 0, (char *)&(points[1]) - (char *)(&points[0]), &pstruct );
MPI_Type_commit(&pstruct);

But I have to do a MPI_Datatype of the following struct BigInteger:

struct mylimb
{
  int x;
};
typedef struct mylimb limb;
typedef enum eBoolean
{
  FALSE = 0,
  TRUE,
} boolean;

enum eSign
{
  SIGN_POSITIVE = 0,
  SIGN_NEGATIVE,
};

typedef struct BigInteger
{
  limb limbs[1000];
  int nbrLimbs;
  enum eSign sign;
} BigInteger;

The struct is widely used in the code so I can not simply change it to a easier way. So can anybody tell my how I can do a MPI_Datatype from the BigInteger?
My main problem is the limb which is a mylimb  how can I concat this into my MPI_Datatype

Thanks in advance!
chrigi

Body:
Derived MPI datatypes can be freely nested in order to create even more complex ones. Nothing prevents you from creating an MPI datatype that matches struct mylimb and then using it in the creation of the datatype that matches struct BigInteger:

MPI_Datatype dt_limb_temp, dt_limb;
disps[0] = offsetof(limb, x);
blocklens[0] = 0;
types[0] = MPI_INT;
MPI_Type_create_struct(1, blocklens, disps, types, &dt_limb_temp);
MPI_Type_create_resized(dt_limb_temp, 0, sizeof limb, &dt_limb);
MPI_Type_free(dt_limb_temp);

MPI_Datatype dt_biginteger;
disps[0] = offsetof(BigInteger, limbs);
disps[1] = offsetof(BigInteger, nbrLimbs);
disps[2] = offsetof(BigInteger, sign);
blocklens[0] = 1000;
blocklens[1] = blocklens[2] = 1;
types[0] = dt_limbs;
types[1] = MPI_INT;
types[2] = dt_esign;
MPI_Type_create_struct(3, blocklens, disps, types, &dt_biginteger);
MPI_Type_commit(&dt_biginteger);

This will work even if you add other members to struct mylib. The tricky part is to get the datatype dt_esign that matches enum eSign. The C standard only states that enums are either char or an (unsigned) integer type and leaves it to the implementation to select an integer of a particular size. Therefore, sizeof enum eSign might differ depending on the compiler, which means that fixing the type as e.g. MPI_INT won't work. Fortran users are lucky as one can use MPI_Type_match_size to obtain a matching predefined MPI integer datatype given its size in bytes. In C one has to iterate over MPI_CHAR, MPI_SHORT, MPI_INT, etc. and compare their size (as returned by MPI_Type_size) to sizeof enum eSign. As the values of the enum are non-negative, the type will most likely be unsigned, i.e. MPI_UNSIGNED_SHORT, MPI_UNSIGNED, etc. It might be tricky (impossible?) to find out whether an unsigned type is used or not. This last part is only relevant for truly portable MPI programs that should run in heterogeneous environments, where type conversion to and from some external representation could be performed by MPI. In a homogeneous environment the enum can be treated as an array of bytes as suggested by Gilles.


问:
How many concurrent query can run in 1 Azure SQL DW Connection
I am new to Azure so trying to understand the Concurrency limits of Azure SQL DW:
As per Concurrency limits in SQL Data Warehouse
"SQL Data Warehouse allows up to 1,024 concurrent connections. All 1,024 connections can submit queries concurrently"

How many concurrent queries can run in a single connection if i take example of DW1000.
is it like 32 Queries in 1 connection or only 32 Queries can run concurrently?

Thanks !!

答:
Concurrency in Azure SQL Data Warehouse is fairly straightforward, but it does need you to understand a few key terms first:

 1. Resource Class

Each login has associated with it a resource class. This can be one of either smallrc, mediumrc, largerc, and xlargerc.  These resource classes control how much resource (eg memory, max transaction size) the login has access to during its current session.  The default is smallrc.  The concept is similar to Resource Governor.  A user executing a query will use so many concurrency slots when executing a query, depending on their resource class:* Data correct at time of publishing but may change.

 2. Concurrency slots

For each DWU, so many concurrency slots are allocated.  See the chart here:
* Data correct at time of publishing but may change.

Generally, higher resource classes allow more resources (or "power") but reduce concurrency.

The maximum concurrent queries executing is always 32 for DWU1000, but it can be lower depending on which resource classes you are using.

So let's do some worked examples which will hopefully aid your understanding.  We can see that for DWU1000, it has a max of 32 concurrent queries with 40 concurrency slots.  This gives us the following possibilities:

For your example of DWU1000, you can one of the following combinations:

As smallrc uses 1 concurrency slot at DWU1000, you could have a max of 32 smallrc users concurrently executing queries OR

As mediumrc uses 8 concurrency slots at DWU1000, you could have a max of 1 mediumrc user, with a max of 31 smallrc users concurrently executing queries OR

2 mediumrc users (totalling 16 concurrency slots used) with 24 smallrc users OR

3 mediumrc users (totalling 24 concurrency slots used) with 16 smallrc users OR

4 mediumrc users (totalling 32 concurrency slots used) with 8 smallrc users OR
...

2 largerc users (totalling 32 concurrency slots) with 8 smallrc users

1 xlargerc user (totalling 32 concurrency slots) with 8 smallrc users

There are many other scenarios / combinations of resource class but hopefully you get the idea by now.


问:
Java Keystore: Command "openssl" not found
I'm using Windows 7 64 bit and I'm trying to export the base64 encoded sha-hash of my Key with this command:

```<code>keytool -exportcert -alias [alias] -keystore [keystore]
| openssl sha1 -binary
| openssl base64
</code>```

Unfortunatly I get the error

```<code>command "openssl" not found
</code>```

I also tried to use other commands, that were shown on this website: http://www.startux.de/index.php/java/44-dealing-with-java-keystores
But I always get the error, that openssl cannot be found. What am I missing?

Solution

I was missing openssl. And I downloaded it here: deanlee.cn/programming/openssl-for-windows

答: It works for me on Windows, so the only conclusion I can draw is that you are missing openssl, or it is not on your PATH. Either add it, or use the full path to the executable.</p>

Body:
I'm using Windows 7 64 bit and I'm trying to export the base64 encoded sha-hash of my Key with this command:

keytool -exportcert -alias [alias] -keystore [keystore]
| openssl sha1 -binary
| openssl base64

Unfortunatly I get the error

command "openssl" not found

I also tried to use other commands, that were shown on this website: http://www.startux.de/index.php/java/44-dealing-with-java-keystores
But I always get the error, that openssl cannot be found. What am I missing?

Solution

I was missing openssl. And I downloaded it here: deanlee.cn/programming/openssl-for-windows


问:
CORS failure even though the headers are setup in dropwizard application?
I am using dropwizard and angular as my UI . My server and my UI are running on different ports. My dropwizard application doesn't seem to set the Origin headers in the response.

No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access.

Please can you advice what could be the issue

I have setup CORS on dropwizard as follows

```<code> @Override
public void run(MyAppConfiguration myAppConfiguration, Environment environment) throws Exception {
    //Force browsers to reload all js and html files for every request as angular gets screwed up
    environment.servlets()
            .addFilter("CacheBustingFilter", new CacheBustingFilter())
            .addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST), true, "/*");

    enableCorsHeaders(environment);

}

private void enableCorsHeaders(Environment env) {
        final FilterRegistration.Dynamic cors = env.servlets().addFilter("CORS", CrossOriginFilter.class);

        // Configure CORS parameters
               corsFilter.setInitParameter("Access-Control-Allow-Credentials", "true");
    corsFilter.setInitParameter("Access-Control-Allow-Origin", "*");
    corsFilter.setInitParameter("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Access-Control-Request-Headers, Access-Control-Request-Method, Cache-Control, Pragma, Expires");
    corsFilter.setInitParameter("Access-Control-Allow-Methods\" ", "OPTIONS,GET,PUT,POST,DELETE,HEAD");

        // Add URL mapping
        cors.addMappingForUrlPatterns(EnumSet.allOf(DispatcherType.class), true, "/*");
    }
</code>```

Angular Service calling into the REST endpoint

```<code> private reconUrl = "http://localhost:8199/api/iceberg/reconciliations";

  getReconciliations(): Promise<Reconciliation[]> {
    return this.http.get(this.reconUrl)
      .toPromise()
      .then(response => response.json().data as Reconciliation[])
      .catch(this.handleError);
  }
</code>```

Request-Response Headers

http://localhost:8199/api/iceberg/reconciliations

```<code>GET http://localhost:8199/api/iceberg/reconciliations
Accept: application/json, text/plain, */*
Origin: http://localhost:4200
X-DevTools-Emulate-Network-Conditions-Client-Id: 90d7ac77-f45f-4d60-a667-a56da9e0582b
X-DevTools-Request-Id: 7836.4077
User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36
Referer: http://localhost:4200/dashboard
Accept-Encoding: gzip, deflate, br
Accept-Language: en-GB,en-US;q=0.8,en;q=0.6

HTTP/1.1 401 Unauthorized
Date: Thu, 06 Jul 2017 10:59:14 GMT
WWW-Authenticate: BASIC realm="application"
Content-Length: 0
</code>```

PreFlight OPTIONS request/response

My browser is not doing any pre-flight requests so I dont see any OPTIONS request-response.

But I tried CURL with OPTIONS command as below and still see the same issue of 410 Unauthorized request

```<code>$ curl -H "Origin: http://example.com"
-H "Access-Control-Request-Method: POST"
-H "Access-Control-Request-Headers: X-Requested-With"
-X OPTIONS --verbose http://localhost:8199/api/iceberg/reconciliations
</code>```

Curl Command Request-Response below

```<code> * STATE: INIT => CONNECT handle 0x6000578f0; line 1410 (connection #-5000)
    * Added connection 0. The cache now contains 1 members
    * STATE: CONNECT => WAITRESOLVE handle 0x6000578f0; line 1446 (connection #0)
    *   Trying ::1...
    * TCP_NODELAY set
    * STATE: WAITRESOLVE => WAITCONNECT handle 0x6000578f0; line 1527 (connection #0)
    * Connected to localhost (::1) port 8199 (#0)
    * STATE: WAITCONNECT => SENDPROTOCONNECT handle 0x6000578f0; line 1579 (connection #0)
    * Marked for [keep alive]: HTTP default
    * STATE: SENDPROTOCONNECT => DO handle 0x6000578f0; line 1597 (connection #0)
    > OPTIONS /api/iceberg/reconciliations HTTP/1.1
    > Host: localhost:8199
    > User-Agent: curl/7.54.1
    > Accept: */*
    > Origin: http://example.com
    > Access-Control-Request-Method: POST
    > Access-Control-Request-Headers: X-Requested-With
    >
    * STATE: DO => DO_DONE handle 0x6000578f0; line 1676 (connection #0)
    * STATE: DO_DONE => WAITPERFORM handle 0x6000578f0; line 1801 (connection #0)
    * STATE: WAITPERFORM => PERFORM handle 0x6000578f0; line 1811 (connection #0)
    * HTTP 1.1 or later with persistent connection, pipelining supported
    < HTTP/1.1 401 Unauthorized
    < Date: Thu, 06 Jul 2017 10:53:52 GMT
    < WWW-Authenticate: BASIC realm="application"
    < Content-Length: 0
</code>```

答:
hey bro if you are using angular cli there is a way first you have to create a file in the project root. More info

https://github.com/angular/angular-cli/blob/cff95a732eaec9c94f41a1476ba9f2524867d11f/docs/documentation/stories/proxy.md

with this content in your case

```<code>[
 {
  "context": "/",
  "target": "http://localhost:8199",
  "secure": false,
  "changeOrigin": true
 }
]
</code>```

after doing this you won't need to select a port in your http call. All your request will go under 8199 port.

I forgot to run you need to add an option like this.

```<code>ng serve --proxy-config proxy-local.conf.json
</code>```

Hope it helps you bro.

Body:
I am using dropwizard and angular as my UI . My server and my UI are running on different ports. My dropwizard application doesn't seem to set the Origin headers in the response.

No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access.

Please can you advice what could be the issue

I have setup CORS on dropwizard as follows

 @Override
public void run(MyAppConfiguration myAppConfiguration, Environment environment) throws Exception {
    //Force browsers to reload all js and html files for every request as angular gets screwed up
    environment.servlets()
            .addFilter("CacheBustingFilter", new CacheBustingFilter())
            .addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST), true, "/*");

    enableCorsHeaders(environment);

}

private void enableCorsHeaders(Environment env) {
        final FilterRegistration.Dynamic cors = env.servlets().addFilter("CORS", CrossOriginFilter.class);

        // Configure CORS parameters
               corsFilter.setInitParameter("Access-Control-Allow-Credentials", "true");
    corsFilter.setInitParameter("Access-Control-Allow-Origin", "*");
    corsFilter.setInitParameter("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Access-Control-Request-Headers, Access-Control-Request-Method, Cache-Control, Pragma, Expires");
    corsFilter.setInitParameter("Access-Control-Allow-Methods\" ", "OPTIONS,GET,PUT,POST,DELETE,HEAD");

        // Add URL mapping
        cors.addMappingForUrlPatterns(EnumSet.allOf(DispatcherType.class), true, "/*");
    }

Angular Service calling into the REST endpoint

 private reconUrl = "http://localhost:8199/api/iceberg/reconciliations";

  getReconciliations(): Promise<Reconciliation[]> {
    return this.http.get(this.reconUrl)
      .toPromise()
      .then(response => response.json().data as Reconciliation[])
      .catch(this.handleError);
  }

Request-Response Headers

http://localhost:8199/api/iceberg/reconciliations

GET http://localhost:8199/api/iceberg/reconciliations
Accept: application/json, text/plain, */*
Origin: http://localhost:4200
X-DevTools-Emulate-Network-Conditions-Client-Id: 90d7ac77-f45f-4d60-a667-a56da9e0582b
X-DevTools-Request-Id: 7836.4077
User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36
Referer: http://localhost:4200/dashboard
Accept-Encoding: gzip, deflate, br
Accept-Language: en-GB,en-US;q=0.8,en;q=0.6

HTTP/1.1 401 Unauthorized
Date: Thu, 06 Jul 2017 10:59:14 GMT
WWW-Authenticate: BASIC realm="application"
Content-Length: 0

PreFlight OPTIONS request/response

My browser is not doing any pre-flight requests so I dont see any OPTIONS request-response.

But I tried CURL with OPTIONS command as below and still see the same issue of 410 Unauthorized request

$ curl -H "Origin: http://example.com"
-H "Access-Control-Request-Method: POST"
-H "Access-Control-Request-Headers: X-Requested-With"
-X OPTIONS --verbose http://localhost:8199/api/iceberg/reconciliations

Curl Command Request-Response below

 * STATE: INIT => CONNECT handle 0x6000578f0; line 1410 (connection #-5000)
    * Added connection 0. The cache now contains 1 members
    * STATE: CONNECT => WAITRESOLVE handle 0x6000578f0; line 1446 (connection #0)
    *   Trying ::1...
    * TCP_NODELAY set
    * STATE: WAITRESOLVE => WAITCONNECT handle 0x6000578f0; line 1527 (connection #0)
    * Connected to localhost (::1) port 8199 (#0)
    * STATE: WAITCONNECT => SENDPROTOCONNECT handle 0x6000578f0; line 1579 (connection #0)
    * Marked for [keep alive]: HTTP default
    * STATE: SENDPROTOCONNECT => DO handle 0x6000578f0; line 1597 (connection #0)
    > OPTIONS /api/iceberg/reconciliations HTTP/1.1
    > Host: localhost:8199
    > User-Agent: curl/7.54.1
    > Accept: */*
    > Origin: http://example.com
    > Access-Control-Request-Method: POST
    > Access-Control-Request-Headers: X-Requested-With
    >
    * STATE: DO => DO_DONE handle 0x6000578f0; line 1676 (connection #0)
    * STATE: DO_DONE => WAITPERFORM handle 0x6000578f0; line 1801 (connection #0)
    * STATE: WAITPERFORM => PERFORM handle 0x6000578f0; line 1811 (connection #0)
    * HTTP 1.1 or later with persistent connection, pipelining supported
    < HTTP/1.1 401 Unauthorized
    < Date: Thu, 06 Jul 2017 10:53:52 GMT
    < WWW-Authenticate: BASIC realm="application"
    < Content-Length: 0

Body:
hey bro if you are using angular cli there is a way first you have to create a file in the project root. More info

https://github.com/angular/angular-cli/blob/cff95a732eaec9c94f41a1476ba9f2524867d11f/docs/documentation/stories/proxy.md

with this content in your case

[
 {
  "context": "/",
  "target": "http://localhost:8199",
  "secure": false,
  "changeOrigin": true
 }
]

after doing this you won't need to select a port in your http call. All your request will go under 8199 port.

I forgot to run you need to add an option like this.

ng serve --proxy-config proxy-local.conf.json

Hope it helps you bro.


问:
Pass dynamic value to test method parameter using TestNG class
I am automating a web page which runs in multi-threading environment, so I am exporting every test result into a file system and I wanted to maintain every test result uniquely for the future reference. So is there a way to pass file name as parameter to a test method dynamically while calling it from TestNG class.

I know we can pass parameters from .xml file but if I do that the values will more like static and can be seen by all the thread running parallel.

Test class will be called from main method as bellow

```<code>public class Test  {

    public static void main(String[] args) throws ParseException {

        try
        {
            TestNG testng = new TestNG();
            testng.setTestClasses(new Class[] { Testing.class });
            testng.run();
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }

    }
}
</code>```

Bellow code is my test method

public class Testing {

```<code>@Test
@Parameters("filename")
public void testMethod(String fileName){

    System.out.println("filename is: "+fileName);

   // ---- remaining test logic -----
}
</code>```

}

Or can we use TestListenerAdapter onStart() method to inject parameter values...?.

答:
You can store your values into ITestContext which will be available for all tests.

You can set up the values in a configuration method (@BeforeSuite for example) or a listener.

Body:
I am automating a web page which runs in multi-threading environment, so I am exporting every test result into a file system and I wanted to maintain every test result uniquely for the future reference. So is there a way to pass file name as parameter to a test method dynamically while calling it from TestNG class.

I know we can pass parameters from .xml file but if I do that the values will more like static and can be seen by all the thread running parallel.

Test class will be called from main method as bellow

public class Test  {

    public static void main(String[] args) throws ParseException {

        try
        {
            TestNG testng = new TestNG();
            testng.setTestClasses(new Class[] { Testing.class });
            testng.run();
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }

    }
}

Bellow code is my test method

public class Testing {

@Test
@Parameters("filename")
public void testMethod(String fileName){

    System.out.println("filename is: "+fileName);

   // ---- remaining test logic -----
}

}

Or can we use TestListenerAdapter onStart() method to inject parameter values...?.


问:
TLS - Where are tls handshakes usually performed for MQTT brokers?
Right now I am working on altering EMQtt, and Erlang MQTT broker, so that I can perform a TLS handshake with Pre-Shared Keys, rather than an asymmetric method.

So far, I have gone through just about every file in the source code and cannot find any crypto-functions. So that gets me thinking, where could they possibly be performed? The application must have some control - in the configuration file it makes you specify the key, cert, and certificate authority certificates - so am I right in assuming that the application does handle the handshake? Or is there some kernel interface?

IF anyone can point me in the right direction or let me know if I am wrong in my understanding, I would greatly appreciate it!

答:
I would guess that TLS is handled first, and then socket connections are passed over to the MQTT handing code.

tserve can do this already, if you don't want to write your own code:
https://github.com/trafero/tstack/blob/master/docs/tserve.md

Otherwise, this might be a good place to start:
http://emqtt.io/docs/v2/design.html


问:
Blocking of port 25
What do I need to do to resolve the port lock problem? 25. I need to install a panel for the email and I'm not able to access it. I have a T.I programmer and he can not do anything because of this problem. I tried to find a solution but I could not.</p>

答:
Google Compute Engine does not allow outbound connections on ports 25, 465, and 587.

By default, these outbound SMTP ports are blocked because of the large amount of abuse these ports are susceptible to.

In addition, having a trusted third-party provider such as SendGrid, Mailgun, or Mailjet relieves Compute Engine and you from maintaining IP reputation with your receivers.

See more in https://cloud.google.com/compute/docs/tutorials/sending-mail/

Title: Blocking of port 25


问:
Need help to create sql query MySQLi PHP
I have two tables
COMPANY: company_id, company_name
REVIEW: review_id, company_id, review_text

I am trying to make search functional on site. I try to display all reviews of specific company. Example, I have search field, I enter there "Microsoft" and then I need all reviews about Microsoft.

I try to do such query, but it is not working

```<code>            $company_name = $_POST["company_name"] ?? '';
            $review_text = $_POST["review_text"] ?? '';
            $searchc = $_POST["searchc"] ?? '';

            if(isset($_POST['show'])){
                $result2 = $mysqli->prepare(
                    "SELECT review_text
                   FROM review
                   WHERE company_id
                   IN (HERE I THINK I NEED EMBED QUERY... BUT NOT SURE..) ?");
                $result2->bind_param("s", $searchc);
                $result2->execute();
                $result2->store_result();
                $row2 = mysqli_fetch_assoc($result2);
            }

            <div class="right">
                <form method="post">
                    <br/>
                    <input name="searchc" type="text" value=""><br/>
                    <input type="submit" value="show" name="show">

                  </form>

                    Text: <?=$row2['review_text']?><br />
            </div>
</code>```

答:
You can perform a SQL join on your tables </p>

```<code>$sql = "SELECT review.*, company.company_name
        FROM review
        INNER JOIN company ON review.company_id = company.company_id WHERE
        company.company_name = ?";
$result2->bind_param("s", $searchc);
</code>```

Body:
I have two tables
COMPANY: company_id, company_name
REVIEW: review_id, company_id, review_text

I am trying to make search functional on site. I try to display all reviews of specific company. Example, I have search field, I enter there "Microsoft" and then I need all reviews about Microsoft.

I try to do such query, but it is not working

            $company_name = $_POST["company_name"] ?? '';
            $review_text = $_POST["review_text"] ?? '';
            $searchc = $_POST["searchc"] ?? '';

            if(isset($_POST['show'])){
                $result2 = $mysqli->prepare(
                    "SELECT review_text
                   FROM review
                   WHERE company_id
                   IN (HERE I THINK I NEED EMBED QUERY... BUT NOT SURE..) ?");
                $result2->bind_param("s", $searchc);
                $result2->execute();
                $result2->store_result();
                $row2 = mysqli_fetch_assoc($result2);
            }

                <form method="post">

                    <input name="searchc" type="text" value="">

                    <input type="submit" value="show" name="show">

                  </form>

                    Text: <?=$row2['review_text']?>

Body:
You can perform a SQL join on your tables

$sql = "SELECT review.*, company.company_name
        FROM review
        INNER JOIN company ON review.company_id = company.company_id WHERE
        company.company_name = ?";
$result2->bind_param("s", $searchc);


问:
How to "redefine" one char * to another char *?
Something like that: (it is task, how to do this, and not to change body of main function)

I thought that it is too simple... but... I don't know how to do it...

```<code>#include <iostream>

#define "a" "b"

int main( int argc,char ** argv) {
   std::cout << "a";
   return 0;
}
</code>```

// output: b

How to do it?

答:
#define is a bad c++ style. Use const.

```<code>#include <iostream>
// const char * string_a = "a"; // Regular: Use const char *
const char * string_a = "b"; // Replacing: Instead of bad    #define "a" "b"

int main( int argc,char ** argv) {
    std::cout << string_a;
    return 0;
}
</code>```

Body:
Something like that: (it is task, how to do this, and not to change body of main function)

I thought that it is too simple... but... I don't know how to do it...

#include <iostream>

#define "a" "b"

int main( int argc,char ** argv) {
   std::cout << "a";
   return 0;
}

// output: b

How to do it?

Body:
#define is a bad c++ style. Use const.

#include <iostream>
// const char * string_a = "a"; // Regular: Use const char *
const char * string_a = "b"; // Replacing: Instead of bad    #define "a" "b"

int main( int argc,char ** argv) {
    std::cout << string_a;
    return 0;
}


问:
Selfmade iterator over a set in Java
In preparation for my exams I'm writing a few of the old exams that were given to us. In one of them we have to Implement an EnterpriseNode. One task is to write an iterator that iterates over the Staffmembers. I wrote the function next() but it doesn't work properly.
This is my code:

```<code>public StaffMemberIterator(HashSet<StaffMember> directSubordinates){
        if(directSubordinates == null) throw new NullPointerException("ofs");
        this.directSubordinates = directSubordinates;
    }

public StaffMember next() {
        if (!this.hasNext()){
            throw new NoSuchElementException("naf");
        }
        ArrayList<StaffMember> subList = new ArrayList<>(directSubordinates);
        StaffMember staffMember = subList.get(position);
        position++;
        return staffMember;
    }
</code>```

and this is the error:

```<code>junit.framework.AssertionFailedError: StaffMemberIterator.next() should return the correct next element if there is one available! expected:<Name: Allie, Job: J1> but was:<Name: Lilith, Job: J3>
    at StaffMemberIteratorTest.testIterator(StaffMemberIteratorTest.java:48)
</code>```

Thank you guys for any help!

答:
Try using LinkedHashSet instead of HashSet

If you are not getting the staff member that you expected, it is because HashSet does not retain the order of insertion of the elements.  As explained in Javadocs:

This class implements the Set interface, backed by a hash table (actually a HashMap instance). It makes no guarantees as to the iteration order of the set; in particular, it does not guarantee that the order will remain constant over time. This class permits the null element.

LinkedHashSet on the other hand, retains the order of insertion. As quoted in the Javadocs:

Hash table and linked list implementation of the Set interface, with predictable iteration order. This implementation differs from HashSet in that it maintains a doubly-linked list running through all of its entries. This linked list defines the iteration ordering, which is the order in which elements were inserted into the set (insertion-order). Note that insertion order is not affected if an element is re-inserted into the set.

Title: Selfmade iterator over a set in Java

Body:
In preparation for my exams I'm writing a few of the old exams that were given to us. In one of them we have to Implement an EnterpriseNode. One task is to write an iterator that iterates over the Staffmembers. I wrote the function next() but it doesn't work properly.
This is my code:

public StaffMemberIterator(HashSet<StaffMember> directSubordinates){
        if(directSubordinates == null) throw new NullPointerException("ofs");
        this.directSubordinates = directSubordinates;
    }

public StaffMember next() {
        if (!this.hasNext()){
            throw new NoSuchElementException("naf");
        }
        ArrayList<StaffMember> subList = new ArrayList<>(directSubordinates);
        StaffMember staffMember = subList.get(position);
        position++;
        return staffMember;
    }

and this is the error:

junit.framework.AssertionFailedError: StaffMemberIterator.next() should return the correct next element if there is one available! expected:<Name: Allie, Job: J1> but was:<Name: Lilith, Job: J3>
    at StaffMemberIteratorTest.testIterator(StaffMemberIteratorTest.java:48)

Thank you guys for any help!


问:
Flask Unittest for Post Method
I am writing a Flask unit test for a function that would return a render template. I tried few ways but it seems not working.
Here is the function:

```<code>@app.route('/', methods=['POST'])
@lti(request='initial', error=error, app=app)
def chooser(lti=lti):
   return_url = request.form.get('launch_presentation_return_url', '#')
   return render_template(
       'chooser.html'
   )
</code>```

Few ways that I have been trying:

```<code># 1st way
rv = self.app.post('/')
self.assertTrue('Choose an Icon to Insert' in rv.get_data(as_text=True))
# Error
self.assertTrue('Choose an Icon to Insert' in rv.get_data(as_text=True))
AssertionError: False is not true

# 2nd way
rv = self.app.post('/chooser.html')
assert '<h1>Choose an Icon to Insert</h1>' in rv.data
# Error
assert 'Choose an Icon to Insert' in rv.data
AssertionError
</code>```

chooser.html

```<code> <body>
    <h1>Choose an Icon to Insert</h1>
 </body>
</code>```

Thanks for all your helps.

答:
Here an example which can help you to understand. Our application - app.py:

```<code>import httplib
import json

from flask import Flask, request, Response

app = Flask(__name__)

@app.route('/', methods=['POST'])
def main():
   url = request.form.get('return_url')
   # just example. will return value of sent return_url
   return Response(
      response=json.dumps({'return_url': url}),
      status=httplib.OK,
      mimetype='application/json'
   )
</code>```

Our tests - test_api.py:

```<code>import json
import unittest

from app import app
# set our application to testing mode
app.testing = True

class TestApi(unittest.TestCase):

    def test_main(self):
        with app.test_client() as client:
            # send data as POST form to endpoint
            sent = {'return_url': 'my_test_url'}
            result = client.post(
                '/',
                data=sent
            )
            # check result from server with expected data
            self.assertEqual(
                result.data,
                json.dumps(sent)
            )
</code>```

How to run:

```<code>python -m unittest discover -p path_to_test_api.py
</code>```

Result:

```<code>----------------------------------------------------------------------
Ran 1 test in 0.009s

OK
</code>```

Hope it helps.

Title: Flask Unittest for Post Method

Body:
I am writing a Flask unit test for a function that would return a render template. I tried few ways but it seems not working.
Here is the function:

@app.route('/', methods=['POST'])
@lti(request='initial', error=error, app=app)
def chooser(lti=lti):
   return_url = request.form.get('launch_presentation_return_url', '#')
   return render_template(
       'chooser.html'
   )

Few ways that I have been trying:

# 1st way
rv = self.app.post('/')
self.assertTrue('Choose an Icon to Insert' in rv.get_data(as_text=True))
# Error
self.assertTrue('Choose an Icon to Insert' in rv.get_data(as_text=True))
AssertionError: False is not true

# 2nd way
rv = self.app.post('/chooser.html')
assert '
Choose an Icon to Insert
' in rv.data
# Error
assert 'Choose an Icon to Insert' in rv.data
AssertionError

chooser.html

Choose an Icon to Insert

Thanks for all your helps.

Body:
Here an example which can help you to understand. Our application - app.py:

import httplib
import json

from flask import Flask, request, Response

app = Flask(__name__)

@app.route('/', methods=['POST'])
def main():
   url = request.form.get('return_url')
   # just example. will return value of sent return_url
   return Response(
      response=json.dumps({'return_url': url}),
      status=httplib.OK,
      mimetype='application/json'
   )

Our tests - test_api.py:

import json
import unittest

from app import app
# set our application to testing mode
app.testing = True

class TestApi(unittest.TestCase):

    def test_main(self):
        with app.test_client() as client:
            # send data as POST form to endpoint
            sent = {'return_url': 'my_test_url'}
            result = client.post(
                '/',
                data=sent
            )
            # check result from server with expected data
            self.assertEqual(
                result.data,
                json.dumps(sent)
            )

How to run:

python -m unittest discover -p path_to_test_api.py

Result:

----------------------------------------------------------------------
Ran 1 test in 0.009s

OK

Hope it helps.