Creating a class with implicit operators but it only works one way - operators

A UDouble is an object that has units associated with the value (Value). The Unit is much more complex than shown here, but was converted to a string for the example.
public class UDouble
{
public string Unit { get; set; }
public double Value;
public UDouble(string unit)
{
Unit = unit;
}
public UDouble(string unit, double value)
{
Unit = unit;
Value = value;
}
public static implicit operator double(UDouble m)
{
return m.Value;
}
//public static implicit operator UDouble(double d)
//{
// return new UDouble("?????????", d); // wrong - units are lost
//}
}
static void Main()
{
UDouble p = new UDouble("mm", 2.3);
p.Value = 3;
double t = p;
p = 10.5;
}
The last line in the main() function (p = 10.5;) does not compile. What I what is the UDouble to act as if it is a double. In other words, I am trying to get p = 10.5; to work like p.Value = 10.5;
Is there a way to make it work?

Related

optaplanner can't get the best solution, and different input orders produce different solutions

I'm trying to make a demo using optaplanner: there are some schemes, each scheme has attribute of gain and cost, and a scheme may conflict with one or more other schemes. The question is to find out a group of schemes which match following constraints:
hard constraint: selected schemea may not conflict with each other in this group
soft constraint: make the difference between total gain and total cost as high as possible
I built following code and try to resolve the question:
#PlanningEntity
#Data
#NoArgsConstructor
public class Scheme {
#PlanningId
private String id;
private int gain;
private int cost;
#PlanningVariable(valueRangeProviderRefs = {"validRange"})
// when valid is ture means this scheme will be selected into the solution group
private Boolean valid;
private Set<String> conflicts = new HashSet<>();
public void addConflict(String id) {
conflicts.add(id);
}
public Scheme(String id, int gain, int cost, String[] conflicts) {
this.id = id;
this.gain = gain;
this.cost = cost;
for (String s : conflicts) {
addConflict(s);
}
}
}
#PlanningSolution
public class SchemeSolution {
private HardSoftScore score;
private List<Scheme> schemeList;
#ProblemFactCollectionProperty
#ValueRangeProvider(id = "validRange")
public List<Boolean> getValidRange() {
return Arrays.asList(Boolean.FALSE, Boolean.TRUE);
}
#PlanningScore
public HardSoftScore getScore() {
return score;
}
public void setScore(HardSoftScore score) {
this.score = score;
}
#PlanningEntityCollectionProperty
public List<Scheme> getSchemeList() {
return schemeList;
}
public void setSchemeList(List<Scheme> schemeList) {
this.schemeList = schemeList;
}
}
And the constraint rule as below:
rule "conflictCheck"
when
Boolean(this==true) from accumulate (
$schs: List() from collect (Scheme(valid==true)),
init(boolean cfl = false;Set cfSet = new HashSet();List ids = new ArrayList()),
action(
for(int i = 0; i < $schs.size(); ++i) {
Scheme sch = (Scheme)$schs.get(i);
cfSet.addAll(sch.getConflicts());
ids.add(sch.getId());
}
for( int i = 0; i < ids.size(); ++i) {
String id = (String)ids.get(i);
if(cfSet.contains(id)) {
cfl = true;
return true;
}
}
),
result(cfl)
)
then
scoreHolder.addHardConstraintMatch(kcontext, -10000);
end
rule "bestGain"
when
$gc : Number() from
accumulate(
Scheme(valid==true, $gain : gain, $cost: cost),
sum($gain - $cost)
)
then
scoreHolder.addSoftConstraintMatch(kcontext, $gc.intValue());
end
Then I constructed three schemes as input of the test. Oddly, I found that optaplanner can't get the best solution, and different input orders produce different solutions.
When I set input as following:
private static List<Scheme> getSchemes() {
List<Scheme> ret = new ArrayList();
ret.add(new Scheme("S1", 5, 2, new String[]{"S3"}));
ret.add(new Scheme("S2", 3, 1, new String[]{"S3"}));
ret.add(new Scheme("S3", 10, 4, new String[]{"S1", "S2"}));
return ret;
}
the output is :
0hard/5soft
Scheme(id=S1, gain=5, cost=2, valid=true, conflicts=[S3])
Scheme(id=S2, gain=3, cost=1, valid=true, conflicts=[S3])
Scheme(id=S3, gain=10, cost=4, valid=false, conflicts=[S1, S2])
And when I set input as following:
private static List<Scheme> getSchemes() {
List<Scheme> ret = new ArrayList();
ret.add(new Scheme("S3", 10, 4, new String[]{"S1", "S2"}));
ret.add(new Scheme("S1", 5, 2, new String[]{"S3"}));
ret.add(new Scheme("S2", 3, 1, new String[]{"S3"}));
return ret;
}
I get the best solution and the output is :
0hard/6soft
Scheme(id=S3, gain=10, cost=4, valid=true, conflicts=[S1, S2])
Scheme(id=S1, gain=5, cost=2, valid=false, conflicts=[S3])
Scheme(id=S2, gain=3, cost=1, valid=false, conflicts=[S3])
Could anyone help me about it?

C# - NAudio - How to change sample rate on a float[] while reading it?

I'm coding my first audio application, and I'm struggling for hours on trying to change samplerate of a cached sound.
I'm using NAudio and I was able to change the Volume, tweaking the Read() method of my ISampleProvider.
Here is the CachedSound Class :
public class CachedSound
{
public float[] AudioData { get; private set; }
public WaveFormat WaveFormat { get; set; }
public CachedSound(string audioFileName)
{
using (var audioFileReader = new AudioFileReader(audioFileName))
{
WaveFormat = audioFileReader.WaveFormat;
var wholeFile = new List<float>((int)(audioFileReader.Length / 4));
var readBuffer = new float[audioFileReader.WaveFormat.SampleRate * audioFileReader.WaveFormat.Channels];
int samplesRead;
while ((samplesRead = audioFileReader.Read(readBuffer, 0, readBuffer.Length)) > 0)
{
wholeFile.AddRange(readBuffer.Take(samplesRead));
}
AudioData = wholeFile.ToArray();
}
}
}
And here is the CachedSoundSampleProvider class :
using NAudio.Wave;
using System;
public delegate void PlaybackEndedHandler();
public class CachedSoundSampleProvider : ISampleProvider
{
public event PlaybackEndedHandler PlaybackEnded;
private CachedSound cachedSound;
private long _position;
public long Position {
get { return _position; }
set { _position = value; }
}
private float _volume;
public float Volume {
get { return _volume; }
set { _volume = value; }
}
private float _pitchMultiplicator;
public float PitchMultiplicator
{
get { return _pitchMultiplicator; }
set { _pitchMultiplicator = value; }
}
public WaveFormat OriginalWaveFormat { get; set; }
public WaveFormat WaveFormat {
get { return cachedSound.WaveFormat; }
}
//Constructeur
public CachedSoundSampleProvider(CachedSound _cachedSound)
{
cachedSound = _cachedSound;
OriginalWaveFormat = WaveFormat;
}
public int Read(float[] destBuffer, int offset, int numBytes)
{
long availableSamples = cachedSound.AudioData.Length - Position;
long samplesToCopy = Math.Min(availableSamples, numBytes);
//Changing original audio data samplerate
//Double speed to check if working
cachedSound.WaveFormat = new WaveFormat(cachedSound.WaveFormat.SampleRate*2, cachedSound.WaveFormat.Channels);
Array.Copy(cachedSound.AudioData, Position, destBuffer, offset, samplesToCopy);
//Changing Volume
for (int i = 0; i < destBuffer.Length; ++i)
destBuffer[i] *= (Volume > -40) ? (float)Math.Pow(10.0f, Volume * 0.05f) : 0;
Position += samplesToCopy;
if (availableSamples == 0) PlaybackEnded();
return (int)samplesToCopy;
}
}
I don't know how I can achieve this yet.
My goal is simple, I want to be able to tweak sample rate at realtime.
I read it's impossible to change it on the ISampleProvider interface.
That's why I tried to change it on the original audioData.
Thanks in advance for your help ! :)

How do you input data into a constructor from scanner?

I am trying to take a constructor(string, string, double) and set the value in it with a scanner input. any help is appreciated. The code is list below.
My programs can assign the values that i put in, but I want to be able to assign them from the keyboard and I would like to use only one constructor method to accomplish this. Thanks
I have it broken up into two classes:
import java.util.Scanner;
public class EmployeeTest
{
public static void main(String [] args)
{
Scanner input = new Scanner(System.in);
Employee employee1 = new Employee("james", "ry", 3200);
Employee employee2 = new Employee("jim" , "bob" , 2500.56 );
System.out.println("What is employyee 1's first name? ");
employee1.setFname(input.nextLine());
}
}
class Employee
{
private String fname;
private String lname;
private double pay;
public Employee(String fname, String lname, double pay)
{
this.setFname(fname);
this.lname = lname;
this.pay = pay;
System.out.println("Employee " + fname +" "+ lname + " makes $" +
+ pay + " this month and with a 10% raise, their new pay is $" + (pay * .10 + pay));
}
void setfname(String fn)
{
setFname(fn);
}
void setlname(String ln)
{
lname = ln;
}
void setpay (double sal)
{
pay = sal;
}
String getfname()
{
return getFname();
}
String getlname()
{
return lname;
}
double getpay()
{
if (pay < 0.00)
{
return pay = 0.0;
}
return pay;
}
public String getFname() {
return fname;
}
public void setFname(String fname)
{
this.fname = fname;
}
}
You can modify you EmployeeTest class something like
class EmployeeTest {
public static void main (String...arg) {
Scanner s = new Scanner(System.in);
String[] elements = null;
while (s.hasNextLine()) {
elements = s.nextLine().split("\\s+");
//To make sure that we have all the three values
//using which we want to construct the object
if (elements.length == 3) {
//call to the method which creates the object needed
//createObject(elements[0], elements[1], Double.parseDouble(elements[2]))
//or, directly use these values to instantiate Employee object
} else {
System.out.println("Wrong values passed");
break;
}
}
s.close();
}
}

How to determine input datatype?

I want to accept two inputs. If both the inputs are integer then add them. If any or both the inputs are string then concatenate them. I want to know the code to determine whether the input is integer or string?
Thanks for reading...
You can use method overloading for this,
Check out Java code given below
public class MethodExample
{
public static void main (String[] args)
{
int a,b;
String string1,string2;
//accept values for all variables...;>>
System.Out.Println("Addtion is "+sum(a,b));
System.Out.Println("Contact is "+sum(string1,string2));
}
int sum(int a,int b)
{
return(a+b);
}
String sum(string a,string b)
{
return(a+b);
}
}
I have used the following logic:
Console.WriteLine("Enter two inputs:");
string s1 = Console.ReadLine();
string s2 = Console.ReadLine();
double num;
int s3;
string s4;
bool isNum1 = double.TryParse(s1, out num);
bool isNum2 = double.TryParse(s2, out num);
if( isNum1==true && isNum2==true)
{
s3 = Convert.ToInt32(s1) + Convert.ToInt32(s2);
Console.WriteLine("Output = {0}", s3);
}
else
{
s4 = s1 + s2;
Console.WriteLine("Output = {0}",s4);
}

Vala - Constant Initialization and Assignment in Object Constructor

I've been looking at the Vala programming language over the past few days, and it looks promising. However, I can't figure out how to properly assign a constant (currently the Vala equivalent to final) in object construction. For example, in Java:
import java.lang.Math;
public class Rectangle {
public final double sideA;
public final double sideB;
public final double area;
public final double diagonal;
public Rectangle (double SideA, double SideB) {
sideA = SideA;
sideB = SideB;
area = SideA * SideB;
diagonal = Math.sqrt(Math.pow(SideA, 2) + Math.pow(SideB, 2));
}
}
How would this be written in Vala?
Vala doesn't have a direct equivalent of Java's final keyword. I think the closest you are going to be able to come is something like this:
public class Rectangle : GLib.Object {
public double sideA { get; construct; }
public double sideB { get; construct; }
public double area { get; construct; }
public double diagonal { get; construct; }
public Rectangle (double SideA, double SideB) {
GLib.Object (
sideA: SideA,
sideB: SideB,
area: SideA * SideB,
diagonal: Math.sqrt(Math.pow(SideA, 2) + Math.pow(SideB, 2)));
}
}
construct properties are a bit different from final, largely because of how GObject construction works. They can only be set at construct time, but unlike final in Java (IIRC... most of my Java knowledge has been repressed) they can also be set during construct by a subclass. For example, this is perfectly acceptable:
public class Square : Rectangle {
public Square (double Side) {
GLib.Object (
sideA: Side,
sideB: Side,
area: Side * Side,
diagonal: Math.sqrt(Math.pow(Side, 2) + Math.pow(Side, 2)));
}
}
So, if you want to allow GObject-style construction (which I would suggest you do if you are making a library other people will call... if the code is just for you there is no need), you might want to do something more like this:
public class Rectangle : GLib.Object {
public double sideA { get; construct; }
public double sideB { get; construct; }
private double? _area = null;
public double area {
get {
if ( _area == null )
_area = sideA * sideB;
return _area;
}
}
private double? _diagonal = null;
public double diagonal {
get {
if ( _diagonal == null )
_diagonal = Math.sqrt(Math.pow(sideA, 2) + Math.pow(sideB, 2));
return _diagonal;
}
}
public Rectangle (double SideA, double SideB) {
GLib.Object (
sideA: SideA,
sideB: SideB,
area: SideA * SideB,
diagonal: Math.sqrt(Math.pow(SideA, 2) + Math.pow(SideB, 2)));
}
}