Netowrkx len() command giving a 'str' object error - python-2.7

To start, I created a Network using 2014 flight data as explained here:https://ipython-books.github.io/142-drawing-flight-routes-with-networkx/
I'm trying to create smaller graphs using airline specific flight paths to test connectivity within each business, starting with American Airlines, I did the following:
AASys = routes[
routes['source'].isin(airports_us.index) &
routes['dest'].isin(airports_us.index) &
routes['airline'].str.contains('AA')]
AASys
AAedges = AASys[['source', 'dest']].values
AAedges
AAg = nx.from_edgelist(AAedges)
len(AAg.nodes()), len(AAg.edges())
This mirrors the tutorial input almost exactly, with the only change being the additional str.contains('AA'). But when I try to test the len() of my new database, I get -- TypeError: 'str' object is not callable.
Can anyone explain why my edgelist is reading as a string? How to I fix the TypeError?

Related

APEX: Assigning a Map without a Key to a List

Sorry for the newbie question. Learning Apex here. Been working on an issue for several hours and can't seem to needle it out.
I have a JSON that I need converted to a List... the JSON is retrieved via an API. The code is pretty simple, it is only a couple of lines.
The JSON looks like this:
{"id":1,"abbreviation":"ATL","city":"Atlanta","conference":"East","division":"Southeast","full_name":"Atlanta Hawks","name":"Hawks"}
And the code I am told to use to retrieve it looks like this:
Map<String, Object> resultsMap = (Map<String, Object>) JSON.deserializeUntyped(results.getBody());
Based on the JSON provided, there does not appear to be a MAP key being assigned, so I have no idea how to get it so that I may assign it to a List...
I've already tried assigning it directly to a List, but I didn't get much success there either.
I've tried this already:
List<Object> other = (List<Object>) results.get('');
I've also tried this:
List<Object> other = (List<Object>) results.keySet()[0];
I'm sure it is something simple. Any help would be appreciated.
Thanks
You cant convert the map to a list without an id. Alternatively why to convert it to List. Use the map itself. Below is a code example of how you can use it using your JSON response. For example, I want to insert this JSON response into the contact record, so I can map it using the MAP itself.:
#RestResource(urlMapping='/URIId/*')
global class OwneriCRM {
#HttpPut
global static String UpdateOwnerinfo(){
RestRequest req= RestContext.request;
RestResponse res= RestContext.response;
res.addHeader('Content-type','application/JSON');
Map<String,Object> responseresult=new Map<String,Object>();
Map<String,Object> results= (Map<String,Object>)JSON.deserializeUntyped(req.requestBody.toString());
List<contact> insertList = new List<contact>();
for (String key : results.keySet()){
System.debug(results.get(key));
contact c= new contact();
c.ContactField__C = results.get(id);
c.ContactField1__C = results.get(city);
c.ContactField2__C = results.get(conference);
c.ContactField3__C = results.get(division);
c.ContactField3__C = results.get(full_name);
c.ContactField3__C = results.get(name);
insertList.add(c);
}
if(!insertList.Isempty()){
update insertList;
}
Question can be disregarded. Not sure if there is a way to withdraw the question.
Question was based on the fact that previous APIs had been sent in the following format:
{"data": {"more stuff": "stuff"} }
And the map key was 'data' with a list. In this scenario, the whole API was a list and the keys to the map were set in place with the actual values instead.

Create Inventory Adjustment giving an error

I am trying to create an inventory adjustment from a MAP/REDUCE script. the record from which i am setting the values is getting ftom a search in getInputData(). In map function i am loading that custom record and setting these values
var newcase_inv_Adj = record.create({type:'inventoryadjustment',isDynamic:true});
newcase_inv_Adj.setValue({fieldId:'account',value:creel_account});
newcase_inv_Adj.setValue({fieldId:'custbody_cp_adjreasoncode',value:creel_reasoncode});
newcase_inv_Adj.setValue({fieldId: 'custbody_c_from', value: name});
newcase_inv_Adj.selectNewLine({sublistId:'inventory'});
newcase_inv_Adj.setCurrentSublistValue({sublistId:'inventory',fieldId:'item',value:creel_item});
newcase_inv_Adj.setCurrentSublistValue({sublistId:'inventory',fieldId:'location',value:creellocation});
newcase_inv_Adj.setCurrentSublistValue({sublistId:'inventory',fieldId:'adjustqtyby',value:creel_weigh_oh});
var create_inv_detail = newcase_inv_Adj.getCurrentSublistSubrecord({sublistId: 'inventory',fieldId: 'inventorydetail'});
create_inv_detail.selectNewLine({sublistId:'inventoryassignment' });
create_inv_detail.setCurrentSublistValue({sublistId:'inventoryassignment',fieldId:'receiptinventorynumber',value: creel_casenumber});
create_inv_detail.setCurrentSublistText({sublistId:'inventoryassignment',fieldId:'binnumber',value: creel_bin });
create_inv_detail.setCurrentSublistValue({sublistId:'inventoryassignment',fieldId:'quantity',value: creel_weigh_oh });
create_inv_detail.commitLine('inventoryassignment');log.debug("N","commited inventoryassignment");
newcase_inv_Adj.commitLine({sublistId:'inventory'});log.debug("N","commited inventory");
var invAdjID = newcase_inv_Adj.save();log.debug("N","invAdjID : "+invAdjID);
But, I am getting this error as {"type":"error.SuiteScriptError","name":"UNEXPECTED_ERROR"
Is it because of Map/Reduce script?
I don't find anything wrong in the code.
Few suggestions:
- Follow the sequence: Set subsidiary value before you setvalue for account or any other mandatory field.
- First try with inventory items without serial numbers and see if you continue to face same problem.
- You need to make sure you all your variables has valid value (not null or undefined).
- First try doing this in a schedule script.

Extracting lat/lon from geocode result list with Python (Google Maps API)

I'm attempting to use the Google Maps API with the GoogleMaps Python library to geocode latitude/longitude when provided with whole or part of an address (in this example, I'm using city/state, but I also have datasets with just zip codes that I'll need to use this for down the line).
import googlemaps
gmaps = googlemaps.Client(key=[insert API key here])
geocode_result = gmaps.geocode('Sacramento, CA')
print(geocode_result)
Result:[{u'geometry': {u'location_type': u'APPROXIMATE', u'bounds': {u'northeast': {u'lat': 38.685507, u'lng': -121.325705}, u'southwest': {u'lat': 38.437574, u'lng': -121.56012}}, u'viewport': {u'northeast': {u'lat': 38.685507, u'lng': -121.325705}, u'southwest': {u'lat': 38.437574, u'lng': -121.56012}}, u'location': {u'lat': 38.5815719, u'lng': -121.4943996}}, u'address_components': [{u'long_name': u'Sacramento', u'types': [u'locality', u'political'], u'short_name': u'Sacramento'}, {u'long_name': u'Sacramento County', u'types': [u'administrative_area_level_2', u'political'], u'short_name': u'Sacramento County'}, {u'long_name': u'California', u'types': [u'administrative_area_level_1', u'political'], u'short_name': u'CA'}, {u'long_name': u'United States', u'types': [u'country', u'political'], u'short_name': u'US'}], u'place_id': u'ChIJ-ZeDsnLGmoAR238ZdKpqH5I', u'formatted_address': u'Sacramento, CA, USA', u'types': [u'locality', u'political']}]
My issue is that I'm not sure how to extract the appropriate lat/lon values from this list. I've tried parsing through the list using the following code (taken from the answer to this question on SO):
import operator
thirditem=operator.itemgetter(3)(geocode_result)
print(thirditem)
When I run this, I get an IndexError saying the index is out of range. I've run it through the debugger also, but I get the same error without any additional information. I've googled around and looked through other SO questions, but i'm still not sure where the issue is.
As a side note, I've also tried to use the code examples in this tutorial, but I get a "0" as my answer when I try to run it, which is unfortunately even less helpful than an IndexError.
My goal is to be able to parse the appropriate lat/lon values from here and insert them dynamically into this basemap script. Values are currently hard-coded, but eventually I'd like to be able to use a variable for the values llcrnrlon, llcrnrlat, urcrnrlon, urcrnrlat, lat_0, and lon_0:
map = Basemap(projection='merc',
# with high resolution,
resolution= 'h',
# And threshold 100000
area_thresh = 100000.0,
# Centered on these coordinates
lat_0=37, lon_0=119,
#and using these corners to specify the lower left lon/lat and upper right lon/lat of the graph)
llcrnrlon=-130, llcrnrlat=30,
urcrnrlon=-110, urcrnrlat=45)
I'm SUPER new to all this, so there could be an easy answer that I'm just not seeing. Any help is welcome! Thanks.
I was able to ask some of my fellow devs for help, and I am answering my own question on here in the hopes that it will help others who are also struggling with the same problem.
Geocoded results return a JSON object, which in Python is treated like a dictionary that only contains a single object (the result). Therefore, in order to extract the appropriate lat-lon values, you need to use "geocode_result[0]["geometry"]["location"]["lat"]", with [0] being the first object in the array (the result).
I wrote this function to use in my Basemap script to extract the lat/lon values from a location passed in as a parameter.
def geocode_address(loc):
gmaps = googlemaps.Client(key=[insert your API key here])
geocode_result = gmaps.geocode(loc)
lat = geocode_result[0]["geometry"]["location"]["lat"]
lon = geocode_result[0]["geometry"]["location"]["lng"]
#test - print results
print (lat,lon)
When I test it out using Sacramento, CA as the loc:
geocode_address('Sacramento, CA')
This is my result:
Result: 38.5815719, -121.4943996

Unparsable MOF Query When Trying to Register Event

Update 2
I accepted an answer and asked a different question elsewhere, where I am still trying to get to the bottom of this.
I don't think that one-lining this query is the answer, as I am still not getting the required results (and multi-lining queries is allowed in .mof, as shown in the URLs in comments to the answer ...
Update
I rewrote the query as a one-liner as suggested, but still got the same error! As it was still talking about lines 11-19 I knew there must be another issue. After saving a new file with the change, I reran mofcomp and it appears to have loaded, but the event which I have subscribed to simply does not work.
I really feel that there is not enough documentation on this topic and it is hard to work out how I am meant to debug this - any help on this would be much appreciated, even if this means using a different more appropriate method.
I have the following .mof file, which I would like to use to register an event on my system :
#pragma namespace("\\\\.\\root\\subscription")
instance of __EventFilter as $EventFilter
{
Name = "Event Filter Instance Name";
Query = "Select * from __InstanceCreationEvent within 1 "
"where targetInstance isa \"Cim_DirectoryContainsFile\" "
"and targetInstance.GroupComponent = \"Win32_Directory.Name=\"c:\\\\test\"\"";
QueryLanguage = "WQL";
EventNamespace = "Root\\Cimv2";
};
instance of ActiveScriptEventConsumer as $Consumer
{
Name = "TestConsumer";
ScriptingEngine = "VBScript";
ScriptText =
"Set objFSO = CreateObject(\"Scripting.FileSystemObject\")\n"
"Set objFile = objFSO.OpenTextFile(\"c:\\test\\Log.txt\", 8, True)\n"
"objFile.WriteLine Time & \" \" & \" File Created\"\n"
"objFile.Close\n";
// Specify any other relevant properties.
};
instance of __FilterToConsumerBinding
{
Filter = $EventFilter;
Consumer = $Consumer;
};
But whenever I run the command mfcomp myfile.mof I am getting this error:
Parsing MOF file: myfile.mof
MOF file has been successfully parsed
Storing data in the repository...
An error occurred while processing item 1 defined on lines 11 - 19 in file myfile.mof:
Error Number: 0x80041058, Facility: WMI
Description: Unparsable query.
Compiler returned error 0x80041058
This error appears to be caused by incorrect syntax in the query, but I don't understand where I have gone wrong with this - is anyone able to advise?
There are no string concatenation or line continuation characters being used in building "Query". To keep it simple, you could put the entire query on one line.

Kernel-PCA, KPCA: embed new data, error

I want to apply KPCA on my training data before I pass it to my SVM which seems to work fine with kernlab. Afterwards I want to embed my testing input into the new space in order to make prediction with my SVM. The documentary recommends to use the predict function, which gives me an error:
dataTrain=as.xts(data)
inputTrain=dataTrain[1:settings$windowTrain,1:ncol(dataTrain)-1]
outputTrain=dataTrain[1:settings$windowTrain,ncol(dataTrain)]
kpcaa=kpca(x=inputTrain,data=NULL,kernel="rbfdot",kpar=list(sigma=0.01))
inputTrain=kpcaa#pcv
predict(object = kpcaa,newdata=inputTest)
predict(object = kpcaa,newdata=inputTest)
Error in .local(object, ...) :
unused argument (newdata = c(0.00065527734617099, -0.00281135973754587, 0.00121922641129046, -0.00356807890285626, 0.00140997344409755, 0.000281756282681123, 0.000657122764787132, -0.000469329337005497, -0.000187793427781635, 0.00046941746156115, -0.000751173744242273, 0.000281756282681123, 0.000187793427781635, -0.000469549710462758, 0.000751173744242273, 0.00140693171451645, -0.000937734502324261, -0.000469197212192185, 0.00112570368360299, -0.0014073277173825, 0.0014073277173825, -0.00112570368360299,
0.000656814473530609, -0.00253580788619168, 0.00187899341266107, -0.00310223515540553, 0.00282061112162602, 0.00121979841537989, -0.00150150178359798, 0.000469461536250826, -0.00140904630893512, -0.000188022939352273, -0.000470212074305643, -0.000282233408900545, 0.00094046842255846, -0.000188022939352273, -0.000470212074305643, -0.000470433277716786, 0.00234995643227709, 0.000938438507310124, 0.000937558666089799, 0.0034613440236777, 0.00493736156014979, 0.00046453292050951
Does anybody can help me with this one?
Thank you!
fortunately I found that there was an error in the code.
kpcaa=kpca(x=inputTrain,data=NULL,kernel="rbfdot",kpar=list(sigma=0.01))
has to be something like...
kpcaa=kpca(~.,data=inputTrain,...)