问:
Downloading content from URL without prompting for authentication in Grails
I am working on a web app programmed in Grails. I have a page used to display a certain report and these reports can contain attachments. The attachment is stored in documentum and currently, when the user clicks on it, it is only a link to the location in documentum where the attachment is stored and prompts the user for his credentials. My app has documentum credentials stored in the configuration file therefore I want to use those rather than forcing the user to enter his own credentials. I am using RESTful services to retrieve link but I am trying to find a way to use the link to download directly to the users computer.

```<code>private def getFileInfo(def id, def subject) {
  // product show view needs the following four lists to display the document information correctly
  def ATRReportInstance = ATRReport.findByTrackingNumber(id)
  def linkList = []
  def nameList = []
  def formatList = []
  def idList = []
  // open up a connection to the documentum server
  def doc = connectToDocumentum()

  if (!doc) return
  def rest = doc.rest
  def response = doc.response
  if (response.status == 200) {
    // retrieve the folder for this product (the name of this folder is the product's ID)
    def rObjectId = rest.get(documentumServer + "/repositories/" + documentumfilestore + "?dql=select r_object_id from dm_folder where any r_folder_path='" + atrreportfolderpath + "/" + id + "'") {
      auth authuser, authpass
    }
    // get the folder's ID from the folder object retrieved above
    def folderObjectID
    rObjectId.json.entries.each {
      entry - >
        folderObjectID = entry.content.properties.r_object_id
    }
    // get all of the documents in the product's MSDS folder using the folder ID retrieved above
    def resp = rest.get(documentumServer + "/repositories/" + documentumfilestore + "?dql=select r_object_id, object_name, a_content_type, subject from cbs_document where any i_folder_id= '" + folderObjectID + "'") {
      auth authuser, authpass
    }
    // cycle through the documents above to populate the four MSDS document information lists
    def x = 0
    resp.json.entries.each {
      entry - >
        if (entry.content.properties.subject == subject) {
          // get the document's content object from the document's ID
          def content = rest.get(documentumServer + "/repositories/" + documentumfilestore + "/objects/" + entry.content.properties.r_object_id + "/contents/content" + "?media-url-policy=local") {
            auth authuser, authpass
          }
          if (entry.content.properties.r_object_id != null && ATRReportInstance.inactiveFiles != null && ATRReportInstance.inactiveFiles.contains(entry.content.properties.r_object_id.toString())) {} else {
            linkList[x] = getLink(content.json.links, "enclosure")
            if (linkList[x].contains("format=msg"))
              linkList[x] = linkList[x].toString().substring(0, linkList[x].toString().indexOf("content-media")) + "content-media.msg"

            formatList[x] = entry.content.properties.a_content_type
            nameList[x] = entry.content.properties.object_name
            idList[x] = entry.content.properties.r_object_id
            x++
          }
        }
    }
    return [linkList: linkList, nameList: nameList, formatList: formatList, idList: idList]
  } else {
    // return null if documentum is unavailable
    flash.message = message(code: 'error.documentum.unavailable')
    return null
  }
}
</code>```

I'm thinking writing another function that can take in a URL and download the document to the user might work, but I can't figure how to retrieve that document within Grails.

答:
Here is the solution I implemented and that worked. It is a method that downloads a file in documentum using authentication credentials found in a configuration file.

def exportAttachment() {
  //uses parameters from gsp file
  def url = params.url
  def name = params.name
  def format = params.format
  def extension

  //find proper extension
  for (s in documentumExtMap) {
    if (s.value.equals(format)) {
      extension = s.key
    }
  }

  def connection = new URL(url).openConnection()
  def remoteAuth = "Basic " + "${authuser}:${authpass}".bytes.encodeBase64()
  connection.setRequestProperty("Authorization", remoteAuth)

  def dataStream = connection.inputStream

  response.setContentType("application/octet-stream")
  response.setHeader('Content-disposition', 'Attachment; filename=' + name + '.' + extension)
  response.outputStream << dataStream
  response.outputStream.flush()
}```

The method has three parameters: url, name, format.

Url is the location of the file in documentum.

Name is the name of the download client side

Format is the type of file that is being downloaded. In my case, I had to use this to get the proper extension needed for the file.

Body:
I am working on a web app programmed in Grails. I have a page used to display a certain report and these reports can contain attachments. The attachment is stored in documentum and currently, when the user clicks on it, it is only a link to the location in documentum where the attachment is stored and prompts the user for his credentials. My app has documentum credentials stored in the configuration file therefore I want to use those rather than forcing the user to enter his own credentials. I am using RESTful services to retrieve link but I am trying to find a way to use the link to download directly to the users computer.

private def getFileInfo(def id, def subject) {
  // product show view needs the following four lists to display the document information correctly
  def ATRReportInstance = ATRReport.findByTrackingNumber(id)
  def linkList = []
  def nameList = []
  def formatList = []
  def idList = []
  // open up a connection to the documentum server
  def doc = connectToDocumentum()

  if (!doc) return
  def rest = doc.rest
  def response = doc.response
  if (response.status == 200) {
    // retrieve the folder for this product (the name of this folder is the product's ID)
    def rObjectId = rest.get(documentumServer + "/repositories/" + documentumfilestore + "?dql=select r_object_id from dm_folder where any r_folder_path='" + atrreportfolderpath + "/" + id + "'") {
      auth authuser, authpass
    }
    // get the folder's ID from the folder object retrieved above
    def folderObjectID
    rObjectId.json.entries.each {
      entry - >
        folderObjectID = entry.content.properties.r_object_id
    }
    // get all of the documents in the product's MSDS folder using the folder ID retrieved above
    def resp = rest.get(documentumServer + "/repositories/" + documentumfilestore + "?dql=select r_object_id, object_name, a_content_type, subject from cbs_document where any i_folder_id= '" + folderObjectID + "'") {
      auth authuser, authpass
    }
    // cycle through the documents above to populate the four MSDS document information lists
    def x = 0
    resp.json.entries.each {
      entry - >
        if (entry.content.properties.subject == subject) {
          // get the document's content object from the document's ID
          def content = rest.get(documentumServer + "/repositories/" + documentumfilestore + "/objects/" + entry.content.properties.r_object_id + "/contents/content" + "?media-url-policy=local") {
            auth authuser, authpass
          }
          if (entry.content.properties.r_object_id != null && ATRReportInstance.inactiveFiles != null && ATRReportInstance.inactiveFiles.contains(entry.content.properties.r_object_id.toString())) {} else {
            linkList[x] = getLink(content.json.links, "enclosure")
            if (linkList[x].contains("format=msg"))
              linkList[x] = linkList[x].toString().substring(0, linkList[x].toString().indexOf("content-media")) + "content-media.msg"

            formatList[x] = entry.content.properties.a_content_type
            nameList[x] = entry.content.properties.object_name
            idList[x] = entry.content.properties.r_object_id
            x++
          }
        }
    }
    return [linkList: linkList, nameList: nameList, formatList: formatList, idList: idList]
  } else {
    // return null if documentum is unavailable
    flash.message = message(code: 'error.documentum.unavailable')
    return null
  }
}

I'm thinking writing another function that can take in a URL and download the document to the user might work, but I can't figure how to retrieve that document within Grails.

Body:
Here is the solution I implemented and that worked. It is a method that downloads a file in documentum using authentication credentials found in a configuration file.

def exportAttachment() {
  //uses parameters from gsp file
  def url = params.url
  def name = params.name
  def format = params.format
  def extension

  //find proper extension
  for (s in documentumExtMap) {
    if (s.value.equals(format)) {
      extension = s.key
    }
  }

  def connection = new URL(url).openConnection()
  def remoteAuth = "Basic " + "${authuser}:${authpass}".bytes.encodeBase64()
  connection.setRequestProperty("Authorization", remoteAuth)

  def dataStream = connection.inputStream

  response.setContentType("application/octet-stream")
  response.setHeader('Content-disposition', 'Attachment; filename=' + name + '.' + extension)
  response.outputStream << dataStream
  response.outputStream.flush()
}

The method has three parameters: url, name, format.

Url is the location of the file in documentum.

Name is the name of the download client side

Format is the type of file that is being downloaded. In my case, I had to use this to get the proper extension needed for the file.


来源: stackexchange

答:
Ok you definitely need to use CASE, and it is complex, and you have only given us a "something like this" ruleset, so I will give you some psuedocode to point you in the direction of a solution, and your final code will be "something like this" depending on your actual rules:</p>

```<code>SELECT DISTINCT ID,
  CASE
    WHEN EXISTS(SELECT a row with this ID WHERE Grade='Copper')
      AND EXISTS(SELECT a row with this ID WHERE Grade='Copper Bonded')
      AND NOT EXISTS(SELECT a row with this ID WHERE Grade is something other than 'Copper' or 'Copper Bonded')
        THEN 'B'
    WHEN EXISTS(SELECT a row with this ID WHERE Grade='Copper')
      AND NOT EXISTS(SELECT a row with this ID WHERE Grade is something other than 'Copper')
        THEN 'A'
    WHEN ... {by now you should be starting to get the idea}
  END AS Copper
FROM MyTable t1  --be sure to alias your table so you can correlate your EXISTS subqueries
</code>```

ContentLicense: CC BY-SA 3.0

Title: Creating a pivot based on rules

Body:
I have a dataset like:

+---------------+----+
| Grade         | ID |
+---------------+----+
| Copper        | 1  |
+---------------+----+
| Copper        | 2  |
+---------------+----+
| Copper Bonded | 2  |
+---------------+----+
| Fiber         | 3  |
+---------------+----+
| Fiber         | 4  |
+---------------+----+

I would like a result like this:

+----+--------+
| ID | Copper |
+----+--------+
| 1  | A      |
+----+--------+
| 2  | B      |
+----+--------+
| 3  | C      |
+----+--------+
| 4  | C      |
+----+--------+

The ruleset is something like this:

A :  Copper only
B :  Copper and Copper Bonded
C :  Fiber only

Is this a candidate for a pivot, how do I express this as a sql query?

Body:
Ok you definitely need to use CASE, and it is complex, and you have only given us a "something like this" ruleset, so I will give you some psuedocode to point you in the direction of a solution, and your final code will be "something like this" depending on your actual rules:

SELECT DISTINCT ID,
  CASE
    WHEN EXISTS(SELECT a row with this ID WHERE Grade='Copper')
      AND EXISTS(SELECT a row with this ID WHERE Grade='Copper Bonded')
      AND NOT EXISTS(SELECT a row with this ID WHERE Grade is something other than 'Copper' or 'Copper Bonded')
        THEN 'B'
    WHEN EXISTS(SELECT a row with this ID WHERE Grade='Copper')
      AND NOT EXISTS(SELECT a row with this ID WHERE Grade is something other than 'Copper')
        THEN 'A'
    WHEN ... {by now you should be starting to get the idea}
  END AS Copper
FROM MyTable t1  --be sure to alias your table so you can correlate your EXISTS subqueries


问:
Last line of code wont execute?
Hi I'm having a problem with the last line of the code. It won't print anything.

```<code>invalid=True
global invalid
def start()
  x = input('Type the correct key:')
  if ("m" == x) or ("M"==x):
   print('Correct!')
  elif x!='m' or x!='M':
   print('Invalid Input.')
   invalid=False
 while invalid:
  start()
print('Next Question')
</code>```

When the input is 'm' or 'M' it should say Correct!

  Next question but it doesn't it just prints Correct!

Thank you in advance!

答:
I ran you code in IDLE and the indentation were off, also as user2357112 mentioned, global should go inside a function but I dont see why you are using it.

Also you should have a condition for your while loop to end. Right now the loop will not end.

```<code>def start():
    invalid=True
    global invalid
    x = input('Type the correct key:')
    if ("m" == x) or ("M"==x):
        print('Correct!')
    else:
        print('Invalid Input.')
        invalid=False
    while invalid:
        start()
        print('Next Question')
</code>```

This might help

```<code>def startm():
    valid = True
    while(valid):
        x = input('Type the correct key:')
        if ("m" == x) or ("M"==x):
            print('Correct!')
        else:
            print('Invalid Input.')
            valid=False
</code>```

You can start the while loop with condition True and as long as its valid the loop will continue to run. Once the loop becomes False. It will break out.

Title: Last line of code wont execute?

Body:
Hi I'm having a problem with the last line of the code. It won't print anything.

invalid=True
global invalid
def start()
  x = input('Type the correct key:')
  if ("m" == x) or ("M"==x):
   print('Correct!')
  elif x!='m' or x!='M':
   print('Invalid Input.')
   invalid=False
 while invalid:
  start()
print('Next Question')

When the input is 'm' or 'M' it should say Correct!

  Next question but it doesn't it just prints Correct!

Thank you in advance!

Body:
I ran you code in IDLE and the indentation were off, also as user2357112 mentioned, global should go inside a function but I dont see why you are using it.

Also you should have a condition for your while loop to end. Right now the loop will not end.

def start():
    invalid=True
    global invalid
    x = input('Type the correct key:')
    if ("m" == x) or ("M"==x):
        print('Correct!')
    else:
        print('Invalid Input.')
        invalid=False
    while invalid:
        start()
        print('Next Question')

This might help

def startm():
    valid = True
    while(valid):
        x = input('Type the correct key:')
        if ("m" == x) or ("M"==x):
            print('Correct!')
        else:
            print('Invalid Input.')
            valid=False

You can start the while loop with condition True and as long as its valid the loop will continue to run. Once the loop becomes False. It will break out.


问:
How to get full URL on the address bar using PHP

Possible Duplicate:

  Get entire URL, including query string and anchor

I have my url like www.domain.com/#!/username (just like in twitter).

How can I retrieve the full URL (the whole string above) including the substring after '#!' in the address using PHP or Javascript??

答: Sled's answer is the best you can do, however, there is no way to get text after a pound sign "#". Anything after a "#" is considered an anchor and is not sent to the server. The "#" is only interpreted by the browser. You might try some Javascript trickery here, but I recommend avoiding passing data after a "#".</p>

ContentLicense: CC BY-SA 2.5


问:
How do i convert a dynamic web project in eclipse to run from an icon on desktop?
I have a dynamic web project in eclipse.  It has html files, Css file, js files, java files, jsp files, and etc.  It also is connected to an oracle database, which the dynamic web project inserts, updates, deletes and shows data into webpage.  The web project works fine in eclipse IDE, and can run it on the external web browser.

I need to take the dynamic web project and put it on the desktop, such as a shortcut icon.  So, i want to be able to open the web project from the desktop and be able to run directly on the web browser, like chrome.  The reason is I need to send that web project to other users to test, and see if what changes needs to be made.  The users do not have eclipse on their systems.  Is there a way I can send them the app. as a desktop application?

If not, Can anybody help me on how I can do it on my local system?

答: For the run of web_application with some jsp-files you need to have one servlet container as Tomcat or Jboss, Wildfly e.t.c. This container must be for you available over the network ( mayby official IP-Address is necessary). Then you can access to URL of your web-application with your local browser and observe the work of your application. With the icon and one link you can start the web browser with your required URL too.</p>


问:
When I send notification is marking as completed but I am still not getting messages in device
I use Firebase for sending notifications to all application users, but even Firebase shows that the message status is Complete, I'm still not getting messages in devices (using emulators).

This is my code :
MyFirebaseMessagingService class :

```<code>import android.util.Log;

import com.google.firebase.messaging.FirebaseMessagingService;
import com.google.firebase.messaging.RemoteMessage;

/**
 * Created by -SAMSUNG- on 06/12/2017.
 */

public class MyFirebaseMessagingService extends FirebaseMessagingService {

    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        super.onMessageReceived(remoteMessage);

        Log.d("myLog","NotificationTitle : "+remoteMessage.getNotification().getTitle());

    }
}
</code>```

MyFirebaseInstanceIDService class :

```<code>import android.util.Log;

import com.google.firebase.iid.FirebaseInstanceId;
import com.google.firebase.iid.FirebaseInstanceIdService;

/**
 * Created by -SAMSUNG- on 06/12/2017.
 */

public class MyFirebaseInstanceIDService extends FirebaseInstanceIdService {

    @Override
    public void onTokenRefresh() {
        super.onTokenRefresh();

        String token = FirebaseInstanceId.getInstance().getToken();
        Log.d("myLog","Token is : "+token);

    }
}
</code>```

This is the gradle :

```<code>dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })

    compile 'com.android.support:appcompat-v7:27.0.2'
    compile 'com.android.support:design:27.0.2'
    compile 'com.android.support:support-v4:27.0.2'
    compile 'com.github.amigold.fundapter:library:1.0'
    compile 'rongi.rotate-layout:rotate-layout:3.0.0'
    compile 'me.grantland:autofittextview:0.2.+'
    testCompile 'junit:junit:4.12'
    compile'com.google.firebase:firebase-messaging:11.6.2'
    compile 'com.google.firebase:firebase-core:11.6.2'
    compile 'com.google.maps.android:android-maps-utils:0.5+'
    compile 'com.google.android.gms:play-services:11.6.2'

}

apply plugin: 'com.google.gms.google-services'
</code>```

This is the Manifest :

```<code><uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.CALL_PHONE" />

<uses-feature
    android:glEsVersion="0x00020000"
    android:required="true" />

<application
    android:allowBackup="true"
    android:icon="@drawable/logofppt"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:theme="@style/AppTheme"
    tools:replace="android:icon">

    <service android:name=".MyFirebaseMessagingService">
        <intent-filter>
            <action android:name="com.google.firebase.MESSAGING_EVENT"/>
        </intent-filter>
    </service>
    <service android:name=".MyFirebaseInstanceIDService">
        <intent-filter>
            <action android:name="com.google.firebase.INSTANCE_ID_EVENT"/>
        </intent-filter>
    </service>

    <meta-data
        android:name="com.google.android.geo.API_KEY"
        android:value="AIzaSyBOhBdH1WXX9jz9kSk8nVmoQgKaM4N0_vs" />

    <activity
        android:name=".MainActivity"
        android:label="@string/app_name"
        android:screenOrientation="portrait"
        android:theme="@style/AppTheme.nobar" />
    <activity
        android:name=".SplashScreen"
        android:theme="@style/AppTheme.nobar">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity
        android:name=".TDIinfo"
        android:label="TDI" />
    <activity
        android:name=".TCAinfo"
        android:label="TCA" />
    <activity
        android:name=".INFOGinfo"
        android:label="INFOG" />
    <activity
        android:name=".TRIinfo"
        android:label="TRI" />
    <activity android:name=".TMSIRinfo" android:label="TMSIR"/>
    <activity android:name=".TLWinfo" android:label="TLW" />
    <activity android:name=".J2EEinfo" android:label="J2EE"/>
</application>
</code>```

This is the error :

```<code>D/FA: Logging event (FE): notification_receive(_nr), Bundle[{firebase_event_origin(_o)=fcm, firebase_screen_class(_sc)=MainActivity, firebase_screen_id(_si)=-947096531520348892, message_device_time(_ndt)=0, message_time(_nmt)=1512583947, message_id(_nmid)=1882982486230769049}]
D/myLog: NotificationTitle : Emplois
V/FA: Connecting to remote service
W/GooglePlayServicesUtil: Google Play services out of date.  Requires 11720000 but found 9683470
W/FA: Service connection failed: ConnectionResult{statusCode=SERVICE_VERSION_UPDATE_REQUIRED, resolution=null, message=null}
D/FA: Logging event (FE): notification_foreground(_nf), Bundle[{firebase_event_origin(_o)=fcm, firebase_screen_class(_sc)=MainActivity, firebase_screen_id(_si)=-947096531520348892, message_device_time(_ndt)=0, message_time(_nmt)=1512583947, message_id(_nmid)=1882982486230769049}]
V/FA: Connecting to remote service
W/GooglePlayServicesUtil: Google Play services out of date.  Requires 11720000 but found 9683470
W/FA: Service connection failed: ConnectionResult{statusCode=SERVICE_VERSION_UPDATE_REQUIRED, resolution=null, message=null}
V/FA: Processing queued up service tasks: 2
E/FA: Discarding data. Failed to send event to service
E/FA: Discarding data. Failed to send event to service
V/FA: Processing queued up service tasks: 0
I/art: Do partial code cache collection, code=60KB, data=50KB
I/art: After code cache collection, code=60KB, data=50KB
I/art: Increasing code cache capacity to 256KB
</code>```

Please! if you have any idea how o solve this, please leave a comment..

答: The problem was the emulators can't receive the notification, I have tried it with real device and it work fine ^_^</p>

Body:
I use Firebase for sending notifications to all application users, but even Firebase shows that the message status is Complete, I'm still not getting messages in devices (using emulators).

This is my code :
MyFirebaseMessagingService class :

import android.util.Log;

import com.google.firebase.messaging.FirebaseMessagingService;
import com.google.firebase.messaging.RemoteMessage;

/**
 * Created by -SAMSUNG- on 06/12/2017.
 */

public class MyFirebaseMessagingService extends FirebaseMessagingService {

    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        super.onMessageReceived(remoteMessage);

        Log.d("myLog","NotificationTitle : "+remoteMessage.getNotification().getTitle());

    }
}

MyFirebaseInstanceIDService class :

import android.util.Log;

import com.google.firebase.iid.FirebaseInstanceId;
import com.google.firebase.iid.FirebaseInstanceIdService;

/**
 * Created by -SAMSUNG- on 06/12/2017.
 */

public class MyFirebaseInstanceIDService extends FirebaseInstanceIdService {

    @Override
    public void onTokenRefresh() {
        super.onTokenRefresh();

        String token = FirebaseInstanceId.getInstance().getToken();
        Log.d("myLog","Token is : "+token);

    }
}

This is the gradle :

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })

    compile 'com.android.support:appcompat-v7:27.0.2'
    compile 'com.android.support:design:27.0.2'
    compile 'com.android.support:support-v4:27.0.2'
    compile 'com.github.amigold.fundapter:library:1.0'
    compile 'rongi.rotate-layout:rotate-layout:3.0.0'
    compile 'me.grantland:autofittextview:0.2.+'
    testCompile 'junit:junit:4.12'
    compile'com.google.firebase:firebase-messaging:11.6.2'
    compile 'com.google.firebase:firebase-core:11.6.2'
    compile 'com.google.maps.android:android-maps-utils:0.5+'
    compile 'com.google.android.gms:play-services:11.6.2'

}

apply plugin: 'com.google.gms.google-services'

This is the Manifest :

<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.CALL_PHONE" />

<uses-feature
    android:glEsVersion="0x00020000"
    android:required="true" />

<application
    android:allowBackup="true"
    android:icon="@drawable/logofppt"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:theme="@style/AppTheme"
    tools:replace="android:icon">

    <service android:name=".MyFirebaseMessagingService">
        <intent-filter>
            <action android:name="com.google.firebase.MESSAGING_EVENT"/>
        </intent-filter>
    </service>
    <service android:name=".MyFirebaseInstanceIDService">
        <intent-filter>
            <action android:name="com.google.firebase.INSTANCE_ID_EVENT"/>
        </intent-filter>
    </service>

    <meta-data
        android:name="com.google.android.geo.API_KEY"
        android:value="AIzaSyBOhBdH1WXX9jz9kSk8nVmoQgKaM4N0_vs" />

    <activity
        android:name=".MainActivity"
        android:label="@string/app_name"
        android:screenOrientation="portrait"
        android:theme="@style/AppTheme.nobar" />
    <activity
        android:name=".SplashScreen"
        android:theme="@style/AppTheme.nobar">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity
        android:name=".TDIinfo"
        android:label="TDI" />
    <activity
        android:name=".TCAinfo"
        android:label="TCA" />
    <activity
        android:name=".INFOGinfo"
        android:label="INFOG" />
    <activity
        android:name=".TRIinfo"
        android:label="TRI" />
    <activity android:name=".TMSIRinfo" android:label="TMSIR"/>
    <activity android:name=".TLWinfo" android:label="TLW" />
    <activity android:name=".J2EEinfo" android:label="J2EE"/>
</application>

This is the error :

D/FA: Logging event (FE): notification_receive(_nr), Bundle[{firebase_event_origin(_o)=fcm, firebase_screen_class(_sc)=MainActivity, firebase_screen_id(_si)=-947096531520348892, message_device_time(_ndt)=0, message_time(_nmt)=1512583947, message_id(_nmid)=1882982486230769049}]
D/myLog: NotificationTitle : Emplois
V/FA: Connecting to remote service
W/GooglePlayServicesUtil: Google Play services out of date.  Requires 11720000 but found 9683470
W/FA: Service connection failed: ConnectionResult{statusCode=SERVICE_VERSION_UPDATE_REQUIRED, resolution=null, message=null}
D/FA: Logging event (FE): notification_foreground(_nf), Bundle[{firebase_event_origin(_o)=fcm, firebase_screen_class(_sc)=MainActivity, firebase_screen_id(_si)=-947096531520348892, message_device_time(_ndt)=0, message_time(_nmt)=1512583947, message_id(_nmid)=1882982486230769049}]
V/FA: Connecting to remote service
W/GooglePlayServicesUtil: Google Play services out of date.  Requires 11720000 but found 9683470
W/FA: Service connection failed: ConnectionResult{statusCode=SERVICE_VERSION_UPDATE_REQUIRED, resolution=null, message=null}
V/FA: Processing queued up service tasks: 2
E/FA: Discarding data. Failed to send event to service
E/FA: Discarding data. Failed to send event to service
V/FA: Processing queued up service tasks: 0
I/art: Do partial code cache collection, code=60KB, data=50KB
I/art: After code cache collection, code=60KB, data=50KB
I/art: Increasing code cache capacity to 256KB

Please! if you have any idea how o solve this, please leave a comment..


答:
In JavaScript, unless you've got something else going on, you should be able to get the full URL from document.location, (so var URLstring = document.location; for example).

In PHP, as others have noted, this is impossible due to the way the hash works (it navigates within the page, and does not trigger a page-reload so the server never knows about it, unless the JS calls an Ajax function that triggers a script on the server).

Title: How to get full URL on the address bar using PHP

Body:
Possible Duplicate:

  Get entire URL, including query string and anchor

I have my url like www.domain.com/#!/username (just like in twitter).

How can I retrieve the full URL (the whole string above) including the substring after '#!' in the address using PHP or Javascript??


问:
Avoiding a java.lang.NullPointerException being thrown while performing arithmetic operations on a collection of values using lambda expressions
Given a list of values to sum up.

```<code>List<CartItems> cartItems = ...

BigDecimal totalWeight = cartItems.stream().reduce(BigDecimal.ZERO, (weight, cart)
        -> weight.add(cart.getProduct().getWeight().multiply(BigDecimal.valueOf(cart.getQty()))), BigDecimal::add)
        .setScale(SCALE, RoundingMode.HALF_UP);
</code>```

Here, cart.getProduct().getWeight() may be null at anytime, since it is an optional field. This will thus throw a java.lang.NullPointerException, if one of the items contains a null value in the weight field of type java.math.BigDecmial.

What is the most concise way to avoid a java.lang.NullPointerException being thrown when an item in a given collection contains a null value other than imposing a nasty conditional check like the following?

```<code>BigDecimal totalWeight = products.stream().reduce(BigDecimal.ZERO, (weight, cart)
        -> weight.add(cart.getProduct().getWeight() == null ? BigDecimal.ZERO : cart.getProduct().getWeight().multiply(BigDecimal.valueOf(cart.getQty()))), BigDecimal::add)
        .setScale(SCALE, RoundingMode.HALF_UP);
</code>```

Similarly, the following will also throw a java.lang.NullPointerException, since the given list contains a null value in it.

```<code>List<Integer> list = new ArrayList<Integer>() {{
        add(1);
        add(2);
        add(3);
        add(null);
        add(5);
    }};

Integer sum = list.stream().reduce(0, Integer::sum); // Or
//Integer sum = list.stream().reduce(0, (a, b) -> a + b);

System.out.println("sum : " + sum);
</code>```

答:
You can do this:

```<code>Integer sum = list.stream().filter(Objects::nonNull).reduce(0, Integer::sum);
</code>```

Bye!

Body:
Given a list of values to sum up.

List<CartItems> cartItems = ...

BigDecimal totalWeight = cartItems.stream().reduce(BigDecimal.ZERO, (weight, cart)
        -> weight.add(cart.getProduct().getWeight().multiply(BigDecimal.valueOf(cart.getQty()))), BigDecimal::add)
        .setScale(SCALE, RoundingMode.HALF_UP);

Here, cart.getProduct().getWeight() may be null at anytime, since it is an optional field. This will thus throw a java.lang.NullPointerException, if one of the items contains a null value in the weight field of type java.math.BigDecmial.

What is the most concise way to avoid a java.lang.NullPointerException being thrown when an item in a given collection contains a null value other than imposing a nasty conditional check like the following?

BigDecimal totalWeight = products.stream().reduce(BigDecimal.ZERO, (weight, cart)
        -> weight.add(cart.getProduct().getWeight() == null ? BigDecimal.ZERO : cart.getProduct().getWeight().multiply(BigDecimal.valueOf(cart.getQty()))), BigDecimal::add)
        .setScale(SCALE, RoundingMode.HALF_UP);

Similarly, the following will also throw a java.lang.NullPointerException, since the given list contains a null value in it.

List<Integer> list = new ArrayList<Integer>() {{
        add(1);
        add(2);
        add(3);
        add(null);
        add(5);
    }};

Integer sum = list.stream().reduce(0, Integer::sum); // Or
//Integer sum = list.stream().reduce(0, (a, b) -> a + b);

System.out.println("sum : " + sum);

Body:
You can do this:

Integer sum = list.stream().filter(Objects::nonNull).reduce(0, Integer::sum);

Bye!


问:
How to delete mat-row from mat-table material design
Currently am using angular material design mat-table. Kindly help me to delete a record of data from mat-table.

Here is the code:

            <mat-table #table [dataSource]="dataSource" matSort slimScroll width="auto" height="450px" color="rgba(0,0,0,0.3)" size="3px">

                    <ng-container matColumnDef="modelname">
                    <mat-header-cell *matHeaderCellDef mat-sort-header> Name </mat-header-cell>
                    <mat-cell *matCellDef="let element" data-toggle="modal" data-target="#deviceView"> {{element.modelname}} </mat-cell>
                    </ng-container>

                    <ng-container matColumnDef="modelnumber">
                    <mat-header-cell *matHeaderCellDef mat-sort-header> Number </mat-header-cell>
                    <mat-cell *matCellDef="let element" data-toggle="modal" data-target="#deviceView"> {{element.modelnumber}} </mat-cell>
                    </ng-container>

                    <ng-container matColumnDef="manufacturer">
                    <mat-header-cell *matHeaderCellDef mat-sort-header> Manufac </mat-header-cell>
                    <mat-cell *matCellDef="let element" data-toggle="modal" data-target="#deviceView"> {{element.manufacturer}} </mat-cell>
                    </ng-container>

                    <mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row>
                    <mat-row *matRowDef="let row; columns: displayedColumns; let i = index;" id="{{row.uuid}}" (click)="displayData(row.uuid); deleterow(index)"></mat-row>
                </mat-table>

                    <mat-paginator [length]="length" [pageSize]="1000" (page)="pageEvent = $event; onPaginateChange($event)">
                    </mat-paginator>

                        {{pageSize}} / {{length}}

= pageEvent.pageSize * pageEvent.pageIndex + pageEvent.pageSize">{{pageEvent.pageSize * pageEvent.pageIndex + pageEvent.pageSize}} / {{pageEvent.length}}

                         <div *ngIf="pageEvent.length <= pageEvent.pageSize * pageEvent.pageIndex + pageEvent.pageSize">{{pageEvent.length}} / {{pageEvent.length}}

```

Kindly check and let me know any suggestions.

答:
This is called from somewhere like a button.  It lives on this main component for the members section that has child components that call it, including the html for this component.  It passes the params from the table along with whatever else is needed for the service above it to work.  I included it so you understand how the delete row in table code works in case that matters.

members.component.ts

  // --- DELETE ---

  public deleteMember(itemId) {
    return this.mainComponentService.deleteItem(
      this.dbTable,
      itemId,
      this.name1,
      this.name2,
      this.tableItemId,
      this.paginator,
      this.dataSource
    );
  }
```

<p>The html that calls from click events.</p>

<p>members.component.html</p>

<pre class="lang-html prettyprint-override"><code><ng-container matColumnDef="options">
          <mat-header-cell *matHeaderCellDef> Options </mat-header-cell>
          <mat-cell *matCellDef="let row">
            <button (click)="viewProfile(row.member_id)">View</button>
            <button (click)="deleteMember(row.member_id)">Delete</button>
            <button (click)="editMember(row.member_id)">Edit</button>
          </mat-cell>
        </ng-container>
</code>```

Now the delete meat. This lives on a higher level component, above sections such as members, projects, etc and is used by the top level components in those sections of the app.  Saves a lot of copying and pasting!

Notice the deleteRowDataTable function below the main action.  This removes the row from the data table so the user sees it removed after their action.  The trick is delete it from the database AND delete the data from the dataSource object.  This way the user doesn't have to refresh the dataSource from the db.

main-component.service.ts

// --- DELETE ---

  public deleteItem(dbTable, itemId, name1, name2, tableItemId, paginator, dataSource) {
    // Get name from record to be deleted to warn in dialog.
    this.dsData = dataSource.data;
    const record = this.dsData.find(obj => obj[tableItemId] === itemId);
    const name = 'Delete ' + record[name1] + ' ' + record[name2] + '?';
// Call the confirm dialog component
this.confirmService.confirm(name, 'This action is final. Gone forever!')
  .switchMap(res => {if (res === true) {
    return this.appService.deleteItem(dbTable, itemId);
  }})
  .subscribe(
    result => {
      this.success();
      // Refresh DataTable to remove row.
      this.deleteRowDataTable (itemId, tableItemId, paginator, dataSource);
    },
    (err: HttpErrorResponse) => {
      console.log(err.error);
      console.log(err.message);
      this.messagesService.openDialog('Error', 'Delete did not happen.');
    }
  );
  }

  // Remove the deleted row from the data table. Need to remove from the downloaded data first.

  private deleteRowDataTable (itemId, tableItemId, paginator, dataSource) {
    this.dsData = dataSource.data;
    const itemIndex = this.dsData.findIndex(obj => obj[tableItemId] === itemId);
    dataSource.data.splice(itemIndex, 1);
    dataSource.paginator = paginator;
  }
```

<p>This service is skinny and lives at the top of the stack along with app.module, etc.  Not part of your question but may be useful for a complete answer for someone.</p>

<p>app.service.ts</p>

<pre class="lang-js prettyprint-override"><code>// ---- DELETES a single record. ----

  public deleteItem(dbTable: string, itemId: number):  Observable<any> {
    return this.http
      .delete(`${this.baseUrl}${dbTable}?ids=${itemId}`, {headers: this.headers});
  }
</code>```

Body:
Currently am using angular material design mat-table. Kindly help me to delete a record of data from mat-table.

Here is the code:

            <mat-table #table [dataSource]="dataSource" matSort slimScroll width="auto" height="450px" color="rgba(0,0,0,0.3)" size="3px">

                    <ng-container matColumnDef="modelname">
                    <mat-header-cell *matHeaderCellDef mat-sort-header> Name </mat-header-cell>
                    <mat-cell *matCellDef="let element" data-toggle="modal" data-target="#deviceView"> {{element.modelname}} </mat-cell>
                    </ng-container>

                    <ng-container matColumnDef="modelnumber">
                    <mat-header-cell *matHeaderCellDef mat-sort-header> Number </mat-header-cell>
                    <mat-cell *matCellDef="let element" data-toggle="modal" data-target="#deviceView"> {{element.modelnumber}} </mat-cell>
                    </ng-container>

                    <ng-container matColumnDef="manufacturer">
                    <mat-header-cell *matHeaderCellDef mat-sort-header> Manufac </mat-header-cell>
                    <mat-cell *matCellDef="let element" data-toggle="modal" data-target="#deviceView"> {{element.manufacturer}} </mat-cell>
                    </ng-container>

                    <mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row>
                    <mat-row *matRowDef="let row; columns: displayedColumns; let i = index;" id="{{row.uuid}}" (click)="displayData(row.uuid); deleterow(index)"></mat-row>
                </mat-table>

                    <mat-paginator [length]="length" [pageSize]="1000" (page)="pageEvent = $event; onPaginateChange($event)">
                    </mat-paginator>

                        {{pageSize}} / {{length}}

= pageEvent.pageSize * pageEvent.pageIndex + pageEvent.pageSize">{{pageEvent.pageSize * pageEvent.pageIndex + pageEvent.pageSize}} / {{pageEvent.length}}

                         <div *ngIf="pageEvent.length <= pageEvent.pageSize * pageEvent.pageIndex + pageEvent.pageSize">{{pageEvent.length}} / {{pageEvent.length}}

Kindly check and let me know any suggestions.

Body:
This is called from somewhere like a button.  It lives on this main component for the members section that has child components that call it, including the html for this component.  It passes the params from the table along with whatever else is needed for the service above it to work.  I included it so you understand how the delete row in table code works in case that matters.

members.component.ts

  // --- DELETE ---

  public deleteMember(itemId) {
    return this.mainComponentService.deleteItem(
      this.dbTable,
      itemId,
      this.name1,
      this.name2,
      this.tableItemId,
      this.paginator,
      this.dataSource
    );
  }

The html that calls from click events.

members.component.html

<ng-container matColumnDef="options">
          <mat-header-cell *matHeaderCellDef> Options </mat-header-cell>
          <mat-cell *matCellDef="let row">
            <button (click)="viewProfile(row.member_id)">View</button>
            <button (click)="deleteMember(row.member_id)">Delete</button>
            <button (click)="editMember(row.member_id)">Edit</button>
          </mat-cell>
        </ng-container>

Now the delete meat. This lives on a higher level component, above sections such as members, projects, etc and is used by the top level components in those sections of the app.  Saves a lot of copying and pasting!

Notice the deleteRowDataTable function below the main action.  This removes the row from the data table so the user sees it removed after their action.  The trick is delete it from the database AND delete the data from the dataSource object.  This way the user doesn't have to refresh the dataSource from the db.

main-component.service.ts

// --- DELETE ---

  public deleteItem(dbTable, itemId, name1, name2, tableItemId, paginator, dataSource) {
    // Get name from record to be deleted to warn in dialog.
    this.dsData = dataSource.data;
    const record = this.dsData.find(obj => obj[tableItemId] === itemId);
    const name = 'Delete ' + record[name1] + ' ' + record[name2] + '?';
// Call the confirm dialog component
this.confirmService.confirm(name, 'This action is final. Gone forever!')
  .switchMap(res => {if (res === true) {
    return this.appService.deleteItem(dbTable, itemId);
  }})
  .subscribe(
    result => {
      this.success();
      // Refresh DataTable to remove row.
      this.deleteRowDataTable (itemId, tableItemId, paginator, dataSource);
    },
    (err: HttpErrorResponse) => {
      console.log(err.error);
      console.log(err.message);
      this.messagesService.openDialog('Error', 'Delete did not happen.');
    }
  );
  }

  // Remove the deleted row from the data table. Need to remove from the downloaded data first.

  private deleteRowDataTable (itemId, tableItemId, paginator, dataSource) {
    this.dsData = dataSource.data;
    const itemIndex = this.dsData.findIndex(obj => obj[tableItemId] === itemId);
    dataSource.data.splice(itemIndex, 1);
    dataSource.paginator = paginator;
  }

This service is skinny and lives at the top of the stack along with app.module, etc.  Not part of your question but may be useful for a complete answer for someone.

app.service.ts

// ---- DELETES a single record. ----

  public deleteItem(dbTable: string, itemId: number):  Observable<any> {
    return this.http
      .delete(`${this.baseUrl}${dbTable}?ids=${itemId}`, {headers: this.headers});
  }


问:
How can add markers on real time on Google maps Android studio
I am using fragments, I want that every time the fragment is restarted add markers from a list that I have in a database

enter image description here

答:
Call your logos() method inside onResume() of Fragment, like following :

```<code> @Override
 public void onResume() {
     Log.e("DEBUG", "onResume of Fragment");
     logos();
  }
</code>```

Also remove static from method defination.

Body:
Call your logos() method inside onResume() of Fragment, like following :

 @Override
 public void onResume() {
     Log.e("DEBUG", "onResume of Fragment");
     logos();
  }

Also remove static from method defination.


问:
how i can compare changing API response body with expected API using restAssured

Hi, I am trying to create a API Automation Framework using Rest assured library what issue i am facing is the API response body is changing very frequently. Plz Help how i can compare changing API response body with expected API
</p>

答: Use Response Specification or Object Mapping options. In the first you may create bunch of expectations in the second compare actual object with expected in the way you like. I prefer first option.</p>


问:
How can I make the await subscribe block complete before executing next line of code?
I am subscribing to Google Maps API to pull in coordinates based on an address. My understanding is that by awaiting the subscribe line, it should wait for that code block to finish before moving onto the following lines.

```<code>  async getCoordinates(address) {
      let url = 'https://maps.googleapis.com/maps/api/geocode/json?address=' + encodeURIComponent(address) + '&key=' + environment.geocodeKey;
      let lat;
      let lng;
      let coord: Coordinate;
      await this.http.get(url).subscribe(data => {
          let map = data.json() as Results;
          lat = map.results[0].geometry.location.lat;
          lng = map.results[0].geometry.location.lng;
          console.log("inner lat is: " + lat)
      });
      console.log("outer lat is: " + lat)
      coord = new Coordinate(lat, lng);
      console.log("coord lat is: "+ coord.latitude)
      return coord;
  }
</code>```

However when I run the app, I see this in the console:

```<code>outer lat is: undefined
coord lat is: undefined
inner lat is: 38.912799
</code>```

That is indicating to me that the code inside the await block is executing last. I have the same results without the async/await. How can I get the subscribe code to execute first and make the other code wait until my lat and lng have a value? Right now they only have values inside the subscribe block, but I can't put a return line inside like this answer suggests.

I have read that await/async in Angular is essentially the same thing as a promise and callback. I am treating the result of this async getCoordinates function as a promise already by using .then():

```<code>service.getCoordinates(this.address).then(
    (val) => this.coordinates = val,
    (err) => console.log(err)
);
</code>```

答:
Angular's http service returns an Observable. You can convert this to a promise by using the rxjs toPromise operator:

```<code>import 'rxjs/add/operator/toPromise';

await this.http.get(url).toPromise().then()
...
</code>```

Body:
I am subscribing to Google Maps API to pull in coordinates based on an address. My understanding is that by awaiting the subscribe line, it should wait for that code block to finish before moving onto the following lines.

  async getCoordinates(address) {
      let url = 'https://maps.googleapis.com/maps/api/geocode/json?address=' + encodeURIComponent(address) + '&key=' + environment.geocodeKey;
      let lat;
      let lng;
      let coord: Coordinate;
      await this.http.get(url).subscribe(data => {
          let map = data.json() as Results;
          lat = map.results[0].geometry.location.lat;
          lng = map.results[0].geometry.location.lng;
          console.log("inner lat is: " + lat)
      });
      console.log("outer lat is: " + lat)
      coord = new Coordinate(lat, lng);
      console.log("coord lat is: "+ coord.latitude)
      return coord;
  }

However when I run the app, I see this in the console:

outer lat is: undefined
coord lat is: undefined
inner lat is: 38.912799

That is indicating to me that the code inside the await block is executing last. I have the same results without the async/await. How can I get the subscribe code to execute first and make the other code wait until my lat and lng have a value? Right now they only have values inside the subscribe block, but I can't put a return line inside like this answer suggests.

I have read that await/async in Angular is essentially the same thing as a promise and callback. I am treating the result of this async getCoordinates function as a promise already by using .then():

service.getCoordinates(this.address).then(
    (val) => this.coordinates = val,
    (err) => console.log(err)
);

Body:
Angular's http service returns an Observable. You can convert this to a promise by using the rxjs toPromise operator:

import 'rxjs/add/operator/toPromise';

await this.http.get(url).toPromise().then()
...


答:
The hash part of the URL (the # and everything after) isn't sent by the browser to the server, so it's not available to PHP.

If you absolutely need your server side to be aware of it, the only way is to load an intermediate page containing Javascript that reads the hash value, and makes another request where the value is contained in a regular HTTP parameter. E.g. the intermediate page could be something like:

```<code><html>
    <!-- snip.. -->
    <body>
        <script type="text/javascript">
            $(document).ready(function() {
                $.get('realContent.php?hash=' + location.hash,
                    function(data) {
                        $('#content').html(data);
                     }
                );
             }
        </script>
        <div id="content"></div>
    </body>
</html>
</code>```

Body:
The hash part of the URL (the # and everything after) isn't sent by the browser to the server, so it's not available to PHP.

If you absolutely need your server side to be aware of it, the only way is to load an intermediate page containing Javascript that reads the hash value, and makes another request where the value is contained in a regular HTTP parameter. E.g. the intermediate page could be something like:

<html>
    <!-- snip.. -->
    <body>
        <script type="text/javascript">
            $(document).ready(function() {
                $.get('realContent.php?hash=' + location.hash,
                    function(data) {
                        $('#content').html(data);
                     }
                );
             }
        </script>
        <div id="content"></div>
    </body>
</html>


答:
I used this function for this(PHP 5.2)::</p>

```<code>function getInstance($uri = 'SERVER')
    {

        if ($uri == 'SERVER')
        {
            if (isset($_SERVER['HTTPS']) && !empty($_SERVER['HTTPS']) && (strtolower($_SERVER['HTTPS']) != 'off')) {
                $https = 's://';
            } else {
                $https = '://';
            }

            if (!empty ($_SERVER['PHP_SELF']) && !empty ($_SERVER['REQUEST_URI'])) {
                $theURI = 'http' . $https . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];

                if (strlen($_SERVER['QUERY_STRING']) && strpos($_SERVER['REQUEST_URI'], $_SERVER['QUERY_STRING']) === false) {
                    $theURI .= '?'.$_SERVER['QUERY_STRING'];
                }
            }
             else
             {
                $theURI = 'http' . $https . $_SERVER['HTTP_HOST'] . $_SERVER['SCRIPT_NAME'];
                if (isset($_SERVER['QUERY_STRING']) && !empty($_SERVER['QUERY_STRING'])) {
                    $theURI .= '?' . $_SERVER['QUERY_STRING'];
                }
            }

            $theURI = urldecode($theURI);
            $theURI = str_replace('"', '"',$theURI);
            $theURI = str_replace('<', '<',$theURI);
            $theURI = str_replace('>', '>',$theURI);
            $theURI = preg_replace('/eval\((.*)\)/', '', $theURI);
            $theURI = preg_replace('/[\\\"\\\'][\\s]*javascript:(.*)[\\\"\\\']/', '""', $theURI);

    }
    echo (string)$theURI;
}
</code>```

Body:
I used this function for this(PHP 5.2)::

function getInstance($uri = 'SERVER')
    {

        if ($uri == 'SERVER')
        {
            if (isset($_SERVER['HTTPS']) && !empty($_SERVER['HTTPS']) && (strtolower($_SERVER['HTTPS']) != 'off')) {
                $https = 's://';
            } else {
                $https = '://';
            }

            if (!empty ($_SERVER['PHP_SELF']) && !empty ($_SERVER['REQUEST_URI'])) {
                $theURI = 'http' . $https . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];

                if (strlen($_SERVER['QUERY_STRING']) && strpos($_SERVER['REQUEST_URI'], $_SERVER['QUERY_STRING']) === false) {
                    $theURI .= '?'.$_SERVER['QUERY_STRING'];
                }
            }
             else
             {
                $theURI = 'http' . $https . $_SERVER['HTTP_HOST'] . $_SERVER['SCRIPT_NAME'];
                if (isset($_SERVER['QUERY_STRING']) && !empty($_SERVER['QUERY_STRING'])) {
                    $theURI .= '?' . $_SERVER['QUERY_STRING'];
                }
            }

            $theURI = urldecode($theURI);
            $theURI = str_replace('"', '&quot;',$theURI);
            $theURI = str_replace('<', '&lt;',$theURI);
            $theURI = str_replace('>', '&gt;',$theURI);
            $theURI = preg_replace('/eval\((.*)\)/', '', $theURI);
            $theURI = preg_replace('/[\\\"\\\'][\\s]*javascript:(.*)[\\\"\\\']/', '""', $theURI);

    }
    echo (string)$theURI;
}


问:
Return a promise without waiting for a dependant promise in function in nodejs
I am using node 8.x. Hence, I have access to all latest features i.e. async/ await etc.

The scenario is similar to following
(Not correct syntax, just for explanation):

```<code>createUser()
{
    let userAddress = createAddress(); // Aync, returns a promise
    User.create(name: 'foo', address: userAddress); // User creation is dependant on address. Also, User.create returns a promise.
}
</code>```

Basically, User object creation is dependant on the creation of address object. I want the createUser function to execute asynchronously i.e. to return a promise as soon as possible without waiting for address object to be created.

The purpose of this question is not to get things done but to understand what is the best way to solve this kind of issues in async programming.

Few ways that I can think of:
1: Create a new promise object and return right away when entered in createUser function. Resolve it when the user object is created.
2: Make createUser an async function and then return user Promise. Facing issues with this method:

```<code>async function createUser()
{
    address = await createAddress();
    return User.create(name: 'foo', address: userAddress);
}
</code>```

The problem is function waits for the address before returning the control which I don't want. (Or it does not make any diff as the function is async. Performance is a big criterion in my case)

How to deal with this kind of promise dependancy where you want to return promise of parent object but you parent object is dependant on child object's promise.

Thank you.

答:
If createAddress is a promise returning the address, let's say address, you can do something like this:

```<code>createAddress().then(function(address) {
  User.create(name: 'foo', address: address).then(function() {
    // User and address has been created
  })
})

// Do something here that runs even though createAddress has not yet been resolved
</code>```

This will require you to wait for the promise to be resolved before doing some other code.

Body:
I am using node 8.x. Hence, I have access to all latest features i.e. async/ await etc.

The scenario is similar to following
(Not correct syntax, just for explanation):

createUser()
{
    let userAddress = createAddress(); // Aync, returns a promise
    User.create(name: 'foo', address: userAddress); // User creation is dependant on address. Also, User.create returns a promise.
}

Basically, User object creation is dependant on the creation of address object. I want the createUser function to execute asynchronously i.e. to return a promise as soon as possible without waiting for address object to be created.

The purpose of this question is not to get things done but to understand what is the best way to solve this kind of issues in async programming.

Few ways that I can think of:
1: Create a new promise object and return right away when entered in createUser function. Resolve it when the user object is created.
2: Make createUser an async function and then return user Promise. Facing issues with this method:

async function createUser()
{
    address = await createAddress();
    return User.create(name: 'foo', address: userAddress);
}

The problem is function waits for the address before returning the control which I don't want. (Or it does not make any diff as the function is async. Performance is a big criterion in my case)

How to deal with this kind of promise dependancy where you want to return promise of parent object but you parent object is dependant on child object's promise.

Thank you.

Body:
If createAddress is a promise returning the address, let's say address, you can do something like this:

createAddress().then(function(address) {
  User.create(name: 'foo', address: address).then(function() {
    // User and address has been created
  })
})

// Do something here that runs even though createAddress has not yet been resolved

This will require you to wait for the promise to be resolved before doing some other code.


问:
Mongoose - ObjectID as key?
I would like to have an object("ingredients" in example) in my mongoose model, where the keys are ObjectIDs, and their values are numbers. Is it possible to do so? How should I define my mongoose schema? You can find an example below.

Example JSON:

```<code>  {
    "_id": ""5a2539b41c574006c46f1a07",
    "name": "xyz",
    "ingredients": {
        "5a23f5e6159f5c3438c75971": 50,
        "5a23f60b159f5c3438c75972": 50,
        "5a255b04c9d9c40ac8927dd5": 50
    }
  }
</code>```

Thank you for your help in advance.

答:
you can use mix schema

```<code>{
    "_id": ""5a2539b41c574006c46f1a07",
    "name": "xyz",
    "ingredients": mongoose.Schema.Types.mix
  }
</code>```

reference how to create dynamic document keys in mongodb

insertion of dynamic key is so simple

```<code>insertData_dynamic_colone: function(collection, colone1, colone2) {
    var obj = {};
    obj[colone1] = "14";
    obj[colone2] = "15";
    dbObject.collection(collection).insertOne(obj, function(err, result) {
        assert.equal(err, null);
    });
}
</code>```

i know you'll also need to update dymanic key in future
take a reference Update Mongo array: remove dynamic key

```<code>collection.update(
    {"_id": ObjectId("5a2539b41c574006c46f1a07")},
    {"$unset": {"ingredients.5a23f5e6159f5c3438c75971": ""}}
)
</code>```

Title: Mongoose - ObjectID as key?

Body:
I would like to have an object("ingredients" in example) in my mongoose model, where the keys are ObjectIDs, and their values are numbers. Is it possible to do so? How should I define my mongoose schema? You can find an example below.

Example JSON:

  {
    "_id": ""5a2539b41c574006c46f1a07",
    "name": "xyz",
    "ingredients": {
        "5a23f5e6159f5c3438c75971": 50,
        "5a23f60b159f5c3438c75972": 50,
        "5a255b04c9d9c40ac8927dd5": 50
    }
  }

Thank you for your help in advance.

Body:
you can use mix schema

{
    "_id": ""5a2539b41c574006c46f1a07",
    "name": "xyz",
    "ingredients": mongoose.Schema.Types.mix
  }

reference how to create dynamic document keys in mongodb

insertion of dynamic key is so simple

insertData_dynamic_colone: function(collection, colone1, colone2) {
    var obj = {};
    obj[colone1] = "14";
    obj[colone2] = "15";
    dbObject.collection(collection).insertOne(obj, function(err, result) {
        assert.equal(err, null);
    });
}

i know you'll also need to update dymanic key in future
take a reference Update Mongo array: remove dynamic key

collection.update(
    {"_id": ObjectId("5a2539b41c574006c46f1a07")},
    {"$unset": {"ingredients.5a23f5e6159f5c3438c75971": ""}}
)


答:
If you want to return a promise, then you're basically looking to use promises the way they were intended to be used:

```<code>createUser() {
    return createAddress()
        .then((address) =>
            User.create({ name: 'foo', address: address })
        );
}
</code>```

Now the createUser method is returning a promise, which will be resolved at some point in the future. Your code can continue work, can add more .then(...) or .catch(...) callbacks to that promise, etc.

Title: Return a promise without waiting for a dependant promise in function in nodejs

Body:
If you want to return a promise, then you're basically looking to use promises the way they were intended to be used:

createUser() {
    return createAddress()
        .then((address) =>
            User.create({ name: 'foo', address: address })
        );
}

Now the createUser method is returning a promise, which will be resolved at some point in the future. Your code can continue work, can add more .then(...) or .catch(...) callbacks to that promise, etc.


问:
print statement delays printing when followed by comma
In Python 2.7, if I use print statement followed by comma as the following:

```<code>print('Generation ...'),
X, y = generate_dataset(num_samples)
print('Done!')
</code>```

The first print print('Generation ...'), will NOT show up in the terminal until X, y = generate_dataset(num_samples) is finished! How can I force the print to immediately step by step with the existence of comma?

答: You can also run the python interpreter with the -u flag if you don't want to handle this in code.

Body:
In Python 2.7, if I use print statement followed by comma as the following:

print('Generation ...'),
X, y = generate_dataset(num_samples)
print('Done!')

The first print print('Generation ...'), will NOT show up in the terminal until X, y = generate_dataset(num_samples) is finished! How can I force the print to immediately step by step with the existence of comma?


问:
Cmake/Ctest test failure when initializing googletest
I am trying to integrate Ctest and googletest in my project. I included googletest in my project as described in https://crascit.com/2015/07/25/cmake-gtest/.

I created a new test folder with a CoreTest.cpp and a CMakeLists.txt. The CMakeLists contains:

```<code>ADD_EXECUTABLE(CoreTest CoreTest.cpp)
TARGET_LINK_LIBRARIES(CoreTest corelib gtest gmock)
ADD_TEST(NAME CoreTest COMMAND CoreTest)
</code>```

CoreTest.cpp contains:

```<code>int main(int argc, char **argv)
{
    testing::InitGoogleTest(&argc, argv);
    //return RUN_ALL_TESTS();
    return 0;
}
</code>```

This fails:

```<code>1>------ Rebuild All started: Project: RUN_TESTS, Configuration: Debug x64 ------
1>  Test project
1>      Start 1: CoreTest
1>  1/1 Test #1: CoreTest .....................***Failed    1.52 sec
1>
1>  0% tests passed, 1 tests failed out of 1
</code>```

However if I comment the InitGoogleTest line then the test succeeds.

Any idea on what could be the problem here ?

Many thanks !

Thanks axalis! I tried to run from the command line and realized that the googletest dlls were not in my path, which was the problem.

I added multiple tests but I can only see the ctest output in MSVC:

```<code>1>------ Rebuild All started: Project: RUN_TESTS, Configuration: Debug x64 ------
1>  Test project
1>      Start 1: CoreTest
1>  1/1 Test #1: CoreTest .....................   Passed    0.03 sec
1>
1>  100% tests passed, 0 tests failed out of 1
</code>```

Is there a way to see the googletest output like what I get from the console ?:

```<code>>CoreTest.exe
[==========] Running 2 tests from 1 test case.
[----------] Global test environment set-up.
[----------] 2 tests from MathTest
[ RUN      ] MathTest.TwoPlusTwoEqualsFour
[       OK ] MathTest.TwoPlusTwoEqualsFour (0 ms)
[ RUN      ] MathTest.TwoPlusFourEqualsSix
[       OK ] MathTest.TwoPlusFourEqualsSix (0 ms)
[----------] 2 tests from MathTest (1 ms total)

[----------] Global test environment tear-down
[==========] 2 tests from 1 test case ran. (4 ms total)
[  PASSED  ] 2 tests.
</code>```

答:
The GoogleTest module provides two functions which can be used to show the result of each individual test defined within your test executable. gtest_add_tests() is the traditional method which scans your source file(s) at configure time, while gtest_discover_tests() (available from CMake 3.10) delays working out the set of tests until either build time or when CTest is run (see below) and is more robust (e.g. it has no problem with things like type- or value-parameterised tests).

By default, gtest_discover_tests() will query the test executable at build time using a POST_BUILD step on the target. With CMake 3.18 or later, you can ask it to query the test executable at test time instead. The DISCOVERY_MODE option controls when the query is performed. POST_BUILD corresponds to the default behavior, while PRE_TEST delays the query to test time. Rather than setting this option on every test, you can change the default behavior globally with the CMAKE_GTEST_DISCOVER_TESTS_DISCOVERY_MODE variable, which accepts the same values as the DISCOVERY_MODE option. If you are cross-compiling, then PRE_TEST mode should be used, since you know the test executable must be runnable at test time (i.e. an emulator would have to be set already), but the same is not true at build time.

If using CMake 3.8 or earlier, the gtest_add_tests() function is provided by FindGTest rather than GoogleTest. If you need compatibility with older CMake versions, use FindGTest because it pulls in the GoogleTest module anyway. If you can require CMake 3.9 or later, use GoogleTest directly because you don't actually want to try to find gtest since you are incorporating it directly into your build. With 3.10 or later, your test can be defined like this:

```<code>include(GoogleTest)
gtest_discover_tests(CoreTest)
</code>```

Body:
I am trying to integrate Ctest and googletest in my project. I included googletest in my project as described in https://crascit.com/2015/07/25/cmake-gtest/.

I created a new test folder with a CoreTest.cpp and a CMakeLists.txt. The CMakeLists contains:

ADD_EXECUTABLE(CoreTest CoreTest.cpp)
TARGET_LINK_LIBRARIES(CoreTest corelib gtest gmock)
ADD_TEST(NAME CoreTest COMMAND CoreTest)

CoreTest.cpp contains:

int main(int argc, char **argv)
{
    testing::InitGoogleTest(&argc, argv);
    //return RUN_ALL_TESTS();
    return 0;
}

This fails:

1>------ Rebuild All started: Project: RUN_TESTS, Configuration: Debug x64 ------
1>  Test project
1>      Start 1: CoreTest
1>  1/1 Test #1: CoreTest .....................***Failed    1.52 sec
1>
1>  0% tests passed, 1 tests failed out of 1

However if I comment the InitGoogleTest line then the test succeeds.

Any idea on what could be the problem here ?

Many thanks !

Thanks axalis! I tried to run from the command line and realized that the googletest dlls were not in my path, which was the problem.

I added multiple tests but I can only see the ctest output in MSVC:

1>------ Rebuild All started: Project: RUN_TESTS, Configuration: Debug x64 ------
1>  Test project
1>      Start 1: CoreTest
1>  1/1 Test #1: CoreTest .....................   Passed    0.03 sec
1>
1>  100% tests passed, 0 tests failed out of 1

Is there a way to see the googletest output like what I get from the console ?:

>CoreTest.exe
[==========] Running 2 tests from 1 test case.
[----------] Global test environment set-up.
[----------] 2 tests from MathTest
[ RUN      ] MathTest.TwoPlusTwoEqualsFour
[       OK ] MathTest.TwoPlusTwoEqualsFour (0 ms)
[ RUN      ] MathTest.TwoPlusFourEqualsSix
[       OK ] MathTest.TwoPlusFourEqualsSix (0 ms)
[----------] 2 tests from MathTest (1 ms total)

[----------] Global test environment tear-down
[==========] 2 tests from 1 test case ran. (4 ms total)
[  PASSED  ] 2 tests.

Body:
The GoogleTest module provides two functions which can be used to show the result of each individual test defined within your test executable. gtest_add_tests() is the traditional method which scans your source file(s) at configure time, while gtest_discover_tests() (available from CMake 3.10) delays working out the set of tests until either build time or when CTest is run (see below) and is more robust (e.g. it has no problem with things like type- or value-parameterised tests).

By default, gtest_discover_tests() will query the test executable at build time using a POST_BUILD step on the target. With CMake 3.18 or later, you can ask it to query the test executable at test time instead. The DISCOVERY_MODE option controls when the query is performed. POST_BUILD corresponds to the default behavior, while PRE_TEST delays the query to test time. Rather than setting this option on every test, you can change the default behavior globally with the CMAKE_GTEST_DISCOVER_TESTS_DISCOVERY_MODE variable, which accepts the same values as the DISCOVERY_MODE option. If you are cross-compiling, then PRE_TEST mode should be used, since you know the test executable must be runnable at test time (i.e. an emulator would have to be set already), but the same is not true at build time.

If using CMake 3.8 or earlier, the gtest_add_tests() function is provided by FindGTest rather than GoogleTest. If you need compatibility with older CMake versions, use FindGTest because it pulls in the GoogleTest module anyway. If you can require CMake 3.9 or later, use GoogleTest directly because you don't actually want to try to find gtest since you are incorporating it directly into your build. With 3.10 or later, your test can be defined like this:

include(GoogleTest)
gtest_discover_tests(CoreTest)

ContentLicense: CC BY-SA 4.0


问:
implementing error with mousemovementListener
I Know this has been asked before, but everywhere I see the question the answer isn't helpful at all... so here goes.

I using the book Learning Java and there's an example that looks like this:

```<code>import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class HelloJava2 {
    public static void main( String [] args ) {
        JFrame frame = new JFrame( "HelloJava2" );
        frame.add( new HelloComponent2("Hello, Java!") );
        frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
        frame.setSize( 300, 300 );
        frame.setVisible( true );
    }
}

class HelloComponent2 extends JComponent
    implements MouseMotionListener
{
    String theMessage;
    int messageX = 125;
    int messageY = 95;

    public HelloComponent2( String message ) {
        theMessage = message;
        addMouseMotionListener(this);
    }

    public void paintComponent(MouseEvent e) {
        // Save the mouse coordinates and paint the message.
        messageX = e.getX();

        messageY = e.getY();
        repaint();
    }

    public void mouseMoved(MouseEvent e) {

    }
}
</code>```

I typed it into the editor, but it gives me the error:

HelloJava2.java:15: error: HelloComponent2 is not abstract and does not override abstract method mouseDragged(MouseEvent) in MouseMotionListener
class HelloComponent2 extends JComponent
^
1 error

I am completely new to this language so I am completely lost on what implementing even means... any help is greatly appreciated!

答:
The problem is you forgot implement a method called mouseDragged(MouseEvent) of the interface MouseMotionListener. So you only need include the method, something like this:

```<code>class HelloComponent2 extends JComponent
    implements MouseMotionListener
{
  String theMessage;
  int messageX = 125;
  int messageY = 95;

  public HelloComponent2( String message ) {
    theMessage = message;
    addMouseMotionListener(this);
  }

  public void paintComponent(MouseEvent e) {
    // Save the mouse coordinates and paint the message.
    messageX = e.getX();

    messageY = e.getY();
    repaint();
  }
  //Here it is the method you forgot include in your class
  @Override
  public void mouseDragged(MouseEvent e) {

  }

  public void mouseMoved(MouseEvent e) {

  }
}
</code>```

Body:
I Know this has been asked before, but everywhere I see the question the answer isn't helpful at all... so here goes.

I using the book Learning Java and there's an example that looks like this:

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class HelloJava2 {
    public static void main( String [] args ) {
        JFrame frame = new JFrame( "HelloJava2" );
        frame.add( new HelloComponent2("Hello, Java!") );
        frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
        frame.setSize( 300, 300 );
        frame.setVisible( true );
    }
}

class HelloComponent2 extends JComponent
    implements MouseMotionListener
{
    String theMessage;
    int messageX = 125;
    int messageY = 95;

    public HelloComponent2( String message ) {
        theMessage = message;
        addMouseMotionListener(this);
    }

    public void paintComponent(MouseEvent e) {
        // Save the mouse coordinates and paint the message.
        messageX = e.getX();

        messageY = e.getY();
        repaint();
    }

    public void mouseMoved(MouseEvent e) {

    }
}

I typed it into the editor, but it gives me the error:

HelloJava2.java:15: error: HelloComponent2 is not abstract and does not override abstract method mouseDragged(MouseEvent) in MouseMotionListener
class HelloComponent2 extends JComponent
^
1 error

I am completely new to this language so I am completely lost on what implementing even means... any help is greatly appreciated!

Body:
The problem is you forgot implement a method called mouseDragged(MouseEvent) of the interface MouseMotionListener. So you only need include the method, something like this:

class HelloComponent2 extends JComponent
    implements MouseMotionListener
{
  String theMessage;
  int messageX = 125;
  int messageY = 95;

  public HelloComponent2( String message ) {
    theMessage = message;
    addMouseMotionListener(this);
  }

  public void paintComponent(MouseEvent e) {
    // Save the mouse coordinates and paint the message.
    messageX = e.getX();

    messageY = e.getY();
    repaint();
  }
  //Here it is the method you forgot include in your class
  @Override
  public void mouseDragged(MouseEvent e) {

  }

  public void mouseMoved(MouseEvent e) {

  }
}


问:
Python: SyntaxError: keyword can't be an expression
In a Python script I call a function from rpy2, but I get this error:

```<code>#using an R module
res = DirichletReg.ddirichlet(np.asarray(my_values),alphas,
                              log=False, sum.up=False)
SyntaxError: keyword can't be an expression
</code>```

What exactly went wrong here?

答:
Using the Elastic search DSL API, you may hit the same error with

```<code>s = Search(using=client, index="my-index") \
    .query("match", category.keyword="Musician")
</code>```

You can solve it by doing:

```<code>s = Search(using=client, index="my-index") \
    .query({"match": {"category.keyword":"Musician/Band"}})
</code>```

Body:
In a Python script I call a function from rpy2, but I get this error:

#using an R module
res = DirichletReg.ddirichlet(np.asarray(my_values),alphas,
                              log=False, sum.up=False)
SyntaxError: keyword can't be an expression

What exactly went wrong here?

Body:
Using the Elastic search DSL API, you may hit the same error with

s = Search(using=client, index="my-index") \
    .query("match", category.keyword="Musician")

You can solve it by doing:

s = Search(using=client, index="my-index") \
    .query({"match": {"category.keyword":"Musician/Band"}})


问:
How to read inline styling of an element?
I'd like to know if it's possible to determine what inline styling has been attributed to an HTML element.  I do not need to retrieve the value, but rather just detect if it's been set inline or not.

For instance, if the HTML were:

```<code><div id="foo" style="width: 100px; height: 100px; background: green;"></div>
</code>```

How can I determine that width, height, and background have been explicitly declared, inline?

As far as I can tell, the solution can work two ways.  I can ask it if a specific attribute is set and it will tell me true or false, or it can tell me all attributes that have been set.  Like so:

```<code>var obj = document.getElementById('foo');
obj.hasInlineStyle('width');  //returns true;
obj.hasInlineStyle('border'); //returns false;

//or

obj.getInlineStyles();   //returns array with values:
                       // 'width' 'height' and 'background'
</code>```

I'm not interested in css attributes that are inherited via declarations in a stylesheet, only inline styles.  One last thing, I have no control over the HTML source.

Thanks

答:
Are you trying to check if a certain styling attribute exists, or just want a list of the possible attributes?
If you already know the attribute, then you can just use

```<code>hasStyle(obj,'width');
function hasStyle(obj, style)
{
     switch(style)
         case 'width':
              return obj.style.width ? true : false;
         case 'background':
              return obj.style.background ? true : false;
}
</code>```

You can use Paolo's function to generate an array of the styles.

OwnerDisplayName: sam

Body:
I'd like to know if it's possible to determine what inline styling has been attributed to an HTML element.  I do not need to retrieve the value, but rather just detect if it's been set inline or not.

For instance, if the HTML were:

How can I determine that width, height, and background have been explicitly declared, inline?

As far as I can tell, the solution can work two ways.  I can ask it if a specific attribute is set and it will tell me true or false, or it can tell me all attributes that have been set.  Like so:

var obj = document.getElementById('foo');
obj.hasInlineStyle('width');  //returns true;
obj.hasInlineStyle('border'); //returns false;

//or

obj.getInlineStyles();   //returns array with values:
                       // 'width' 'height' and 'background'

I'm not interested in css attributes that are inherited via declarations in a stylesheet, only inline styles.  One last thing, I have no control over the HTML source.

Thanks

Body:
Are you trying to check if a certain styling attribute exists, or just want a list of the possible attributes?
If you already know the attribute, then you can just use

hasStyle(obj,'width');
function hasStyle(obj, style)
{
     switch(style)
         case 'width':
              return obj.style.width ? true : false;
         case 'background':
              return obj.style.background ? true : false;
}

You can use Paolo's function to generate an array of the styles.


问:
Exporting JAR projects that use a common project
I have 4 different Java Projects created in Eclipse.

One of them contains all my Utilities and Helper methods, that the other 3 projects use.

I don't want to copy that same package 3 times into each project, since I want to be able to just edit it in one place if I should have to. So, I have referenced the myUtilities project from all other 3 projects.

I'll be exporting the 3 main projects and they will be going to different servers to run independently as  "java -jar myproject.jar"

Everytime I do an export, the myUtilities.jar is not getting compiled in the JAR. If I open the JAR, I can see it is not there.  And this is going to be a problem when I move them to the other servers.

Is there a way to add the package into the source for the JAR? Or am I going to have to copy the myUtilities.jar into the JAVA_HOME of each server?

This is my current Manifest file:

```<code>Manifest-Version: 1.0
Main-Class: com.elcool.process.alpha.RetrieverMain
</code>```

答:
You can place a reference to the external utility jars (myUtility.jar in your question) in the manifest in your project (myproject.jar). The manifest is a text file within the jar of your project, and many build tools support adding information to it.

This way, you can compile your utility jar once, make a reference to it in your projects, and deploy it alongside the three main projects, perhaps in the same directory or a nearby subdirectory.

Body:
I have 4 different Java Projects created in Eclipse.

One of them contains all my Utilities and Helper methods, that the other 3 projects use.

I don't want to copy that same package 3 times into each project, since I want to be able to just edit it in one place if I should have to. So, I have referenced the myUtilities project from all other 3 projects.

I'll be exporting the 3 main projects and they will be going to different servers to run independently as  "java -jar myproject.jar"

Everytime I do an export, the myUtilities.jar is not getting compiled in the JAR. If I open the JAR, I can see it is not there.  And this is going to be a problem when I move them to the other servers.

Is there a way to add the package into the source for the JAR? Or am I going to have to copy the myUtilities.jar into the JAVA_HOME of each server?

This is my current Manifest file:

Manifest-Version: 1.0
Main-Class: com.elcool.process.alpha.RetrieverMain


问:
file handling I/O c++ error

this is the code which i am trying to run.The compiler shows some warning that the variable 'p' may be possible to be used uninitialized.
  And ..on running it has a problem ..i will show..below.
  please correct me and explain .
  Thank you.
  execution of code
  *
  code
  that error is that..the first two elements of the character array being output are somewhat messed up!!!*

```<code>#include<bits/stdc++.h>
using namespace std;
class file{
public:int a;
char* name;
public:
file(int x,char* b):a(x){name=b;}
void printfile(){cout<<a<<" "<<name<<endl;}
};
int main(){
char *p;
int x=10;
cout<<"enter a name"<<endl;
cin>>p;
file k(x,p);
ofstream f("file",ios::out|ios::binary);
f.write((char*)&k,sizeof(class file));
f.close();
ifstream of("file",ios::in|ios::binary);
file o(0,'\0');
of.read((char*)&o,sizeof(class file));
o.printfile();
of.close();
return 1;
}
</code>```

答:
First of all I would advise you to read some basic manual about the c++ pointers and memory handling so you will better understand the source of the problem.

There are two major problems in your code.
The first is that you are creating a pointer which is not connected to any allocated memory. In simple words you are asking to access a memory address without asking the system to reserve it for you.

Additionally, in that memory location there can already be stored any bit configuration. The initialization of a variable is the task of giving a chunk of memory some data which have a meaningful interpretation. I'm not even sure what the in-stream operator of char* is supposed to do in this particular case. He is probably appending your characters after the last one which is not a 0 or an end of line.

Title: file handling I/O c++ error

Body:
this is the code which i am trying to run.The compiler shows some warning that the variable 'p' may be possible to be used uninitialized.
  And ..on running it has a problem ..i will show..below.
  please correct me and explain .
  Thank you.
  execution of code
  *
  code
  that error is that..the first two elements of the character array being output are somewhat messed up!!!*

#include<bits/stdc++.h>
using namespace std;
class file{
public:int a;
char* name;
public:
file(int x,char* b):a(x){name=b;}
void printfile(){cout<<a<<" "<<name<<endl;}
};
int main(){
char *p;
int x=10;
cout<<"enter a name"<<endl;
cin>>p;
file k(x,p);
ofstream f("file",ios::out|ios::binary);
f.write((char*)&k,sizeof(class file));
f.close();
ifstream of("file",ios::in|ios::binary);
file o(0,'\0');
of.read((char*)&o,sizeof(class file));
o.printfile();
of.close();
return 1;
}


问:
Converting List of Vectors to Data Frame in R
I'm trying to convert a list of vectors into a data frame, with there being a column for Company Names and column for the MPE. My list is generated by running the following code for each company:

```<code>MPE[[2]] <- c("Google", abs(((forecasted - goog[nrow(goog),]$close)
/ goog[nrow(goog),]$close)*100))
</code>```

Now, i'm having trouble making it into the appropriate data frame for further manipulation. What's the easiest way to do this?

This is an example list of vectors that I would want to manipulate into a dataframe with the company names in one column and the number in the second column.

```<code>test <- list(c("Google", 2))
test[[2]] <- c("Microsoft", 3)
test[[3]] <- c("Apple", 4)
</code>```

答:
You can use unlist with matrix and then turn into a dataframe. reducing with rbind could take a long time with a large dataframe I think.

```<code>df <- data.frame(matrix(unlist(test), nrow=length(test), byrow=T))
colnames(df) <- c("Company", "MPE")
</code>```

Body:
I'm trying to convert a list of vectors into a data frame, with there being a column for Company Names and column for the MPE. My list is generated by running the following code for each company:

MPE[[2]] <- c("Google", abs(((forecasted - goog[nrow(goog),]$close)
/ goog[nrow(goog),]$close)*100))

Now, i'm having trouble making it into the appropriate data frame for further manipulation. What's the easiest way to do this?

This is an example list of vectors that I would want to manipulate into a dataframe with the company names in one column and the number in the second column.

test <- list(c("Google", 2))
test[[2]] <- c("Microsoft", 3)
test[[3]] <- c("Apple", 4)

Body:
You can use unlist with matrix and then turn into a dataframe. reducing with rbind could take a long time with a large dataframe I think.

df <- data.frame(matrix(unlist(test), nrow=length(test), byrow=T))
colnames(df) <- c("Company", "MPE")


问:
Table MYSQL query
I have used WPAllImport to import data from a CSV-file to Advanced Custom Fields.
I now want to put them back together with a SQL query, but dont know how to do it.

I've tried WPDataTables, but when I choose 5 or more tables, WPDataTables stops.
If I pick 2, I get this code

```<code>SELECT posts_podukter.post_title AS podukter_post_title,
       podukter_meta_produkter_0_pris_tbl.meta_value AS podukter_meta_produkter_0_pris
FROM beta_h3L_posts AS posts_podukter
  INNER JOIN (SELECT podukter_meta_produkter_0_pris_tbl_posts.ID as id, meta_value, meta_key  FROM beta_h3L_postmeta AS podukter_meta_produkter_0_pris_tbl_postmeta  INNER JOIN beta_h3L_posts AS podukter_meta_produkter_0_pris_tbl_posts   ON podukter_meta_produkter_0_pris_tbl_postmeta.post_id = podukter_meta_produkter_0_pris_tbl_posts.ID   AND podukter_meta_produkter_0_pris_tbl_posts.post_type = 'podukter') AS podukter_meta_produkter_0_pris_tbl
     ON podukter_meta_produkter_0_pris_tbl.meta_key = 'produkter_0_pris' AND podukter_meta_produkter_0_pris_tbl.id = posts_podukter.ID
WHERE 1=1
   AND posts_podukter.post_type = 'podukter'
</code>```

I think this is too much code.
Can someone help me to get on the right way.... :-)

This is what the table should look like

Here is a capture how the table should look like

答:
I would agree that this is "too much code" which sounds sort of ridiculous, but in this case totally applies. That SQL statement that was produced could be written as:

```<code>    SELECT
        post.post_title as podukter_post_title,
        postmeta.meta_value as podukter_meta_produkter_0_pris
    FROM beta_h3L_posts AS posts
        INNER JOIN beta_h3L_postmeta AS postmeta
            ON postmeta.post_id = post.ID
            AND postmeta.meta_key = 'produkter_0_pris'
    WHERE posts.post_type = 'podukter'
</code>```

If there is another metavalue that you need you can join again to your meta table:

```<code>    SELECT
        post.post_title as podukter_post_title,
        postmeta.meta_value as podukter_meta_produkter_0_pris,
        postmeta2.meta_value as tilbudspris
    FROM beta_h3L_posts AS posts
        INNER JOIN beta_h3L_postmeta AS postmeta
            ON postmeta.post_id = post.ID
            AND postmeta.meta_key = 'produkter_0_pris'
        INNER JOIN beta_h3L_postmeta AS postmeta2
            ON postmeta.post_id = post.ID
            AND postmeta2.meta_key = 'tilbudspris'
    WHERE posts.post_type = 'podukter'
</code>```

I don't know what any of these words mean (besides post and postmeta) so I'm just going to assume that this is right/helpful.

The only thing is that you may want to switch to using a LEFT OUTER JOIN to your postmeta table just in case the meta_key you are after doesn't exist for the post.id you are querying. In that case, with an INNER JOIN the id/post will be dropped from the result set where a LEFT OUTER JOIN will show the id/post record with a blank for whatever that corresponding meta_value is that you are joining in.

Title: Table MYSQL query

Body:
I have used WPAllImport to import data from a CSV-file to Advanced Custom Fields.
I now want to put them back together with a SQL query, but dont know how to do it.

I've tried WPDataTables, but when I choose 5 or more tables, WPDataTables stops.
If I pick 2, I get this code

SELECT posts_podukter.post_title AS podukter_post_title,
       podukter_meta_produkter_0_pris_tbl.meta_value AS podukter_meta_produkter_0_pris
FROM beta_h3L_posts AS posts_podukter
  INNER JOIN (SELECT podukter_meta_produkter_0_pris_tbl_posts.ID as id, meta_value, meta_key  FROM beta_h3L_postmeta AS podukter_meta_produkter_0_pris_tbl_postmeta  INNER JOIN beta_h3L_posts AS podukter_meta_produkter_0_pris_tbl_posts   ON podukter_meta_produkter_0_pris_tbl_postmeta.post_id = podukter_meta_produkter_0_pris_tbl_posts.ID   AND podukter_meta_produkter_0_pris_tbl_posts.post_type = 'podukter') AS podukter_meta_produkter_0_pris_tbl
     ON podukter_meta_produkter_0_pris_tbl.meta_key = 'produkter_0_pris' AND podukter_meta_produkter_0_pris_tbl.id = posts_podukter.ID
WHERE 1=1
   AND posts_podukter.post_type = 'podukter'

I think this is too much code.
Can someone help me to get on the right way.... :-)

This is what the table should look like

Here is a capture how the table should look like

Body:
I would agree that this is "too much code" which sounds sort of ridiculous, but in this case totally applies. That SQL statement that was produced could be written as:

    SELECT
        post.post_title as podukter_post_title,
        postmeta.meta_value as podukter_meta_produkter_0_pris
    FROM beta_h3L_posts AS posts
        INNER JOIN beta_h3L_postmeta AS postmeta
            ON postmeta.post_id = post.ID
            AND postmeta.meta_key = 'produkter_0_pris'
    WHERE posts.post_type = 'podukter'

If there is another metavalue that you need you can join again to your meta table:

    SELECT
        post.post_title as podukter_post_title,
        postmeta.meta_value as podukter_meta_produkter_0_pris,
        postmeta2.meta_value as tilbudspris
    FROM beta_h3L_posts AS posts
        INNER JOIN beta_h3L_postmeta AS postmeta
            ON postmeta.post_id = post.ID
            AND postmeta.meta_key = 'produkter_0_pris'
        INNER JOIN beta_h3L_postmeta AS postmeta2
            ON postmeta.post_id = post.ID
            AND postmeta2.meta_key = 'tilbudspris'
    WHERE posts.post_type = 'podukter'

I don't know what any of these words mean (besides post and postmeta) so I'm just going to assume that this is right/helpful.

The only thing is that you may want to switch to using a LEFT OUTER JOIN to your postmeta table just in case the meta_key you are after doesn't exist for the post.id you are querying. In that case, with an INNER JOIN the id/post will be dropped from the result set where a LEFT OUTER JOIN will show the id/post record with a blank for whatever that corresponding meta_value is that you are joining in.


问:
Cannot set value to Dictionary Key
I fall in a weird situation, so essentially I need to create a Dictionary with a string as Key and a custom object as Value. The Dictionary have this implementation:

```<code>public static Dictionary<string, ForecastType> FullTime
{
    get
    {
        return new Dictionary<string, ForecastType>()
        {
            { "1", new ForecastType { Type = SignType.PartialFinal, Sign = Signs.HomeHomePF } },
            ...
        }
    }
}
</code>```

as you can see the key is 1 and the value is a custom class called ForecastType:

```<code>public class ForecastType : ViewModel
{
    private double _value;

    public double Value
    {
        get { return _value; }
        set
        {
            _value = value;
            OnPropertyChanged();
        }
    }

    public Signs Sign { get; set; }
    public SignType Type { get; set; }
}
</code>```

the property Sign and Type don't need an explaination, it's only an implementation of an Enum.
The property Value instead, cause me a lot of headache. In particular I can't set the value to this property, each value that I assign I get 0.

I also implemented the ViewModel, I though to an issue related on PropertyChanged, but even this hasn't fixed the situation.

I valorize the Value property in this way:

```<code>FullTime["1"].Value = 5;
</code>```

Note that the OnPropertyChanged() is called correctly, and the value inside it is 5, but when I set a breakpoint, later the FullTime["1"].. line I get as .Value "0".

What am I doing wrong?

Thanks for any help. Best regards.

答:
Your FullTime has only a getter, which whenever is called returns a new dictionary with the default value of ForecastType.Value. One possible solution it would be the following:

```<code>public static Dictionary<string, ForecastType> FullTime { get; } =
    new Dictionary<string, ForecastType>
    {
        { "1", new ForecastType
            {
                Type = SignType.PartialFinal,
                Sign = Signs.HomeHomePF
            }
        // ...
    };
</code>```

The difference is that now you have create a property with only a getter but with a default value, which cannot be changed. This value is a reference to a dictionary Dictionary<string, ForecastType>. Whenever you read the value of this property you would get the same reference but now you could mutate the state of the object that this reference points to, by adding new items to the dictionary, changing values etc.

Title: Cannot set value to Dictionary Key

Body:
I fall in a weird situation, so essentially I need to create a Dictionary with a string as Key and a custom object as Value. The Dictionary have this implementation:

public static Dictionary<string, ForecastType> FullTime
{
    get
    {
        return new Dictionary<string, ForecastType>()
        {
            { "1", new ForecastType { Type = SignType.PartialFinal, Sign = Signs.HomeHomePF } },
            ...
        }
    }
}

as you can see the key is 1 and the value is a custom class called ForecastType:

public class ForecastType : ViewModel
{
    private double _value;

    public double Value
    {
        get { return _value; }
        set
        {
            _value = value;
            OnPropertyChanged();
        }
    }

    public Signs Sign { get; set; }
    public SignType Type { get; set; }
}

the property Sign and Type don't need an explaination, it's only an implementation of an Enum.
The property Value instead, cause me a lot of headache. In particular I can't set the value to this property, each value that I assign I get 0.

I also implemented the ViewModel, I though to an issue related on PropertyChanged, but even this hasn't fixed the situation.

I valorize the Value property in this way:

FullTime["1"].Value = 5;

Note that the OnPropertyChanged() is called correctly, and the value inside it is 5, but when I set a breakpoint, later the FullTime["1"].. line I get as .Value "0".

What am I doing wrong?

Thanks for any help. Best regards.

Body:
Your FullTime has only a getter, which whenever is called returns a new dictionary with the default value of ForecastType.Value. One possible solution it would be the following:

public static Dictionary<string, ForecastType> FullTime { get; } =
    new Dictionary<string, ForecastType>
    {
        { "1", new ForecastType
            {
                Type = SignType.PartialFinal,
                Sign = Signs.HomeHomePF
            }
        // ...
    };

The difference is that now you have create a property with only a getter but with a default value, which cannot be changed. This value is a reference to a dictionary Dictionary<string, ForecastType>. Whenever you read the value of this property you would get the same reference but now you could mutate the state of the object that this reference points to, by adding new items to the dictionary, changing values etc.


答:
The problem is in the FullTime property itself.  It always returns a new dictionary:

```<code>get
{
    return new Dictionary<string, ForecastType>() {...};
}
</code>```

Every time you call it, whether to set or get anything in that dictionary, you're always getting a brand new dictionary.  No dictionary is ever persisted in memory.

Save an instance in the class and return that instance instead.  Perhaps something like this:

```<code>private static Dictionary<string, ForecastType> _myDict;

public static Dictionary<string, ForecastType> FullTime
{
    get
    {
        if (_myDict == null)
            _myDict = new Dictionary<string, ForecastType>() {...};
        return _myDict;
    }
}
</code>```

This way it will be initialized the first time you call that property, and any subsequent calls to that property will yield the previously initialized dictionary.

Title: Cannot set value to Dictionary Key

Body:
The problem is in the FullTime property itself.  It always returns a new dictionary:

get
{
    return new Dictionary<string, ForecastType>() {...};
}

Every time you call it, whether to set or get anything in that dictionary, you're always getting a brand new dictionary.  No dictionary is ever persisted in memory.

Save an instance in the class and return that instance instead.  Perhaps something like this:

private static Dictionary<string, ForecastType> _myDict;

public static Dictionary<string, ForecastType> FullTime
{
    get
    {
        if (_myDict == null)
            _myDict = new Dictionary<string, ForecastType>() {...};
        return _myDict;
    }
}

This way it will be initialized the first time you call that property, and any subsequent calls to that property will yield the previously initialized dictionary.