问:
JDK7 SSL conenction Issue Ignoring unsupported cipher suite: TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256
I am making a SSL connection (as client) and according to this Oracle article the following two cypher suits are supported in JDK7 if you use TLSv1.2 and enable the Strong version of the jurisdiction policy.

TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384

TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256

However the two cypher algorithms are ignored when making secure connection.

```<code>Ignoring unsupported cipher suite: TLS_DHE_DSS_WITH_AES_128_CBC_SHA256
Ignoring unsupported cipher suite: TLS_DHE_DSS_WITH_AES_256_CBC_SHA256
Ignoring unsupported cipher suite: TLS_DHE_RSA_WITH_AES_128_CBC_SHA256
Ignoring unsupported cipher suite: TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256
Ignoring unsupported cipher suite: TLS_DHE_RSA_WITH_AES_256_CBC_SHA256
**Ignoring unsupported cipher suite: TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384**
Ignoring unsupported cipher suite: TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA384
Ignoring unsupported cipher suite: TLS_RSA_WITH_AES_256_CBC_SHA256
**Ignoring unsupported cipher suite: TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256**
Ignoring unsupported cipher suite: TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384
Ignoring unsupported cipher suite: TLS_ECDH_RSA_WITH_AES_256_CBC_SHA384
Ignoring unsupported cipher suite: TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256
Ignoring unsupported cipher suite: TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256
Ignoring unsupported cipher suite: TLS_RSA_WITH_AES_128_CBC_SHA256
Allow unsafe renegotiation: false
Allow legacy hello messages: true
Is initial handshake: true
Is secure renegotiation: false
%% No cached client session
*** ClientHello, TLSv1.2
RandomCookie:  GMT: 1496192143 bytes = { 166, 200, 78, 178, 69, 10, 17, 174, 212, 142, 188, 108, 136, 152, 242, 222, 94, 231, 4, 86, 2, 99, 202, 4, 204, 130, 236, 120 }
Session ID:  {}
Cipher Suites: [TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA, TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA, TLS_RSA_WITH_AES_256_CBC_SHA, TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA, TLS_ECDH_RSA_WITH_AES_256_CBC_SHA, TLS_DHE_RSA_WITH_AES_256_CBC_SHA, TLS_DHE_DSS_WITH_AES_256_CBC_SHA, TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA, TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA, TLS_RSA_WITH_AES_128_CBC_SHA, TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA, TLS_ECDH_RSA_WITH_AES_128_CBC_SHA, TLS_DHE_RSA_WITH_AES_128_CBC_SHA, TLS_DHE_DSS_WITH_AES_128_CBC_SHA, TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA, TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA, SSL_RSA_WITH_3DES_EDE_CBC_SHA, TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA, TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA, SSL_DHE_RSA_WITH_3DES_EDE_CBC_SHA, SSL_DHE_DSS_WITH_3DES_EDE_CBC_SHA, TLS_ECDHE_ECDSA_WITH_RC4_128_SHA, TLS_ECDHE_RSA_WITH_RC4_128_SHA, SSL_RSA_WITH_RC4_128_SHA, TLS_ECDH_ECDSA_WITH_RC4_128_SHA, TLS_ECDH_RSA_WITH_RC4_128_SHA, SSL_RSA_WITH_RC4_128_MD5, TLS_EMPTY_RENEGOTIATION_INFO_SCSV]
Compression Methods:  { 0 }
Extension elliptic_curves, curve names: {secp256r1, sect163k1, sect163r2, secp192r1, secp224r1, sect233k1, sect233r1, sect283k1, sect283r1, secp384r1, sect409k1, sect409r1, secp521r1, sect571k1, sect571r1, secp160k1, secp160r1, secp160r2, sect163r1, secp192k1, sect193r1, sect193r2, secp224k1, sect239k1, secp256k1}
Extension ec_point_formats, formats: [uncompressed]
Extension signature_algorithms, signature_algorithms: SHA512withECDSA, SHA512withRSA, SHA384withECDSA, SHA384withRSA, SHA256withECDSA, SHA256withRSA, SHA224withECDSA, SHA224withRSA, SHA1withECDSA, SHA1withRSA, SHA1withDSA, MD5withRSA
Extension server_name, server_name: [host_name: api.sms.optus.com.au]
***
main, WRITE: **TLSv1.2** Handshake, length = 222
main, READ: TLSv1.2 Alert, length = 2
main, RECV TLSv1 ALERT:  fatal, handshake_failure
main, called closeSocket()
main, handling exception: javax.net.ssl.SSLHandshakeException: Received fatal alert: handshake_failure
ERROR [main] (TestRest.java:42) - Error :
</code>```

I have set the TLSv1.2

-Dhttps.protocols=TLSv1.2

I have installed the "JCE Unlimited Strength Jurisdiction Policy Files" and I can confirm its successfully installed by running the following code

```<code>try {
    int maxAllowedKeyLength = Cipher.getMaxAllowedKeyLength("AES");
    System.out.println("AES: " + maxAllowedKeyLength);
    return maxAllowedKeyLength >= 256;
} catch (NoSuchAlgorithmException e) {
    return false;
}
</code>```

I think the two cypher algorithms are not supported in JDK7 but mistakenly mentioned in the Oracle article?

Notes:

There is no problem if I run the c0ode in JDK8.

I am behind firewal and had to setup proxy. but I dont think its related as I can connect in JDK8 with no issue.

答:
The initial setting of the 'enabled' ciphers list is computed in SSLContextImpl.init before any tailoring is done, and in Java7 client the initial protocol list is only SSLv3 and TLSv1 (and in recent versions java.security configures jdk.tls.disabledAlgorithms to remove SSLv3 because of POODLE) so this disables all TLSv1.2-only ciphers, which are the only ones this server will agree to. This is the source of the Ignoring unsupported messages in your trace before the actual handshake starts.

If using HttpsURLConnection you need to set both https.protocols and https.cipherSuites (note capital S) sysprops. If directly using SSLSocket you need to call both .setEnabledProtocols including (at least) TLSv1.2 and .setEnabledCipherSuites including (at least) one of the ciphersuites you highlighted in your Q, or substitute/wrap the factory to do the equivalent.

Java8 does not have the problem because its default protocol list for both client and server is SSLv3,TLSv1,TLSv1.1,TLSv1.2, again with SSLv3 removed by jdk.tls.disabledAlgorithms

Body:
I am making a SSL connection (as client) and according to this Oracle article the following two cypher suits are supported in JDK7 if you use TLSv1.2 and enable the Strong version of the jurisdiction policy.

TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384

TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256

However the two cypher algorithms are ignored when making secure connection.

Ignoring unsupported cipher suite: TLS_DHE_DSS_WITH_AES_128_CBC_SHA256
Ignoring unsupported cipher suite: TLS_DHE_DSS_WITH_AES_256_CBC_SHA256
Ignoring unsupported cipher suite: TLS_DHE_RSA_WITH_AES_128_CBC_SHA256
Ignoring unsupported cipher suite: TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256
Ignoring unsupported cipher suite: TLS_DHE_RSA_WITH_AES_256_CBC_SHA256
**Ignoring unsupported cipher suite: TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384**
Ignoring unsupported cipher suite: TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA384
Ignoring unsupported cipher suite: TLS_RSA_WITH_AES_256_CBC_SHA256
**Ignoring unsupported cipher suite: TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256**
Ignoring unsupported cipher suite: TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384
Ignoring unsupported cipher suite: TLS_ECDH_RSA_WITH_AES_256_CBC_SHA384
Ignoring unsupported cipher suite: TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256
Ignoring unsupported cipher suite: TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256
Ignoring unsupported cipher suite: TLS_RSA_WITH_AES_128_CBC_SHA256
Allow unsafe renegotiation: false
Allow legacy hello messages: true
Is initial handshake: true
Is secure renegotiation: false
%% No cached client session
*** ClientHello, TLSv1.2
RandomCookie:  GMT: 1496192143 bytes = { 166, 200, 78, 178, 69, 10, 17, 174, 212, 142, 188, 108, 136, 152, 242, 222, 94, 231, 4, 86, 2, 99, 202, 4, 204, 130, 236, 120 }
Session ID:  {}
Cipher Suites: [TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA, TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA, TLS_RSA_WITH_AES_256_CBC_SHA, TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA, TLS_ECDH_RSA_WITH_AES_256_CBC_SHA, TLS_DHE_RSA_WITH_AES_256_CBC_SHA, TLS_DHE_DSS_WITH_AES_256_CBC_SHA, TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA, TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA, TLS_RSA_WITH_AES_128_CBC_SHA, TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA, TLS_ECDH_RSA_WITH_AES_128_CBC_SHA, TLS_DHE_RSA_WITH_AES_128_CBC_SHA, TLS_DHE_DSS_WITH_AES_128_CBC_SHA, TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA, TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA, SSL_RSA_WITH_3DES_EDE_CBC_SHA, TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA, TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA, SSL_DHE_RSA_WITH_3DES_EDE_CBC_SHA, SSL_DHE_DSS_WITH_3DES_EDE_CBC_SHA, TLS_ECDHE_ECDSA_WITH_RC4_128_SHA, TLS_ECDHE_RSA_WITH_RC4_128_SHA, SSL_RSA_WITH_RC4_128_SHA, TLS_ECDH_ECDSA_WITH_RC4_128_SHA, TLS_ECDH_RSA_WITH_RC4_128_SHA, SSL_RSA_WITH_RC4_128_MD5, TLS_EMPTY_RENEGOTIATION_INFO_SCSV]
Compression Methods:  { 0 }
Extension elliptic_curves, curve names: {secp256r1, sect163k1, sect163r2, secp192r1, secp224r1, sect233k1, sect233r1, sect283k1, sect283r1, secp384r1, sect409k1, sect409r1, secp521r1, sect571k1, sect571r1, secp160k1, secp160r1, secp160r2, sect163r1, secp192k1, sect193r1, sect193r2, secp224k1, sect239k1, secp256k1}
Extension ec_point_formats, formats: [uncompressed]
Extension signature_algorithms, signature_algorithms: SHA512withECDSA, SHA512withRSA, SHA384withECDSA, SHA384withRSA, SHA256withECDSA, SHA256withRSA, SHA224withECDSA, SHA224withRSA, SHA1withECDSA, SHA1withRSA, SHA1withDSA, MD5withRSA
Extension server_name, server_name: [host_name: api.sms.optus.com.au]
***
main, WRITE: **TLSv1.2** Handshake, length = 222
main, READ: TLSv1.2 Alert, length = 2
main, RECV TLSv1 ALERT:  fatal, handshake_failure
main, called closeSocket()
main, handling exception: javax.net.ssl.SSLHandshakeException: Received fatal alert: handshake_failure
ERROR [main] (TestRest.java:42) - Error :

I have set the TLSv1.2

-Dhttps.protocols=TLSv1.2

I have installed the "JCE Unlimited Strength Jurisdiction Policy Files" and I can confirm its successfully installed by running the following code

try {
    int maxAllowedKeyLength = Cipher.getMaxAllowedKeyLength("AES");
    System.out.println("AES: " + maxAllowedKeyLength);
    return maxAllowedKeyLength >= 256;
} catch (NoSuchAlgorithmException e) {
    return false;
}

I think the two cypher algorithms are not supported in JDK7 but mistakenly mentioned in the Oracle article?

Notes:

There is no problem if I run the c0ode in JDK8.

I am behind firewal and had to setup proxy. but I dont think its related as I can connect in JDK8 with no issue.


来源: stackexchange

问:
How to exclude document fields while importing from Mongo DB to target systems like ElasticSearch/Solr using Mongo-Connector?
Mongo DB provides a connector to integrate the data from Mongo database to targets like Solr, ElasticSearch. I am using this connector to move data from Mongo Collection from a particular database to ElasticSearch index.

How can I exclude the specified fields while loading data from Mongo database to index in ElasticSearch?.

答:
Mongo-Connector https://github.com/mongodb-labs/mongo-connector is a perfect solution to move the data from Mongo Databases to target systems like Solr, ElasticSearch, etc...

This connector offers several options which are used to exclude fields, exclude collections, exclude namespaces i.e., databases, include fields, mapping to destination namespaces i.e., index names in ElasticSearch, etc...

To Exclude fields, run the mongo-connector as follows:

```<code>mongo-connector -t http://localhost:9200 -m localhost:27017 -d elastic2_doc_manager -e city,name -n <database_name>.<collection_name>
</code>```

Mongo-connector also supports excluding nested fields. Use the
  following notation to exclude the nested fields:

```<code>mongo-connector -t http://localhost:9200 -m localhost:27017 -d elastic2_doc_manager -e address.city,address.geopoint.lat -n <database_name>.<collection_name>
</code>```

Note: we cannot use both include_fields and exclude_fields with connector because they are mutually exclusive.
Do not prefix the database name and collection name for the exclude fields.

ContentLicense: CC BY-SA 3.0

Body:
Mongo-Connector https://github.com/mongodb-labs/mongo-connector is a perfect solution to move the data from Mongo Databases to target systems like Solr, ElasticSearch, etc...

This connector offers several options which are used to exclude fields, exclude collections, exclude namespaces i.e., databases, include fields, mapping to destination namespaces i.e., index names in ElasticSearch, etc...

To Exclude fields, run the mongo-connector as follows:

mongo-connector -t http://localhost:9200 -m localhost:27017 -d elastic2_doc_manager -e city,name -n <database_name>.<collection_name>

Mongo-connector also supports excluding nested fields. Use the
  following notation to exclude the nested fields:

mongo-connector -t http://localhost:9200 -m localhost:27017 -d elastic2_doc_manager -e address.city,address.geopoint.lat -n <database_name>.<collection_name>

Note: we cannot use both include_fields and exclude_fields with connector because they are mutually exclusive.
Do not prefix the database name and collection name for the exclude fields.


问:
Adding fragment destroys activity
I have an Activity with a container being a FrameLayout. I need to add a fragment to that container, but doing so throws an IllegalStateException, destroying my Activity.

This is my container in the activity layout:

```<code><FrameLayout
    android:id="@+id/seeMoreContainer"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
</FrameLayout>
</code>```

This is how I add the fragment to the activity

```<code>PlacesSeeMoreFragment placesSeeMoreFragment = new PlacesSeeMoreFragment();
Bundle bundle = new Bundle();
bundle.putInt(PlacesSeeMoreFragment.KEY, poiID);
placesSeeMoreFragment.setArguments(bundle);
getSupportFragmentManager().beginTransaction().add(R.id.seeMoreContainer,
placesSeeMoreFragment).commit();
</code>```

And this is the logcat

```<code>java.lang.IllegalStateException: Activity has been destroyed
                                                                   at android.support.v4.app.FragmentManagerImpl.enqueueAction(FragmentManager.java:1515)
                                                                   at android.support.v4.app.BackStackRecord.commitInternal(BackStackRecord.java:634)
                                                                   at android.support.v4.app.BackStackRecord.commit(BackStackRecord.java:613)
                                                                   at net.ilb.Activities.PlacesActivity.openPlaceSeeMore(PlacesActivity.java:140)
</code>```

What am I doing wrong here?

EDIT:

I add the fragment to the activity from a public method, which I call from onItemClickListener of a ListView

This is the whole method

```<code>public void openPlaceSeeMore(int poiID){
    PlacesSeeMoreFragment placesSeeMoreFragment = new PlacesSeeMoreFragment();
    Bundle bundle = new Bundle();
    bundle.putInt(PlacesSeeMoreFragment.KEY, poiID);
    placesSeeMoreFragment.setArguments(bundle);
    getSupportFragmentManager().beginTransaction().add(R.id.seeMoreContainer, placesSeeMoreFragment).commit();
}
</code>```

And this is how the method is called

```<code>mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            PlacesActivity placesActivity = new PlacesActivity();
            placesActivity.openPlaceSeeMore(poi.getId());
        }
    });
</code>```

答:
Sometime I faced the same issue and this is what I did. Use commitAllowingStateLoss() instead of commit(). Try this one

```<code>getSupportFragmentManager().beginTransaction().add(R.id.seeMoreContainer, placesSeeMoreFragment).commitAllowingStateLoss();
</code>```

Title: Adding fragment destroys activity

Body:
I have an Activity with a container being a FrameLayout. I need to add a fragment to that container, but doing so throws an IllegalStateException, destroying my Activity.

This is my container in the activity layout:

<FrameLayout
    android:id="@+id/seeMoreContainer"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
</FrameLayout>

This is how I add the fragment to the activity

PlacesSeeMoreFragment placesSeeMoreFragment = new PlacesSeeMoreFragment();
Bundle bundle = new Bundle();
bundle.putInt(PlacesSeeMoreFragment.KEY, poiID);
placesSeeMoreFragment.setArguments(bundle);
getSupportFragmentManager().beginTransaction().add(R.id.seeMoreContainer,
placesSeeMoreFragment).commit();

And this is the logcat

java.lang.IllegalStateException: Activity has been destroyed
                                                                   at android.support.v4.app.FragmentManagerImpl.enqueueAction(FragmentManager.java:1515)
                                                                   at android.support.v4.app.BackStackRecord.commitInternal(BackStackRecord.java:634)
                                                                   at android.support.v4.app.BackStackRecord.commit(BackStackRecord.java:613)
                                                                   at net.ilb.Activities.PlacesActivity.openPlaceSeeMore(PlacesActivity.java:140)

What am I doing wrong here?

EDIT:

I add the fragment to the activity from a public method, which I call from onItemClickListener of a ListView

This is the whole method

public void openPlaceSeeMore(int poiID){
    PlacesSeeMoreFragment placesSeeMoreFragment = new PlacesSeeMoreFragment();
    Bundle bundle = new Bundle();
    bundle.putInt(PlacesSeeMoreFragment.KEY, poiID);
    placesSeeMoreFragment.setArguments(bundle);
    getSupportFragmentManager().beginTransaction().add(R.id.seeMoreContainer, placesSeeMoreFragment).commit();
}

And this is how the method is called

mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            PlacesActivity placesActivity = new PlacesActivity();
            placesActivity.openPlaceSeeMore(poi.getId());
        }
    });

Body:
Sometime I faced the same issue and this is what I did. Use commitAllowingStateLoss() instead of commit(). Try this one

getSupportFragmentManager().beginTransaction().add(R.id.seeMoreContainer, placesSeeMoreFragment).commitAllowingStateLoss();


问:
Using R to list all files with a specified extension
I'm very new to R and am working on updating an R script to iterate through a series of .dbf tables created using ArcGIS and produce a series of graphs.

I have a directory, C:\Scratch, that will contain all of my .dbf files. However, when ArcGIS creates these tables, it also includes a .dbf.xml file. I want to remove these .dbf.xml files from my file list and thus my iteration. I've tried searching and experimenting with regular expressions to no avail. This is the basic expression I'm using (Excluding all of the various experimentation):

```<code>files <- list.files(pattern = "dbf")
</code>```

Can anyone give me some direction?

答:
Gives you the list of files with full path:

```<code>  Sys.glob(file.path(file_dir, "*.dbf")) ## file_dir = file containing directory
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I'm very new to R and am working on updating an R script to iterate through a series of .dbf tables created using ArcGIS and produce a series of graphs.

I have a directory, C:\Scratch, that will contain all of my .dbf files. However, when ArcGIS creates these tables, it also includes a .dbf.xml file. I want to remove these .dbf.xml files from my file list and thus my iteration. I've tried searching and experimenting with regular expressions to no avail. This is the basic expression I'm using (Excluding all of the various experimentation):

files <- list.files(pattern = "dbf")

Can anyone give me some direction?

Body:
Gives you the list of files with full path:

  Sys.glob(file.path(file_dir, "*.dbf")) ## file_dir = file containing directory


问:
How to create a Liferay 7 Web Content template programmatically?
In Liferay 7, I have a structure, some FTL code, and I want to create a template from that, in a Java Liferay module (no portlet). Just like a human would do with the UI below, but programmatically:

Note: The code proposed at How to create Structure & Template programmatically in Liferay 6 does not work, it results in Someone may be trying to circumvent the permission checker exceptions.

See also: How to create a Liferay 7 structure programmatically?

答:
This code takes a structure (DDMStructure) and successfully creates a template:

```<code>ServiceContext serviceContext = new ServiceContext();
serviceContext.setScopeGroupId(group.getGroupId());
serviceContext.setAddGroupPermissions(true);
serviceContext.setAddGuestPermissions(true);
serviceContext.setWorkflowAction(WorkflowConstants.ACTION_PUBLISH);

String templateKey = "my template"; // Any name you want.

long classNameId = PortalUtil.getPortal().getClassNameId(DDMStructure.class);
long classPK = structure.getPrimaryKey();
long resourceClassNameId = PortalUtil.getPortal().getClassNameId(JournalArticle.class);
nameMap = Utils.createLocalesMap(templateKey);
descriptionMap = nameMap; // Use the same.
String type = "display";
String mode = "create";
String language = "ftl";
String script = null;
try {
    script = new String(Files.readAllBytes(Paths.get("/path/to/my/template.ftl")));
} catch (IOException e) {
    log.error("Exception when reading template: " + templateDefinitionFilePath, e);
}

try {
    DDMTemplate template = DDMTemplateLocalServiceUtil.addTemplate(
        user.getUserId(), group.getGroupId(), classNameId, classPK,
        resourceClassNameId, nameMap, descriptionMap,
        type, mode, language, script, serviceContext);
} catch (PortalException e) {
    log.error("Exception when creating template: " + templateDefinitionFilePath, e);
    return false;
}
</code>```

Body:
This code takes a structure (DDMStructure) and successfully creates a template:

ServiceContext serviceContext = new ServiceContext();
serviceContext.setScopeGroupId(group.getGroupId());
serviceContext.setAddGroupPermissions(true);
serviceContext.setAddGuestPermissions(true);
serviceContext.setWorkflowAction(WorkflowConstants.ACTION_PUBLISH);

String templateKey = "my template"; // Any name you want.

long classNameId = PortalUtil.getPortal().getClassNameId(DDMStructure.class);
long classPK = structure.getPrimaryKey();
long resourceClassNameId = PortalUtil.getPortal().getClassNameId(JournalArticle.class);
nameMap = Utils.createLocalesMap(templateKey);
descriptionMap = nameMap; // Use the same.
String type = "display";
String mode = "create";
String language = "ftl";
String script = null;
try {
    script = new String(Files.readAllBytes(Paths.get("/path/to/my/template.ftl")));
} catch (IOException e) {
    log.error("Exception when reading template: " + templateDefinitionFilePath, e);
}

try {
    DDMTemplate template = DDMTemplateLocalServiceUtil.addTemplate(
        user.getUserId(), group.getGroupId(), classNameId, classPK,
        resourceClassNameId, nameMap, descriptionMap,
        type, mode, language, script, serviceContext);
} catch (PortalException e) {
    log.error("Exception when creating template: " + templateDefinitionFilePath, e);
    return false;
}


问:
Modern GUI programming in Python 3.3
I am putting together a few programs, and it's about time to start making GUI's for some of them. The code is currently written in Python 3.3.

I have researched a few GUI's for Python, namely Tkinter, wxPython and PyGTK. Everything I am finding seems to only create GUI's that look fairly archaic. I have created a couple of example GUI's, and they all work, they just look very Windows 95.

An example of what I am finding/creating:

An example of what I want-ish:

Is it simply an advanced knowledge of how the GUI's work, or are there just GUI modules more suited for "modern" looking GUI's?

If it is advanced knowledge of how the GUI's work, are there some tutorials out there for how to make GUI's look more "modern".

Thanks in advance.

答: You can use htmlPy. So you can create GUI's with css html js with good looks.</p>

Title: Modern GUI programming in Python 3.3


问:
Eigen: modify sparse matrix' triplet list, instead of using coeffRef
I am facing the problem of assembling an Eigen::SparseMatrix. In reality it concerns a finite element system matrix, assembled by looping over elements and integration points. Below I have made the problem more abstract.

I initialize the matrix by first constructing a list of triplets (as suggested in the Eigen documentation). I then perform the assembly in concurrent loops using coeffRef (see example below). The question concerns the fact that coeffRef "performs a binary search", while I know exactly where each item is in the list of triplets (T below). More specifically:

Is it more efficient to modify the list of triplets to avoid coeffRef, at the cost of having to reinitialize the sparse matrix?

If one wants to modify a value in the list of triplets, is there something more elegant than

```<code>T[i] = Trip(T[i].row(),T[i].col(),T[i].value()+X);
</code>```

I realize that the answer may largely depend on the bandwidth of the matrix (i.e. how costly the search is), but there might be generic things to say about this.

Example

```<code>#include <iostream>
#include <Eigen/Sparse>

typedef Eigen::SparseMatrix<double> SpMat;
typedef Eigen::Triplet     <double> Trip;

int main(void)
{
  size_t N = 100;

  SpMat A(N,N);

  std::vector<Trip> T;
  T.reserve(3*N);

  for ( size_t i=0; i<N; ++i )
  {
    if ( i==0   ) T.push_back(Trip(i,i  ,-1.0));
    else          T.push_back(Trip(i,i-1,-1.0));

    T.push_back(Trip(i,i,+2.0));

    if ( i==N-1 ) T.push_back(Trip(i,0  ,-1.0));
    else          T.push_back(Trip(i,i+1,-1.0));
  }

  A.setFromTriplets(T.begin(),T.end());

  for ( size_t i=0; i<N; ++i )
    A.coeffRef(i,i) += static_cast<double>(i);

  return 0;
}
</code>```

Compiled using e.g.:

```<code>clang++ -I/usr/local/include/eigen3 test.cpp
</code>```

答:
My guess is that as long as the coefficients accessed by coeffRef already exist in the matrix, then calling coeffRef should be faster than reconstructing the matrix from the triplet list.

You might also outsmart the binary search performed by coeffRef by directly accessing the underlying data structure with A.valuePtr()[A.outerIndexPtr()[i]+some_offset] += ..., assuming you can directly compute some_offset taking advantage of the known structure.

Finally, if you need to update all entries, you can also sequentially iterate over them using an InnerIterator it and update the entries with it.valueRef() += ....

Body:
I am facing the problem of assembling an Eigen::SparseMatrix. In reality it concerns a finite element system matrix, assembled by looping over elements and integration points. Below I have made the problem more abstract.

I initialize the matrix by first constructing a list of triplets (as suggested in the Eigen documentation). I then perform the assembly in concurrent loops using coeffRef (see example below). The question concerns the fact that coeffRef "performs a binary search", while I know exactly where each item is in the list of triplets (T below). More specifically:

Is it more efficient to modify the list of triplets to avoid coeffRef, at the cost of having to reinitialize the sparse matrix?

If one wants to modify a value in the list of triplets, is there something more elegant than

T[i] = Trip(T[i].row(),T[i].col(),T[i].value()+X);

I realize that the answer may largely depend on the bandwidth of the matrix (i.e. how costly the search is), but there might be generic things to say about this.

Example

#include <iostream>
#include <Eigen/Sparse>

typedef Eigen::SparseMatrix<double> SpMat;
typedef Eigen::Triplet     <double> Trip;

int main(void)
{
  size_t N = 100;

  SpMat A(N,N);

  std::vector<Trip> T;
  T.reserve(3*N);

  for ( size_t i=0; i<N; ++i )
  {
    if ( i==0   ) T.push_back(Trip(i,i  ,-1.0));
    else          T.push_back(Trip(i,i-1,-1.0));

    T.push_back(Trip(i,i,+2.0));

    if ( i==N-1 ) T.push_back(Trip(i,0  ,-1.0));
    else          T.push_back(Trip(i,i+1,-1.0));
  }

  A.setFromTriplets(T.begin(),T.end());

  for ( size_t i=0; i<N; ++i )
    A.coeffRef(i,i) += static_cast<double>(i);

  return 0;
}

Compiled using e.g.:

clang++ -I/usr/local/include/eigen3 test.cpp

ContentLicense: CC BY-SA 4.0


问:
Acess AdapterView from Dialog
I have my ListActivity that when you tap on an item, it pops up a Dialog that ask the user for user and password. How can I get the selected position from the dialog?

Here's how I initialize the ListActivity:

```<code>protected void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);

 ListView listView = getListView();
 listView.setOnItemClickListener(new OnItemClickListener() {
  public void onItemClick(AdapterView<?> parent, View view,
    int position, long id) {
   showDialog(DIALOG_USER_PASSWORD);
  }
 });
}
</code>```

The Dialog I pop up is a simple AlertDialog with 2 EditText which I inflate from an xml file

```<code>protected Dialog onCreateDialog(int id) {
        switch (id) {
        ...
        case DIALOG_USER_PASSWORD:
            LayoutInflater factory = LayoutInflater.from(this);
                        final View dialogView = factory.inflate(R.layout.alert_dialog_text_entry, null);
                        return new AlertDialog.Builder(MyListActivity.this)
                        .setIcon(R.drawable.alert_dialog_icon)
                        .setTitle(R.string.ask_user_password)
                        .setView(dialogView)
                        .setPositiveButton(R.string.ok_text, new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int whichButton) {
                    String userName = ((EditText) findViewById(R.id.username_edit_alert_dialog))
                            .getText().toString();
                    String password = ((EditText) findViewById(R.id.password_edit_alert_dialog))
                            .getText().toString();
                    Credentials cred = new CredentialsL1(userName, password);

                    /* HERE IS WHERE i NEED THE SELECTED ITEM
                    mId IS THE OBJECT ASSOCIATED TO THE SELECTED POSITION */
                    mService.connect(mId, cred);

                    }
                })
                // Cancel button
                .setNegativeButton(R.string.cancel_text,
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int whichButton) {
                            dialog.cancel();
                        }
                    })
                .create();
        }
        return null;
    }
</code>```

The only I've come up with is creating a new field "mId" and setting it when the user taps and using it when the user taps OK in the Dialog. Any more elegant idea?
Thanks

答:
```<code>private int selectedPosition;
...
protected void onCreate(Bundle savedInstanceState) {
....
// inside the item listener...
selectedPosition = position;
showDialog(DIALOG_USER_PASSWORD);

/* HERE IS WHERE i NEED THE SELECTED ITEM
mId IS THE OBJECT ASSOCIATED TO THE SELECTED POSITION */
// just use selectedPosition var
</code>```

Any more elegant idea?

It seems that you use a normal ListView (not a checkbox one)... so, it's fine to do it this way.

Title: Acess AdapterView from Dialog

Body:
I have my ListActivity that when you tap on an item, it pops up a Dialog that ask the user for user and password. How can I get the selected position from the dialog?

Here's how I initialize the ListActivity:

protected void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);

 ListView listView = getListView();
 listView.setOnItemClickListener(new OnItemClickListener() {
  public void onItemClick(AdapterView<?> parent, View view,
    int position, long id) {
   showDialog(DIALOG_USER_PASSWORD);
  }
 });
}

The Dialog I pop up is a simple AlertDialog with 2 EditText which I inflate from an xml file

protected Dialog onCreateDialog(int id) {
        switch (id) {
        ...
        case DIALOG_USER_PASSWORD:
            LayoutInflater factory = LayoutInflater.from(this);
                        final View dialogView = factory.inflate(R.layout.alert_dialog_text_entry, null);
                        return new AlertDialog.Builder(MyListActivity.this)
                        .setIcon(R.drawable.alert_dialog_icon)
                        .setTitle(R.string.ask_user_password)
                        .setView(dialogView)
                        .setPositiveButton(R.string.ok_text, new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int whichButton) {
                    String userName = ((EditText) findViewById(R.id.username_edit_alert_dialog))
                            .getText().toString();
                    String password = ((EditText) findViewById(R.id.password_edit_alert_dialog))
                            .getText().toString();
                    Credentials cred = new CredentialsL1(userName, password);

                    /* HERE IS WHERE i NEED THE SELECTED ITEM
                    mId IS THE OBJECT ASSOCIATED TO THE SELECTED POSITION */
                    mService.connect(mId, cred);

                    }
                })
                // Cancel button
                .setNegativeButton(R.string.cancel_text,
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int whichButton) {
                            dialog.cancel();
                        }
                    })
                .create();
        }
        return null;
    }

The only I've come up with is creating a new field "mId" and setting it when the user taps and using it when the user taps OK in the Dialog. Any more elegant idea?
Thanks

Body:
private int selectedPosition;
...
protected void onCreate(Bundle savedInstanceState) {
....
// inside the item listener...
selectedPosition = position;
showDialog(DIALOG_USER_PASSWORD);

/* HERE IS WHERE i NEED THE SELECTED ITEM
mId IS THE OBJECT ASSOCIATED TO THE SELECTED POSITION */
// just use selectedPosition var

Any more elegant idea?

It seems that you use a normal ListView (not a checkbox one)... so, it's fine to do it this way.


问:
"Missing required key 'Key' in params" in Get operation of Dynamo dB
I am writing Lambda function in node.js to getitems from dynamodB. Table is employee where emo_Id is the Partition key. Below is the code snippet I am writing:

```<code>var table = "Employee_Test";
var emp_Id=event.emp_Id;
var emp_Name=event.emp_Name;
var params = {
TableName: table,
    KeyConditionExpression: "#eId = :Id",
        ExpressionAttributeNames:{
            "#eId": "emp_Id"
        },
        ExpressionAttributeValues: {
            ":Id":emp_Id
        }}
</code>```

The error I am getting is :
  "message": "Missing required key 'Key' in params",
  "code": "MissingRequiredParameter",

I know the resolution of the error is to add:
 Key:{
        "emp_Id": emp_Id,
} to the code. But If I have to query the employees who have joined after a particular date then I cannot provide emp_Id as a parameter.

In the AWS release notes I have found that we can disable parameter validation,
https://aws.amazon.com/releasenotes/6967335344676381  I tried this but this is also not working.

Can somebody please help?

Thanks
Shweta

答: I was hit with a same error when querying the secondary indexes. Turns out that I was using the wrong API. Confused between getItem and Query.</p>

Body:
I am writing Lambda function in node.js to getitems from dynamodB. Table is employee where emo_Id is the Partition key. Below is the code snippet I am writing:

var table = "Employee_Test";
var emp_Id=event.emp_Id;
var emp_Name=event.emp_Name;
var params = {
TableName: table,
    KeyConditionExpression: "#eId = :Id",
        ExpressionAttributeNames:{
            "#eId": "emp_Id"
        },
        ExpressionAttributeValues: {
            ":Id":emp_Id
        }}

The error I am getting is :
  "message": "Missing required key 'Key' in params",
  "code": "MissingRequiredParameter",

I know the resolution of the error is to add:
 Key:{
        "emp_Id": emp_Id,
} to the code. But If I have to query the employees who have joined after a particular date then I cannot provide emp_Id as a parameter.

In the AWS release notes I have found that we can disable parameter validation,
https://aws.amazon.com/releasenotes/6967335344676381  I tried this but this is also not working.

Can somebody please help?

Thanks
Shweta


问:
How to push to next view controller from xib select button
I would like to push to ParcelPickUpViewController after I clicked a button in LocationDetailsTableViewCell xib. But I've written the code below and it able to run. But the result won't happen at all. Need help on this issue. Thanks.

In LocationDetailsTableViewCell.h

```<code>@property (nonatomic, strong) UINavigationController *viewController;
</code>```

In LocationDetailsTableViewCell.m

```<code>- (IBAction)selectBtn:(id)sender {

    UIStoryboard *mainStoryBoard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
    ParcelPickUpViewController *vc = [mainStoryBoard instantiateViewControllerWithIdentifier: @ "pickUpVC"];
    [self.viewController pushViewController:vc animated: YES];
    [self.viewController setNavigationBarHidden:YES animated:YES];
}
</code>```

答:
I think you have button in UITableViewCell.Now you want to navigate to next view from the button click.

```<code>- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{

    static NSString *CellIdentifier = @"CustomCell";
    CustomCell *cell = (CustomCell *) [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if(cell == nil) {
        NSArray *nibObjects = [[NSBundle mainBundle] loadNibNamed:@"CustomCell" owner:nil options:nil];
        cell = [nibObjects objectAtIndex:0];

    }
    cell.btnSelct.tag = indexPath.row;
    [cell.btnSelct addTarget:self action:@selector(selectBtn:) forControlEvents:UIControlEventTouchUpInside];
    return cell;
}

- (IBAction)selectBtn:(id)sender
{
    //This is for XIB
    ParcelPickUpViewController *vc = [[ParcelPickUpViewController alloc]initWithNibName:@"pickUpVC" bundle:nil];

   //If you use storyboard
   UIStoryboard *mainStoryBoard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
   ParcelPickUpViewController *vc = [mainStoryBoard instantiateViewControllerWithIdentifier: @"parcelpickup"];

   [self.viewController pushViewController:vc animated: YES];

}
</code>```

Body:
I would like to push to ParcelPickUpViewController after I clicked a button in LocationDetailsTableViewCell xib. But I've written the code below and it able to run. But the result won't happen at all. Need help on this issue. Thanks.

In LocationDetailsTableViewCell.h

@property (nonatomic, strong) UINavigationController *viewController;

In LocationDetailsTableViewCell.m

- (IBAction)selectBtn:(id)sender {

    UIStoryboard *mainStoryBoard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
    ParcelPickUpViewController *vc = [mainStoryBoard instantiateViewControllerWithIdentifier: @ "pickUpVC"];
    [self.viewController pushViewController:vc animated: YES];
    [self.viewController setNavigationBarHidden:YES animated:YES];
}

Body:
I think you have button in UITableViewCell.Now you want to navigate to next view from the button click.

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{

    static NSString *CellIdentifier = @"CustomCell";
    CustomCell *cell = (CustomCell *) [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if(cell == nil) {
        NSArray *nibObjects = [[NSBundle mainBundle] loadNibNamed:@"CustomCell" owner:nil options:nil];
        cell = [nibObjects objectAtIndex:0];

    }
    cell.btnSelct.tag = indexPath.row;
    [cell.btnSelct addTarget:self action:@selector(selectBtn:) forControlEvents:UIControlEventTouchUpInside];
    return cell;
}

- (IBAction)selectBtn:(id)sender
{
    //This is for XIB
    ParcelPickUpViewController *vc = [[ParcelPickUpViewController alloc]initWithNibName:@"pickUpVC" bundle:nil];

   //If you use storyboard
   UIStoryboard *mainStoryBoard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
   ParcelPickUpViewController *vc = [mainStoryBoard instantiateViewControllerWithIdentifier: @"parcelpickup"];

   [self.viewController pushViewController:vc animated: YES];

}


问:
How to convert the text from a label into double
I am new to C# and just started to learn how to code. I was trying to convert and sum an amounts for several items displayed in a label, then displays the total in another label.I used parse to convert the values to double ,but I've frequently got an error message saying that"cannot implicitly convert type int to string.Here is a sample of my code.

```<code>int Cost;

double total = 0;
costLabel.Text = Convert.ToInt32(priceLabel2.Text);
Cost = int.Parse(priceLabel2.Text);
total += double.Parse(priceLabel2.Text);
costLabel.Text = total.ToString("c");
</code>```

can any one help me to solve this problem?

答:
The problem is in the line costLabel.Text = Convert.ToInt32(priceLabel2.Text);.  You have a lot of unnecessary code, so it could all be simplified to the following:

```<code>double total = double.Parse(priceLabel2.Text);
costLabel.Text = total.ToString("c");
</code>```

Body:
I am new to C# and just started to learn how to code. I was trying to convert and sum an amounts for several items displayed in a label, then displays the total in another label.I used parse to convert the values to double ,but I've frequently got an error message saying that"cannot implicitly convert type int to string.Here is a sample of my code.

int Cost;

double total = 0;
costLabel.Text = Convert.ToInt32(priceLabel2.Text);
Cost = int.Parse(priceLabel2.Text);
total += double.Parse(priceLabel2.Text);
costLabel.Text = total.ToString("c");

can any one help me to solve this problem?

Body:
The problem is in the line costLabel.Text = Convert.ToInt32(priceLabel2.Text);.  You have a lot of unnecessary code, so it could all be simplified to the following:

double total = double.Parse(priceLabel2.Text);
costLabel.Text = total.ToString("c");


问:
Java Inheritance: static variables confusion
I have two classes. Class2 and Class3. Class2 is parent class of child Class3.

```<code>package package1;

public class Class2 {

public static int a, b;

public void add() {
    System.out.println("the sum is =" + (a + b));

}

public void product() {
    System.out.println("the product is " + (a * b));
}

public Class2() {
    System.out.println("class 2 constructor");

}

public Class2(int a, int b) {

    this.a = a;
    this.b = b;

}

}
</code>```

And the code for Class3 is

```<code>package package2;
import package1.*;

public class Class3 extends Class2 {

public Class3(){
    //super(3,4);
    call();
    System.out.println(super.a);
    System.out.println(b);
    System.out.println("class 3 constructor");

}

public void call(){
    Class2 c=new Class2(3,4);
    super.add();
    super.product();

}
public void add(){
    System.out.println("child class add method");

}

}
</code>```

The above code works fine and the output is

```<code>class 2 constructor
the sum is =7
the product is 12
3
4
class 3 constructor
</code>```

Problem: when i make the parent class variables non-static, then the value is not initialized the the result look like this

```<code>class 2 constructor ,
the sum is =0
the product is 0
0
0
class 3 constructor.
</code>```

But while keeping variables non-static if i call the parent class constructor in child class using super(), then it gives the result.
what is the reason of this problem and how can i solve it?

答:
static variables are those whose values will be constant for all objects of that class. Any change in them will be reflected in other objects too.

With non-static variables, object c will have its int a and int b i.e. c.a will be 3, and c.b will be 4. But these values belong to c; while super (another object for Class2) will have its values for a and b i.e. super.a and super.b as 0 and 0.

With static variables, when you create object c, you initialize a and b to 3 and 4, but now, every single object of Class2 (including super) will have a and b initialized to 3 and 4.

Body:
I have two classes. Class2 and Class3. Class2 is parent class of child Class3.

package package1;

public class Class2 {

public static int a, b;

public void add() {
    System.out.println("the sum is =" + (a + b));

}

public void product() {
    System.out.println("the product is " + (a * b));
}

public Class2() {
    System.out.println("class 2 constructor");

}

public Class2(int a, int b) {

    this.a = a;
    this.b = b;

}

}

And the code for Class3 is

package package2;
import package1.*;

public class Class3 extends Class2 {

public Class3(){
    //super(3,4);
    call();
    System.out.println(super.a);
    System.out.println(b);
    System.out.println("class 3 constructor");

}

public void call(){
    Class2 c=new Class2(3,4);
    super.add();
    super.product();

}
public void add(){
    System.out.println("child class add method");

}

}

The above code works fine and the output is

class 2 constructor
the sum is =7
the product is 12
3
4
class 3 constructor

Problem: when i make the parent class variables non-static, then the value is not initialized the the result look like this

class 2 constructor ,
the sum is =0
the product is 0
0
0
class 3 constructor.

But while keeping variables non-static if i call the parent class constructor in child class using super(), then it gives the result.
what is the reason of this problem and how can i solve it?


答:
You are assigning integers to strings, that won't work. You are also performing multiple operations on the same input. For currencies, you must use decimal since that is a safer (more precise) data type.

```<code>decimal total = 0;
...

decimal price = Convert.ToDecimal(priceLabel2.Text);
total += price;

costLabel.Text = total.ToString("c");
</code>```

If you want to validate the input first, you should use decimal.TryParse:

```<code>if (decimal.TryParse(priceLabel2.Text, out decimal price))
{
    total += price;
}
else
{
    MessageBox.Show("Input is not a valid decimal.");
}
</code>```

Title: How to convert the text from a label into double

Body:
You are assigning integers to strings, that won't work. You are also performing multiple operations on the same input. For currencies, you must use decimal since that is a safer (more precise) data type.

decimal total = 0;
...

decimal price = Convert.ToDecimal(priceLabel2.Text);
total += price;

costLabel.Text = total.ToString("c");

If you want to validate the input first, you should use decimal.TryParse:

if (decimal.TryParse(priceLabel2.Text, out decimal price))
{
    total += price;
}
else
{
    MessageBox.Show("Input is not a valid decimal.");
}


问:
Curl request from command line and via Groovy script
I am facing an issue which i do not understand, I have written a simple groovy script that when called from the command line works as expected

```<code>#!/usr/bin/env groovy

def jsonParse(def json) {
  new groovy.json.JsonSlurperClassic().parseText(json)
}

def ticketNumbers = ["MYSTATS-2695", "MYSTATS-2694"]

 ArrayList<String> jiraLinks = new ArrayList<String>();

  for(int i =0; i < ticketNumbers.size(); i++) {
    def jira_json = "curl -o /dev/null -X GET -H Content-Type: application/json --cert-type PEM --key-type PEM -E /Users/Jenkins/.jenkins/workspace/certificates/cert.pem --key /Users/Jenkins/.jenkins/workspace/certificates/cert.pem https://jira.dev.org.co.uk:443/rest/api/2/issue/${ticketNumbers[i]}".execute().text;
    def json = jsonParse(jira_json);
    def summary = json['fields']['summary'].toString();
    jiraLinks.add("[" + ticketNumbers[i] + "](https://jira.dev.org.co.uk/browse/" + ticketNumbers[i] + ")" + " - " + summary);
  }

 println "${jiraLinks}"
</code>```

so when i do groovy myscript.groovy

This will print out

```<code>[[MYSTATS-2695 ](https://jira.dev.org.co.uk/browse/MYSTATS-2695 ) - Jenkins build pipeline should ignore draft and pre-releases, [MYSTATS-2694 ](https://jira.dev.org.co.uk/browse/MYSTATS-2694 ) - Android Jenkins pipeline should populate the comscore SDK version automatically]
</code>```

So that is as expected.

What i then have is a groovy script which i call as part of a jenkins pipeline build

```<code>class Helpers {

   def jsonParse(def json) {
     new groovy.json.JsonSlurperClassic().parseText(json)
   }

  def createJiraLinks(def ticketNumbers) {

    ArrayList<String> jiraLinks = new ArrayList<String>();
    for(int i =0; i < ticketNumbers.size(); i++) {
      def jira_json = "/usr/bin/curl -o /dev/null -X GET -H Content-Type: application/json --cert-type PEM --key-type PEM -E /Users/Jenkins/.jenkins/workspace/certificates/cert.pem --key /Users/Jenkins/.jenkins/workspace/certificates/cert.pem https://jira.dev.org.co.uk:443/rest/api/2/issue/MYSTATS-2695".execute().text;
      def json = jsonParse(jira_json);
      def summary = json['fields']['summary'].toString();
    jiraLinks.add("[" + ticketNumbers[i] + "](https://jira.dev.org.co.uk/browse/" + ticketNumbers[i] + ")" + " - " + summary);
    }
    return jiraLinks;
  }

}
return new Helpers();
</code>```

As part of my Jenkins build i have

```<code>def groovyMethod = load("${env.WORKSPACE}/groovy_scripts/release_pipeline.groovy")
def jira = groovyMethod.createJiraLinks(ticketNumberCommits);
echo "JIRA LINKAS ARE $jira"
// $jira is always returned as empty string
</code>```

Am i misunderstanding anything here as i would have expected this to work? but it seems as if the curl request never gets anything back

Thanks

答:
groovy String.execute() returns Process that could be still running (depends on system load and weather))

if you want to wait until process ended do like this:

    def txt = "cmd /c dir c:\\".execute().with{
        def output = new StringWriter()
        def error = new StringWriter()
        //wait for process ended and catch stderr and stdout
        it.waitForProcessOutput(output, error)
        //check there is no error
        assert error.toString().size()==0: "$error"
        //println it.exitValue() //we can do check with error code
        //return stdout from closure
        return output.toString()
    }
```
<p>for <code>jenkins pipeline</code> to avoid error <code>java.io.NotSerializableException</code>
use the following code:</p>
<pre class="lang-js prettyprint-override"><code>    node {
        def res = runAndWait("cmd /c dir c:\\")
        echo res
    }

    @NonCPS
    String runAndWait(Object cmd){
        def proc = cmd.execute()
        def output = new StringWriter()
        def error = new StringWriter()
        //wait for process ended and catch stderr and stdout
        proc.waitForProcessOutput(output, error)
        //check there is no error
        assert error.toString().trim().size()==0: "$error"
        //assert proc.exitValue()==0 //we can do check with error code
        //return stdout from closure
        return output.toString()
    }
</code>```

Body:
I am facing an issue which i do not understand, I have written a simple groovy script that when called from the command line works as expected

#!/usr/bin/env groovy

def jsonParse(def json) {
  new groovy.json.JsonSlurperClassic().parseText(json)
}

def ticketNumbers = ["MYSTATS-2695", "MYSTATS-2694"]

 ArrayList<String> jiraLinks = new ArrayList<String>();

  for(int i =0; i < ticketNumbers.size(); i++) {
    def jira_json = "curl -o /dev/null -X GET -H Content-Type: application/json --cert-type PEM --key-type PEM -E /Users/Jenkins/.jenkins/workspace/certificates/cert.pem --key /Users/Jenkins/.jenkins/workspace/certificates/cert.pem https://jira.dev.org.co.uk:443/rest/api/2/issue/${ticketNumbers[i]}".execute().text;
    def json = jsonParse(jira_json);
    def summary = json['fields']['summary'].toString();
    jiraLinks.add("[" + ticketNumbers[i] + "](https://jira.dev.org.co.uk/browse/" + ticketNumbers[i] + ")" + " - " + summary);
  }

 println "${jiraLinks}"

so when i do groovy myscript.groovy

This will print out

[[MYSTATS-2695 ](https://jira.dev.org.co.uk/browse/MYSTATS-2695 ) - Jenkins build pipeline should ignore draft and pre-releases, [MYSTATS-2694 ](https://jira.dev.org.co.uk/browse/MYSTATS-2694 ) - Android Jenkins pipeline should populate the comscore SDK version automatically]

So that is as expected.

What i then have is a groovy script which i call as part of a jenkins pipeline build

class Helpers {

   def jsonParse(def json) {
     new groovy.json.JsonSlurperClassic().parseText(json)
   }

  def createJiraLinks(def ticketNumbers) {

    ArrayList<String> jiraLinks = new ArrayList<String>();
    for(int i =0; i < ticketNumbers.size(); i++) {
      def jira_json = "/usr/bin/curl -o /dev/null -X GET -H Content-Type: application/json --cert-type PEM --key-type PEM -E /Users/Jenkins/.jenkins/workspace/certificates/cert.pem --key /Users/Jenkins/.jenkins/workspace/certificates/cert.pem https://jira.dev.org.co.uk:443/rest/api/2/issue/MYSTATS-2695".execute().text;
      def json = jsonParse(jira_json);
      def summary = json['fields']['summary'].toString();
    jiraLinks.add("[" + ticketNumbers[i] + "](https://jira.dev.org.co.uk/browse/" + ticketNumbers[i] + ")" + " - " + summary);
    }
    return jiraLinks;
  }

}
return new Helpers();

As part of my Jenkins build i have

def groovyMethod = load("${env.WORKSPACE}/groovy_scripts/release_pipeline.groovy")
def jira = groovyMethod.createJiraLinks(ticketNumberCommits);
echo "JIRA LINKAS ARE $jira"
// $jira is always returned as empty string

Am i misunderstanding anything here as i would have expected this to work? but it seems as if the curl request never gets anything back

Thanks

Body:
groovy String.execute() returns Process that could be still running (depends on system load and weather))

if you want to wait until process ended do like this:

    def txt = "cmd /c dir c:\\".execute().with{
        def output = new StringWriter()
        def error = new StringWriter()
        //wait for process ended and catch stderr and stdout
        it.waitForProcessOutput(output, error)
        //check there is no error
        assert error.toString().size()==0: "$error"
        //println it.exitValue() //we can do check with error code
        //return stdout from closure
        return output.toString()
    }

for jenkins pipeline to avoid error java.io.NotSerializableException
use the following code:

    node {
        def res = runAndWait("cmd /c dir c:\\")
        echo res
    }

    @NonCPS
    String runAndWait(Object cmd){
        def proc = cmd.execute()
        def output = new StringWriter()
        def error = new StringWriter()
        //wait for process ended and catch stderr and stdout
        proc.waitForProcessOutput(output, error)
        //check there is no error
        assert error.toString().trim().size()==0: "$error"
        //assert proc.exitValue()==0 //we can do check with error code
        //return stdout from closure
        return output.toString()
    }


问:
Is it possible to re-launch and test xsbti.AppMain derived application from sbt?
I'm developing an sbt launched application with custom command line interface.
The problem is that every time I want to test it I have to remove the previously published boot directory and then recompile and publish locally the artefacts, and then finally run the app and test it manually. Part of this is accomplished by running external shell scripts.

How could I make sbt doing the job for me? I've already made the skeleton command for it:

```<code>  lazy val root = Project(
    id       = "app",
    base     = file("."),
    settings = buildSettings ++ Seq( resolvers := rtResolvers,
      libraryDependencies ++= libs,
      scalacOptions  ++= Seq("-encoding", "UTF-8", "-deprecation", "-unchecked"),
      commands ++= Seq(launchApp))
  )

  val launchApp = Command.command("launch") { state =>
    state.log.info("Re-launching app")
    state
  }
</code>```

答:
Create launcher configuration file, e.g. fqb.build.properties in the project's main directory.

Create a script that launches the application

```<code>#!/usr/bin/env bash

java -jar /path/to/sbt-launch.jar "$@"
</code>```

Define task and command:

```<code>lazy val launcherTask = TaskKey[Unit]("launch", "Starts the application from the locally published JAR")

lazy val launchApp: Seq[Setting[_]] = Seq(
    commands += Command.command("publish-launch") { state =>
    state.log.info("Re-launching app")
    val modulesProj = modules.id
    s"$modulesProj/publishLocal" ::
      "publishLocal" ::
      launcherTask.key.label ::
      state
  },
  launcherTask := {
    "launch @fqb.build.properties" !<
  }
)
</code>```

Add it as a setting to a project:

```<code>lazy val root = Project(
    id       = "app",
    base     = file("."),
    settings = buildSettings ++ Seq( resolvers := rtResolvers,
      libraryDependencies ++= libs,
      scalacOptions  ++= Seq("-encoding", "UTF-8", "-deprecation", "-unchecked"),
      launchApp)
)
</code>```

Remember to delete old ~/.<app_name> directory when re-deploying, so the changes could take effect.

Body:
I'm developing an sbt launched application with custom command line interface.
The problem is that every time I want to test it I have to remove the previously published boot directory and then recompile and publish locally the artefacts, and then finally run the app and test it manually. Part of this is accomplished by running external shell scripts.

How could I make sbt doing the job for me? I've already made the skeleton command for it:

  lazy val root = Project(
    id       = "app",
    base     = file("."),
    settings = buildSettings ++ Seq( resolvers := rtResolvers,
      libraryDependencies ++= libs,
      scalacOptions  ++= Seq("-encoding", "UTF-8", "-deprecation", "-unchecked"),
      commands ++= Seq(launchApp))
  )

  val launchApp = Command.command("launch") { state =>
    state.log.info("Re-launching app")
    state
  }

Body:
Create launcher configuration file, e.g. fqb.build.properties in the project's main directory.

Create a script that launches the application

#!/usr/bin/env bash

java -jar /path/to/sbt-launch.jar "$@"

Define task and command:

lazy val launcherTask = TaskKey[Unit]("launch", "Starts the application from the locally published JAR")

lazy val launchApp: Seq[Setting[_]] = Seq(
    commands += Command.command("publish-launch") { state =>
    state.log.info("Re-launching app")
    val modulesProj = modules.id
    s"$modulesProj/publishLocal" ::
      "publishLocal" ::
      launcherTask.key.label ::
      state
  },
  launcherTask := {
    "launch @fqb.build.properties" !<
  }
)

Add it as a setting to a project:

lazy val root = Project(
    id       = "app",
    base     = file("."),
    settings = buildSettings ++ Seq( resolvers := rtResolvers,
      libraryDependencies ++= libs,
      scalacOptions  ++= Seq("-encoding", "UTF-8", "-deprecation", "-unchecked"),
      launchApp)
)

Remember to delete old ~/.<app_name> directory when re-deploying, so the changes could take effect.


问:
real-time plotting in Torch
I'm new to torch. I'm training a neural network model where I want to make a plot for training and validation error with each iteration, a quick search shows me plotting with gnuplot, http://torch.ch/docs/five-simple-examples.html but it's not done in real-time rather it plots the whole thing when all data from each time step/iteration is obtained.

I have made real-time plotting in python, something similar to this real-time plotting in while loop with matplotlib

Anyway I can do it in Torch?

答: You could just move the plotting code into the training loop. Then you can either rewrite the same plot on every loop or create a new plot per X iteration. Alternatively you can look at https://github.com/facebookresearch/visdom</p>

Title: real-time plotting in Torch


问:
NLTK single-word part-of-speech tagging
Is there a way to use NLTK to get a set of possible parts of speech of a single string of letters, taking into account that different words might have homonyms?

For example: report -> {Noun, Verb}  ,  kind -> {Adjective, Noun}

I have not been able to find a POS-tokenizer that tags part-of-speech for words outside of the context of a full sentence. This seems like a very basic request of NLTK, so I'm confused as to why I've had so much trouble finding it.

答:
Yes. The simplest way is not to use a tagger, but simply load up one or more corpora and collect the set of all tags for the word you are interested in. If you're interested in more than one word, it's simplest to collect the tags for all words in the corpus, then look up anything you want. I'll add frequency counts, just because I can. For example, using the Brown corpus and the simple "universal" tagset:</p>

```<code>>>> wordtags = nltk.ConditionalFreqDist((w.lower(), t)
        for w, t in nltk.corpus.brown.tagged_words(tagset="universal"))
>>> wordtags["report"]
FreqDist({'NOUN': 135, 'VERB': 39})
>>> list(wordtags["kind"])
['ADJ', 'NOUN']
</code>```

Title: NLTK single-word part-of-speech tagging

Body:
Yes. The simplest way is not to use a tagger, but simply load up one or more corpora and collect the set of all tags for the word you are interested in. If you're interested in more than one word, it's simplest to collect the tags for all words in the corpus, then look up anything you want. I'll add frequency counts, just because I can. For example, using the Brown corpus and the simple "universal" tagset:

>>> wordtags = nltk.ConditionalFreqDist((w.lower(), t)
        for w, t in nltk.corpus.brown.tagged_words(tagset="universal"))
>>> wordtags["report"]
FreqDist({'NOUN': 135, 'VERB': 39})
>>> list(wordtags["kind"])
['ADJ', 'NOUN']


问:
No package mod_fastcgi available on centos 6.8
I'm newbie, I'm trying to install php mod fastcgi for apache 2.2 on centos 6.8, but I got error with message: "No package mod_fastcgi available. Nothing to do".
Please help me, thank so much.

[root@host15 ~]# yum install -y mod_fastcgi

Loaded plugins: fastestmirror, priorities

Setting up Install Process

Loading mirror speeds from cached hostfile

base: mirror.digistar.vn

epel: mirrors.digipower.vn

extras: mirror.digistar.vn

remi: mirror.upb.edu.co

remi-php56: mirror.upb.edu.co

remi-safe: mirror.upb.edu.co

updates: mirrors.viethosting.com

2347 packages excluded due to repository priority protections

No package mod_fastcgi available.

Error: Nothing to do

答:
This mod_fastcgi extension is dead for years, and not available in the repositories.

You can use, instead

mod_fcgid, see its documentation and package information

mod_proxy_fcgi, see its documentation and package information

The second one is a backport from httpd 2.4 to 2.2 of the default fastcgi implementation. To use it, see the ProxyPass directive.


问:
Is Flex development without FlexBuilder realistic?
Is it realistic to try and learn and code a Flex 3 application without purchasing FlexBuilder? Since the SDK and BlazeDS are open source, it seems technically possible to develop without Flex Builder, but how realistic is it.

I would like to test out Flex but don't want to get into a situation where I am dependent on the purchase of FlexBuilder (at least not until I am confident and competent enough with the technology to recommend purchase to my employer).

I am experimenting right now, so I'm taking a long time and the trial license on my Windows machine has expired. Also Linux is my primary development platform and there is only an alpha available for Linux.

Most of the documentation I've found seem to use Flex Builder.

Maybe I should use Laszlo...

答:
FlashDevelop is really easy to setup with the Flex SDK.  Just download FlashDevelop, then download the Flex SDK.  In FlashDevelop go to Tools > Program Options > AS3Context (under Plugins) > Set the "Flex SDK Location" to the root of the folder you extracted the SDK to and build away. FlashDevelop even has a basic MXML project that will get you going.

If you use ColdFusion for the backend, having FlexBuilder in Eclipse and CFEclipse can mean one less IDE to have to get familiar with.

OwnerDisplayName: Lloyd Meinholz


问:
Trusted Sites IE 7 problem
I have links which are pointing to a javascript method. The javascript method call some ajax logic and decides which file to download. If i add my site URL into trusted sites clicking on these links shows up a yellow bar as a warning which then allows me to download the file. Can anyone suggest how to avoid that yellow bar. Or whats the reason behind it. </p>

答:
You have to change it to a custom setting, even trusted sites disables automatic download. Look in the security settings under Download -> Automatic prompting for file downloads, and change it to Enable. Disable means you get the bar. Changing the security level to Low also does this.

It's a security mechanism to prevent unexpected drive-by downloads in sites, even trusted ones.

Title: Trusted Sites IE 7 problem


问:
How do you use php Session when you navigate via an html link?
I have used session which works on my first page but when I click a link to go to another page it doesn't work. here is a section of the code for the first page:

```<code><a href = "preferences.php">Preferences</a></div>

<?php $uname = $_SESSION['uname1']; $_SESSION['uname1'] = $uname; echo ($uname . "fanta");?>
</code>```

This prints out that session is fine.
Here is a section of the preferences.php, the second page:

```<code></form>

<?php $uname = $_SESSION['uname1']; $_SESSION['uname1'] = $uname; echo ($uname . "fanta");?>
</code>```

This time it prints only "fanta" the session is not working.

答: Thank a lot. The problem was that I was not using session_start(). It now fully works.</p>

Body:
I have used session which works on my first page but when I click a link to go to another page it doesn't work. here is a section of the code for the first page:

Preferences

<?php $uname = $_SESSION['uname1']; $_SESSION['uname1'] = $uname; echo ($uname . "fanta");?>

This prints out that session is fine.
Here is a section of the preferences.php, the second page:

</form>

<?php $uname = $_SESSION['uname1']; $_SESSION['uname1'] = $uname; echo ($uname . "fanta");?>

This time it prints only "fanta" the session is not working.


问:
How run Angular-CLI project on Apache php localhost:8888, not -prod version
I am  new on Angular 2, and I am traing to run Angular-CLI  project on Apache php localhost:8888, but I cant do it. I run ng serve, but it run on localhost:4200, I put all my files in htdogs directory, change all html files to php (index.php), but still cant run project.  I can run Angular project when I make it by npm start, and with system.config.server.js.    Please help me :)

答:
Execute the following command in your terminal:

ng serve --port 8888

This will order the lighttpd webserver that the angular cli uses to serve on the specified port 8888.

You can also use the shorthand -p as well.

You can find out this and more info on using the cli in the official documentation.


答:
Please, mind types; your code amended:

```<code> // Are you sure that price is integer? What about 4.95$?
 // More natural choice is double (decimal is the best for the currency)
 double Cost;

 // Let's preserve double (but decimal is a better choice)
 double total = 0;

 // string assigned to string; no Convert.ToInt32
 // It's useless line, however, since costLabel.Text = total.ToString("c");
 // will rewrite the label
 costLabel.Text = priceLabel2.Text;

 // Since cost is not an integer value
 Cost = double.Parse(priceLabel2.Text);

 // You don't want to parse twice
 total += Cost;
 costLabel.Text = total.ToString("c");
</code>```

A better choice is to use decimal for currency:

```<code> decimal total = 0m;

 //TODO: it seem's that you want to add some logic here; otherwise total == cost

 decimal cost = decimal.Parse(priceLabel2.Text);
 total += cost;

 costLabel.Text = total.ToString("c");
</code>```

Body:
Please, mind types; your code amended:

 // Are you sure that price is integer? What about 4.95$?
 // More natural choice is double (decimal is the best for the currency)
 double Cost;

 // Let's preserve double (but decimal is a better choice)
 double total = 0;

 // string assigned to string; no Convert.ToInt32
 // It's useless line, however, since costLabel.Text = total.ToString("c");
 // will rewrite the label
 costLabel.Text = priceLabel2.Text;

 // Since cost is not an integer value
 Cost = double.Parse(priceLabel2.Text);

 // You don't want to parse twice
 total += Cost;
 costLabel.Text = total.ToString("c");

A better choice is to use decimal for currency:

 decimal total = 0m;

 //TODO: it seem's that you want to add some logic here; otherwise total == cost

 decimal cost = decimal.Parse(priceLabel2.Text);
 total += cost;

 costLabel.Text = total.ToString("c");


问:
How to Split row into multiple columns in MySQL

Hi can somebody help me, i have some question on how to separate this row into columns with the same id number. I have tried some SQL function like GROUP_CONCAT() or SUBSTRING_INDEX() function but i dont know how it works

I want the output to look something like this

答:
I guess you can't separate it to columns, because then you could theoreticaly have infinite number of columns when the ID would be the same for infinite number of rows. But you can make GROUP_CONCACT() as you suggested and then separate the values in application with for example split() function.

```<code>SELECT ID, GROUP_CONCAT(Unit_Cost SEPARATOR ';') Unit_Cost
FROM CostTable
GROUP BY ID
</code>```

Here are more examples with GROUP_CONCAT()

Body:
I guess you can't separate it to columns, because then you could theoreticaly have infinite number of columns when the ID would be the same for infinite number of rows. But you can make GROUP_CONCACT() as you suggested and then separate the values in application with for example split() function.

SELECT ID, GROUP_CONCAT(Unit_Cost SEPARATOR ';') Unit_Cost
FROM CostTable
GROUP BY ID

Here are more examples with GROUP_CONCAT()


问:
Is there a standard C function for computing the string length up to some limit?
Consider a situation: I have a buffer of known length that presumably stores a null-terminated string and I need to know the length of the string.

The problem is if I use strlen() and the string turns out to be not null-terminated the program runs into undefined behavior while reading beyond the buffer end. So I'd like to have a function like the following:

```<code> size_t strlenUpTo( char* buffer, size_t limit )
 {
     size_t count = 0;
     while( count < limit && *buffer != 0 ) {
        count++;
        buffer++;
     }
     return count;
 }
</code>```

so that it returns the length of the string but never tries to read beyond the buffer end.

Is there such function already in C library or do I have to use my own?

答:
you can use strnlen.  This is it's manpage:

```<code>NAME
       strnlen - determine the length of a fixed-size string

SYNOPSIS
       #include <string.h>

       size_t strnlen(const char *s, size_t maxlen);

DESCRIPTION
       The  strnlen  function returns the number of characters in
       the string pointed to by s, not including the  terminating
       '\0' character, but at most maxlen. In doing this, strnlen
       looks only at the first maxlen characters at s  and  never
       beyond s+maxlen.

RETURN VALUE
       The  strnlen  function  returns strlen(s), if that is less
       than maxlen, or maxlen if there is no '\0' character among
       the first maxlen characters pointed to by s.

CONFORMING TO
       This function is a GNU extension.

SEE ALSO
       strlen(3)
</code>```

Body:
Consider a situation: I have a buffer of known length that presumably stores a null-terminated string and I need to know the length of the string.

The problem is if I use strlen() and the string turns out to be not null-terminated the program runs into undefined behavior while reading beyond the buffer end. So I'd like to have a function like the following:

 size_t strlenUpTo( char* buffer, size_t limit )
 {
     size_t count = 0;
     while( count < limit && *buffer != 0 ) {
        count++;
        buffer++;
     }
     return count;
 }

so that it returns the length of the string but never tries to read beyond the buffer end.

Is there such function already in C library or do I have to use my own?

Body:
you can use strnlen.  This is it's manpage:

NAME
       strnlen - determine the length of a fixed-size string

SYNOPSIS
       #include <string.h>

       size_t strnlen(const char *s, size_t maxlen);

DESCRIPTION
       The  strnlen  function returns the number of characters in
       the string pointed to by s, not including the  terminating
       '\0' character, but at most maxlen. In doing this, strnlen
       looks only at the first maxlen characters at s  and  never
       beyond s+maxlen.

RETURN VALUE
       The  strnlen  function  returns strlen(s), if that is less
       than maxlen, or maxlen if there is no '\0' character among
       the first maxlen characters pointed to by s.

CONFORMING TO
       This function is a GNU extension.

SEE ALSO
       strlen(3)


答:
costLabel.Text property type is a string.</p>

```<code>costLabel.Text = priceLabel2.Text;
</code>```

Body:
costLabel.Text property type is a string.

costLabel.Text = priceLabel2.Text;


问:
php-ncurses cannot recognize the already installed php-common
I am trying to update my php version from 5.1.6 to 5.3.10 at Centos 5.4

I am trying to install the following rpm(i cannot yum or anything like that).

```<code>rpm -ivh php-ncurses-5.2.12-1.i386.rpm
error: Failed dependencies:
php-common = 5.2.12-1 is needed by php-ncurses-5.2.12-1.i386
</code>```

but i have install the php-common-5.3.10-1.el5.i386.rpm.

i have tried also other versions of ncurses for el5 but the same error occured

答:
I'm not CentOS user (Archlinux here), but the general rule of updating php on Linux system is - you must have same version of php and plugins/extensions to make it work.

Afaik you are trying to update php to version 5.3.3, (and yet you've just install php-common in 5.3.10), staying with php-ncurses 5.2.12. I don't think that's going to work on any system. As you can see php-ncurses-5.2.12 needs php-common in specific version (5.2.12 as well).

I'm almost sure that you should find backports of php-ncurses and php-common in 5.3.X version (same version for all the packages!) and then install it all together. If it's for some reason not possible, and if I were you I would probably remove php-ncurses, install php-5.3.X with php-common-5.3.X , then download and compile php-ncurses from source [1] (there is another version naming scheme though).

I know nothing about machine you are working on, but if it's production machine you should probably do some tests on mirror machine/system first to make sure you will not break anything.

Body:
I am trying to update my php version from 5.1.6 to 5.3.10 at Centos 5.4

I am trying to install the following rpm(i cannot yum or anything like that).

rpm -ivh php-ncurses-5.2.12-1.i386.rpm
error: Failed dependencies:
php-common = 5.2.12-1 is needed by php-ncurses-5.2.12-1.i386

but i have install the php-common-5.3.10-1.el5.i386.rpm.

i have tried also other versions of ncurses for el5 but the same error occured


问:
Java Socket connection -> weird crash when writing to Server
I am recently making a little 2D Platformer and tried to implement some Online-2-Player features. There's a Server Program and of course the client. It works like this: your client can choose between ID 1 and ID 2 and the ID is directly sent to the server, so the server can decide what data to receive and what data to send you back (Client 1 wants the coordinates of Client 2 for ex.).

The problem now is that the sent data somehow gets manipulated and there are wrong values. In addition, if I sent a true boolean my client stops right in the line where I sent the boolean and doesn't continue running the code!

I rebuilt the "connect" method 1 by 1 in a new Client Program and there is just the same issue than with my gameclient!

Thanks for your advice! After long googling it seems none got the same problem :-(

Code from (rebuilt) client:

```<code>import java.io.*;
import java.net.Socket;

public class main {

    public int x=5,y=10,id=2;
    public int rX=0,rY=0;
    public boolean receivedAttacked = false;
    public boolean attacked=false;

    public static void main(String[] args) {
        System.out.println("Connecting...");
        new main();
    }

    public main() {
        try {
            Socket socket = new Socket("localhost",6789);
            DataOutputStream dout = new DataOutputStream(socket.getOutputStream());
            DataInputStream din = new DataInputStream(socket.getInputStream());

            dout.writeByte(1);
            dout.writeInt(id);
            dout.flush();

            dout.writeByte(2);
            dout.writeInt(x);
            System.out.print("X: " + x + " / ");
            dout.flush();

            dout.writeByte(3);
            dout.writeInt(y);
            System.out.print("Y: " + y + " / ");
            dout.flush();

            dout.writeByte(4);
            System.out.print("Attacked: " + attacked + " / " + "\n");
            dout.writeBoolean(attacked);
            dout.flush();

            int byteIndex = 3;
            byte byteRead;
            for(int i = 0; i < byteIndex; i++) {
                byteRead = din.readByte();

                switch(byteRead) {
                    case 1:
                        rX = din.readInt();
                        System.out.print("RECEIVED:" +  "x: " + rX + " / ");
                    case 2:
                        rY = din.readInt();
                        System.out.print("Y: " + rY + " / ");
                    case 3:
                        receivedAttacked = din.readBoolean();
                        System.out.print("rAttacked: " + receivedAttacked + " / " + "\n");
                    default:
                }
            }
            System.out.println("PAUSE");
            dout.close();
            din.close();
            socket.close();
        } catch(Exception e) {
            e.printStackTrace();
        }
    }
}
</code>```

Server Code (Just the thread handling all inputs and outputs):

```<code>package me.server.lel;

import java.awt.BorderLayout;
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.image.BufferStrategy;
import java.awt.image.BufferedImage;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.net.Socket;
import java.net.SocketException;

import javax.swing.JFrame;

public class ServerThread extends Canvas implements Runnable {

    Socket incoming; //the client socket so to say

    public int id;
    public  int x1 = 0,y1 = 0,x2 = 0,y2 = 0;
    public  boolean attacked1 = false, attacked2 = false;

    public ServerThread(Socket incoming, int id) {
        this.incoming = incoming;
        this.id = id;
    }

    @Override
    public void run() {

        try {
            //Reading the input and saving it in global variables
            DataInputStream in  = new DataInputStream(incoming.getInputStream());

            byte index;
            int byteAmount = 4;

            for(int i = 0; i < byteAmount; i++ ){
                index = in.readByte();
                switch(index) {
                    case 1:
                        id = in.readInt();
                        break;
                    case 2:
                        if(id == 1) {
                        x1 = in.readInt();
                        } else if(id == 2) {
                            x2 = in.readInt(); ;
                        }
                        break;
                    case 3:
                        if(id == 1) {
                            y1 = in.readInt();
                        } else if(id == 2) {
                            y2 = in.readInt();
                        }
                    case 4:
                        if(id == 1) {
                            attacked1 = in.readBoolean();
                        } else if(id == 2) {
                            attacked2 = in.readBoolean();
                        }
                    default:
                }
            }

            //Writing back the values of the opposite player
            DataOutputStream out = new DataOutputStream(incoming.getOutputStream());

            if(id == 1) {
                out.writeByte(1);
                out.writeInt(x2);
                out.flush();

                out.writeByte(2);
                out.writeInt(y2);
                out.flush();

                out.writeByte(3);
                out.writeBoolean(attacked2);
                out.flush();

            } else if(id == 2) {
                out.writeByte(1);
                out.writeInt(x1);
                out.flush();

                out.writeByte(2);
                out.writeInt(y1);
                out.flush();

                out.writeByte(3);
                out.writeBoolean(attacked1);
                out.flush();
            }
        } catch(SocketException e) {
            System.out.println("User Disconnected: " + incoming.getLocalAddress());
            e.printStackTrace();
        } catch(Exception e) {
            e.printStackTrace();
        }
    }
}
</code>```

So as you were able to see I did some Console Outputs in my Client-Code. So if I run the program as it is this is the console output:

```<code>Connecting...
X: 5 / Y: 10 / Attacked: false /
RECEIVED:x: 0 / Y: 33554432 / rAttacked: false /
rAttacked: false /
</code>```

So you can see every value received is somehow wrong, except from the boolean. Now if I go into my client code and set the "attacked" boolean to true, the output just runs like this:

```<code>Connecting...
X: 5 / Y: 10 / Attacked: true /
</code>```

So I assume the code just stops and doesn't go on with the code (that happened with my client which even stopped ticking then)

Sorry for the long post, and I hope my code is enough for you guys to check it! Thank you very much!

答:
You forgot your break in your client cases and in case 3 and case 4 in your server. So for example here, when your client sends the third byte, the server reads it, but also passes through your case 4, which handles the boolean.
This might not be the source of the weird number values, but I'm pretty sure this is the cause of the boolean bug.

Try adding all your break statements, so that it won't do some unintended crazy stuff with byte manipulation at execution.

Body:
I am recently making a little 2D Platformer and tried to implement some Online-2-Player features. There's a Server Program and of course the client. It works like this: your client can choose between ID 1 and ID 2 and the ID is directly sent to the server, so the server can decide what data to receive and what data to send you back (Client 1 wants the coordinates of Client 2 for ex.).

The problem now is that the sent data somehow gets manipulated and there are wrong values. In addition, if I sent a true boolean my client stops right in the line where I sent the boolean and doesn't continue running the code!

I rebuilt the "connect" method 1 by 1 in a new Client Program and there is just the same issue than with my gameclient!

Thanks for your advice! After long googling it seems none got the same problem :-(

Code from (rebuilt) client:

import java.io.*;
import java.net.Socket;

public class main {

    public int x=5,y=10,id=2;
    public int rX=0,rY=0;
    public boolean receivedAttacked = false;
    public boolean attacked=false;

    public static void main(String[] args) {
        System.out.println("Connecting...");
        new main();
    }

    public main() {
        try {
            Socket socket = new Socket("localhost",6789);
            DataOutputStream dout = new DataOutputStream(socket.getOutputStream());
            DataInputStream din = new DataInputStream(socket.getInputStream());

            dout.writeByte(1);
            dout.writeInt(id);
            dout.flush();

            dout.writeByte(2);
            dout.writeInt(x);
            System.out.print("X: " + x + " / ");
            dout.flush();

            dout.writeByte(3);
            dout.writeInt(y);
            System.out.print("Y: " + y + " / ");
            dout.flush();

            dout.writeByte(4);
            System.out.print("Attacked: " + attacked + " / " + "\n");
            dout.writeBoolean(attacked);
            dout.flush();

            int byteIndex = 3;
            byte byteRead;
            for(int i = 0; i < byteIndex; i++) {
                byteRead = din.readByte();

                switch(byteRead) {
                    case 1:
                        rX = din.readInt();
                        System.out.print("RECEIVED:" +  "x: " + rX + " / ");
                    case 2:
                        rY = din.readInt();
                        System.out.print("Y: " + rY + " / ");
                    case 3:
                        receivedAttacked = din.readBoolean();
                        System.out.print("rAttacked: " + receivedAttacked + " / " + "\n");
                    default:
                }
            }
            System.out.println("PAUSE");
            dout.close();
            din.close();
            socket.close();
        } catch(Exception e) {
            e.printStackTrace();
        }
    }
}

Server Code (Just the thread handling all inputs and outputs):

package me.server.lel;

import java.awt.BorderLayout;
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.image.BufferStrategy;
import java.awt.image.BufferedImage;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.net.Socket;
import java.net.SocketException;

import javax.swing.JFrame;

public class ServerThread extends Canvas implements Runnable {

    Socket incoming; //the client socket so to say

    public int id;
    public  int x1 = 0,y1 = 0,x2 = 0,y2 = 0;
    public  boolean attacked1 = false, attacked2 = false;

    public ServerThread(Socket incoming, int id) {
        this.incoming = incoming;
        this.id = id;
    }

    @Override
    public void run() {

        try {
            //Reading the input and saving it in global variables
            DataInputStream in  = new DataInputStream(incoming.getInputStream());

            byte index;
            int byteAmount = 4;

            for(int i = 0; i < byteAmount; i++ ){
                index = in.readByte();
                switch(index) {
                    case 1:
                        id = in.readInt();
                        break;
                    case 2:
                        if(id == 1) {
                        x1 = in.readInt();
                        } else if(id == 2) {
                            x2 = in.readInt(); ;
                        }
                        break;
                    case 3:
                        if(id == 1) {
                            y1 = in.readInt();
                        } else if(id == 2) {
                            y2 = in.readInt();
                        }
                    case 4:
                        if(id == 1) {
                            attacked1 = in.readBoolean();
                        } else if(id == 2) {
                            attacked2 = in.readBoolean();
                        }
                    default:
                }
            }

            //Writing back the values of the opposite player
            DataOutputStream out = new DataOutputStream(incoming.getOutputStream());

            if(id == 1) {
                out.writeByte(1);
                out.writeInt(x2);
                out.flush();

                out.writeByte(2);
                out.writeInt(y2);
                out.flush();

                out.writeByte(3);
                out.writeBoolean(attacked2);
                out.flush();

            } else if(id == 2) {
                out.writeByte(1);
                out.writeInt(x1);
                out.flush();

                out.writeByte(2);
                out.writeInt(y1);
                out.flush();

                out.writeByte(3);
                out.writeBoolean(attacked1);
                out.flush();
            }
        } catch(SocketException e) {
            System.out.println("User Disconnected: " + incoming.getLocalAddress());
            e.printStackTrace();
        } catch(Exception e) {
            e.printStackTrace();
        }
    }
}

So as you were able to see I did some Console Outputs in my Client-Code. So if I run the program as it is this is the console output:

Connecting...
X: 5 / Y: 10 / Attacked: false /
RECEIVED:x: 0 / Y: 33554432 / rAttacked: false /
rAttacked: false /

So you can see every value received is somehow wrong, except from the boolean. Now if I go into my client code and set the "attacked" boolean to true, the output just runs like this:

Connecting...
X: 5 / Y: 10 / Attacked: true /

So I assume the code just stops and doesn't go on with the code (that happened with my client which even stopped ticking then)

Sorry for the long post, and I hope my code is enough for you guys to check it! Thank you very much!


问:
How to properly rewrite with templates this C++ code that uses inheritance
I have a C++ code that currently looks like this: there is a class hierarchy to do perform some comparison and a list class that uses it. Which comparison operation to use is determined at runtime based on some schema object. Here is the structure:

```<code>class A{
    bool doComparison(const string& s1, const string& s2) const=0;
}

class B: public A{
    bool doComparison(const string& s1, const string& s2) const {
        ...
    }
}

class C: public A{
    bool doComparison(const string& s1, const string& s2) const {
        ...
    }
}

template <class, S>
public FancyList{
    shared_ptr<A> z_;
    vector<S> v;

    FancyList(shared_ptr<A> z) : z_(z);

    void DoSmth(){
        ....
        z_->doComparison(arg1, arg2);
    }

}

typedef FancyList<string> FancyStringList;

// Determine which comparison to use at runtime
shared_ptr<A> c = nullptr;
    switch(type):
        case int:
          c = make_shared<B>();
          break;
        case double:
          c = make_shared<B>();
          break;
    FancyStringList l(c);
    l.push_back("stuff");
</code>```

C# used to be my main language so this code seemed ok to me. But I was told that the problem with this approach is that it uses virtual functions so there is a slight overhead in a method call. What is the proper C++-way of reorganizing this code so there is no need to have this class hierarchy and no need to use virtual functions?

答:
Contrary to what you want, the overhead of virtual function is unavoidable because the decision of which actual function is called is made in runtime.

If the decision is always made in runtime, the compiler cannot hard-code the function call into the generated machine code. It has to be a indirect function call: to use a pointer to point to a function, and to dereference the pointer before the function call. Virtual function is just one way to do indirect function call.

Template is a way tell the compiler to generate code during compile-time. All template can do is to not introduce overhead when the decision is made during compile-time. It can't help you remove works that must be done in runtime.

If you are still interested in using template, you may consider having the comparator as a template parameter.

```<code>template <class T, class Comparator>
class MyList
{
    std::vector<T> vec;
    Comparator comp;

public:
    void do_thing(const T& a, const T& b)
    {
        vec.push_back(a);
        vec.push_back(b);
        bool x = comp(vec[0], vec[1]); // for example
        std::cout << x;
    }
};
</code>```

In the comparator class, overload the function call operator.

```<code>class Compare1
{
public:
    bool operator()(const std::string& lhs, const std::string& rhs) const
    {
        return lhs < rhs;
    }
};

class Compare2
{
public:
    bool operator()(const std::string& lhs, const std::string& rhs) const
    {
        return lhs.size() < rhs.size();
    }
};

int main()
{
    MyList<std::string, Compare1> myli1;
    myli1.do_thing("a", "b");

    MyList<std::string, Compare2> myli2;
    myli2.do_thing("c", "d");
}
</code>```

You can even hide indirect function call behind comparator class. But it does not remove the overhead.

```<code>class A
{
public:
    virtual bool doComparison(const std::string& s1, const std::string& s2) const=0;
    virtual ~A() = default;
};

class PolymorphicComparator
{
private:
    std::shared_ptr<A> comp;
public:
    PolymorphicComp(std::shared_ptr<A> c) : comp(c) {}

    bool operator()(const std::string& lhs, const std::string& rhs) const
    {
        return comp->doComparison(lhs, rhs);
    }
};
</code>```

Body:
I have a C++ code that currently looks like this: there is a class hierarchy to do perform some comparison and a list class that uses it. Which comparison operation to use is determined at runtime based on some schema object. Here is the structure:

class A{
    bool doComparison(const string& s1, const string& s2) const=0;
}

class B: public A{
    bool doComparison(const string& s1, const string& s2) const {
        ...
    }
}

class C: public A{
    bool doComparison(const string& s1, const string& s2) const {
        ...
    }
}

template <class, S>
public FancyList{
    shared_ptr z_;
    vector<S> v;

    FancyList(shared_ptr z) : z_(z);

    void DoSmth(){
        ....
        z_->doComparison(arg1, arg2);
    }

}

typedef FancyList<string> FancyStringList;

// Determine which comparison to use at runtime
shared_ptr c = nullptr;
    switch(type):
        case int:
          c = make_shared();
          break;
        case double:
          c = make_shared();
          break;
    FancyStringList l(c);
    l.push_back("stuff");

C# used to be my main language so this code seemed ok to me. But I was told that the problem with this approach is that it uses virtual functions so there is a slight overhead in a method call. What is the proper C++-way of reorganizing this code so there is no need to have this class hierarchy and no need to use virtual functions?

Body:
Contrary to what you want, the overhead of virtual function is unavoidable because the decision of which actual function is called is made in runtime.

If the decision is always made in runtime, the compiler cannot hard-code the function call into the generated machine code. It has to be a indirect function call: to use a pointer to point to a function, and to dereference the pointer before the function call. Virtual function is just one way to do indirect function call.

Template is a way tell the compiler to generate code during compile-time. All template can do is to not introduce overhead when the decision is made during compile-time. It can't help you remove works that must be done in runtime.

If you are still interested in using template, you may consider having the comparator as a template parameter.

template <class T, class Comparator>
class MyList
{
    std::vector<T> vec;
    Comparator comp;

public:
    void do_thing(const T& a, const T& b)
    {
        vec.push_back(a);
        vec.push_back(b);
        bool x = comp(vec[0], vec[1]); // for example
        std::cout << x;
    }
};

In the comparator class, overload the function call operator.

class Compare1
{
public:
    bool operator()(const std::string& lhs, const std::string& rhs) const
    {
        return lhs < rhs;
    }
};

class Compare2
{
public:
    bool operator()(const std::string& lhs, const std::string& rhs) const
    {
        return lhs.size() < rhs.size();
    }
};

int main()
{
    MyList<std::string, Compare1> myli1;
    myli1.do_thing("a", "b");

    MyList<std::string, Compare2> myli2;
    myli2.do_thing("c", "d");
}

You can even hide indirect function call behind comparator class. But it does not remove the overhead.

class A
{
public:
    virtual bool doComparison(const std::string& s1, const std::string& s2) const=0;
    virtual ~A() = default;
};

class PolymorphicComparator
{
private:
    std::shared_ptr<A> comp;
public:
    PolymorphicComp(std::shared_ptr<A> c) : comp(c) {}

    bool operator()(const std::string& lhs, const std::string& rhs) const
    {
        return comp->doComparison(lhs, rhs);
    }
};