When I run the code dfx deploy, it shows:
Candid interface compatibility check failed for canister 'dbank'.
You are making a BREAKING change. Other canisters or frontend clients relying on your canister may stop working.
Method topUp: func (nat) -> () oneway is not a subtype of func () -> () oneway
Do you want to proceed? yes/No
y
Error: Refusing to install canister without approval
How can I solve the problem????
import Debug "mo:base/Debug";
actor DBank {
var currentValue = 300;
currentValue := 100;
let id = 12545856545;
public func topUp(amount: Nat){
currentValue += amount;
Debug.print(debug_show(currentValue));
};
public func withdraw(amount: Nat) {
if (amount <= currentValue) {
currentValue -= amount;
Debug.print(debug_show(currentValue));
} else {
Debug.print("amount too large, not enough balance");
}
};
}
I am trying to show my application to Candid user Interface.
If I remember correctly you have to type yes and not y.
Related
i want to implement a step counter in my app, so i search how to make that and i found lot of differents implementations.
I notably found an app on GitHub which works. I have tried to implement this code in my app and in an other "test" app but any of them works and i don't no why.
The problem is caused by the onSensorChanged function of my STEP_COUNTER which is not called.
I have search in all the files of the app and i don't found the problem.
If somebody have a solution...
(I'm french so sorry if it's badly written)
the code i use:
private var sensorManager: SensorManager? = null
// Creating a variable which will give the running status
// and initially given the boolean value as false
private var running = false
// Creating a variable which will counts total steps
// and it has been given the value of 0 float
private var totalSteps = 0f
// Creating a variable which counts previous total
// steps and it has also been given the value of 0 float
private var previousTotalSteps = 0f
//in the onCreate
loadData()
resetSteps()
// Adding a context of SENSOR_SERVICE as Sensor Manager
sensorManager = getSystemService(Context.SENSOR_SERVICE) as SensorManager
override fun onResume() {
super.onResume()
mainHandler.post(pingRunnable)
binding.map.onResume()
running = true
// Returns the number of steps taken by the user since the last reboot while activated
// This sensor requires permission android.permission.ACTIVITY_RECOGNITION.
// So don't forget to add the following permission in AndroidManifest.xml present in manifest folder of the app.
val stepSensor = sensorManager?.getDefaultSensor(Sensor.TYPE_STEP_COUNTER)
if (stepSensor == null) {
// This will give a toast message to the user if there is no sensor in the device
Toast.makeText(this, "No sensor detected on this device", Toast.LENGTH_SHORT).show()
} else {
// Rate suitable for the user interface
sensorManager?.registerListener(this, stepSensor, SensorManager.SENSOR_DELAY_UI)
}
}
override fun onSensorChanged(event: SensorEvent?) {
// Calling the TextView that we made in activity_main.xml
// by the id given to that TextView
var tvStepsTaken = findViewById<TextView>(R.id.step)
if (running) {
totalSteps = event!!.values[0]
// Current steps are calculated by taking the difference of total steps
// and previous steps
val currentSteps = totalSteps.toInt() - previousTotalSteps.toInt()
// It will show the current steps to the user
tvStepsTaken.text = ("$currentSteps")
}
}
private fun resetSteps() {
var resetButton = findViewById<Button>(R.id.reset)
resetButton.setOnClickListener {
// This will give a toast message if the user want to reset the steps
previousTotalSteps = totalSteps
// When the user will click long tap on the screen,
// the steps will be reset to 0
testFragment?.binding?.step?.text = 0.toString()
// This will save the data
saveData()
true
}
}
private fun saveData() {
// Shared Preferences will allow us to save
// and retrieve data in the form of key,value pair.
// In this function we will save data
val sharedPreferences = getSharedPreferences("myPrefs", Context.MODE_PRIVATE)
val editor = sharedPreferences.edit()
editor.putFloat("key1", previousTotalSteps)
editor.apply()
}
private fun loadData() {
// In this function we will retrieve data
val sharedPreferences = getSharedPreferences("myPrefs", Context.MODE_PRIVATE)
val savedNumber = sharedPreferences.getFloat("key1", 0f)
// Log.d is used for debugging purposes
Log.d("MainActivity", "$savedNumber")
previousTotalSteps = savedNumber
}
override fun onAccuracyChanged(sensor: Sensor?, accuracy: Int) {
// We do not have to write anything in this function for this app
}
This is my first time using Kotlin, I have to write a simple command-line application where it takes a list of user input strings. Valid inputs are only "Apple" or "Orange" and calculate the price (which is 60 cents and 25 cents respectively). I'm having some trouble with the 3rd requirement
"Build a service that listens for when orders are complete and sends a notification to the customer regarding its status and estimated delivery time. The Mail service subscribes to events from the Orders service and publishes the appropriate event that the customer (you) is able to read from the terminal"
this is what I have done so far
MainApp.tk
import java.util.Scanner
import kotlin.system.exitProcess;
import app.Checkout;
var shopRunning = true;
var applecount = 0;
fun main(args: Array<String>) {
while (shopRunning) {
println("Welcome to Express Store");
println("1. Checkout");
println("2. exit");
var userOption = 0;
//request the user to eneter an option
//if user eneter a options that is not valid it will keep looping til option that is enterd is accepted;
var userSeletedOption = false;
val inputScanner = Scanner(System.`in`);
while (!userSeletedOption) {
print("Select an Option: ");
userOption = inputScanner.nextInt();
//if input entered by the user is not accepted and invaliud message is printed and is promted to enter an option again.
if (userOption != 1 && userOption != 2) {
println("Invalid input detected!");
} else {
userSeletedOption = true;
}
}
if (userOption == 1) {
val checkout = Checkout();
println("We currently have apples and oranges in Stock.")
var list: MutableList<String> = ArrayList();
println(list.size);
var doneAddingToCart = false;
while(!doneAddingToCart){
print("enter name of item to be enter or exit to finish adding to the cart: ")
var item = inputScanner.next();
if(item.equals("exit")){
doneAddingToCart=true;
}
else{
list.add(item);
}
}
if(checkout.verify(list)){ //checks if list has any item that is not an apple or orange
println("Thank you for your Pruchse");
val cost = checkout.Chasher(list)
println("You bought: "+ list.toString());
print("your total is: "+ cost);//returns the total cost
exitProcess(1);//exits from the application
}
} else if (userOption == 2) {
print("Have a great day.");
exitProcess(1);
}
}
}
CheckOut.tk
class Checkout {
//checks if the user entered any invaild items
public fun verify (cart: MutableList<String>) : Boolean{
for(item in cart){
if(!item.equals("Apple") && !item.equals("Orange")){
return false;
}
}
return true;
}
public fun Chasher (cart: MutableList<String>) : Double{
var total = 0.0;
var orangecount = 0;//step 2 offers
var applecount = 0;//step 2 offers
for(item in cart){//step 1 function
if(item.equals("Apple") || item.equals("apple")){
applecount+=1;
total= total + 0.6;
}
if(item.equals("Orange") || item.equals("orange")){
orangecount +=1;
total=total +0.25;
}
}
if(orangecount ==3){//buy three for the price of 2.step 2
println("You qaulidified for our buy 3 oragnes for the price of 2 offer")
total -=0.25;
}
if(applecount ==1){//buy one aple get 1 free. step 2
println("You buy 1 apple get one free")
cart.add("Apple");
}
return total;
}
}
I don't need to send an email just send a message to the command line. Currently, I'm just printing messages (just to see if what I currently have even works). Yeah, I know there many spelling errors, english and writing was never my strongest subject
I can only provide three hints that might help you:
If you exit your program using System.exit, use 0 if the run did not have any problem. (Excerpt from JavaDoc: "The argument serves as a status code; by convention, a nonzero status code indicates abnormal termination.")
For checking equality, simply use == which corresponds to equals in Java. In your special case however, you can use item.equals("apple", ignoreCase=true) or simply item.equals("apple", true).
I'm not sure what the author of your task exactly expects as a solution.
In can imagine you are expected to use lambdas.
An example: Your could refactor your Checkout class like that:
class Checkout {
/**
* Checks if the given [cart] contains only apples and oranges,
* and calls [onSuccess].
* If also other articles are contained, [onSuccess] is not called.
*/
fun verify(cart: List<String>, onSuccess: (List<String>) -> Unit): Unit {
for (item in cart) {
if (!item.equals("apple", true) && !item.equals("Orange", true)) {
return
}
}
onSuccess(cart)
}
}
And then call
val cart = listOf("Orange", "Apple", "apple", "orange")
Checkout().verify(cart, { cart: List<String> ->
println("Thanks you for your purchase: $cart")
})
or even shorter (curly brackets are outside of parenthesis)
Checkout().verify(cart) { cart: List<String> ->
println("Thanks you for your purchase: $cart")
}
What I did here was to extract what is executed if your validation succeeds:
For that, I used a lambda function that accepts a list of articles/strings (List<String>) and returns something I ignore/don't care about -> Unit.
The advantage of that approach is that callers of your verify method can decide what to do on success at their liking because they can pass a lambda function around like any other variable. Here:
val cart = listOf("Orange", "Apple", "apple", "orange")
val onSuccess = { cart: List<String> ->
println("Thanks you for your purchase: $cart")
}
Checkout().verify(cart, onSuccess)
You could also extend Checkout to allow an observer to register.
I deliberately kept the code very simple. Normally you would allow multiple observers to register, only expose what clients are supposed to see and hide the rest, etc.
class Checkout(
val onSuccess : (List<String>) -> Unit
) {
fun verify(cart: List<String>): Unit {
for (item in cart) {
if (!item.equals("apple", true) && !item.equals("Orange", true)) {
return
}
}
onSuccess(cart)
}
}
val checkout = Checkout({ cart: List<String> ->
println("Thanks you for your purchase: $cart")
})
and then
val cart = listOf("Orange", "Apple", "apple", "orange")
checkout.verify(cart)
Be sure to check out https://play.kotlinlang.org/byExample/04_functional/01_Higher-Order%20Functions to learn more about lambda / higher-order functions.
I'm trying to figure out how to
programically instantiate a struct with set values (one of those might be yet another nested struct - or not) - and save it in Redis.
fetch it back into a struct from Redis
I am aware that the 2 traits ToRedisArgs and FromRedisValue are to be implemented here, but even for my very simple 2 structs I have no clue what to write to impl them in Rust. I've made a simple example:
extern crate redis;
use redis::Commands;
// fn fetch_an_integer() -> redis::RedisResult<isize> {
// // connect to redis
// let client = try!(redis::Client::open("redis://127.0.0.1/"));
// let con = try!(client.get_connection());
// // throw away the result, just make sure it does not fail
// let _ : () = try!(con.set("my_key", 42));
// // read back the key and return it. Because the return value
// // from the function is a result for integer this will automatically
// // convert into one.
// con.get("my_key")
// }
fn fetch_a_struct() -> redis::RedisResult<MyStruct> {
// connect to redis
let client = try!(redis::Client::open("redis://127.0.0.1/"));
let con = try!(client.get_connection());
// throw away the result, just make sure it does not fail
let another_struct = AnotherStruct{x: "another_struct".to_string()};
let mut my_vec: Vec<AnotherStruct> = Vec::new();
my_vec.push(another_struct);
let my_struct = MyStruct{x: "my_struct".to_string(), y: 1, z: my_vec};
let _ : () = try!(con.set("my_key_struct", my_struct));
con.get("my_key_struct")
}
fn main() {
match fetch_a_struct() {
Err(err) => {
println!("{}", err)
},
Ok(x) => {
println!("{}", x.x)
}
}
}
struct MyStruct {
x: String,
y: i64,
z: Vec<AnotherStruct>,
}
struct AnotherStruct {
x: String
}
(Playground)
I need to save different visitors, their browsing behavior (duration, pages visited and other interactions etc) and other stats while they browse around my website - That's why I was thinking about using Redis instead of MongoDB, as my outproc session store.
In MongoDB I'd have a user collection, interactions collection etc... but what might the equivalent way in Redis be?
Being a complete newbie at both Redis and Rust I hope you can help me at least to get a few ideas how to achieve something like this.
Serialize your data to a JSON string, save it as a string and then deserialize it when needed.
I am working with a team of React-Native JS developers who asked me to give them a native module for listening for Bluetooth state changes.
I created a ReactMethod that takes a Callback:
#ReactMethod
public void registerForBlueToothStateChanges(Callback listener){
mainActivity = (MainActivity)getCurrentActivity();
mainActivity.registerBTStateChangeListener(listener);
}
This method essentially is designed to set a Callback that will be used by my broadcast Receiver and at the same time send the current Bluetooth state back to the call back.. That all works fine, but in my Actual BroadCast Receiver i get an error: "The callback registerForBlueToothStateChanges() exists in module TripManager, but only one callback maybe registered to a function in a native Module"
Main Activity Relative Code:
#Subscribe
public void onBluetoothStateChanged(BluetoothStateChange state){
//check against current state to avoid duplicate offs
Log.v(TAG, "STATE CHANGED WOOT");
if(!state.equals(lastBluetoothState)){
lastBluetoothState = state;
Log.v(TAG, "BT STATE CHANGE***: "+state +" "+state.equals(BluetoothStateChange.ON));
if(blueToothStateListener != null) {
int i = 0;
if (state.equals(BluetoothStateChange.ON)) {
i = 1;
}
sendBTStateChange(i);
}
}
lastBluetoothState = state;
}
public void registerBTStateChangeListener(Callback listener){
blueToothStateListener = listener;
int i = 0;
if(lastBluetoothState.equals(BluetoothStateChange.ON)){
i = 1;
}
sendBTStateChange(i);
}
private void sendBTStateChange(int code){
blueToothStateListener.invoke(code);
}
Any pointers how i can get around this?
I have create a progress bar for my bootstrapper installer. It goes correctly upto 100% while installing. But while uninstalling it only goes to 50% and stops there. Below is my code.
In the constructor of my ViewModel class.
this.Bootstrapper.CacheAcquireProgress += (sender, args) =>
{
this.cacheProgress = args.OverallPercentage;
this.Progress = (this.cacheProgress + this.executeProgress) / 2;
};
this.Bootstrapper.ExecuteProgress += (sender, args) =>
{
this.executeProgress = args.OverallPercentage;
this.Progress = (this.cacheProgress + this.executeProgress) / 2;
};
Then getter and setter as follows.
private int progress;
public int Progress
{
get { return progress; }
set
{
this.progress = value;
RaisePropertyChanged("Progress");
}
}
private int cacheProgress;
private int executeProgress;
what am I doing wrong here? Why does the bar stay at 50% while uninstalling, though the uninstall is complete? Please advice.
Not every Apply action will have a Cache phase, use the OnApplyPhaseCount (in v4 it's in the OnApplyBegin) callback to know what that denominator should be.