How to fix the lambda expression delegate error? - json

I am using this method to get data
private void getNews(int cat_id, int page)
{
this.progress.Visibility = Visibility.Visible;
var m = new SharpGIS.GZipWebClient();
Microsoft.Phone.Reactive.Observable.FromEvent<DownloadStringCompletedEventArgs>(m, "DownloadStringCompleted").Subscribe(l =>
{
try
{
//List<NewsKeys> deserialized = JsonConvert.DeserializeObject<List<NewsKeys>>(r.EventArgs.Result);
ObservableCollection<NewsKeys> deserialized = JsonConvert.DeserializeObject<List<NewsKeys>>(l.EventArgs.Result);
foreach (NewsKeys item in deserialized)
{
items.Add(new NewsKeys { nId = item.nId, title = item.title, shortDesc = item.shortDesc, fullDesc = item.fullDesc, tags = item.tags, smallPic = item.smallPic, bigPic = item.bigPic, video = item.video, audio = item.audio, youtube = item.youtube, doc = item.doc, date_create = item.date_create, date_modify = item.date_modify, date_publish = item.date_publish, catId = item.catId, viewOrder = item.viewOrder, viewCount = item.viewCount, viewStatus = item.viewStatus, viewHome = item.viewHome, uId = item.uId, uFname = item.uFname });
}
}
catch (Exception)
{
MessageBox.Show("Sorry, Some unexpected error.");
}
});
m.DownloadStringAsync(new Uri(Resource.NEWS_API+cat_id+"&page="+page));
}
The error i get is
Error 1 Cannot convert lambda expression to type 'System.IObserver>' because it is not a delegate type C:\Users\Adodis\Documents\Visual Studio 2010\Projects\TV\NewsListPage.xaml.cs 51 133
I have tried all the fixes but unable to fix this problem. Am using the same block in different method in a different class it is working fine but, this method in this class killing me. Please help me if you have idea on this.
Thanks in advance.

Try this (I've separated the Select and Subscribe operations):
var m = new SharpGIS.GZipWebClient();
Observable.FromEvent<DownloadStringCompletedEventArgs>(m, "DownloadStringCompleted")
.Select(l => l.EventArgs.Result)
.Subscribe(res =>
{
try
{
var deserialized = JsonConvert.DeserializeObject<List<NewsKeys>>(res);
foreach (NewsKeys item in deserialized)
{
items.Add(
new NewsKeys
{
nId = item.nId,
title = item.title,
shortDesc = item.shortDesc,
fullDesc = item.fullDesc,
tags = item.tags,
smallPic = item.smallPic,
bigPic = item.bigPic,
video = item.video,
audio = item.audio,
youtube = item.youtube,
doc = item.doc,
date_create = item.date_create,
date_modify = item.date_modify,
date_publish = item.date_publish,
catId = item.catId,
viewOrder = item.viewOrder,
viewCount = item.viewCount,
viewStatus = item.viewStatus,
viewHome = item.viewHome,
uId = item.uId,
uFname = item.uFname
});
}
}
catch (Exception)
{
MessageBox.Show("Sorry, Some unexpected error.");
}
});
m.DownloadStringAsync(new Uri("Resource.NEWS_API" + cat_id + "&page=" + page));

Related

Parse Bloomberg API response to JSON in python3

How can I convert the response message that returned from using bloomberg API in (python3 and flask) in to JSON
here is a response example:
ReferenceDataResponse = {
securityData[] = {
securityData = {
security = "FB EQUITY"
eidData[] = {
}
fieldExceptions[] = {
}
sequenceNumber = 0
fieldData = {
PX_LAST = 186.270000
VOLUME = 16746904.000000
}
}
securityData = {
security = "IBM EQUITY"
eidData[] = {
}
fieldExceptions[] = {
}
sequenceNumber = 1
fieldData = {
PX_LAST = 134.400000
VOLUME = 2551009.000000
}
}
}
}
dealing with it with the comming piece of code :
if str(msg.messageType()) == "ReferenceDataResponse":
securities = msg.getElement('securityData')
securities_count = securities.numValues()
for i in range(securities_count):
security = securities.getValueAsElement(i)
ticker = security.getElementAsString('security')
if (security.hasElement('fieldData')):
fields = security.getElement('fieldData')
fields_count = fields.numElements()
for j in range (fields_count):
security_dict = None
field = fields.getElement(j)
f_name = field.name()
f_value = field.getValueAsString()
security_dict = {"ticker":ticker ,"f_name":f_name , "f_value":f_value}
bloom_data.append(security_dict)
give me (Object of type Name is not JSON serializable)
now, I cant not access the name object to reach the name of the fields
any help will be very appreciated
After a lot of search I found this doc that is very helpful for as a schema for using the bloomberg api for dealing with the response ....
Here's the link ==> api schema
example for handeling respnse using python3:
bloom_data = []
if str(msg.messageType()) == "ReferenceDataResponse":
securities = msg.getElement('securityData')
securities_count = securities.numValues()
for i in range(securities_count):
security = securities.getValueAsElement(i)
ticker = security.getElementAsString('security')
if (security.hasElement('fieldData')):
fields = security.getElement('fieldData')
fields_count = fields.numElements()
for j in range (fields_count):
security_dict = None
field = fields.getElement(j)
f_name = field.name()
f_value = field.getValueAsString()
security_dict = {"ticker":ticker ,"f_name":str(f_name) , "f_value":f_value}
bloom_data.append(security_dict)

Adding discount by coupon code programmatically

public function coupon($data) {
$couponCode = $data['couponcode'];
if (!Zend_Validate::is(trim($couponCode), 'NotEmpty')) {
throw new Exception($this->__('coupon code cannot be empty.'));
}
$oCoupon = Mage::getModel('salesrule/coupon')->load($couponCode, 'code');
$data = $oCoupon->getData();
if (empty($data)) {
throw new Exception($this->__('coupon code did not match.'));
}
$quote = Mage::getModel('checkout/session')->getQuote();
$quote->setCouponCode($couponCode);
$quote->save();
$quoteData = Mage::getModel('checkout/cart')->getQuote();
$subTotal = $quoteData['subtotal'];
$subtotal_with_discount = $quoteData['subtotal_with_discount'];
$grandTotal = $quoteData['grand_total'];
$discountTotal = ($subTotal - $subtotal_with_discount);
$discount = number_format($discountTotal, 4, null, '');
return $discount;
}
The Coupon code is applied and showing but when I Print the quoteData->GetData() then discount is not coming,and when I will update the refresh cart page then discount is coming
I got the solution
public function coupon($data) {
$couponCode = $data['couponcode'];
if (!Zend_Validate::is(trim($couponCode), 'NotEmpty')) {
throw new Exception($this->__('coupon code cannot be empty.'));
}
$oCoupon = Mage::getModel('salesrule/coupon')->load($couponCode, 'code');
$data = $oCoupon->getData();
if (empty($data)) {
throw new Exception($this->__('coupon code did not match.'));
}
Mage::getSingleton('checkout/cart')->getQuote()->getShippingAddress()
->setCollectShippingRates(true);
Mage::getSingleton('checkout/cart')->getQuote()
->setCouponCode($couponCode)->collectTotals()->save();
$quoteData = Mage::getModel('checkout/cart')->getQuote();
$subTotal = $quoteData['subtotal'];
$subtotal_with_discount = $quoteData['subtotal_with_discount'];
$grandTotal = $quoteData['grand_total'];
$discountTotal = ($subTotal - $subtotal_with_discount);
$discount = number_format($discountTotal, 4, null, '');
return $discount;
}

Json data serialized with JsonConvert.SerializeObject is always string in ASP.NET Web API

I am developing a ASP.NET MVC Web Api. Project. I am returning data with JSON format. Before I return data to user I serialize data using JsonConvert.SerializeObject to change their json property names.My code return data in JSON format. But with an issue. That is it always return data into string even if the data is array or object.
This is my action method that returns json.
public HttpResponseMessage Get()
{
IEnumerable<Region> dbRegions = regionRepo.GetCachedRegions();
List<ContentRegion> regions = new List<ContentRegion>();
if(dbRegions!=null && dbRegions.Count()>0)
{
foreach(var region in dbRegions)
{
ContentRegion contentRegion = new ContentRegion
{
Id = region.Id,
ImageUrl = Url.AbsoluteContent(region.ImagePath),
SmallImageUrl = (String.IsNullOrEmpty(region.ImagePath))?null:Url.AbsoluteContent(CommonHelper.GetImageUrl(region.ImagePath,AppConfig.SmallThumbSuffix)),
MediumImageUrl = (String.IsNullOrEmpty(region.ImagePath))?null:Url.AbsoluteContent(CommonHelper.GetImageUrl(region.ImagePath,AppConfig.MediumThumbSuffix)),
Name = region.Name,
MmName = region.MmName,
Description = region.Description,
MmDescription = region.MmDescription,
Latitude = region.Latitude,
Longitude = region.Longitude
};
regions.Add(contentRegion);
}
}
string json = JsonConvert.SerializeObject(regions);
if(!string.IsNullOrEmpty(json))
{
json = json.Trim(new char[] { '"' });
}
return new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new ObjectContent(json.GetType(),json,Configuration.Formatters.JsonFormatter)
};
}
Actually this code should return Json array. But when I parse data from client (from Android using Volley). It cannot be parsed into Json Array.
This is the data I get:
As you can see the double quote both in the beginning and at the end. The reason I cannot parse it into array in Volley is it is returning as a string because of that double. How can I serialize it trimming that quote? I used trim, but not removed.
You are unnecessarily complicating things. In Web API you can return JSON just by returning any object inside the built-in methods, the framework will serialize it for you.
public IHttpActionResult Get()
{
IEnumerable<Region> dbRegions = regionRepo.GetCachedRegions();
List<ContentRegion> regions = new List<ContentRegion>();
if(dbRegions != null && dbRegions.Count() > 0) {
foreach(var region in dbRegions)
{
ContentRegion contentRegion = new ContentRegion
{
Id = region.Id,
ImageUrl = Url.AbsoluteContent(region.ImagePath),
SmallImageUrl = (String.IsNullOrEmpty(region.ImagePath))?null:Url.AbsoluteContent(CommonHelper.GetImageUrl(region.ImagePath,AppConfig.SmallThumbSuffix)),
MediumImageUrl = (String.IsNullOrEmpty(region.ImagePath))?null:Url.AbsoluteContent(CommonHelper.GetImageUrl(region.ImagePath,AppConfig.MediumThumbSuffix)),
Name = region.Name,
MmName = region.MmName,
Description = region.Description,
MmDescription = region.MmDescription,
Latitude = region.Latitude,
Longitude = region.Longitude
};
regions.Add(contentRegion);
}
}
return Ok(regions);
}
As an aside: from what I can see you are mapping manually your domain objects into DTOs: take into consideration the use of an automatic mapping mechanism like AutoMapper.
I am not sure this is the best solution or not. I solved the problem using this way.
This is my action method
public HttpResponseMessage Get()
{
try
{
IEnumerable<Region> dbRegions = regionRepo.GetCachedRegions();
List<ContentRegion> regions = new List<ContentRegion>();
if (dbRegions != null && dbRegions.Count() > 0)
{
foreach (var region in dbRegions)
{
ContentRegion contentRegion = new ContentRegion
{
Id = region.Id,
ImageUrl = Url.AbsoluteContent(region.ImagePath),
SmallImageUrl = (String.IsNullOrEmpty(region.ImagePath)) ? null : Url.AbsoluteContent(CommonHelper.GetImageUrl(region.ImagePath, AppConfig.SmallThumbSuffix)),
MediumImageUrl = (String.IsNullOrEmpty(region.ImagePath)) ? null : Url.AbsoluteContent(CommonHelper.GetImageUrl(region.ImagePath, AppConfig.MediumThumbSuffix)),
Name = region.Name,
MmName = region.MmName,
Description = region.Description,
MmDescription = region.MmDescription,
Latitude = region.Latitude,
Longitude = region.Longitude
};
regions.Add(contentRegion);
}
}
string json = JsonConvert.SerializeObject(regions);
return new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new StringContent(json, Encoding.Default, "application/json")
};
}
catch
{
return Request.CreateResponse(HttpStatusCode.InternalServerError);
}
}
It's not required to convert object to json string.
You can try :
return Request.CreateResponse<List<ContentRegion>>(HttpStatusCode.OK,regions);
Not tested.
config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));
Use this line in your WebApiConfig.
And here your code should be
public HttpResponseMessage Get()
{
IEnumerable<Region> dbRegions = regionRepo.GetCachedRegions();
List<ContentRegion> regions = new List<ContentRegion>();
HttpResponseMessage temp = ControllerContext.Request.CreateResponse(HttpStatusCode.OK, "");
if (dbRegions != null && dbRegions.Count() > 0)
{
foreach (var region in dbRegions)
{
ContentRegion contentRegion = new ContentRegion
{
Id = region.Id,
ImageUrl = Url.AbsoluteContent(region.ImagePath),
SmallImageUrl = (String.IsNullOrEmpty(region.ImagePath)) ? null : Url.AbsoluteContent(CommonHelper.GetImageUrl(region.ImagePath, AppConfig.SmallThumbSuffix)),
MediumImageUrl = (String.IsNullOrEmpty(region.ImagePath)) ? null : Url.AbsoluteContent(CommonHelper.GetImageUrl(region.ImagePath, AppConfig.MediumThumbSuffix)),
Name = region.Name,
MmName = region.MmName,
Description = region.Description,
MmDescription = region.MmDescription,
Latitude = region.Latitude,
Longitude = region.Longitude
};
regions.Add(contentRegion);
}
}
temp = ControllerContext.Request.CreateResponse(HttpStatusCode.OK, regions);
return temp;
//string json = JsonConvert.SerializeObject(regions);
//if (!string.IsNullOrEmpty(json))
//{
// json = json.Trim(new char[] { '"' });
//}
//return new HttpResponseMessage(HttpStatusCode.OK)
//{
// Content = new ObjectContent(json.GetType(), json, Configuration.Formatters.JsonFormatter)
//};
}

Reading parameters from json using swift 2

iv'e been trying for few days to get parameters from specific json structure with no success so far. I have a NSDictionary that get json data (i need the mToken and data from mHeader for example)
{
"$id" = 1;
mHeaders = (
{
"$id" = 4;
mPoints = 0;
mRealLeagueId = 57172a6e2276fe28bcf0d91c;
mTeamId = 57172a762276fe28bcf0e053;
mTeamLogo = avatar;
mTeamName = "Hungry Animals";
}
);
mToken = "5k8ziTBn0G5Gozs7qz68LCLBfLSgymOcLwRshMax1Q5pZi4bx6hbEOFgupoXrBNNGzsWosLs6KPsK6cG1kk/9o5778Y7JEKfo3CAPXS7qAg=";
mUser = {
"$id" = 2;
mAge = 42;
mCreateDate = "2016-04-20T07:06:30.507Z";
mEmail = "email0#gmail.com";
mFirstName = Alesandro;
mGender = 1;
mId = 57172a762276fe28bcf0e06d;
mLastLogin = "2016-04-21T07:20:40.402Z";
mLastName = Zohar;
mLogo = avatar;
mNick = "Big Boss 0";
mRegion = Global;
mTeams = (
{
"$id" = 3;
mRealLeagueId = 57172a6e2276fe28bcf0d91c;
mTeamId = 57172a762276fe28bcf0e053;
}
);
mTokens = 9644998;
};
}
So you have a dictionary after parsing the json. You need mToken which in root level of the json data, you can simply get the value by
jsonDict["mToken"]
Your mHeader is an array of dictionary so for getting the value, Do like this
for dict in jsonDict["mHeaders"] as! Array<NSDictionary> {
print(dict["mRealLeagueId"]) //prints 57172a6e2276fe28bcf0d91c
print(dict["mTeamId"]) //57172a762276fe28bcf0e053
}
Hope this helps

How to insert a Path in between an existing Path

I am working on an implementation to generate alternate Paths using via node method.
While checking for local optimality I do the following
forwardEdge = bestWeightMapFrom.get(viaNode);
reverseEdge = bestWeightMapTo.get(viaNode);
double unpackedUntilDistance = 0;
while(forwardEdge.edge != -1) {
double parentDist = forwardEdge.parent != null ? forwardEdge.parent.distance : 0;
double dist = forwardEdge.distance - parentDist;
if(unpackedUntilDistance + dist >= T_THRESHOLD) {
EdgeSkipIterState edgeState = (EdgeSkipIterState) graph.getEdgeProps(forwardEdge.edge, forwardEdge.adjNode);
unpackStack.add(new EdgePair(edgeState, false));
sV = forwardEdge.adjNode;
forwardEdge = forwardEdge.parent;
break;
}
else {
unpackedUntilDistance += dist;
forwardEdge = forwardEdge.parent;
sV = forwardEdge.adjNode;
}
}
int oldSV = forwardEdge.adjNode;
EdgeEntry oldForwardEdge = forwardEdge;
I unpack the edge in the stack to further narrow down sV.
I get vT and oldVt in a similar fashion by traversing reverseEdge.
if I determine that the path from sV and vT is <= length of unpacked edges I accept this via node and construct the alternatePath as follows.
PathBidirRef p = (PathBidirRef) algo.calcPath(oldSV, oldVT);
Path4CHAlt p1 = new Path4CHAlt(graph, flagEncoder);
p1.setSwitchToFrom(false);
p1.setEdgeEntry(oldForwardEdge);
p1.segmentEdgeEntry = p.edgeEntry;
double weight = oldForwardEdge.weight + oldReverseEdge.weight + p.edgeEntry.weight + p.edgeTo.weight;
p1.setWeight(weight);
p1.edgeTo = oldReverseEdge;
p1.segmentEdgeTo = p.edgeTo;
Path p2 = p1.extract();
Path4CHAlt is
public class Path4CHAlt extends Path4CH {
private boolean switchWrapper = false;
public EdgeEntry segmentEdgeTo;
public EdgeEntry segmentEdgeEntry;
public Path4CHAlt( Graph g, FlagEncoder encoder )
{
super(g, encoder);
}
public Path4CHAlt setSwitchToFrom( boolean b )
{
switchWrapper = b;
return this;
}
#Override
public Path extract()
{
System.out.println("Path4CHAlt extract");
if (edgeEntry == null || edgeTo == null || segmentEdgeEntry == null || segmentEdgeTo == null)
return this;
if (switchWrapper)
{
EdgeEntry ee = edgeEntry;
edgeEntry = edgeTo;
edgeTo = ee;
ee = segmentEdgeEntry;
segmentEdgeEntry = segmentEdgeTo;
segmentEdgeTo = ee;
}
EdgeEntry currEdge = segmentEdgeEntry;
while (EdgeIterator.Edge.isValid(currEdge.edge))
{
processEdge(currEdge.edge, currEdge.adjNode);
currEdge = currEdge.parent;
}
currEdge.parent = edgeEntry;
currEdge = edgeEntry;
while (EdgeIterator.Edge.isValid(currEdge.edge))
{
processEdge(currEdge.edge, currEdge.adjNode);
currEdge = currEdge.parent;
}
setFromNode(currEdge.adjNode);
reverseOrder();
currEdge = segmentEdgeTo;
int tmpEdge = currEdge.edge;
while (EdgeIterator.Edge.isValid(tmpEdge))
{
currEdge = currEdge.parent;
processEdge(tmpEdge, currEdge.adjNode);
tmpEdge = currEdge.edge;
}
currEdge.parent = edgeTo;
currEdge = edgeTo;
tmpEdge = currEdge.edge;
while (EdgeIterator.Edge.isValid(tmpEdge))
{
currEdge = currEdge.parent;
processEdge(tmpEdge, currEdge.adjNode);
tmpEdge = currEdge.edge;
}
setEndNode(currEdge.adjNode);
return setFound(true);
}
}
This is not working all the time. I get exceptions in Path4CH
java.lang.NullPointerException
at com.graphhopper.routing.ch.Path4CH.expandEdge(Path4CH.java:62)
at com.graphhopper.routing.ch.Path4CH.processEdge(Path4CH.java:56)
at com.graphhopper.routing.PathBidirRef.extract(PathBidirRef.java:95)
at com.graphhopper.routing.DijkstraBidirectionRef.extractPath(DijkstraBidirectionRef.java:99)
at com.graphhopper.routing.AbstractBidirAlgo.runAlgo(AbstractBidirAlgo.java:74)
at com.graphhopper.routing.AbstractBidirAlgo.calcPath(AbstractBidirAlgo.java:60)
In Path
java.lang.IllegalStateException: Edge 1506012 was empty when requested with node 1289685, array index:0, edges:318
at com.graphhopper.routing.Path.forEveryEdge(Path.java:253)
at com.graphhopper.routing.Path.calcInstructions(Path.java:349)
I dont know what I am doing wrong. I could really use some help with this.
Thanks.
I solved this issue.
Inside DijkstraBidirectionRef.calcPath I was trying to calculate shortest path from an arbitrary node to source node and vertex node.
The error used to occur because the original call to calcPath was operating on QueryGraph and inside I was creating a new Object of DijkstraBidirectionRef using LevelGraphStorage.
This was a problem because QueryGraph may create virtual nodes and edges for source and target nodes. Call to calcPath(node, virtualNode) operating on LevelGraphStorage would throw an exception.
The fix was to call algo.setGraph(queryGraph) after creating DijkstraBidirectionRef.