why do `coin::initialize` enforce `coin_address<CoinType> == account_addr`? - move-lang

In coin.move:
assert!(
coin_address<CoinType>() == account_addr,
error::invalid_argument(ECOIN_INFO_ADDRESS_MISMATCH),
);
My guess is it prevents account A from initializing coins on behalf of account B to avoid scam?
But look forward to more clarification!

The intent is to ensure that a coin can ever be initialized once as that is how all the capabilities (burn, freeze, mint) are generated.
Specifically,
assert!(
coin_address<CoinType>() == account_addr,
error::invalid_argument(ECOIN_INFO_ADDRESS_MISMATCH),
);
prevents anyone other than the actual account that publishes CoinType from initializing it.
The next bit of code ensures it can only be initialized once:
assert!(
!exists<CoinInfo<CoinType>>(account_addr),
error::already_exists(ECOIN_INFO_ALREADY_PUBLISHED),
);

Related

peek in a parallel stream for incrementing a counter

I have a pipeline where files are processes in parallel, but I am a bit suspicious about the peek function.
File file = articles.parallelStream( )
.map( article -> {
String fileName = processer.getFriendlyName( article, locale );
currentCount.incrementAndGet();
return new ImmutablePair<>( fileName, converted );
} )
.peek( pair -> statusMessageSender.sendStatusMessage( totalCount, currentCount.get(), pair.getKey( ) ) )
.collect( new Archiver( archivePath ) );
By reading the javadocs, I am not completely sure if the counter that is supposed to send the current status of progress is doing its job (basically, looking for assurance in the docs here)
For parallel stream pipelines, the action may be called at whatever
time and in whatever thread the element is made available by the
upstream operation.
It seems to me that an observer would get the current count, regardless if the file name is correct in relation to the processing order, which is fine. but in the end of the day,I am in a path where I am distrusting the peek, and leading towards sync on sendStatusMessage's receptor.
In the end I am looking for a way to send status in a parallel stream, any thoughts?
Initially the discussion had a lot about the peek and why I was splitting the messaging part from the mapping expression. This was more a matter of style as I tend to favor mapping functions for mapping and nothing more.
I could see why people would defend peek or argue against it. But button line it acts to consume a value and pass it along in the pipe. So, as I was looking for a colateral behavior (passing a message) the peek function seemed perfect.
In the parallel stream the issue is that one cannot predict when peek is actually called. but there was two aspects to consider: when the message is sent was irrelevant for the problem at hands and the message itself could be sent at anytime.
In the end the counter could be in the peek part as well with the message receiver was the only true factor here. The message receiver could have its own counter or only consider the highest received in the time frame.
Button line, the question that begun with suggestions around peek, ended up with the following:
In terms of functionality, the peek function would do its job just fine: mainly because the sequence in the pipe was not ordered.
However the message consumer would tell if it could consume that message correctly.Given that only one consumer was using this information and the others were not, the final conclusion was that we had a problem in the protocol design and not around the peek function. We removed the counter from the std message and the problem was gone. peek could be used in a safe way for this problem, yes it could but...
so:
It could be:
File archive = articles.parallelStream( )
.map( article -> {
File converted = converter.getFile( ... );
String fileName = converter.getFriendlyName( ... );
return new ImmutablePair<>( fileName, converted );
} )
.peek( pair -> statusMessageSender.sendStatusMessage( pair.getKey() ) )
.collect( new Archiver( archivePath, deleteArchivedFiles ) );
or:
File archive = articles.parallelStream( )
.map( article -> {
File converted = converter.getFile( ... );
String fileName = converter.getFriendlyName( ... );
return new ImmutablePair<>( fileName, converted );
} )
.peek( pair -> statusMessageSender.sendStatusMessage( currentCount.incrementAndGet(), pair.getKey() ) )
.collect( new Archiver( archivePath, deleteArchivedFiles ) );
But in the end it was about the protocol and not peek. peek could definitely be used, and the non ordered nature of the problem was the reason way it could be used. (thanks for your help people on SO)

How to disable autotrading globally from MQL4/5 program (EA) without DLLs?

How do I disable autotrading globally in MetaTrader 4/5 from within MQL4/5 code without using DLLs?
Here you go, (Author is Tiago Praxedes)
#define MT_WMCMD_EXPERTS 32851
#define WM_COMMAND 0x0111
#define GA_ROOT 2
#include <WinAPI\winapi.mqh>
void SetAlgoTradingStatus(bool Enable)
{
bool Status = (bool) TerminalInfoInteger(TERMINAL_TRADE_ALLOWED);
if(Enable != Status)
{
HANDLE hChart = (HANDLE) ChartGetInteger(ChartID(), CHART_WINDOW_HANDLE);
PostMessageW(GetAncestor(hChart, GA_ROOT), WM_COMMAND, MT_WMCMD_EXPERTS, 0);
}
}
void OnTick()
{
SetAlgoTradingStatus(false);
}
Lifted it from here: Source
Yes, MQL4/5 Expert Adviser may locally forbid self to trade this way:
if ( IsTradeAllowed() )
{ Comment( __FILE__, " [EA] Trading is allowed, will disable self." );
...
}
else
{ Comment( __FILE__, " [EA] Trading is not allowed, will disable self." );
...
}
// ---------------------------------------// GRACEFULLY RELEASE ALL RESOURCES BEFORE FIN'd
// ********
// FINALLY: EXPERT-ADVISOR SIG_TERM -> self ( MT4 )
ExpertRemove(); /* MT4 The Expert Advisor
is not stopped immediately
as you call ExpertRemove();
just a flag to stop the EA operation is set.
That is:
- any next event won't be processed,
- OnDeinit() will be called
and
- the Expert Advisor will be unloaded and removed from the chart.
*/
If the idea is that you have several EA's on different pairs and you want to disable them all at the same time you could place a specific trade, that I would call an information trade and not meant to be used for trading.
Choose a price very far away from current price.
For this example, we can use 9,999.000 as price and we place the trade.
Loop through the trades and look for a price = 9999.
If you find it use that to disable trading.
If you want it to start again, you can have a button or manually delete that trade that is 9999.
Now the block is not there.
All the EA's you may have going can see this.
Also, an offsite computer will be able to see it as well.
This was used as a way to hand off trading control to a team of traders.
The new owner would send the trade that bumps everyone off.
Remove that trade but the other EA's are asleep until a human turns them back on or a "Wake Up" trade is sent.
You can send values in the Comment, TP and SL values as prices.
There are many ways to use this method.
For this to work though you would have to have your own code and make the changes. If you buy an EA and want to turn it on and off without the source code then this method won't work.

How to get a value of setting "gps location enabled" in windows phone?

While my app is working - I need to check, that GPS-location is on.
I DO NOT need any complex things with statusChanged and other - just check a value of setting.
If that setting is off - I must stop execute current operation. I got one method, which called every time, when user execute operation. And I wanna place check rule there. So - it must be fast and cheap.
Is there any human way? Without keeping GPSWatcher ON all the time, and check his last status. I must care about battery.
Thanks.
You can use this:
Geolocator geolocator = new Geolocator();
if (geolocator.LocationStatus == PositionStatus.Disabled)
{
...
}
According to the documentation
var accessStatus = await Geolocator.RequestAccessAsync();
switch (accessStatus)
{
case GeolocationAccessStatus.Allowed:
break;
case GeolocationAccessStatus.Denied:
_
break;
case GeolocationAccessStatus.Unspecified:
break;
}

Efficient Independent Synchronized Blocks?

I have a scenario where, at certain points in my program, a thread needs to update several shared data structures. Each data structure can be safely updated in parallel with any other data structure, but each data structure can only be updated by one thread at a time. The simple, naive way I've expressed this in my code is:
synchronized updateStructure1();
synchronized updateStructure2();
// ...
This seems inefficient because if multiple threads are trying to update structure 1, but no thread is trying to update structure 2, they'll all block waiting for the lock that protects structure 1, while the lock for structure 2 sits untaken.
Is there a "standard" way of remedying this? In other words, is there a standard threading primitive that tries to update all structures in a round-robin fashion, blocks only if all locks are taken, and returns when all structures are updated?
This is a somewhat language agnostic question, but in case it helps, the language I'm using is D.
If your language supported lightweight threads or Actors, you could always have the updating thread spawn a new a new thread to change each object, where each thread just locks, modifies, and unlocks each object. Then have your updating thread join on all its child threads before returning. This punts the problem to the runtime's schedule, and it's free to schedule those child threads any way it can for best performance.
You could do this in langauges with heavier threads, but the spawn and join might have too much overhead (though thread pooling might mitigate some of this).
I don't know if there's a standard way to do this. However, I would implement this something like the following:
do
{
if (!updatedA && mutexA.tryLock())
{
scope(exit) mutexA.unlock();
updateA();
updatedA = true;
}
if (!updatedB && mutexB.tryLock())
{
scope(exit) mutexB.unlock();
updateB();
updatedB = true;
}
}
while (!(updatedA && updatedB));
Some clever metaprogramming could probably cut down the repetition, but I leave that as an exercise for you.
Sorry if I'm being naive, but do you not just Synchronize on objects to make the concerns independent?
e.g.
public Object lock1 = new Object; // access to resource 1
public Object lock2 = new Object; // access to resource 2
updateStructure1() {
synchronized( lock1 ) {
...
}
}
updateStructure2() {
synchronized( lock2 ) {
...
}
}
To my knowledge, there is not a standard way to accomplish this, and you'll have to get your hands dirty.
To paraphrase your requirements, you have a set of data structures, and you need to do work on them, but not in any particular order. You only want to block waiting on a data structure if all other objects are blocked. Here's the pseudocode I would base my solution on:
work = unshared list of objects that need updating
while work is not empty:
found = false
for each obj in work:
try locking obj
if successful:
remove obj from work
found = true
obj.update()
unlock obj
if !found:
// Everything is locked, so we have to wait
obj = randomly pick an object from work
remove obj from work
lock obj
obj.update()
unlock obj
An updating thread will only block if it finds that all objects it needs to use are locked. Then it must wait on something, so it just picks one and locks it. Ideally, it would pick the object that will be unlocked earliest, but there's no simple way of telling that.
Also, it's conceivable that an object might become free while the updater is in the try loop and so the updater would skip it. But if the amount of work you're doing is large enough, relative to the cost of iterating through that loop, the false conflict should be rare, and it would only matter in cases of extremely high contention.
I don't know any "standard" way of doing this, sorry. So this below is just a ThreadGroup, abstracted by a Swarm-class, that »hacks» at a job list until all are done, round-robin style, and makes sure that as many threads as possible are used. I don't know how to do this without a job list.
Disclaimer: I'm very new to D, and concurrency programming, so the code is rather amateurish. I saw this more as a fun exercise. (I'm too dealing with some concurrency stuff.) I also understand that this isn't quite what you're looking for. If anyone has any pointers I'd love to hear them!
import core.thread,
core.sync.mutex,
std.c.stdio,
std.stdio;
class Swarm{
ThreadGroup group;
Mutex mutex;
auto numThreads = 1;
void delegate ()[int] jobs;
this(void delegate()[int] aJobs, int aNumThreads){
jobs = aJobs;
numThreads = aNumThreads;
group = new ThreadGroup;
mutex = new Mutex();
}
void runBlocking(){
run();
group.joinAll();
}
void run(){
foreach(c;0..numThreads)
group.create( &swarmJobs );
}
void swarmJobs(){
void delegate () myJob;
do{
myJob = null;
synchronized(mutex){
if(jobs.length > 0)
foreach(i,job;jobs){
myJob = job;
jobs.remove(i);
break;
}
}
if(myJob)
myJob();
}while(myJob)
}
}
class Jobs{
void job1(){
foreach(c;0..1000){
foreach(j;0..2_000_000){}
writef("1");
fflush(core.stdc.stdio.stdout);
}
}
void job2(){
foreach(c;0..1000){
foreach(j;0..1_000_000){}
writef("2");
fflush(core.stdc.stdio.stdout);
}
}
}
void main(){
auto jobs = new Jobs();
void delegate ()[int] jobsList =
[1:&jobs.job1,2:&jobs.job2,3:&jobs.job1,4:&jobs.job2];
int numThreads = 2;
auto swarm = new Swarm(jobsList,numThreads);
swarm.runBlocking();
writefln("end");
}
There's no standard solution but rather a class of standard solutions depending on your needs.
http://en.wikipedia.org/wiki/Scheduling_algorithm

Large application design (WPF/Silverlight)

Aside from the MVVM, as well as MVC patterns for the overall structure of a WPF app, how exactly do you break up the model/controller aspect of an app into subcomponents? The reason I ask is that I have no problem architecting the solution from the perspective of the patterns mentioned above, but when it comes to actually writing the backend; I feel that i'm fudging a lot of it. I end up with high quality apps from the user perspective, but my design asthetics don't allow me accept this.
To clarify; a lot of my business logic cannot be refactored into a class (or class hierarchy, with all associated interfaces) in any easy or meaningful way without having to change the entire app. I've been developing professionally for a year and a half now, so it may be an issue of inexperience; but I feel that it's still no excuse. Any pointers to this admittedly open ended question?
Edit: code request (in Silverlight)- The following is a -snippet- from a mousebuttonup handler in a drag-drop allocation application that's part of a much larger app-
I just really don't like how blunt the logic is, and hate the way that it's all completely unfactorable, since everything is getting stuffed into event handlers.
//determine if there is a previously existing allocated sale corresponding to this purchase's ID
SaleWS allocSaleExisting = colltoaddsale.FirstOrDefault(s => (s.p_TRADEID == allocPurch.TRADEID));
if (allocSaleExisting != null && allocSale.TRADEID == allocSaleExisting.TRADEID)
{
PurchaseWS allocPurchExisting = colltoadd.First(p => p.TRADEID == allocPurch.TRADEID);
//allocPurchExisting.AMOUNT += allocPurch.AMOUNT;
allocSaleExisting.AMOUNT += allocSale.AMOUNT;
allocPurchExisting.AMOUNT += allocSale.AMOUNT;
allocPurch.AMOUNT -= allocSale.AMOUNT;
colltoaddsale.Remove(allocSale);
//colltoadd.Remove(allocPurch);
}
else
{
//Create new "split" item in the data source for the source table
PurchaseWS splitAllocPurch = new PurchaseWS { COMMODITY = allocPurch.COMMODITY, CONTRACTNUMBER = allocPurch.CONTRACTNUMBER, AMOUNT = allocPurch.AMOUNT - allocSale.AMOUNT, FORM = allocPurch.FORM, GRADE = allocPurch.GRADE, LOCATION = allocPurch.LOCATION, SHIP_DATE = allocPurch.SHIP_DATE, TRADEID = allocPurch.TRADEID, UNITS = allocPurch.UNITS };
//update the source table's selecteditem datacontext with the target allocation id
allocPurch.s_TRADEID = allocSale.TRADEID;
allocSale.p_TRADEID = allocPurch.TRADEID;
allocPurch.AMOUNT = allocSale.AMOUNT;
colltoadd.Insert(colltoadd.IndexOf(allocPurch) + 1, splitAllocPurch);
}
}
Take a look at the Composite Application Guidance from the Patterns and Practices group.
It's geared specifically towards this, including using MVVM for WPF/Silverlight in large scale applications, and how to handle business logic concerns, etc.
You should also check Caliburn.

Resources