问:
Why are my points not being plotted?
I am currently creating a graph that that analyzes the correlation of absorption and concentration (Beer's law). While creating the graph, I've ran into a few problems, and I am now stuck. My plots are not showing up within my graph. Is it due to placement error? If possible, I would like to leave the ticks, labels, and title in the same (or similar format). Sorry in advance for the sloppiness, trying to get the function down before I make it pretty. But anyways, here is the code:</p>

```<code>#importing matplotlib to create a graph
import matplotlib.pyplot as plt

#ploting out the points while labeling the graph
plt.plot([1.95E-06, 9.75E-06, 1.95E-05, 9.75E-05, 1.95E-04, 9.75E-04, 1.95E-
03],[0.2,0.4,0.6,0.8,1.0,1.2,1.4])
plt.xticks([1, 2, 3, 4, 5, 6, 7], [str('1.95E-03'), str('9.75E-04'),
str('1.95E-04'), str('9.75E-05'),str('1.95E-05'), str('9.75E-06'),
str('1.95E-06')])
plt.title('Red')
plt.ylabel('Absorption')
plt.xlabel('Concentration')
plt.grid(True)
plt.show()
</code>```

答:
Your data has x values well below 0.01, while your ticks start at 1, so your data will be to the left of the plot. I would suggest using a logarithmic x axis, just like the example below. This will also fix the problem with the x values being of different orders of magnitude. Note that I also put the tick strings in reverse order, assuming that you mistakenly wrote them the other way round. If not, please just go ahead and re-reverse them!

```<code>#importing matplotlib to create a graph
import matplotlib.pyplot as plt

x = [1.95e-06, 9.75e-06, 1.95e-05, 9.75e-05, 1.95e-04, 9.75e-04, 1.95e-03]
#ploting out the points while labeling the graph
plt.semilogx(x ,[0.2,0.4,0.6,0.8,1.0,1.2,1.4])
plt.xticks(x, [str('1.95E-03'), str('9.75E-04'), str('1.95E-04'), str('9.75E-05'),str('1.95E-05'), str('9.75E-06'), str('1.95E-06')], rotation=45)
plt.title('Red')
plt.ylabel('Absorption')
plt.xlabel('Concentration')
plt.grid(True)
plt.tight_layout()
plt.savefig('points.png')
plt.show()
</code>```

Title: Why are my points not being plotted?

Body:
I am currently creating a graph that that analyzes the correlation of absorption and concentration (Beer's law). While creating the graph, I've ran into a few problems, and I am now stuck. My plots are not showing up within my graph. Is it due to placement error? If possible, I would like to leave the ticks, labels, and title in the same (or similar format). Sorry in advance for the sloppiness, trying to get the function down before I make it pretty. But anyways, here is the code:

#importing matplotlib to create a graph
import matplotlib.pyplot as plt

#ploting out the points while labeling the graph
plt.plot([1.95E-06, 9.75E-06, 1.95E-05, 9.75E-05, 1.95E-04, 9.75E-04, 1.95E-
03],[0.2,0.4,0.6,0.8,1.0,1.2,1.4])
plt.xticks([1, 2, 3, 4, 5, 6, 7], [str('1.95E-03'), str('9.75E-04'),
str('1.95E-04'), str('9.75E-05'),str('1.95E-05'), str('9.75E-06'),
str('1.95E-06')])
plt.title('Red')
plt.ylabel('Absorption')
plt.xlabel('Concentration')
plt.grid(True)
plt.show()

Body:
Your data has x values well below 0.01, while your ticks start at 1, so your data will be to the left of the plot. I would suggest using a logarithmic x axis, just like the example below. This will also fix the problem with the x values being of different orders of magnitude. Note that I also put the tick strings in reverse order, assuming that you mistakenly wrote them the other way round. If not, please just go ahead and re-reverse them!

#importing matplotlib to create a graph
import matplotlib.pyplot as plt

x = [1.95e-06, 9.75e-06, 1.95e-05, 9.75e-05, 1.95e-04, 9.75e-04, 1.95e-03]
#ploting out the points while labeling the graph
plt.semilogx(x ,[0.2,0.4,0.6,0.8,1.0,1.2,1.4])
plt.xticks(x, [str('1.95E-03'), str('9.75E-04'), str('1.95E-04'), str('9.75E-05'),str('1.95E-05'), str('9.75E-06'), str('1.95E-06')], rotation=45)
plt.title('Red')
plt.ylabel('Absorption')
plt.xlabel('Concentration')
plt.grid(True)
plt.tight_layout()
plt.savefig('points.png')
plt.show()


来源: stackexchange

问:
WCF error - There was no endpoint listening at
I am developing a WCF service, running IIS6 on Window server 2003. I have built a test client to talk to the WCF service and I am getting the error below. I have been looking at this error for days and went through people's suggestions on forums, but with no luck. Any help would be appreciated, many thanks

There was no endpoint listening at
  https://webbooking.infodata.uk.com/Synxis/Synxis.svc that could accept
  the message. This is often caused by an incorrect address or SOAP
  action. See InnerException, if present, for more details.

```<code>System.Net.WebException: The remote server returned an error: (404) Not Found.
  at System.Net.HttpWebRequest.GetResponse()
  at System.ServiceModel.Channels.HttpChannelFactory.HttpRequestChannel.HttpChannelRequest.WaitForReply(TimeSpan timeout)

Server stack trace:
   at System.ServiceModel.Channels.HttpChannelUtilities.ProcessGetResponseWebException(WebException webException, HttpWebRequest request, HttpAbortReason abortReason)
   at System.ServiceModel.Channels.HttpChannelFactory.HttpRequestChannel.HttpChannelRequest.WaitForReply(TimeSpan timeout)
   at System.ServiceModel.Channels.RequestChannel.Request(Message message, TimeSpan timeout)
   at System.ServiceModel.Dispatcher.RequestChannelBinder.Request(Message message, TimeSpan timeout)
   at System.ServiceModel.Channels.ServiceChannel.Call(String action, Boolean oneway, ProxyOperationRuntime operation, Object[] ins, Object[] outs, TimeSpan timeout)
   at System.ServiceModel.Channels.ServiceChannelProxy.InvokeService(IMethodCallMessage methodCall, ProxyOperationRuntime operation)
   at System.ServiceModel.Channels.ServiceChannelProxy.Invoke(IMessage message)

Exception rethrown at [0]:
   at System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg)
   at System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type)
   at IOta2010A.ReservationSynch_SubmitRequest(ReservationSynchRequest request)
   at Ota2010AClient.IOta2010A.ReservationSynch_SubmitRequest(ReservationSynchRequest request) in c:\Development\WorkingFolder\Webservices\SynxisNew\App_Code\OTA2010A.cs:line 57589
   at Ota2010AClient.ReservationSynch_SubmitRequest(Security Security, DateTime& TimeStamp, String CorrelationID, String RelatesToCorrelationID, ReplyTo ReplyTo, OTA_HotelResNotifRQ OTA_HotelResNotifRQ) in c:\Development\WorkingFolder\Webservices\SynxisNew\App_Code\OTA2010A.cs:line 57601
   at Update.Page_Load(Object sender, EventArgs e) in c:\Development\WorkingFolder\Webservices\SynxisNew\Update.aspx.cs:line 72
</code>```

Client config

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <system.web>
    <compilation debug="true"/>
  </system.web>
  <system.serviceModel>
    <bindings>
        <wsHttpBinding>
            <binding name="ota2010AEndpoint" closeTimeout="00:01:00" openTimeout="00:01:00"
                receiveTimeout="00:10:00" sendTimeout="00:01:00" bypassProxyOnLocal="false"
                transactionFlow="false" hostNameComparisonMode="StrongWildcard"
                maxBufferPoolSize="524288" maxReceivedMessageSize="65536"
                messageEncoding="Text" textEncoding="utf-8" useDefaultWebProxy="true"
                allowCookies="false">
                <readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384"
                    maxBytesPerRead="4096" maxNameTableCharCount="16384" />
                <reliableSession ordered="true" inactivityTimeout="00:10:00"
                    enabled="false" />
                <security mode="Transport">
                    <transport clientCredentialType="None" proxyCredentialType="None"
                        realm="" />
                    <message clientCredentialType="Windows" negotiateServiceCredential="true"
                        establishSecurityContext="true" />
                </security>
            </binding>
        </wsHttpBinding>
        </bindings>
        <client>
            <endpoint address="https://webbooking.infodata.uk.com/synxis/synxis.svc"
                binding="wsHttpBinding" bindingConfiguration="ota2010AEndpoint"
                contract="IOta2010A" name="ota2010AEndpoint" />
        </client>
    </system.serviceModel>
</configuration>
```

<p><strong>Service config</strong></p>

<pre class="lang-xml prettyprint-override"><code><?xml version="1.0"?>
<configuration>
  <system.web>
    <compilation debug="true" targetFramework="4.0">
      <assemblies>
        <add assembly="Pervasive.Data.SqlClient, Version=2.10.0.34, Culture=neutral, PublicKeyToken=C84CD5C63851E072"/>
      </assemblies>
    </compilation>
    <authentication mode="Windows"/>
    <pages controlRenderingCompatibilityVersion="3.5" clientIDMode="AutoID"/>
  </system.web>
  <system.serviceModel>
    <services>
      <service name="Synxis" behaviorConfiguration="SynxisWCF">
        <endpoint address="" name="wsHttpEndpoint"  binding="wsHttpBinding" contract="Synxis" />
        <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
      </service>
    </services>
    <diagnostics>
      <messageLogging logEntireMessage="true" logMalformedMessages="true"
         logMessagesAtServiceLevel="true" logMessagesAtTransportLevel="true"
         maxMessagesToLog="300" />
    </diagnostics>
    <behaviors>
      <serviceBehaviors>
        <behavior name="SynxisWCF" >
          <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true" externalMetadataLocation="https://webbooking.infodata.uk.com/synxis/Synxis.svc.wsdl" />
            <serviceDebug includeExceptionDetailInFaults="true" />
        </behavior>
      </serviceBehaviors>
    </behaviors>
  </system.serviceModel>
</configuration>
</code>```

答:
Different case but may help someone:

In my case, the Windows firewall was enabled on the Server.

Either of these two things can be done:

Disable the Windows firewall (at your own risk, but it will get things work).

Add the port in an inbound rule.

Thanks.

ContentLicense: CC BY-SA 4.0

Body:
I am developing a WCF service, running IIS6 on Window server 2003. I have built a test client to talk to the WCF service and I am getting the error below. I have been looking at this error for days and went through people's suggestions on forums, but with no luck. Any help would be appreciated, many thanks

There was no endpoint listening at
  https://webbooking.infodata.uk.com/Synxis/Synxis.svc that could accept
  the message. This is often caused by an incorrect address or SOAP
  action. See InnerException, if present, for more details.

System.Net.WebException: The remote server returned an error: (404) Not Found.
  at System.Net.HttpWebRequest.GetResponse()
  at System.ServiceModel.Channels.HttpChannelFactory.HttpRequestChannel.HttpChannelRequest.WaitForReply(TimeSpan timeout)

Server stack trace:
   at System.ServiceModel.Channels.HttpChannelUtilities.ProcessGetResponseWebException(WebException webException, HttpWebRequest request, HttpAbortReason abortReason)
   at System.ServiceModel.Channels.HttpChannelFactory.HttpRequestChannel.HttpChannelRequest.WaitForReply(TimeSpan timeout)
   at System.ServiceModel.Channels.RequestChannel.Request(Message message, TimeSpan timeout)
   at System.ServiceModel.Dispatcher.RequestChannelBinder.Request(Message message, TimeSpan timeout)
   at System.ServiceModel.Channels.ServiceChannel.Call(String action, Boolean oneway, ProxyOperationRuntime operation, Object[] ins, Object[] outs, TimeSpan timeout)
   at System.ServiceModel.Channels.ServiceChannelProxy.InvokeService(IMethodCallMessage methodCall, ProxyOperationRuntime operation)
   at System.ServiceModel.Channels.ServiceChannelProxy.Invoke(IMessage message)

Exception rethrown at [0]:
   at System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg)
   at System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type)
   at IOta2010A.ReservationSynch_SubmitRequest(ReservationSynchRequest request)
   at Ota2010AClient.IOta2010A.ReservationSynch_SubmitRequest(ReservationSynchRequest request) in c:\Development\WorkingFolder\Webservices\SynxisNew\App_Code\OTA2010A.cs:line 57589
   at Ota2010AClient.ReservationSynch_SubmitRequest(Security Security, DateTime& TimeStamp, String CorrelationID, String RelatesToCorrelationID, ReplyTo ReplyTo, OTA_HotelResNotifRQ OTA_HotelResNotifRQ) in c:\Development\WorkingFolder\Webservices\SynxisNew\App_Code\OTA2010A.cs:line 57601
   at Update.Page_Load(Object sender, EventArgs e) in c:\Development\WorkingFolder\Webservices\SynxisNew\Update.aspx.cs:line 72

Client config

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <system.web>
    <compilation debug="true"/>
  </system.web>
  <system.serviceModel>
    <bindings>
        <wsHttpBinding>
            <binding name="ota2010AEndpoint" closeTimeout="00:01:00" openTimeout="00:01:00"
                receiveTimeout="00:10:00" sendTimeout="00:01:00" bypassProxyOnLocal="false"
                transactionFlow="false" hostNameComparisonMode="StrongWildcard"
                maxBufferPoolSize="524288" maxReceivedMessageSize="65536"
                messageEncoding="Text" textEncoding="utf-8" useDefaultWebProxy="true"
                allowCookies="false">
                <readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384"
                    maxBytesPerRead="4096" maxNameTableCharCount="16384" />
                <reliableSession ordered="true" inactivityTimeout="00:10:00"
                    enabled="false" />
                <security mode="Transport">
                    <transport clientCredentialType="None" proxyCredentialType="None"
                        realm="" />
                    <message clientCredentialType="Windows" negotiateServiceCredential="true"
                        establishSecurityContext="true" />
                </security>
            </binding>
        </wsHttpBinding>
        </bindings>
        <client>
            <endpoint address="https://webbooking.infodata.uk.com/synxis/synxis.svc"
                binding="wsHttpBinding" bindingConfiguration="ota2010AEndpoint"
                contract="IOta2010A" name="ota2010AEndpoint" />
        </client>
    </system.serviceModel>
</configuration>

Service config

<?xml version="1.0"?>
<configuration>
  <system.web>
    <compilation debug="true" targetFramework="4.0">
      <assemblies>
        <add assembly="Pervasive.Data.SqlClient, Version=2.10.0.34, Culture=neutral, PublicKeyToken=C84CD5C63851E072"/>
      </assemblies>
    </compilation>
    <authentication mode="Windows"/>
    <pages controlRenderingCompatibilityVersion="3.5" clientIDMode="AutoID"/>
  </system.web>
  <system.serviceModel>
    <services>
      <service name="Synxis" behaviorConfiguration="SynxisWCF">
        <endpoint address="" name="wsHttpEndpoint"  binding="wsHttpBinding" contract="Synxis" />
        <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
      </service>
    </services>
    <diagnostics>
      <messageLogging logEntireMessage="true" logMalformedMessages="true"
         logMessagesAtServiceLevel="true" logMessagesAtTransportLevel="true"
         maxMessagesToLog="300" />
    </diagnostics>
    <behaviors>
      <serviceBehaviors>
        <behavior name="SynxisWCF" >
          <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true" externalMetadataLocation="https://webbooking.infodata.uk.com/synxis/Synxis.svc.wsdl" />
            <serviceDebug includeExceptionDetailInFaults="true" />
        </behavior>
      </serviceBehaviors>
    </behaviors>
  </system.serviceModel>
</configuration>


问:
why getting "array_map(): Argument #2 should be an array" error while running complex query?
I am writing code for filter search where user selects atleast one option from a list of 3 checkboxes then I have to write a query for the selected options(checkboxes). If I try to run my code then I am getting "array_map(): Argument #2 should be an array".

My form is :

```<code><form id="statistics" method="post" action="{{ action('MyController@store') }}"">
<div class="form-group">
 <label><input type="checkbox" value="suppliers" name="suppliers">suppliers</label>
</div>
<div class="form-group">
 <label><input type="checkbox" value="campaign" name="campaign">campaign</label>
</div>
<div class="form-group">
 <label><input type="checkbox" value="clients" name="clients">clients</label>
</div>
<div class="form-group">
 <label for="start_date">From:</label><input type="text" name="startdate" id="startdate">
</div>
<div class="form-group">
 <label for="start_date">From:</label><input type="text" name="enddate" id="enddate">
</div>
<div class="form-group">
 <button type="submit" id="process" class="btn btn-primary submit">Run Report</button>
</div>
</code>```

My query is below:

```<code>if($request->suppliers == 'suppliers'){
        $results->leftjoin('suppliers AS s', 's.id', '=', 'l.supplier_id')
                ->select('s.name AS Supplier')
                ->groupBy('s.name')
                ->orderBy('s.name');
    }
if($request->campaign == 'campaign'){
        $results->leftjoin('campaigns AS c', 'c.id', '=', 'l.campaign_id')
                ->select('c.name AS Campaign')
                ->groupBy('c.name')
                ->orderBy('c.name');
    }
if($request->clients == 'clients'){
        $results->leftjoin('clients AS cl', 'cl.id', '=', 'l.client_id')
                ->groupBy('cl.name')
                ->orderBy('cl.name');
    }
$results->whereBetween('l.received', [$start, $end])
        ->groupBy('l.disposition')
        ->orderBy('l.disposition')
        ->get()->toArray();
$count = count($results);
if($count > 0)
{
 $results = array_map(function ($value) {
            return (array)$value;
        }, $results);
 Excel::create('Statistics', function($excel) use($results) {
            $excel->sheet('Statistics', function($sheet) use($results) {
                $sheet->fromArray($results);
            });
        })->download('csv');
    }
</code>```

If I run the above code then I am getting ann error like "array_map(): Argument #2 should be an array"

It was working fine With normal query like below:

```<code>$results = DB::table('lead_audit AS l')
         ->leftjoin('suppliers AS s', 's.id', '=', 'l.supplier_id')
         ->leftjoin('campaigns AS c', 'c.id', '=', 'l.campaign_id')
         ->select('s.name AS Supplier', 'c.name AS Campaign', 'l.disposition AS Disposition')
         ->whereBetween('l.received', [$start, $end])
         ->groupBy('s.name', 'c.name', 'l.disposition')
         ->orderBy('s.name')
         ->orderBy('c.name')
         ->orderBy('l.disposition')
         ->get()->toArray();
$count = count($results);
</code>```

Can anyone please helpme how to sort out this, Thanks.

答:
Look like $results is just a query not an array. You need to change to code below

```<code>$queryResults = $results->whereBetween('l.received', [$start, $end])
    ->groupBy('l.disposition')
    ->orderBy('l.disposition')
    ->get()->toArray();
$count = count($results);
if($count > 0)
{
 $results = array_map(function ($value) {
            return (array)$value;
        }, $results);
</code>```

to following code

```<code>$results->whereBetween('l.received', [$start, $end])
    ->groupBy('l.disposition')
    ->orderBy('l.disposition')
    ->get()->toArray();
$count = count($results);
if($count > 0)
{
 $results = array_map(function ($value) {
            return (array)$value;
        },$queryResults);
</code>```

In the above code, I assign result of the query to variable $queryResults, then pass it into array_map function.

ContentLicense: CC BY-SA 3.0

Body:
I am writing code for filter search where user selects atleast one option from a list of 3 checkboxes then I have to write a query for the selected options(checkboxes). If I try to run my code then I am getting "array_map(): Argument #2 should be an array".

My form is :

<form id="statistics" method="post" action="{{ action('MyController@store') }}"">

 <input type="checkbox" value="suppliers" name="suppliers">suppliers

 <input type="checkbox" value="campaign" name="campaign">campaign

 <input type="checkbox" value="clients" name="clients">clients

 From:<input type="text" name="startdate" id="startdate">

 From:<input type="text" name="enddate" id="enddate">

 <button type="submit" id="process" class="btn btn-primary submit">Run Report</button>

My query is below:

if($request->suppliers == 'suppliers'){
        $results->leftjoin('suppliers AS s', 's.id', '=', 'l.supplier_id')
                ->select('s.name AS Supplier')
                ->groupBy('s.name')
                ->orderBy('s.name');
    }
if($request->campaign == 'campaign'){
        $results->leftjoin('campaigns AS c', 'c.id', '=', 'l.campaign_id')
                ->select('c.name AS Campaign')
                ->groupBy('c.name')
                ->orderBy('c.name');
    }
if($request->clients == 'clients'){
        $results->leftjoin('clients AS cl', 'cl.id', '=', 'l.client_id')
                ->groupBy('cl.name')
                ->orderBy('cl.name');
    }
$results->whereBetween('l.received', [$start, $end])
        ->groupBy('l.disposition')
        ->orderBy('l.disposition')
        ->get()->toArray();
$count = count($results);
if($count > 0)
{
 $results = array_map(function ($value) {
            return (array)$value;
        }, $results);
 Excel::create('Statistics', function($excel) use($results) {
            $excel->sheet('Statistics', function($sheet) use($results) {
                $sheet->fromArray($results);
            });
        })->download('csv');
    }

If I run the above code then I am getting ann error like "array_map(): Argument #2 should be an array"

It was working fine With normal query like below:

$results = DB::table('lead_audit AS l')
         ->leftjoin('suppliers AS s', 's.id', '=', 'l.supplier_id')
         ->leftjoin('campaigns AS c', 'c.id', '=', 'l.campaign_id')
         ->select('s.name AS Supplier', 'c.name AS Campaign', 'l.disposition AS Disposition')
         ->whereBetween('l.received', [$start, $end])
         ->groupBy('s.name', 'c.name', 'l.disposition')
         ->orderBy('s.name')
         ->orderBy('c.name')
         ->orderBy('l.disposition')
         ->get()->toArray();
$count = count($results);

Can anyone please helpme how to sort out this, Thanks.

Body:
Look like $results is just a query not an array. You need to change to code below

$queryResults = $results->whereBetween('l.received', [$start, $end])
    ->groupBy('l.disposition')
    ->orderBy('l.disposition')
    ->get()->toArray();
$count = count($results);
if($count > 0)
{
 $results = array_map(function ($value) {
            return (array)$value;
        }, $results);

to following code

$results->whereBetween('l.received', [$start, $end])
    ->groupBy('l.disposition')
    ->orderBy('l.disposition')
    ->get()->toArray();
$count = count($results);
if($count > 0)
{
 $results = array_map(function ($value) {
            return (array)$value;
        },$queryResults);

In the above code, I assign result of the query to variable $queryResults, then pass it into array_map function.


问:
Cloud Functions for Firebase Image download function Error
I am building a web application using Firebase and the new feature Cloud Functions for Firebase. I have created a function that takes a URL and downloads the image into a 64-bit encoded string as below using the node modules request and request-promise-native:

```<code>module.exports = {
downloadImageFromUrl: function (url) {
    var options = {
        method: 'GET',
        uri: url,
        resolveWithFullResponse: true,
        simple: false,
        family: 4
    };
    return rp.get(options)
        .then(function (res) {
            return "data:" + res.headers["content-type"] + ";base64," + new Buffer(res.body).toString('base64');
        })
        .catch(function (error) {
            console.log("ERROR GETTING image", error);
            return error;
        });
    }
};
</code>```

The top function works perfectly running locally but once on firebase it gives the error:

```<code>RequestError: Error: getaddrinfo EAI_AGAIN lh6.googleusercontent.com:443
at new RequestError (/user_code/node_modules/request-promise/node_modules/request-promise-core/lib/errors.js:14:15)
at Request.plumbing.callback (/user_code/node_modules/request-promise/node_modules/request-promise-core/lib/plumbing.js:87:29)
at Request.RP$callback [as _callback] (/user_code/node_modules/request-promise/node_modules/request-promise-core/lib/plumbing.js:46:31)
at self.callback (/user_code/node_modules/request/request.js:188:22)
at emitOne (events.js:96:13)
at Request.emit (events.js:188:7)
at Request.onRequestError (/user_code/node_modules/request/request.js:884:8)
at emitOne (events.js:96:13)
at ClientRequest.emit (events.js:188:7)
at TLSSocket.socketErrorListener (_http_client.js:310:9)
at emitOne (events.js:96:13)
at TLSSocket.emit (events.js:188:7)
at connectErrorNT (net.js:1020:8)
at _combinedTickCallback (internal/process/next_tick.js:74:11)
at process._tickDomainCallback (internal/process/next_tick.js:122:9)
</code>```

I am calling the function in the firebase auth trigger when a user is created as below:

```<code>exports.createUser = functions.auth.user().onCreate(event => {
    if (event.data.photoURL) {
    utils.downloadImageFromUrl(event.data.photoURL)
        .then(function(res){
            console.log("User Photo", res);

        })
        .catch(function(error){
            console.log("Error", error);
        })
}
});
</code>```

Any help would be greatly appreciated.

答: Not entirely sure yet if this is the answer, but after reading the documentation, I read their free plan which says you cannot make any out bound requests.  So I guess getting an image from a Url counts as an outbound request. After I start paying for their service, I will come back to verify if this was the problem.</p>

Body:
I am building a web application using Firebase and the new feature Cloud Functions for Firebase. I have created a function that takes a URL and downloads the image into a 64-bit encoded string as below using the node modules request and request-promise-native:

module.exports = {
downloadImageFromUrl: function (url) {
    var options = {
        method: 'GET',
        uri: url,
        resolveWithFullResponse: true,
        simple: false,
        family: 4
    };
    return rp.get(options)
        .then(function (res) {
            return "data:" + res.headers["content-type"] + ";base64," + new Buffer(res.body).toString('base64');
        })
        .catch(function (error) {
            console.log("ERROR GETTING image", error);
            return error;
        });
    }
};

The top function works perfectly running locally but once on firebase it gives the error:

RequestError: Error: getaddrinfo EAI_AGAIN lh6.googleusercontent.com:443
at new RequestError (/user_code/node_modules/request-promise/node_modules/request-promise-core/lib/errors.js:14:15)
at Request.plumbing.callback (/user_code/node_modules/request-promise/node_modules/request-promise-core/lib/plumbing.js:87:29)
at Request.RP$callback [as _callback] (/user_code/node_modules/request-promise/node_modules/request-promise-core/lib/plumbing.js:46:31)
at self.callback (/user_code/node_modules/request/request.js:188:22)
at emitOne (events.js:96:13)
at Request.emit (events.js:188:7)
at Request.onRequestError (/user_code/node_modules/request/request.js:884:8)
at emitOne (events.js:96:13)
at ClientRequest.emit (events.js:188:7)
at TLSSocket.socketErrorListener (_http_client.js:310:9)
at emitOne (events.js:96:13)
at TLSSocket.emit (events.js:188:7)
at connectErrorNT (net.js:1020:8)
at _combinedTickCallback (internal/process/next_tick.js:74:11)
at process._tickDomainCallback (internal/process/next_tick.js:122:9)

I am calling the function in the firebase auth trigger when a user is created as below:

exports.createUser = functions.auth.user().onCreate(event => {
    if (event.data.photoURL) {
    utils.downloadImageFromUrl(event.data.photoURL)
        .then(function(res){
            console.log("User Photo", res);

        })
        .catch(function(error){
            console.log("Error", error);
        })
}
});

Any help would be greatly appreciated.


问:
Get the complete graph information (properties,id etc ) in hierarchical way under a particular node in gremlin
```<code>I am able to get all the child nodes and its related information under a parent node but in a array of objects format , for the query

g.V(4128).repeat(out()).emit()

[
  {
    "id": 4152.0,
    "label": "location",
    "type": "vertex",
    "properties": {
      "displayName": [
        {
          "id": "1l3-37c-1l1",
          "value": "XYZ"
        }
      ],
      "description": [
        {
          "id": "1zb-37c-7wl",
          "value": "XYZ World"
        }
      ],
      "shortName": [
        {
          "id": "16v-37c-745",
          "value": "XYZ"
        }
      ]
    }
  },
  {
    "id": 4176.0,
    "label": "location",
    "type": "vertex",
    "properties": {
      "displayName": [
        {
          "id": "1l6-380-1l1",
          "value": "XYZ-XYZW"
        }
      ],
      "description": [
        {
          "id": "1ze-380-7wl",
          "value": "XYZ West Campus"
        }
      ],
      "shortName": [
        {
          "id": "16y-380-745",
          "value": "XYZW"
        }
      ]
    }
  },
  {
    "id": 8344.0,
    "label": "location",
    "type": "vertex",
    "properties": {
      "displayName": [
        {
          "id": "3kj-6fs-1l1",
          "value": "XYZ-XYZE"
        }
      ],
      "description": [
        {
          "id": "3yr-6fs-7wl",
          "value": "XYZ East Campus"
        }
      ],
      "shortName": [
        {
          "id": "36b-6fs-745",
          "value": "XYZE"
        }
      ]
    }
  },
  {
    "id": 4104.0,
    "label": "location",
    "type": "vertex",
    "properties": {
      "displayName": [
        {
          "id": "1kx-360-1l1",
          "value": "XYZ-XYZW-P1"
        }
      ],
      "description": [
        {
          "id": "1z5-360-7wl",
          "value": "XYZ West Campus-Phase-1"
        }
      ],
      "shortName": [
        {
          "id": "16p-360-745",
          "value": "P1"
        }
      ]
    }
  },
  {
    "id": 4296.0,
    "label": "location",
    "type": "vertex",
    "properties": {
      "displayName": [
        {
          "id": "1ll-3bc-1l1",
          "value": "XYZ-XYZW-P3"
        }
      ],
      "description": [
        {
          "id": "1zt-3bc-7wl",
          "value": "XYZ West Campus-Phase-3"
        }
      ],
      "shortName": [
        {
          "id": "17d-3bc-745",
          "value": "P3"
        }
      ]
    }
  },
  {
    "id": 8200.0,
    "label": "location",
    "type": "vertex",
    "properties": {
      "displayName": [
        {
          "id": "3k1-6bs-1l1",
          "value": "XYZ-XYZW-P2"
        }
      ],
      "description": [
        {
          "id": "3y9-6bs-7wl",
          "value": "XYZ West Campus-Phase-2"
        }
      ],
      "shortName": [
        {
          "id": "35t-6bs-745",
          "value": "P2"
        }
      ]
    }
  },
  {
    "id": 8224.0,
    "label": "location",
    "type": "vertex",
    "properties": {
      "displayName": [
        {
          "id": "3yc-6cg-1l1",
          "value": "XYZ-XYZE-P1"
        }
      ],
      "description": [
        {
          "id": "4ck-6cg-7wl",
          "value": "XYZ East Campus-Phase-1"
        }
      ],
      "shortName": [
        {
          "id": "3k4-6cg-745",
          "value": "P1"
        }
      ]
    }
  },
  {
    "id": 8392.0,
    "label": "location",
    "type": "vertex",
    "properties": {
      "displayName": [
        {
          "id": "3kp-6h4-1l1",
          "value": "XYZ-XYZE-P2"
        }
      ],
      "description": [
        {
          "id": "3yx-6h4-7wl",
          "value": "XYZ East Campus-Phase-2"
        }
      ],
      "shortName": [
        {
          "id": "36h-6h4-745",
          "value": "P2"
        }
      ]
    }
  }
]
</code>```

I need to get the same information in hierarchial way .

I tried the following query

g.V(4128).repeat(out()).emit().tree().by(__.valueMap(true))

but I don't get the valid json.

I need to get the above data but in hierarchical way

Updated

 I tried the following query

   g.V(4128).repeat(out()).emit().tree().by(__.valueMap(true))

And the response I received was

```<code>[
   {
"{label = org, name = [XYZ], orgId = [00000000-0000-0000-0000-000000000001], desc = [XYZ Organization], id = 4128}": {
  "{label = location, displayName = [hh], description = [hfds], shortName = [kk], id = 8272}": {

  },
  "{label = location, displayName = [XYZ], description = [XYZ World], shortName = [XYZ], id = 4152}": {
    "{label = location, displayName = [XYZ-XYZW], description = [XYZ West Campus], shortName = [XYZW], id = 4176}": {
      "{label = location, displayName = [XYZ-XYZW-P3], description = [XYZ West Campus-Phase-3], shortName = [P3], id = 4296}": {

      },
      "{label = location, displayName = [XYZ-XYZW-P2], description = [XYZ West Campus-Phase-2], shortName = [P2], id = 8200}": {

      },
      "{label = location, displayName = [XYZ-XYZW-P1], description = [XYZ West Campus-Phase-1], shortName = [P1], id = 4104}": {

      }
    },
    "{label = location, displayName = [XYZ-XYZE], description = [XYZ East Campus], shortName = [XYZE], id = 8344}": {
      "{label = location, displayName = [XYZ-XYZE-P1], description = [XYZ East Campus-Phase-1], shortName = [P1], id = 8224}": {

      },
      "{label = location, displayName = [XYZ-XYZE-P2], description = [XYZ East Campus-Phase-2], shortName = [P2], id = 8392}": {

      }
    }
  },
  "{label = location, displayName = [hh], description = [hfds], shortName = [kk], id = 8248}": {

  },
  "{label = location, displayName = [hh], description = [hfds], shortName = [kk], id = 12488}": {

  }
}
</code>```

}
]

Now as you can see the json so received is not appropriate because the key contains fields that are '=' separated .

Now as for the answer I also tried the folowing query

g.V(4128).repeat(out()).emit().tree().next()

but the response returned only ids and didnt resolve the vertex properties

```<code>[
  {
    "4128": {
      "8272": {},
      "4152": {
        "4176": {
          "4104": {},
          "4296": {},
          "8200": {}
        },
        "8344": {
          "8224": {},
          "8392": {}
        }
      },
      "8248": {},
      "12488": {}
    }
  }
]
</code>```

For the context I am using the following configurations  in my gremlin-server.yaml file

```<code>authentication: {className: org.apache.tinkerpop.gremlin.server.auth.AllowAllAuthenticator,
  config: null}
channelizer: org.apache.tinkerpop.gremlin.server.channel.HttpChannelizer
graphs: {graph: 'D:/graph-data-access/src/test/resources/titan-inmemory.properties'}
gremlinPool: 8
host: localhost
maxAccumulationBufferComponents: 1024
maxChunkSize: 8192
maxContentLength: 65536
maxHeaderSize: 8192
maxInitialLineLength: 4096
metrics:
  consoleReporter: null
  csvReporter: null
  gangliaReporter: null
  graphiteReporter: null
  jmxReporter: null
  slf4jReporter: {enabled: true, interval: 180000, loggerName: org.apache.tinkerpop.gremlin.server.Settings$Slf4jReporterMetrics}
plugins: [aurelius.titan, tinkerpop.gephi]
port: 8182
processors: []
resultIterationBatchSize: 64
scriptEngines:
  gremlin-groovy:
    config: null
    imports: [java.lang.Math]
    scripts: ['D:/graph-data-access/src/test/resources/generate-locations.groovy']
    staticImports: [java.lang.Math.PI]
scriptEvaluationTimeout: 30000
serializedResponseTimeout: 30000
serializers:
- className: org.apache.tinkerpop.gremlin.driver.ser.GryoMessageSerializerV1d0
  config: {useMapperFromGraph: graph}
- className: org.apache.tinkerpop.gremlin.driver.ser.GryoMessageSerializerV1d0
  config: {serializeResultToString: true}
- className: org.apache.tinkerpop.gremlin.driver.ser.GraphSONMessageSerializerV1d0
  config: {useMapperFromGraph: graph}
- className: org.apache.tinkerpop.gremlin.driver.ser.GraphSONMessageSerializerGremlinV1d0
  config: {useMapperFromGraph: graph}
ssl: {enabled: false, keyCertChainFile: null, keyFile: null, keyPassword: null, trustCertChainFile: null}
threadPoolBoss: 1
threadPoolWorker: 1
writeBufferHighWaterMark: 65536
writeBufferLowWaterMark: 32768
</code>```

I am using Tinkerpop version 3.0.1 incubating as I am trying to use Titan 1.0.0 with DynamoDb as storage backend for the remote connection.

答:
Not sure what you mean by "but i don't get valid json". You should be able to serialized a Tree in GraphSON 1.0 if you don't include by(valueMap(true)) and just serialize the full vertex. There is a failure if you try to do it as just maps as it makes some assumptions about there being a graph Element as the key (which is probably bad).

```<code>gremlin> mapper = graph.io(graphson()).mapper().version(GraphSONVersion.V1_0).create().createMapper()
==>org.apache.tinkerpop.shaded.jackson.databind.ObjectMapper@6b2e0f78
gremlin> mapper.writeValueAsString(g.V(1).repeat(out()).emit().tree().next())
==>{"1":{"key":{"id":1,"label":"vertex","type":"vertex","properties":{"name":[{"id":0,"value":"marko"}],"age":[{"id":2,"value":29}]}},"value":{"2":{"key":{"id":2,"label":"vertex","type":"vertex","properties":{"name":[{"id":3,"value":"vadas"}],"age":[{"id":4,"value":27}]}},"value":{}},"3":{"key":{"id":3,"label":"vertex","type":"vertex","properties":{"name":[{"id":5,"value":"lop"}],"lang":[{"id":6,"value":"java"}]}},"value":{}},"4":{"key":{"id":4,"label":"vertex","type":"vertex","properties":{"name":[{"id":7,"value":"josh"}],"age":[{"id":8,"value":32}]}},"value":{"3":{"key":{"id":3,"label":"vertex","type":"vertex","properties":{"name":[{"id":5,"value":"lop"}],"lang":[{"id":6,"value":"java"}]}},"value":{}},"5":{"key":{"id":5,"label":"vertex","type":"vertex","properties":{"name":[{"id":9,"value":"ripple"}],"lang":[{"id":10,"value":"java"}]}},"value":{}}}}}}}
</code>```

That formats to:

```<code>{
    "1": {
        "key": {
            "id": 1,
            "label": "vertex",
            "type": "vertex",
            "properties": {
                "name": [{
                    "id": 0,
                    "value": "marko"
                }],
                "age": [{
                    "id": 2,
                    "value": 29
                }]
            }
        },
        "value": {
            "2": {
                "key": {
                    "id": 2,
                    "label": "vertex",
                    "type": "vertex",
                    "properties": {
                        "name": [{
                            "id": 3,
                            "value": "vadas"
                        }],
                        "age": [{
                            "id": 4,
                            "value": 27
                        }]
                    }
                },
                "value": {}
            },
            "3": {
                "key": {
                    "id": 3,
                    "label": "vertex",
                    "type": "vertex",
                    "properties": {
                        "name": [{
                            "id": 5,
                            "value": "lop"
                        }],
                        "lang": [{
                            "id": 6,
                            "value": "java"
                        }]
                    }
                },
                "value": {}
            },
            "4": {
                "key": {
                    "id": 4,
                    "label": "vertex",
                    "type": "vertex",
                    "properties": {
                        "name": [{
                            "id": 7,
                            "value": "josh"
                        }],
                        "age": [{
                            "id": 8,
                            "value": 32
                        }]
                    }
                },
                "value": {
                    "3": {
                        "key": {
                            "id": 3,
                            "label": "vertex",
                            "type": "vertex",
                            "properties": {
                                "name": [{
                                    "id": 5,
                                    "value": "lop"
                                }],
                                "lang": [{
                                    "id": 6,
                                    "value": "java"
                                }]
                            }
                        },
                        "value": {}
                    },
                    "5": {
                        "key": {
                            "id": 5,
                            "label": "vertex",
                            "type": "vertex",
                            "properties": {
                                "name": [{
                                    "id": 9,
                                    "value": "ripple"
                                }],
                                "lang": [{
                                    "id": 10,
                                    "value": "java"
                                }]
                            }
                        },
                        "value": {}
                    }
                }
            }
        }
    }
}
</code>```

In GraphSON 2.0 you get this:

```<code>gremlin> mapper = graph.io(graphson()).mapper().version(GraphSONVersion.V2_0).create().createMapper()
==>org.apache.tinkerpop.shaded.jackson.databind.ObjectMapper@3ffb3598
gremlin> mapper.writeValueAsString(g.V(1).repeat(out()).emit().tree().next())
==>{"@type":"g:Tree","@value":[{"key":{"@type":"g:Vertex","@value":{"id":{"@type":"g:Int32","@value":1},"label":"vertex","properties":{"name":[{"@type":"g:VertexProperty","@value":{"id":{"@type":"g:Int32","@value":0},"value":"marko","label":"name"}}],"age":[{"@type":"g:VertexProperty","@value":{"id":{"@type":"g:Int32","@value":2},"value":{"@type":"g:Int32","@value":29},"label":"age"}}]}}},"value":{"@type":"g:Tree","@value":[{"key":{"@type":"g:Vertex","@value":{"id":{"@type":"g:Int32","@value":2},"label":"vertex","properties":{"name":[{"@type":"g:VertexProperty","@value":{"id":{"@type":"g:Int32","@value":3},"value":"vadas","label":"name"}}],"age":[{"@type":"g:VertexProperty","@value":{"id":{"@type":"g:Int32","@value":4},"value":{"@type":"g:Int32","@value":27},"label":"age"}}]}}},"value":{"@type":"g:Tree","@value":[]}},{"key":{"@type":"g:Vertex","@value":{"id":{"@type":"g:Int32","@value":3},"label":"vertex","properties":{"name":[{"@type":"g:VertexProperty","@value":{"id":{"@type":"g:Int32","@value":5},"value":"lop","label":"name"}}],"lang":[{"@type":"g:VertexProperty","@value":{"id":{"@type":"g:Int32","@value":6},"value":"java","label":"lang"}}]}}},"value":{"@type":"g:Tree","@value":[]}},{"key":{"@type":"g:Vertex","@value":{"id":{"@type":"g:Int32","@value":4},"label":"vertex","properties":{"name":[{"@type":"g:VertexProperty","@value":{"id":{"@type":"g:Int32","@value":7},"value":"josh","label":"name"}}],"age":[{"@type":"g:VertexProperty","@value":{"id":{"@type":"g:Int32","@value":8},"value":{"@type":"g:Int32","@value":32},"label":"age"}}]}}},"value":{"@type":"g:Tree","@value":[{"key":{"@type":"g:Vertex","@value":{"id":{"@type":"g:Int32","@value":3},"label":"vertex","properties":{"name":[{"@type":"g:VertexProperty","@value":{"id":{"@type":"g:Int32","@value":5},"value":"lop","label":"name"}}],"lang":[{"@type":"g:VertexProperty","@value":{"id":{"@type":"g:Int32","@value":6},"value":"java","label":"lang"}}]}}},"value":{"@type":"g:Tree","@value":[]}},{"key":{"@type":"g:Vertex","@value":{"id":{"@type":"g:Int32","@value":5},"label":"vertex","properties":{"name":[{"@type":"g:VertexProperty","@value":{"id":{"@type":"g:Int32","@value":9},"value":"ripple","label":"name"}}],"lang":[{"@type":"g:VertexProperty","@value":{"id":{"@type":"g:Int32","@value":10},"value":"java","label":"lang"}}]}}},"value":{"@type":"g:Tree","@value":[]}}]}}]}}]}
</code>```

which formats as:

```<code>{
    "@type": "g:Tree",
    "@value": [{
        "key": {
            "label": "vertex",
            "name": ["marko"],
            "id": {
                "@type": "g:Int32",
                "@value": 1
            },
            "age": [{
                "@type": "g:Int32",
                "@value": 29
            }]
        },
        "value": {
            "@type": "g:Tree",
            "@value": [{
                "key": {
                    "label": "vertex",
                    "name": ["lop"],
                    "id": {
                        "@type": "g:Int32",
                        "@value": 3
                    },
                    "lang": ["java"]
                },
                "value": {
                    "@type": "g:Tree",
                    "@value": []
                }
            }, {
                "key": {
                    "label": "vertex",
                    "name": ["vadas"],
                    "id": {
                        "@type": "g:Int32",
                        "@value": 2
                    },
                    "age": [{
                        "@type": "g:Int32",
                        "@value": 27
                    }]
                },
                "value": {
                    "@type": "g:Tree",
                    "@value": []
                }
            }, {
                "key": {
                    "label": "vertex",
                    "name": ["josh"],
                    "id": {
                        "@type": "g:Int32",
                        "@value": 4
                    },
                    "age": [{
                        "@type": "g:Int32",
                        "@value": 32
                    }]
                },
                "value": {
                    "@type": "g:Tree",
                    "@value": [{
                        "key": {
                            "label": "vertex",
                            "name": ["ripple"],
                            "id": {
                                "@type": "g:Int32",
                                "@value": 5
                            },
                            "lang": ["java"]
                        },
                        "value": {
                            "@type": "g:Tree",
                            "@value": []
                        }
                    }, {
                        "key": {
                            "label": "vertex",
                            "name": ["lop"],
                            "id": {
                                "@type": "g:Int32",
                                "@value": 3
                            },
                            "lang": ["java"]
                        },
                        "value": {
                            "@type": "g:Tree",
                            "@value": []
                        }
                    }]
                }
            }]
        }
    }]
}
</code>```

Note that you can also use by(valueMap(true)) in the case of GraphSON 2.0:

```<code>gremlin> mapper.writeValueAsString(g.V(1).repeat(out()).emit().tree().by(valueMap(true)).next())
==>{"@type":"g:Tree","@value":[{"key":{"label":"vertex","name":["marko"],"id":{"@type":"g:Int32","@value":1},"age":[{"@type":"g:Int32","@value":29}]},"value":{"@type":"g:Tree","@value":[{"key":{"label":"vertex","name":["lop"],"id":{"@type":"g:Int32","@value":3},"lang":["java"]},"value":{"@type":"g:Tree","@value":[]}},{"key":{"label":"vertex","name":["vadas"],"id":{"@type":"g:Int32","@value":2},"age":[{"@type":"g:Int32","@value":27}]},"value":{"@type":"g:Tree","@value":[]}},{"key":{"label":"vertex","name":["josh"],"id":{"@type":"g:Int32","@value":4},"age":[{"@type":"g:Int32","@value":32}]},"value":{"@type":"g:Tree","@value":[{"key":{"label":"vertex","name":["ripple"],"id":{"@type":"g:Int32","@value":5},"lang":["java"]},"value":{"@type":"g:Tree","@value":[]}},{"key":{"label":"vertex","name":["lop"],"id":{"@type":"g:Int32","@value":3},"lang":["java"]},"value":{"@type":"g:Tree","@value":[]}}]}}]}}]}
</code>```

which formats to:

```<code>{
    "@type": "g:Tree",
    "@value": [{
        "key": {
            "label": "vertex",
            "name": ["marko"],
            "id": {
                "@type": "g:Int32",
                "@value": 1
            },
            "age": [{
                "@type": "g:Int32",
                "@value": 29
            }]
        },
        "value": {
            "@type": "g:Tree",
            "@value": [{
                "key": {
                    "label": "vertex",
                    "name": ["lop"],
                    "id": {
                        "@type": "g:Int32",
                        "@value": 3
                    },
                    "lang": ["java"]
                },
                "value": {
                    "@type": "g:Tree",
                    "@value": []
                }
            }, {
                "key": {
                    "label": "vertex",
                    "name": ["vadas"],
                    "id": {
                        "@type": "g:Int32",
                        "@value": 2
                    },
                    "age": [{
                        "@type": "g:Int32",
                        "@value": 27
                    }]
                },
                "value": {
                    "@type": "g:Tree",
                    "@value": []
                }
            }, {
                "key": {
                    "label": "vertex",
                    "name": ["josh"],
                    "id": {
                        "@type": "g:Int32",
                        "@value": 4
                    },
                    "age": [{
                        "@type": "g:Int32",
                        "@value": 32
                    }]
                },
                "value": {
                    "@type": "g:Tree",
                    "@value": [{
                        "key": {
                            "label": "vertex",
                            "name": ["ripple"],
                            "id": {
                                "@type": "g:Int32",
                                "@value": 5
                            },
                            "lang": ["java"]
                        },
                        "value": {
                            "@type": "g:Tree",
                            "@value": []
                        }
                    }, {
                        "key": {
                            "label": "vertex",
                            "name": ["lop"],
                            "id": {
                                "@type": "g:Int32",
                                "@value": 3
                            },
                            "lang": ["java"]
                        },
                        "value": {
                            "@type": "g:Tree",
                            "@value": []
                        }
                    }]
                }
            }]
        }
    }]
}
</code>```

If you are on older version of TinkerPop going back to 3.0.x, then there are some limitations with tree that aren't easily worked around. The only approach is to take a raw tree and post-process it to get it to a form that is friendly to JSON. Here is one way to do that:

```<code>gremlin> convert = { it.collectEntries{ k,v -> [(k.id()): [k, v.isEmpty() ? v : convert(v)]] }}
==>groovysh_evaluate$_run_closure1@255e5e2e
gremlin> t = g.V(1).repeat(out()).emit().tree().next()
==>v[1]={v[2]={}, v[3]={}, v[4]={v[3]={}, v[5]={}}}
gremlin> convert(t)
==>1=[v[1], {2=[v[2], {}], 3=[v[3], {}], 4=[v[4], {3=[v[3], {}], 5=[v[5], {}]}]}]
gremlin> mapper.writeValueAsString(convert(t))
==>{"1":[{"id":1,"label":"vertex","type":"vertex","properties":{"name":[{"id":0,"value":"marko"}],"age":[{"id":2,"value":29}]}},{"2":[{"id":2,"label":"vertex","type":"vertex","properties":{"name":[{"id":3,"value":"vadas"}],"age":[{"id":4,"value":27}]}},{}],"3":[{"id":3,"label":"vertex","type":"vertex","properties":{"name":[{"id":5,"value":"lop"}],"lang":[{"id":6,"value":"java"}]}},{}],"4":[{"id":4,"label":"vertex","type":"vertex","properties":{"name":[{"id":7,"value":"josh"}],"age":[{"id":8,"value":32}]}},{"3":[{"id":3,"label":"vertex","type":"vertex","properties":{"name":[{"id":5,"value":"lop"}],"lang":[{"id":6,"value":"java"}]}},{}],"5":[{"id":5,"label":"vertex","type":"vertex","properties":{"name":[{"id":9,"value":"ripple"}],"lang":[{"id":10,"value":"java"}]}},{}]}]}]}
</code>```

This formats in GraphSON 1.0 (which is what is used in 3.0.x) to:

```<code>{
    "1": [{
        "id": 1,
        "label": "vertex",
        "type": "vertex",
        "properties": {
            "name": [{
                "id": 0,
                "value": "marko"
            }],
            "age": [{
                "id": 2,
                "value": 29
            }]
        }
    }, {
        "2": [{
            "id": 2,
            "label": "vertex",
            "type": "vertex",
            "properties": {
                "name": [{
                    "id": 3,
                    "value": "vadas"
                }],
                "age": [{
                    "id": 4,
                    "value": 27
                }]
            }
        }, {}],
        "3": [{
            "id": 3,
            "label": "vertex",
            "type": "vertex",
            "properties": {
                "name": [{
                    "id": 5,
                    "value": "lop"
                }],
                "lang": [{
                    "id": 6,
                    "value": "java"
                }]
            }
        }, {}],
        "4": [{
            "id": 4,
            "label": "vertex",
            "type": "vertex",
            "properties": {
                "name": [{
                    "id": 7,
                    "value": "josh"
                }],
                "age": [{
                    "id": 8,
                    "value": 32
                }]
            }
        }, {
            "3": [{
                "id": 3,
                "label": "vertex",
                "type": "vertex",
                "properties": {
                    "name": [{
                        "id": 5,
                        "value": "lop"
                    }],
                    "lang": [{
                        "id": 6,
                        "value": "java"
                    }]
                }
            }, {}],
            "5": [{
                "id": 5,
                "label": "vertex",
                "type": "vertex",
                "properties": {
                    "name": [{
                        "id": 9,
                        "value": "ripple"
                    }],
                    "lang": [{
                        "id": 10,
                        "value": "java"
                    }]
                }
            }, {}]
        }]
    }]
}
</code>```

The convert() function i created just recursively iterates the tree and turns every [vertex: children] into [vertexId: [vertex,children]. You can convert to whatever format you like, so long as you build valid JSON where there is a usable String key field. I could have just as easily made the convert() function return [vertexId: [node: vertex, leaves: children]:

```<code>gremlin> convert = { it.collectEntries{ k,v -> [(k.id()): [node: k, leaves:v.isEmpty() ? v : convert(v)]] }}
==>groovysh_evaluate$_run_closure1@2ab5afc7
gremlin> mapper.writeValueAsString(convert(t))
==>{"1":{"node":{"id":1,"label":"vertex","type":"vertex","properties":{"name":[{"id":0,"value":"marko"}],"age":[{"id":2,"value":29}]}},"leaves":{"2":{"node":{"id":2,"label":"vertex","type":"vertex","properties":{"name":[{"id":3,"value":"vadas"}],"age":[{"id":4,"value":27}]}},"leaves":{}},"3":{"node":{"id":3,"label":"vertex","type":"vertex","properties":{"name":[{"id":5,"value":"lop"}],"lang":[{"id":6,"value":"java"}]}},"leaves":{}},"4":{"node":{"id":4,"label":"vertex","type":"vertex","properties":{"name":[{"id":7,"value":"josh"}],"age":[{"id":8,"value":32}]}},"leaves":{"3":{"node":{"id":3,"label":"vertex","type":"vertex","properties":{"name":[{"id":5,"value":"lop"}],"lang":[{"id":6,"value":"java"}]}},"leaves":{}},"5":{"node":{"id":5,"label":"vertex","type":"vertex","properties":{"name":[{"id":9,"value":"ripple"}],"lang":[{"id":10,"value":"java"}]}},"leaves":{}}}}}}}
</code>```

Body:
I am able to get all the child nodes and its related information under a parent node but in a array of objects format , for the query

g.V(4128).repeat(out()).emit()

[
  {
    "id": 4152.0,
    "label": "location",
    "type": "vertex",
    "properties": {
      "displayName": [
        {
          "id": "1l3-37c-1l1",
          "value": "XYZ"
        }
      ],
      "description": [
        {
          "id": "1zb-37c-7wl",
          "value": "XYZ World"
        }
      ],
      "shortName": [
        {
          "id": "16v-37c-745",
          "value": "XYZ"
        }
      ]
    }
  },
  {
    "id": 4176.0,
    "label": "location",
    "type": "vertex",
    "properties": {
      "displayName": [
        {
          "id": "1l6-380-1l1",
          "value": "XYZ-XYZW"
        }
      ],
      "description": [
        {
          "id": "1ze-380-7wl",
          "value": "XYZ West Campus"
        }
      ],
      "shortName": [
        {
          "id": "16y-380-745",
          "value": "XYZW"
        }
      ]
    }
  },
  {
    "id": 8344.0,
    "label": "location",
    "type": "vertex",
    "properties": {
      "displayName": [
        {
          "id": "3kj-6fs-1l1",
          "value": "XYZ-XYZE"
        }
      ],
      "description": [
        {
          "id": "3yr-6fs-7wl",
          "value": "XYZ East Campus"
        }
      ],
      "shortName": [
        {
          "id": "36b-6fs-745",
          "value": "XYZE"
        }
      ]
    }
  },
  {
    "id": 4104.0,
    "label": "location",
    "type": "vertex",
    "properties": {
      "displayName": [
        {
          "id": "1kx-360-1l1",
          "value": "XYZ-XYZW-P1"
        }
      ],
      "description": [
        {
          "id": "1z5-360-7wl",
          "value": "XYZ West Campus-Phase-1"
        }
      ],
      "shortName": [
        {
          "id": "16p-360-745",
          "value": "P1"
        }
      ]
    }
  },
  {
    "id": 4296.0,
    "label": "location",
    "type": "vertex",
    "properties": {
      "displayName": [
        {
          "id": "1ll-3bc-1l1",
          "value": "XYZ-XYZW-P3"
        }
      ],
      "description": [
        {
          "id": "1zt-3bc-7wl",
          "value": "XYZ West Campus-Phase-3"
        }
      ],
      "shortName": [
        {
          "id": "17d-3bc-745",
          "value": "P3"
        }
      ]
    }
  },
  {
    "id": 8200.0,
    "label": "location",
    "type": "vertex",
    "properties": {
      "displayName": [
        {
          "id": "3k1-6bs-1l1",
          "value": "XYZ-XYZW-P2"
        }
      ],
      "description": [
        {
          "id": "3y9-6bs-7wl",
          "value": "XYZ West Campus-Phase-2"
        }
      ],
      "shortName": [
        {
          "id": "35t-6bs-745",
          "value": "P2"
        }
      ]
    }
  },
  {
    "id": 8224.0,
    "label": "location",
    "type": "vertex",
    "properties": {
      "displayName": [
        {
          "id": "3yc-6cg-1l1",
          "value": "XYZ-XYZE-P1"
        }
      ],
      "description": [
        {
          "id": "4ck-6cg-7wl",
          "value": "XYZ East Campus-Phase-1"
        }
      ],
      "shortName": [
        {
          "id": "3k4-6cg-745",
          "value": "P1"
        }
      ]
    }
  },
  {
    "id": 8392.0,
    "label": "location",
    "type": "vertex",
    "properties": {
      "displayName": [
        {
          "id": "3kp-6h4-1l1",
          "value": "XYZ-XYZE-P2"
        }
      ],
      "description": [
        {
          "id": "3yx-6h4-7wl",
          "value": "XYZ East Campus-Phase-2"
        }
      ],
      "shortName": [
        {
          "id": "36h-6h4-745",
          "value": "P2"
        }
      ]
    }
  }
]

I need to get the same information in hierarchial way .

I tried the following query

g.V(4128).repeat(out()).emit().tree().by(__.valueMap(true))

but I don't get the valid json.

I need to get the above data but in hierarchical way

Updated

 I tried the following query

   g.V(4128).repeat(out()).emit().tree().by(__.valueMap(true))

And the response I received was

[
   {
"{label = org, name = [XYZ], orgId = [00000000-0000-0000-0000-000000000001], desc = [XYZ Organization], id = 4128}": {
  "{label = location, displayName = [hh], description = [hfds], shortName = [kk], id = 8272}": {

  },
  "{label = location, displayName = [XYZ], description = [XYZ World], shortName = [XYZ], id = 4152}": {
    "{label = location, displayName = [XYZ-XYZW], description = [XYZ West Campus], shortName = [XYZW], id = 4176}": {
      "{label = location, displayName = [XYZ-XYZW-P3], description = [XYZ West Campus-Phase-3], shortName = [P3], id = 4296}": {

      },
      "{label = location, displayName = [XYZ-XYZW-P2], description = [XYZ West Campus-Phase-2], shortName = [P2], id = 8200}": {

      },
      "{label = location, displayName = [XYZ-XYZW-P1], description = [XYZ West Campus-Phase-1], shortName = [P1], id = 4104}": {

      }
    },
    "{label = location, displayName = [XYZ-XYZE], description = [XYZ East Campus], shortName = [XYZE], id = 8344}": {
      "{label = location, displayName = [XYZ-XYZE-P1], description = [XYZ East Campus-Phase-1], shortName = [P1], id = 8224}": {

      },
      "{label = location, displayName = [XYZ-XYZE-P2], description = [XYZ East Campus-Phase-2], shortName = [P2], id = 8392}": {

      }
    }
  },
  "{label = location, displayName = [hh], description = [hfds], shortName = [kk], id = 8248}": {

  },
  "{label = location, displayName = [hh], description = [hfds], shortName = [kk], id = 12488}": {

  }
}

}
]

Now as you can see the json so received is not appropriate because the key contains fields that are '=' separated .

Now as for the answer I also tried the folowing query

g.V(4128).repeat(out()).emit().tree().next()

but the response returned only ids and didnt resolve the vertex properties

[
  {
    "4128": {
      "8272": {},
      "4152": {
        "4176": {
          "4104": {},
          "4296": {},
          "8200": {}
        },
        "8344": {
          "8224": {},
          "8392": {}
        }
      },
      "8248": {},
      "12488": {}
    }
  }
]

For the context I am using the following configurations  in my gremlin-server.yaml file

authentication: {className: org.apache.tinkerpop.gremlin.server.auth.AllowAllAuthenticator,
  config: null}
channelizer: org.apache.tinkerpop.gremlin.server.channel.HttpChannelizer
graphs: {graph: 'D:/graph-data-access/src/test/resources/titan-inmemory.properties'}
gremlinPool: 8
host: localhost
maxAccumulationBufferComponents: 1024
maxChunkSize: 8192
maxContentLength: 65536
maxHeaderSize: 8192
maxInitialLineLength: 4096
metrics:
  consoleReporter: null
  csvReporter: null
  gangliaReporter: null
  graphiteReporter: null
  jmxReporter: null
  slf4jReporter: {enabled: true, interval: 180000, loggerName: org.apache.tinkerpop.gremlin.server.Settings$Slf4jReporterMetrics}
plugins: [aurelius.titan, tinkerpop.gephi]
port: 8182
processors: []
resultIterationBatchSize: 64
scriptEngines:
  gremlin-groovy:
    config: null
    imports: [java.lang.Math]
    scripts: ['D:/graph-data-access/src/test/resources/generate-locations.groovy']
    staticImports: [java.lang.Math.PI]
scriptEvaluationTimeout: 30000
serializedResponseTimeout: 30000
serializers:
- className: org.apache.tinkerpop.gremlin.driver.ser.GryoMessageSerializerV1d0
  config: {useMapperFromGraph: graph}
- className: org.apache.tinkerpop.gremlin.driver.ser.GryoMessageSerializerV1d0
  config: {serializeResultToString: true}
- className: org.apache.tinkerpop.gremlin.driver.ser.GraphSONMessageSerializerV1d0
  config: {useMapperFromGraph: graph}
- className: org.apache.tinkerpop.gremlin.driver.ser.GraphSONMessageSerializerGremlinV1d0
  config: {useMapperFromGraph: graph}
ssl: {enabled: false, keyCertChainFile: null, keyFile: null, keyPassword: null, trustCertChainFile: null}
threadPoolBoss: 1
threadPoolWorker: 1
writeBufferHighWaterMark: 65536
writeBufferLowWaterMark: 32768

I am using Tinkerpop version 3.0.1 incubating as I am trying to use Titan 1.0.0 with DynamoDb as storage backend for the remote connection.

Body:
Not sure what you mean by "but i don't get valid json". You should be able to serialized a Tree in GraphSON 1.0 if you don't include by(valueMap(true)) and just serialize the full vertex. There is a failure if you try to do it as just maps as it makes some assumptions about there being a graph Element as the key (which is probably bad).

gremlin> mapper = graph.io(graphson()).mapper().version(GraphSONVersion.V1_0).create().createMapper()
==>org.apache.tinkerpop.shaded.jackson.databind.ObjectMapper@6b2e0f78
gremlin> mapper.writeValueAsString(g.V(1).repeat(out()).emit().tree().next())
==>{"1":{"key":{"id":1,"label":"vertex","type":"vertex","properties":{"name":[{"id":0,"value":"marko"}],"age":[{"id":2,"value":29}]}},"value":{"2":{"key":{"id":2,"label":"vertex","type":"vertex","properties":{"name":[{"id":3,"value":"vadas"}],"age":[{"id":4,"value":27}]}},"value":{}},"3":{"key":{"id":3,"label":"vertex","type":"vertex","properties":{"name":[{"id":5,"value":"lop"}],"lang":[{"id":6,"value":"java"}]}},"value":{}},"4":{"key":{"id":4,"label":"vertex","type":"vertex","properties":{"name":[{"id":7,"value":"josh"}],"age":[{"id":8,"value":32}]}},"value":{"3":{"key":{"id":3,"label":"vertex","type":"vertex","properties":{"name":[{"id":5,"value":"lop"}],"lang":[{"id":6,"value":"java"}]}},"value":{}},"5":{"key":{"id":5,"label":"vertex","type":"vertex","properties":{"name":[{"id":9,"value":"ripple"}],"lang":[{"id":10,"value":"java"}]}},"value":{}}}}}}}

That formats to:

{
    "1": {
        "key": {
            "id": 1,
            "label": "vertex",
            "type": "vertex",
            "properties": {
                "name": [{
                    "id": 0,
                    "value": "marko"
                }],
                "age": [{
                    "id": 2,
                    "value": 29
                }]
            }
        },
        "value": {
            "2": {
                "key": {
                    "id": 2,
                    "label": "vertex",
                    "type": "vertex",
                    "properties": {
                        "name": [{
                            "id": 3,
                            "value": "vadas"
                        }],
                        "age": [{
                            "id": 4,
                            "value": 27
                        }]
                    }
                },
                "value": {}
            },
            "3": {
                "key": {
                    "id": 3,
                    "label": "vertex",
                    "type": "vertex",
                    "properties": {
                        "name": [{
                            "id": 5,
                            "value": "lop"
                        }],
                        "lang": [{
                            "id": 6,
                            "value": "java"
                        }]
                    }
                },
                "value": {}
            },
            "4": {
                "key": {
                    "id": 4,
                    "label": "vertex",
                    "type": "vertex",
                    "properties": {
                        "name": [{
                            "id": 7,
                            "value": "josh"
                        }],
                        "age": [{
                            "id": 8,
                            "value": 32
                        }]
                    }
                },
                "value": {
                    "3": {
                        "key": {
                            "id": 3,
                            "label": "vertex",
                            "type": "vertex",
                            "properties": {
                                "name": [{
                                    "id": 5,
                                    "value": "lop"
                                }],
                                "lang": [{
                                    "id": 6,
                                    "value": "java"
                                }]
                            }
                        },
                        "value": {}
                    },
                    "5": {
                        "key": {
                            "id": 5,
                            "label": "vertex",
                            "type": "vertex",
                            "properties": {
                                "name": [{
                                    "id": 9,
                                    "value": "ripple"
                                }],
                                "lang": [{
                                    "id": 10,
                                    "value": "java"
                                }]
                            }
                        },
                        "value": {}
                    }
                }
            }
        }
    }
}

In GraphSON 2.0 you get this:

gremlin> mapper = graph.io(graphson()).mapper().version(GraphSONVersion.V2_0).create().createMapper()
==>org.apache.tinkerpop.shaded.jackson.databind.ObjectMapper@3ffb3598
gremlin> mapper.writeValueAsString(g.V(1).repeat(out()).emit().tree().next())
==>{"@type":"g:Tree","@value":[{"key":{"@type":"g:Vertex","@value":{"id":{"@type":"g:Int32","@value":1},"label":"vertex","properties":{"name":[{"@type":"g:VertexProperty","@value":{"id":{"@type":"g:Int32","@value":0},"value":"marko","label":"name"}}],"age":[{"@type":"g:VertexProperty","@value":{"id":{"@type":"g:Int32","@value":2},"value":{"@type":"g:Int32","@value":29},"label":"age"}}]}}},"value":{"@type":"g:Tree","@value":[{"key":{"@type":"g:Vertex","@value":{"id":{"@type":"g:Int32","@value":2},"label":"vertex","properties":{"name":[{"@type":"g:VertexProperty","@value":{"id":{"@type":"g:Int32","@value":3},"value":"vadas","label":"name"}}],"age":[{"@type":"g:VertexProperty","@value":{"id":{"@type":"g:Int32","@value":4},"value":{"@type":"g:Int32","@value":27},"label":"age"}}]}}},"value":{"@type":"g:Tree","@value":[]}},{"key":{"@type":"g:Vertex","@value":{"id":{"@type":"g:Int32","@value":3},"label":"vertex","properties":{"name":[{"@type":"g:VertexProperty","@value":{"id":{"@type":"g:Int32","@value":5},"value":"lop","label":"name"}}],"lang":[{"@type":"g:VertexProperty","@value":{"id":{"@type":"g:Int32","@value":6},"value":"java","label":"lang"}}]}}},"value":{"@type":"g:Tree","@value":[]}},{"key":{"@type":"g:Vertex","@value":{"id":{"@type":"g:Int32","@value":4},"label":"vertex","properties":{"name":[{"@type":"g:VertexProperty","@value":{"id":{"@type":"g:Int32","@value":7},"value":"josh","label":"name"}}],"age":[{"@type":"g:VertexProperty","@value":{"id":{"@type":"g:Int32","@value":8},"value":{"@type":"g:Int32","@value":32},"label":"age"}}]}}},"value":{"@type":"g:Tree","@value":[{"key":{"@type":"g:Vertex","@value":{"id":{"@type":"g:Int32","@value":3},"label":"vertex","properties":{"name":[{"@type":"g:VertexProperty","@value":{"id":{"@type":"g:Int32","@value":5},"value":"lop","label":"name"}}],"lang":[{"@type":"g:VertexProperty","@value":{"id":{"@type":"g:Int32","@value":6},"value":"java","label":"lang"}}]}}},"value":{"@type":"g:Tree","@value":[]}},{"key":{"@type":"g:Vertex","@value":{"id":{"@type":"g:Int32","@value":5},"label":"vertex","properties":{"name":[{"@type":"g:VertexProperty","@value":{"id":{"@type":"g:Int32","@value":9},"value":"ripple","label":"name"}}],"lang":[{"@type":"g:VertexProperty","@value":{"id":{"@type":"g:Int32","@value":10},"value":"java","label":"lang"}}]}}},"value":{"@type":"g:Tree","@value":[]}}]}}]}}]}

which formats as:

{
    "@type": "g:Tree",
    "@value": [{
        "key": {
            "label": "vertex",
            "name": ["marko"],
            "id": {
                "@type": "g:Int32",
                "@value": 1
            },
            "age": [{
                "@type": "g:Int32",
                "@value": 29
            }]
        },
        "value": {
            "@type": "g:Tree",
            "@value": [{
                "key": {
                    "label": "vertex",
                    "name": ["lop"],
                    "id": {
                        "@type": "g:Int32",
                        "@value": 3
                    },
                    "lang": ["java"]
                },
                "value": {
                    "@type": "g:Tree",
                    "@value": []
                }
            }, {
                "key": {
                    "label": "vertex",
                    "name": ["vadas"],
                    "id": {
                        "@type": "g:Int32",
                        "@value": 2
                    },
                    "age": [{
                        "@type": "g:Int32",
                        "@value": 27
                    }]
                },
                "value": {
                    "@type": "g:Tree",
                    "@value": []
                }
            }, {
                "key": {
                    "label": "vertex",
                    "name": ["josh"],
                    "id": {
                        "@type": "g:Int32",
                        "@value": 4
                    },
                    "age": [{
                        "@type": "g:Int32",
                        "@value": 32
                    }]
                },
                "value": {
                    "@type": "g:Tree",
                    "@value": [{
                        "key": {
                            "label": "vertex",
                            "name": ["ripple"],
                            "id": {
                                "@type": "g:Int32",
                                "@value": 5
                            },
                            "lang": ["java"]
                        },
                        "value": {
                            "@type": "g:Tree",
                            "@value": []
                        }
                    }, {
                        "key": {
                            "label": "vertex",
                            "name": ["lop"],
                            "id": {
                                "@type": "g:Int32",
                                "@value": 3
                            },
                            "lang": ["java"]
                        },
                        "value": {
                            "@type": "g:Tree",
                            "@value": []
                        }
                    }]
                }
            }]
        }
    }]
}

Note that you can also use by(valueMap(true)) in the case of GraphSON 2.0:

gremlin> mapper.writeValueAsString(g.V(1).repeat(out()).emit().tree().by(valueMap(true)).next())
==>{"@type":"g:Tree","@value":[{"key":{"label":"vertex","name":["marko"],"id":{"@type":"g:Int32","@value":1},"age":[{"@type":"g:Int32","@value":29}]},"value":{"@type":"g:Tree","@value":[{"key":{"label":"vertex","name":["lop"],"id":{"@type":"g:Int32","@value":3},"lang":["java"]},"value":{"@type":"g:Tree","@value":[]}},{"key":{"label":"vertex","name":["vadas"],"id":{"@type":"g:Int32","@value":2},"age":[{"@type":"g:Int32","@value":27}]},"value":{"@type":"g:Tree","@value":[]}},{"key":{"label":"vertex","name":["josh"],"id":{"@type":"g:Int32","@value":4},"age":[{"@type":"g:Int32","@value":32}]},"value":{"@type":"g:Tree","@value":[{"key":{"label":"vertex","name":["ripple"],"id":{"@type":"g:Int32","@value":5},"lang":["java"]},"value":{"@type":"g:Tree","@value":[]}},{"key":{"label":"vertex","name":["lop"],"id":{"@type":"g:Int32","@value":3},"lang":["java"]},"value":{"@type":"g:Tree","@value":[]}}]}}]}}]}

which formats to:

{
    "@type": "g:Tree",
    "@value": [{
        "key": {
            "label": "vertex",
            "name": ["marko"],
            "id": {
                "@type": "g:Int32",
                "@value": 1
            },
            "age": [{
                "@type": "g:Int32",
                "@value": 29
            }]
        },
        "value": {
            "@type": "g:Tree",
            "@value": [{
                "key": {
                    "label": "vertex",
                    "name": ["lop"],
                    "id": {
                        "@type": "g:Int32",
                        "@value": 3
                    },
                    "lang": ["java"]
                },
                "value": {
                    "@type": "g:Tree",
                    "@value": []
                }
            }, {
                "key": {
                    "label": "vertex",
                    "name": ["vadas"],
                    "id": {
                        "@type": "g:Int32",
                        "@value": 2
                    },
                    "age": [{
                        "@type": "g:Int32",
                        "@value": 27
                    }]
                },
                "value": {
                    "@type": "g:Tree",
                    "@value": []
                }
            }, {
                "key": {
                    "label": "vertex",
                    "name": ["josh"],
                    "id": {
                        "@type": "g:Int32",
                        "@value": 4
                    },
                    "age": [{
                        "@type": "g:Int32",
                        "@value": 32
                    }]
                },
                "value": {
                    "@type": "g:Tree",
                    "@value": [{
                        "key": {
                            "label": "vertex",
                            "name": ["ripple"],
                            "id": {
                                "@type": "g:Int32",
                                "@value": 5
                            },
                            "lang": ["java"]
                        },
                        "value": {
                            "@type": "g:Tree",
                            "@value": []
                        }
                    }, {
                        "key": {
                            "label": "vertex",
                            "name": ["lop"],
                            "id": {
                                "@type": "g:Int32",
                                "@value": 3
                            },
                            "lang": ["java"]
                        },
                        "value": {
                            "@type": "g:Tree",
                            "@value": []
                        }
                    }]
                }
            }]
        }
    }]
}

If you are on older version of TinkerPop going back to 3.0.x, then there are some limitations with tree that aren't easily worked around. The only approach is to take a raw tree and post-process it to get it to a form that is friendly to JSON. Here is one way to do that:

gremlin> convert = { it.collectEntries{ k,v -> [(k.id()): [k, v.isEmpty() ? v : convert(v)]] }}
==>groovysh_evaluate$_run_closure1@255e5e2e
gremlin> t = g.V(1).repeat(out()).emit().tree().next()
==>v[1]={v[2]={}, v[3]={}, v[4]={v[3]={}, v[5]={}}}
gremlin> convert(t)
==>1=[v[1], {2=[v[2], {}], 3=[v[3], {}], 4=[v[4], {3=[v[3], {}], 5=[v[5], {}]}]}]
gremlin> mapper.writeValueAsString(convert(t))
==>{"1":[{"id":1,"label":"vertex","type":"vertex","properties":{"name":[{"id":0,"value":"marko"}],"age":[{"id":2,"value":29}]}},{"2":[{"id":2,"label":"vertex","type":"vertex","properties":{"name":[{"id":3,"value":"vadas"}],"age":[{"id":4,"value":27}]}},{}],"3":[{"id":3,"label":"vertex","type":"vertex","properties":{"name":[{"id":5,"value":"lop"}],"lang":[{"id":6,"value":"java"}]}},{}],"4":[{"id":4,"label":"vertex","type":"vertex","properties":{"name":[{"id":7,"value":"josh"}],"age":[{"id":8,"value":32}]}},{"3":[{"id":3,"label":"vertex","type":"vertex","properties":{"name":[{"id":5,"value":"lop"}],"lang":[{"id":6,"value":"java"}]}},{}],"5":[{"id":5,"label":"vertex","type":"vertex","properties":{"name":[{"id":9,"value":"ripple"}],"lang":[{"id":10,"value":"java"}]}},{}]}]}]}

This formats in GraphSON 1.0 (which is what is used in 3.0.x) to:

{
    "1": [{
        "id": 1,
        "label": "vertex",
        "type": "vertex",
        "properties": {
            "name": [{
                "id": 0,
                "value": "marko"
            }],
            "age": [{
                "id": 2,
                "value": 29
            }]
        }
    }, {
        "2": [{
            "id": 2,
            "label": "vertex",
            "type": "vertex",
            "properties": {
                "name": [{
                    "id": 3,
                    "value": "vadas"
                }],
                "age": [{
                    "id": 4,
                    "value": 27
                }]
            }
        }, {}],
        "3": [{
            "id": 3,
            "label": "vertex",
            "type": "vertex",
            "properties": {
                "name": [{
                    "id": 5,
                    "value": "lop"
                }],
                "lang": [{
                    "id": 6,
                    "value": "java"
                }]
            }
        }, {}],
        "4": [{
            "id": 4,
            "label": "vertex",
            "type": "vertex",
            "properties": {
                "name": [{
                    "id": 7,
                    "value": "josh"
                }],
                "age": [{
                    "id": 8,
                    "value": 32
                }]
            }
        }, {
            "3": [{
                "id": 3,
                "label": "vertex",
                "type": "vertex",
                "properties": {
                    "name": [{
                        "id": 5,
                        "value": "lop"
                    }],
                    "lang": [{
                        "id": 6,
                        "value": "java"
                    }]
                }
            }, {}],
            "5": [{
                "id": 5,
                "label": "vertex",
                "type": "vertex",
                "properties": {
                    "name": [{
                        "id": 9,
                        "value": "ripple"
                    }],
                    "lang": [{
                        "id": 10,
                        "value": "java"
                    }]
                }
            }, {}]
        }]
    }]
}

The convert() function i created just recursively iterates the tree and turns every [vertex: children] into [vertexId: [vertex,children]. You can convert to whatever format you like, so long as you build valid JSON where there is a usable String key field. I could have just as easily made the convert() function return [vertexId: [node: vertex, leaves: children]:

gremlin> convert = { it.collectEntries{ k,v -> [(k.id()): [node: k, leaves:v.isEmpty() ? v : convert(v)]] }}
==>groovysh_evaluate$_run_closure1@2ab5afc7
gremlin> mapper.writeValueAsString(convert(t))
==>{"1":{"node":{"id":1,"label":"vertex","type":"vertex","properties":{"name":[{"id":0,"value":"marko"}],"age":[{"id":2,"value":29}]}},"leaves":{"2":{"node":{"id":2,"label":"vertex","type":"vertex","properties":{"name":[{"id":3,"value":"vadas"}],"age":[{"id":4,"value":27}]}},"leaves":{}},"3":{"node":{"id":3,"label":"vertex","type":"vertex","properties":{"name":[{"id":5,"value":"lop"}],"lang":[{"id":6,"value":"java"}]}},"leaves":{}},"4":{"node":{"id":4,"label":"vertex","type":"vertex","properties":{"name":[{"id":7,"value":"josh"}],"age":[{"id":8,"value":32}]}},"leaves":{"3":{"node":{"id":3,"label":"vertex","type":"vertex","properties":{"name":[{"id":5,"value":"lop"}],"lang":[{"id":6,"value":"java"}]}},"leaves":{}},"5":{"node":{"id":5,"label":"vertex","type":"vertex","properties":{"name":[{"id":9,"value":"ripple"}],"lang":[{"id":10,"value":"java"}]}},"leaves":{}}}}}}}


问:
Checking constraints at runtime
I'm trying to define a function that detects whether the type of an input satisfies a given constraint:

```<code>satisfies :: (c a => a -> b) -> a -> Maybe b

-- or the more general
claim :: (c => a) -> Maybe a
</code>```

So the desired behaviour would be:

```<code>>>> :t satisfies @Show show
satisfies @Show show :: a -> Maybe String
>>> satisfies @Show show (0 :: Int)
Just "0"
>>> satisfies @Show show (id :: Int -> Int)
Nothing
</code>```

The goal is to make it easy to define fully polymorphic functions that take
advantage of specializations when possible:

```<code>showAny :: a -> String
showAny (satisfies @Show show -> Just str) = str
showAny (satisfies @Typeable showType -> Just str) = "_ :: " ++ str
showAny _ = "_"
</code>```

As the easiest thing I could try, my first attempt tried using -fdefer-to-runtime

```<code>{-# OPTIONS_GHC -fdefer-type-errors -Wno-deferred-type-errors #-}
{-# LANGUAGE ConstraintKinds #-}
{-# LANGUAGE RankNTypes #-}
module Claim where
import System.IO.Unsafe (unsafePerformIO)
import System.IO.Error (catchIOError)

satisfies :: (c a => a -> b) -> a -> Maybe b
satisfies f a = unsafePerformIO $
  (return . Just $! f a) `catchIOError` \_ -> return Nothing
</code>```

This failed because -fdefer-type-errors doesn't defer the checking to
runtime, or allow further checking to be done in the context which it is
actually used (as I had hoped), but instead at compile time replaces found
type errors with the equivalent of error "MESSAGE".

Now I'm out of ideas. Is implementing satisfies even possible?

答:
An alternate workaround to the accepted answer is to pass the dictionaries around manually.

That is, given:

```<code>{-# LANGUAGE GADTs #-}
{-# LANGUAGE ConstraintKinds #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE TypeOperators #-}
module Claim where

data Proof c where QED :: c => Proof c
type Claim c = Maybe (Proof c)
type c ? a = Maybe (Proof (c a))
</code>```

One can write:

```<code>showAny :: (Show? a, Typeable? a) -> a -> String
showAny (Just QED, _) a = show a
showAny (_, Just QED) a = "_ :: " ++ showType a
showAny _ _ = "_"
</code>```

Which works accepably well:

```<code>>>> showAny (Nothing, Just QED) (id :: Int -> Int)
"_ :: Int -> Int"
>>> showAny (Just QED, Just QED) (0 :: Int)
"0"
>>> showAny (Nothing, Nothing) undefined
"_"
</code>```

Title: Checking constraints at runtime

Body:
I'm trying to define a function that detects whether the type of an input satisfies a given constraint:

satisfies :: (c a => a -> b) -> a -> Maybe b

-- or the more general
claim :: (c => a) -> Maybe a

So the desired behaviour would be:

>>> :t satisfies @Show show
satisfies @Show show :: a -> Maybe String
>>> satisfies @Show show (0 :: Int)
Just "0"
>>> satisfies @Show show (id :: Int -> Int)
Nothing

The goal is to make it easy to define fully polymorphic functions that take
advantage of specializations when possible:

showAny :: a -> String
showAny (satisfies @Show show -> Just str) = str
showAny (satisfies @Typeable showType -> Just str) = "_ :: " ++ str
showAny _ = "_"

As the easiest thing I could try, my first attempt tried using -fdefer-to-runtime

{-# OPTIONS_GHC -fdefer-type-errors -Wno-deferred-type-errors #-}
{-# LANGUAGE ConstraintKinds #-}
{-# LANGUAGE RankNTypes #-}
module Claim where
import System.IO.Unsafe (unsafePerformIO)
import System.IO.Error (catchIOError)

satisfies :: (c a => a -> b) -> a -> Maybe b
satisfies f a = unsafePerformIO $
  (return . Just $! f a) `catchIOError` \_ -> return Nothing

This failed because -fdefer-type-errors doesn't defer the checking to
runtime, or allow further checking to be done in the context which it is
actually used (as I had hoped), but instead at compile time replaces found
type errors with the equivalent of error "MESSAGE".

Now I'm out of ideas. Is implementing satisfies even possible?

Body:
An alternate workaround to the accepted answer is to pass the dictionaries around manually.

That is, given:

{-# LANGUAGE GADTs #-}
{-# LANGUAGE ConstraintKinds #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE TypeOperators #-}
module Claim where

data Proof c where QED :: c => Proof c
type Claim c = Maybe (Proof c)
type c ? a = Maybe (Proof (c a))

One can write:

showAny :: (Show? a, Typeable? a) -> a -> String
showAny (Just QED, _) a = show a
showAny (_, Just QED) a = "_ :: " ++ showType a
showAny _ _ = "_"

Which works accepably well:

>>> showAny (Nothing, Just QED) (id :: Int -> Int)
"_ :: Int -> Int"
>>> showAny (Just QED, Just QED) (0 :: Int)
"0"
>>> showAny (Nothing, Nothing) undefined
"_"


问:
ng test throws Error: Cannot find module '@angular-cli/plugins/karma'
I am trying to get started with testing in my project. I saw many posts that said I needed to update my karma.conf.js file from angular-cli/plugins/karma to @angular-cli/plugins/karma. Anywhere where I am referencing angular-cli I put the @ symbol in front of it. This has not fixed my error.

What am I missing?

Here is the error:

```<code>06 06 2017 11:04:09.268:ERROR [config]: Error in config file!
 { Error: Cannot find module '@angular-cli/plugins/karma'
    at Function.Module._resolveFilename (module.js:470:15)
    at Function.Module._load (module.js:418:25)
    at Module.require (module.js:498:17)
    at require (internal/module.js:20:19)
    at module.exports (/.../karma.conf.js:12:7)
    at Object.parseConfig (.../node_modules/karma/lib/config.js:410:5)
    at new Server (.../node_modules/karma/lib/server.js:56:20)
    at Promise (.../node_modules/@angular/cli/tasks/test.js:34:33)
    at Class.run (.../node_modules/@angular/cli/tasks/test.js:15:16)
    at Class.run (.../node_modules/@angular/cli/commands/test.js:101:25)
    at Class.Command.validateAndRun (.../node_modules/@angular/cli/ember-cli/lib/models/command.js:128:15)
    at .../node_modules/@angular/cli/ember-cli/lib/cli/cli.js:92:22
    at tryCatch (.../node_modules/rsvp/dist/lib/rsvp/-internal.js:216:12)
    at invokeCallback (.../node_modules/rsvp/dist/lib/rsvp/-internal.js:231:13)
    at .../node_modules/rsvp/dist/lib/rsvp/then.js:29:16
    at flush (.../node_modules/rsvp/dist/lib/rsvp/asap.js:85:5) code: 'MODULE_NOT_FOUND' }
</code>```

Here is my config file

```<code>// Karma configuration file, see link for more information
// https://karma-runner.github.io/0.13/config/configuration-file.html

module.exports = function (config) {
  config.set({
    basePath: '',
    frameworks: ['jasmine', '@angular-cli'],
    plugins: [
      require('karma-jasmine'),
      require('karma-chrome-launcher'),
      require('karma-remap-istanbul'),
      require('@angular-cli/plugins/karma'),
      require('karma-htmlfile-reporter')
    ],
    files: [
      { pattern: './src/test.ts', watched: false }
    ],
    preprocessors: {
      './src/test.ts': ['@angular-cli']
    },
    remapIstanbulReporter: {
      reports: {
        html: 'coverage',
        lcovonly: './coverage/coverage.lcov'
      }
    },
    angularCli: {
      config: './angular-cli.json',
      environment: 'dev'
    },
    mime: {
      'text/x-typescript': ['ts','tsx']
    },
    reporters: ['progress', 'karma-remap-istanbul', 'html'],
    htmlReporter: {
      outputFile: 'tests/units.html',

      // Optional
      pageTitle: 'Unit Tests for Frontend',
      subPageTitle: 'Should always be passing.',
      groupSuites: true,
      useCompactStyle: true,
      useLegacyStyle: true
    },
    port: 9876,
    colors: true,
    logLevel: config.LOG_INFO,
    autoWatch: true,
    browsers: ['Chrome'],
    singleRun: false
  });
};
</code>```

答:
remove config entry

```<code>angularCli: {
  environment: 'dev'
},
</code>```

more info https://github.com/angular/angular-cli/wiki/stories-rc.0-update

Body:
I am trying to get started with testing in my project. I saw many posts that said I needed to update my karma.conf.js file from angular-cli/plugins/karma to @angular-cli/plugins/karma. Anywhere where I am referencing angular-cli I put the @ symbol in front of it. This has not fixed my error.

What am I missing?

Here is the error:

06 06 2017 11:04:09.268:ERROR [config]: Error in config file!
 { Error: Cannot find module '@angular-cli/plugins/karma'
    at Function.Module._resolveFilename (module.js:470:15)
    at Function.Module._load (module.js:418:25)
    at Module.require (module.js:498:17)
    at require (internal/module.js:20:19)
    at module.exports (/.../karma.conf.js:12:7)
    at Object.parseConfig (.../node_modules/karma/lib/config.js:410:5)
    at new Server (.../node_modules/karma/lib/server.js:56:20)
    at Promise (.../node_modules/@angular/cli/tasks/test.js:34:33)
    at Class.run (.../node_modules/@angular/cli/tasks/test.js:15:16)
    at Class.run (.../node_modules/@angular/cli/commands/test.js:101:25)
    at Class.Command.validateAndRun (.../node_modules/@angular/cli/ember-cli/lib/models/command.js:128:15)
    at .../node_modules/@angular/cli/ember-cli/lib/cli/cli.js:92:22
    at tryCatch (.../node_modules/rsvp/dist/lib/rsvp/-internal.js:216:12)
    at invokeCallback (.../node_modules/rsvp/dist/lib/rsvp/-internal.js:231:13)
    at .../node_modules/rsvp/dist/lib/rsvp/then.js:29:16
    at flush (.../node_modules/rsvp/dist/lib/rsvp/asap.js:85:5) code: 'MODULE_NOT_FOUND' }

Here is my config file

// Karma configuration file, see link for more information
// https://karma-runner.github.io/0.13/config/configuration-file.html

module.exports = function (config) {
  config.set({
    basePath: '',
    frameworks: ['jasmine', '@angular-cli'],
    plugins: [
      require('karma-jasmine'),
      require('karma-chrome-launcher'),
      require('karma-remap-istanbul'),
      require('@angular-cli/plugins/karma'),
      require('karma-htmlfile-reporter')
    ],
    files: [
      { pattern: './src/test.ts', watched: false }
    ],
    preprocessors: {
      './src/test.ts': ['@angular-cli']
    },
    remapIstanbulReporter: {
      reports: {
        html: 'coverage',
        lcovonly: './coverage/coverage.lcov'
      }
    },
    angularCli: {
      config: './angular-cli.json',
      environment: 'dev'
    },
    mime: {
      'text/x-typescript': ['ts','tsx']
    },
    reporters: ['progress', 'karma-remap-istanbul', 'html'],
    htmlReporter: {
      outputFile: 'tests/units.html',

      // Optional
      pageTitle: 'Unit Tests for Frontend',
      subPageTitle: 'Should always be passing.',
      groupSuites: true,
      useCompactStyle: true,
      useLegacyStyle: true
    },
    port: 9876,
    colors: true,
    logLevel: config.LOG_INFO,
    autoWatch: true,
    browsers: ['Chrome'],
    singleRun: false
  });
};

Body:
remove config entry

angularCli: {
  environment: 'dev'
},

more info https://github.com/angular/angular-cli/wiki/stories-rc.0-update