for_each bind2nd mem_fun vs 2005 - stl

Having problems with STL under VS 2005. I am restricted to VS 2005.
class SpeedTest
{
public:
void AddDataPair(const std::pair<std::string, double> & datum, const std::string & insertName = "");
private:
std::map <std::string, double> _Data;
}
void SpeedTest::AddDataPair(const pair<string, double> & datum, const string & insertName)
{
string key = insertName + '_' + datum.first;
_Data[key] += datum.second;
}
void SpeedTest::Insert(SpeedTest * toCopy, const string & insertName)
{
map<string, double>::iterator dataIter;
map<string, double>::iterator beginIter = toCopy->_Data.begin();
map<string, double>::iterator endIter = toCopy->_Data.end();
for_each
(
beginIter,
endIter,
bind2nd(mem_fun(&INGSpeedTest::AddDataPair)(), insertName)
);
}
I get error C2784:
'std::const_mem_fun1_t<_Result,_Ty,_Arg> std::mem_fun(Result (_thiscall _Ty::* )(_Arg) const)' :
could not deduce template argument for 'Result (_thiscall _Ty::* )(_Arg) const'
from 'void (__thiscall INGSpeedTest::* )(const std::pair<_Ty1,_Ty2> &,const std::string &)'
with
[
_Ty1=std::string,
_Ty2=double
]
If I replace the for_each with a for loop
for (dataIter = beginIter;
dataIter != endIter;
++dataIter)
{
AddDataPair(*dataIter, insertName);
}
It compiles nicely.
But I would still like to know what is failing with the for_each.
Thank you very much for any time, knowledge and effort you can spare me,
Robert

std::mem_fun can only wrap a member function taking zero or one parameter. Yours takes two.

Related

Write a Program To Add a Binary

I'm trying to implement a program to add a Binary.
The code that is displayed results in run time error.
class Solution {
public String addBinary(String a, String b)
{
return Integer.toBinaryString(Integer.parseInt(a, 2) + Integer.parseInt(b, 2));
}
}
The error:
Runtime Error Message:
Line 5: java.lang.NumberFormatException: For input string: "10100000100100110110010000010101111011011001
Input :a = "11", b = "1"
Output: "100"
Tell me if the code bellow can help you. It works here
public class Main
{
public static void main(String[] args) {
addBinary("11", "1");
}
public static void addBinary(String a, String b)
{
int value1 = Integer.parseInt(a,2);
int value2 = Integer.parseInt(b,2);
System.out.println("String to int: "+ value1 + " " + value2);
String binary1 = Integer.toBinaryString(value1);
String binary2 = Integer.toBinaryString(value2);
System.out.println("Your input in binary: "+ binary1 + " " + binary2);
}
}

Parsing issue with Dart - [no build value ^ serializable ^ ]

Aye Aye good people,
[edited:
running this in dartpad
import 'dart:convert';
void main() {
const String _json = '{"myListInt": [1]}';
final Map<String, dynamic> _map = jsonDecode(_json);
final List<int> _list = _map['myListInt'] as List<int>;
_list.forEach((i) {
String _s = i.toString();
print(_s);
});
}
returns
Uncaught exception:
CastError: Instance of 'JSArray': type 'JSArray' is not a subtype of type
'List<int>'
in case I use
final List<int> _list = List<int>.from(_map['myListInt'] as List<int>);
or
List<int>.generate(_map['myListInt'].length, (i)=>_map['myListInt'][i] as int);
returns
Uncaught exception:
Cannot read property 'length' of undefined
]
what am I doing wrong?
Thank you in advance
Francesco
Instead of this line
myListInt: List<int>.from(_map['myListInt'] as List<int>),
you can use
myListInt: List<int>.generate(_map['myListInt'].length, (i)=>_map['myListInt'][i] as int
Basically instead of casting the whole list, you have to cast each element one by one.
ok, using ""as Iterable"" works,
import 'dart:convert';
void main() {
const String _json = '{"myListInt": [1]}';
final Map<String, dynamic> _map = jsonDecode(_json);
final List<int> _list= List<int>.from(_map['myListInt'] as Iterable);
_list.forEach((i) {
String _s = i.toString();
print(_s);
});
}

Graphhopper - calculating travel time

I'm developing a project using Graphhopper core to calculate optimal routes. I incorporated some real traffic data by modifying speed assigned to edges and calculated optimal routes in two ways: the "default" way and the way, which considers traffic.
Now, I try to compare those routes and investigate how travel time changes. What I would like to do is to calculate travel time on the optimal route, which was found using default speed assigned to edges, but travel time should be calculated using custom speed values (those, which take into account real traffic). In other words, is it possible to use Graphhopper to calculate travel time on a specific route (not optimal one)?
A solution, which came to my mind, is to implement custom FlagEncoder (as described here), extend Path class and use them to calculate travel time using speed values, which considers traffic. However, maybe you, guys, know simpler way to achieve this.
I finally managed to solve the problem so I share my solution.
To store custom speed as an extra value I extended class CarFlagEncoder.
public class CustomCarFlagEncoder extends CarFlagEncoder {
public static final int CUSTOM_SPEED_KEY = 12345;
private EncodedDoubleValue customSpeedEncoder;
public CustomCarFlagEncoder() {
super();
}
public CustomCarFlagEncoder(PMap properties) {
super(properties);
}
public CustomCarFlagEncoder(String propertiesStr) {
super(propertiesStr);
}
public CustomCarFlagEncoder(int speedBits, double speedFactor, int maxTurnCosts) {
super(speedBits, speedFactor, maxTurnCosts);
}
#Override
public int defineWayBits(int index, int shift) {
shift = super.defineWayBits(index, shift);
customSpeedEncoder = new EncodedDoubleValue("Custom speed", shift, speedBits, speedFactor,
defaultSpeedMap.get("secondary"), maxPossibleSpeed);
shift += customSpeedEncoder.getBits();
return shift;
}
#Override
public double getDouble(long flags, int key) {
switch (key) {
case CUSTOM_SPEED_KEY:
return customSpeedEncoder.getDoubleValue(flags);
default:
return super.getDouble(flags, key);
}
}
#Override
public long setDouble(long flags, int key, double value) {
switch (key) {
case CUSTOM_SPEED_KEY:
if (value < 0 || Double.isNaN(value))
throw new IllegalArgumentException("Speed cannot be negative or NaN: " + value
+ ", flags:" + BitUtil.LITTLE.toBitString(flags));
if (value > getMaxSpeed())
value = getMaxSpeed();
return customSpeedEncoder.setDoubleValue(flags, value);
default:
return super.setDouble(flags, key, value);
}
}
#Override
public String toString() {
return CustomEncodingManager.CUSTOM_CAR;
}
}
In order to be able to use custom FlagEncoder, I created CustomEncodingManager, which extends EncodingManager and handles CustomCarFlagEncoder.
public class CustomEncodingManager extends EncodingManager {
public static final String CUSTOM_CAR = "custom_car";
public CustomEncodingManager(String flagEncodersStr) {
this(flagEncodersStr, 4);
}
public CustomEncodingManager(String flagEncodersStr, int bytesForFlags )
{
this(parseEncoderString(flagEncodersStr), bytesForFlags);
}
public CustomEncodingManager(FlagEncoder... flagEncoders) {
super(flagEncoders);
}
public CustomEncodingManager(List<? extends FlagEncoder> flagEncoders) {
super(flagEncoders);
}
public CustomEncodingManager(List<? extends FlagEncoder> flagEncoders, int bytesForEdgeFlags) {
super(flagEncoders, bytesForEdgeFlags);
}
static List<FlagEncoder> parseEncoderString(String encoderList )
{
if (encoderList.contains(":"))
throw new IllegalArgumentException("EncodingManager does no longer use reflection instantiate encoders directly.");
String[] entries = encoderList.split(",");
List<FlagEncoder> resultEncoders = new ArrayList<FlagEncoder>();
for (String entry : entries)
{
entry = entry.trim().toLowerCase();
if (entry.isEmpty())
continue;
String entryVal = "";
if (entry.contains("|"))
{
entryVal = entry;
entry = entry.split("\\|")[0];
}
PMap configuration = new PMap(entryVal);
AbstractFlagEncoder fe;
if (entry.equals(CAR))
fe = new CarFlagEncoder(configuration);
else if (entry.equals(BIKE))
fe = new BikeFlagEncoder(configuration);
else if (entry.equals(BIKE2))
fe = new Bike2WeightFlagEncoder(configuration);
else if (entry.equals(RACINGBIKE))
fe = new RacingBikeFlagEncoder(configuration);
else if (entry.equals(MOUNTAINBIKE))
fe = new MountainBikeFlagEncoder(configuration);
else if (entry.equals(FOOT))
fe = new FootFlagEncoder(configuration);
else if (entry.equals(MOTORCYCLE))
fe = new MotorcycleFlagEncoder(configuration);
else if (entry.equals(CUSTOM_CAR)) {
fe = new CustomCarFlagEncoder(configuration);
}
else
throw new IllegalArgumentException("entry in encoder list not supported " + entry);
if (configuration.has("version"))
{
if (fe.getVersion() != configuration.getInt("version", -1))
{
throw new IllegalArgumentException("Encoder " + entry + " was used in version "
+ configuration.getLong("version", -1) + ", but current version is " + fe.getVersion());
}
}
resultEncoders.add(fe);
}
return resultEncoders;
}
}
Then, I set the custom EncodingManager to GraphHopper object hopper.setEncodingManager(new CustomEncodingManager(CustomEncodingManager.CUSTOM_CAR));
I assign custom speed to an edge as an extra value edge.setFlags(customCarEncoder.setDouble(existingFlags, CustomCarFlagEncoder.CUSTOM_SPEED_KEY,
newSpeed));
Finally, to use custom speed while calculating travel time, I slightly modified method clacMillis form class Path from package com.graphhoper.routing.
protected long calcMillis( double distance, long flags, boolean revert )
{
if (revert && !encoder.isBackward(flags)
|| !revert && !encoder.isForward(flags))
throw new IllegalStateException("Calculating time should not require to read speed from edge in wrong direction. "
+ "Reverse:" + revert + ", fwd:" + encoder.isForward(flags) + ", bwd:" + encoder.isBackward(flags));
double speed = revert ? encoder.getReverseSpeed(flags) : encoder.getSpeed(flags);
double customSpeed = encoder.getDouble(flags, 12345);
if (customSpeed > 0) {
speed = customSpeed;
}
if (Double.isInfinite(speed) || Double.isNaN(speed) || speed < 0)
throw new IllegalStateException("Invalid speed stored in edge! " + speed);
if (speed == 0)
throw new IllegalStateException("Speed cannot be 0 for unblocked edge, use access properties to mark edge blocked! Should only occur for shortest path calculation. See #242.");
return (long) (distance * 3600 / speed);
}

how to pass argument to Marionette.CompositeView

how to pass a values dynamically to an Marionette.CompositeView during run time? like in java we create a method like the following
package com.test.poc;
public class SampleMethod {
public int add(int a, int b) {
return a + b;
}
public static void main(String[] args) {
SampleMethod method = new SampleMethod();
int firstValue = 90, secondValue = 90;
System.out.println("add : " + method.add(firstValue, secondValue));
}
}
the above is the simple java code anybody can understand like the above how to create and pass arguments to Marionette.CompositeView and work on them?
Best Regards
at the moment you instanciate a view, you can pass whatever arguments you want. normally you pass the model and the collection to be rendered in the compositeView, but you can pass more data if you need.
var MyCompositeView = Backbone.Mationette.CompositeView.extend({
initialize : function (options){
this.dataValue = options.dataValue1;
this.helperObject = options.helperObject;
this.useValues();
},
useValues: function () {
console.log(this.dataValue);
}
});
var helperObject = {
value3 : "I have a value",
value4 : "I dont!"
}; /// a js object literal
var myModel = new MyModel();
var myCollection = new MyCollection();
var myCompositeView = new MyCompositeView({model:myModel,
collection:myCollection,
helperObject:helperObject,
dataValue1:"Hi there"});
notice that Im passing 4 values in the at the time to intanciate the view, and Im reading just two of them, the model and the collection will be handled by marionette, but the other two you can read them in your initialize function.
hope that helps.

Google end point returns JSON for long data type in quotes

I am using Google cloud end point for my rest service. I am consuming this data in a GWT web client using RestyGWT.
I noticed that cloud end point is automatically enclosing a long datatype in double quotes which is causing an exception in RestyGWT when I try to convert JSON to POJO.
Here is my sample code.
#Api(name = "test")
public class EndpointAPI {
#ApiMethod(httpMethod = HttpMethod.GET, path = "test")
public Container test() {
Container container = new Container();
container.testLong = (long)3234345;
container.testDate = new Date();
container.testString = "sathya";
container.testDouble = 123.98;
container.testInt = 123;
return container;
}
public class Container {
public long testLong;
public Date testDate;
public String testString;
public double testDouble;
public int testInt;
}
}
This is what is returned as JSON by cloud end point. You can see that testLong is serialized as "3234345" rather than 3234345.
I have the following questions.
(1) How can I remove double quotes in long values ?
(2) How can I change the string format to "yyyy-MMM-dd hh:mm:ss" ?
Regards,
Sathya
What version of restyGWT are you using ? Did you try 1.4 snapshot ?
I think this is the code (1.4) responsible for parsing a long in restygwt, it might help you :
public static final AbstractJsonEncoderDecoder<Long> LONG = new AbstractJsonEncoderDecoder<Long>() {
public Long decode(JSONValue value) throws DecodingException {
if (value == null || value.isNull() != null) {
return null;
}
return (long) toDouble(value);
}
public JSONValue encode(Long value) throws EncodingException {
return (value == null) ? getNullType() : new JSONNumber(value);
}
};
static public double toDouble(JSONValue value) {
JSONNumber number = value.isNumber();
if (number == null) {
JSONString val = value.isString();
if (val != null){
try {
return Double.parseDouble(val.stringValue());
}
catch(NumberFormatException e){
// just through exception below
}
}
throw new DecodingException("Expected a json number, but was given: " + value);
}
return number.doubleValue();
}