Hi all,
I started building my openEnergyMonitor some months ago, then I stopped to move to a new home and now I am restarting the project.
I have updated all the code (jeelib, emonlib and emontxFirmware) to the last versions.
Now I am stuck with a problem and need some help to debug it, it seems that the rf12_sendWait(2) is blocking everything. (I tried with 0, 1, 2, or 3 but the result seems to be the same)
To simplify the debugging and exclude some problems I am now using this sample sketch:
https://github.com/openenergymonitor/emonTxFirmware/blob/master/emonTxV2...
If I comment out all the rf12_sleep() calls and the rf12_sendWait() the loop runs.
The rfm12 seems to work as when the wait/sleep are commented out the pi is receiving the data (not every time the data is sent, only some times but I thnk this will be a problem to solve after).
The question now is: there are known bugs/problems/solutions to this issue? could it be solved in some way? if not, how could I try to investigate more on this?
Thanks
Re: emontx with rfm12 v2 stuck at rf12_sendWait(2)
It does sound like a problem with your RFM12B (is that what you have?) radio module. I cannot remember anyone reporting an issue like this, that was not traced to a faulty radio module or a bad connection to it.
Re: emontx with rfm12 v2 stuck at rf12_sendWait(2)
I have this:
http://it.farnell.com/rf-solutions/alpha-trx433s/rf-module-transceiver-f...
I read on the oem site when I bought all the components that these were the same as the RFM12B, the radio seems to be not entirely faulty as without the sleep stuffs the pi sometimes receives the data. I ordered some RFM69CW but they will arrive in 2-3 weeks so I would try to make it working with the RFM12.
I have understood correctly that I can mix RFM12 and RFM69? for example have the RFM12 on the pi and RFM69 on the tx?
Re: emontx with rfm12 v2 stuck at rf12_sendWait(2)
That module does indeed look like a RFM12B. Do you have an emonTx, or an emonTx Shield and Arduino, and if so, which Arduino?
Yes, the RFM12B and RFM69CW can work with each other.
This "the radio seems to be not entirely faulty as without the sleep stuffs the pi sometimes receives the data." is what is confusing me. Usually, a fault with the radio module or the soldering will result in the sketch stopping forever at the point where it initialises the radio module.
rf12_sendWait(2); waits for the send to finish - this means blocking the processor and preventing it from continuing until the message has been sent. It is this that makes me think that the library cannot detect that the radio has actually finished sending the message, so it waits.
rf12_sleep(RF12_SLEEP); only sends the radio to sleep.
Taking those commands out will allow the loop to run, but may result in incomplete messages, which emonHub will reject (but log).
Re: emontx with rfm12 v2 stuck at rf12_sendWait(2)
@Robert,
> rf12_sendWait(2); waits for the send to finish
Does this routine wait for a "quiet" channel before starting the send?
Re: emontx with rfm12 v2 stuck at rf12_sendWait(2)
I don't think that's its function. It's hard to see exactly how it operates, as it means chasing interrupts, but it doesn't wait to send, it waits for the send (which I presume is - it must be - interrupt-driven) to complete before returning. [In the RFM69CW, there's a buffer to look at and when it's empty, it's safe to release the processor to continue.] So it's quite possible that by taking this out, Valerio is sending incomplete messages but sometimes a complete one gets through and is decoded. It would be worth trying any sort of wait to see if the messages get through.
If you look at MartinR's PLL sketch, you'll see he sends 3 dummy bytes after the end of the message - I think that's to achieve the same end. My 3-phase sketch also has Martin's code - and the '69 equivalent.
Re: emontx with rfm12 v2 stuck at rf12_sendWait(2)
Hi,
I have ad emontx , not the arduino shield.
The fact that it's sometimes sending confuses me too...
I forgot to mention that I have added a delay(1000) in place of the rf12_sendWait(2), so the sketch is waiting 6 seconds between the loops (delay(1000) + Sleepy::loseSomeTime(5000)). Could this be the problem with the data sent only sometimes? If I comment out the delay(1000) and leave only the Sleepy::loseSomeTime(5000) the loop is continous (without waiting 5 seconds). To "monitor" the loops I added a led flash in the loop().
There's another way to wait for the message to be sent? could be the delay(1000) that is stopping the sending process?
Re: emontx with rfm12 v2 stuck at rf12_sendWait(2)
"I forgot to mention that I have added a delay(1000) in place of the rf12_sendWait(2), so the sketch is waiting 6 seconds between the loops (delay(1000) + Sleepy::loseSomeTime(5000)). Could this be the problem with the data sent only sometimes?" .... "could be the delay(1000) that is stopping the sending process? "
I don't think so. I've loaded that demonstration sketch (g_TransmittingData.ino) into an emonTx V3.4 with RFM12B radio and it works just fine for me with delay(1000) in place of rf12_sendWait(2); sending every 6 s or so without fail.
"If I comment out the delay(1000) and leave only the Sleepy::loseSomeTime(5000) the loop is continous (without waiting 5 seconds)."
I too see that behaviour. It is not right, but JeeLabs say that if an interrupt occurs, loseSomeTime will return immediately, so I'm guessing that the RFM12B is firing an interrupt inside that first second. I find mine works most times with delay(4), never (does not send at all) with delay(3) or less, and always works with delay(5). That's with a 4-byte message. If I increase the message to 10 bytes, it sometimes fails with delay(5). This demonstrates what rf12_sendWait( ) should do.
I think all this is pointing to a hardware problem with your radio module, or the connections. Have you looked very carefully at the soldering - with a magnifying lens - and checked every joint? Did you buy the emonTx assembled with its radio from the shop, or did you add the radio yourself?
Re: emontx with rfm12 v2 stuck at rf12_sendWait(2)
I bought only the pcb and some other parts and added the radio myself, as I had a problem with a radio in the pi I soldered in a "temporary" way on this board to check the radio before soldering it permanently, I checked all the joins when I soldered them, I will do it again when I will be back home just to be sure.
With the delay > 5 you are always receiving the packets on the other side? so the fact that I am not always getting the packets to the raspberry is not caused by the delay.
Re: emontx with rfm12 v2 stuck at rf12_sendWait(2)
I was using an emonGLCD running my own diagnostic sketch to check the transmissions, I did not notice any failures when the delay was long enough to be sure that the message had completed sending. "so the fact that I am not always getting the packets to the raspberry is not caused by the delay." - Yes, I think that is correct.
Is there another transmitter nearby on the same frequency band that could be 'jamming' your emonTx? - if you have the delay and not sendWait( ), then while it does not mean that your transmitter always works, it could be working and something else is corrupting the message.
Re: emontx with rfm12 v2 stuck at rf12_sendWait(2)
Hi,
I rechecked everything and there were no shorts, but yesterday it started to deliver all the messages, so I added the sleep and then the send_wait and all is working except that after some time it gets stuck again and the tx stops working, if I power down and power it up again it starts again and stops after some time (less than an hour of 5-sec transmissions)
Re: emontx with rfm12 v2 stuck at rf12_sendWait(2)
This has all the signs of a faulty connection. You handled and checked it, then it worked for a time. You left it for a time and it stopped working. I wonder whether there is a hairline break somewhere, that connected when you handled it and then broke the connection as something cooled or relaxed back into position? Can you check continuity on all the tracks that connect to the RFM12B module - and while you are doing that, bend and twist the PCB so as to stress the joints and the tracks.
Re: emontx with rfm12 v2 stuck at rf12_sendWait(2)
If Robert's suggestion of very close track examination show nothing, there is a further possibility. If the catalog photo is accurate, the radio module is the 'epoxy blob' type. The silicon die is flipped and pushed directly against pads on the PCB, then the epoxy holds this in place and (mostly) keeps out contaminants.
If the module has been stored for long periods in high humidity, the chip to pad interface can be compromised during soldering and give symptoms all the way from intermittent operation to completely dead. Once in a while you can actually demonstrate this by pressure on the blob restoring function for a time.
Later versions from Hope RF moved away from the 'blob' and used conventional lead-frame packaging with welded bonding wires.
Re: emontx with rfm12 v2 stuck at rf12_sendWait(2)
hi all, I'm back here to update you with some good news as finally it's working, I don't know why but after checking everything another time and "bending and twisting the PCB" at the end it started working properly, so I uploaded the power+voltage sketch, calibrated everything and saturday morning I installed it on the main panel and from then it's working ok!
Thanks to all for the quick support!!!
I modified the sketch to use the Sleepy::loseSomeTime(5000) instead of the delay as it's consuming much less power (I think is has been commented on the github code for the 2.5 board that is powered directly by the ac adapter).
For now the board is hanging from the panel, I am now looking for a solution to put it somewhere less visible. if I cannot find sufficient space inside the panel do you think I can extend the CT wire or it will cause problems to the readings? I don't have solar or other, so I am evaluating the idea to try to design a "small as possible" single CT + voltage board, do you think it could be useful for someone else too?
If extending the CT cable is not a solution do you think I can extend the ac voltage cable?
Re: emontx with rfm12 v2 stuck at rf12_sendWait(2)
First, don't trust it. What you describe exactly fits a bad connection somewhere. You have a badly soldered joint or the problem that emjay described. I can almost guarantee that it will come back, my guess would be in about 2 years' time when a bit of oxidation sets in.
[I once spent two years trying to find a badly soldered joint in an audio amplifier - every time I as much as touched the screws holding the lid on, the problem went away. It was only after the joint had tarnished enough for the fault to remain while I got inside that I could find the problem, one touch with the iron and it was fixed.]
You can extend either or both cables. The CT is a current source (unless you have one with an internal burden) so voltage drop isn't a problem, but if you're extending it by more than a metre or two, you just need to get the screening right. I've repeated what you must do many times here. Voltage drop with the ac adapter, if it's also the power supply, might be a problem if you use the thinnest of wires, otherwise that too will be fine.
I don't think many people would want a single channel board, most of those who aren't happy with the emonTx want many more channels than four.
Re: emontx with rfm12 v2 stuck at rf12_sendWait(2)
Thanks for the explanation.
i will not trust it, it's just to get a visualization of the data, so if it one day fails and stop sending data the only problem will be that I will not know how much I'm consuming, and the rf module is still "temporarily soldered" so there's the possibility that I will work on the board again to solder it. If it would work for 2 years then I will surely know if I really need it and then if I will need to replace/rework it or not.
I have a ct bought from the oem shop so it should be a current source, and the burden is on the board. I have a relatively small pcb-mountable ac ac adapter, from what I can find it's 9V 222mA, the one sold in the shop is 666mA, do you think it could be used for ac measurements? I think it could be a little underpowered to also power the board (and the tx v2.2 could not be powered from AC so it should need a board redesign) am I right?
My problem is that I can't fit the standard pluggable AC adaptor in the panel, so I need to move the adaptor away and fit the rest in the panel or move everyhing away, extend the CT cable and plug it or use the pcb ac adapter and try to fit everything in the panel.
Re: emontx with rfm12 v2 stuck at rf12_sendWait(2)
The 9 V adapter should be fine for the ac measurements, but if you have an emonTx V2, then that needs a separate 5 V d.c. supply to power it. As your adapter isn't the standard one, you'll need to recalculate (or adjust by trial and error) the voltage calibration coefficient so that your emonTx reads the correct voltage. All that is in Resources > Building Blocks.
The problem with powering the emonTx from the ac adapter isn't so much power (200 mA is more than enough), but you can only have a half-wave rectifier to get the d.c., and the current pulse when the reservoir capacitor (which needs to be twice the size you'd expect) charges causes a dip in the voltage wave that makes it inaccurate. Therefore you need an adapter that's capable of delivering a short, high-current pulse without too much dip, and you need to stretch the current pulse as much as possible to limit the amplitude.
Re: emontx with rfm12 v2 stuck at rf12_sendWait(2)
the voltage calibration is not a big problem, I did it for the node that is now running.
could a large capacitor make it more stable? if I remember well the moment when the circuit draws more current is when the rf is sending, and it's not in the same moment as when it's reading the voltage (the next voltage reading is 5-10 seconds after, so the capacitor should be recharged in that time?).
Re: emontx with rfm12 v2 stuck at rf12_sendWait(2)
No, a large reservoir capacitor makes no real difference, the problem is the current charging that capacitor. Every cycle, you need to restore the charge that's drained away running the emonTx for the last 19 ms or so, and it's that 1 ms pulse of current that distorts the voltage wave while you're measuring the voltage. I've published a simulation showing the dip, which a search should find for you.


Jorge Martinez
Software EngineerSummary
Experience
Dec 2016Present
Lead Engineer
Bloomberg San Francisco, CA- Building a PaaS for Bloomberg engineering based on Kubernetes.
DockerKubernetesAngularNodeJS - Went from days + many tickets to one click deployments.
- Grew the product from a handful of users to 100+ teams.
20142015
Software Engineer
Vertica Palo Alto, CA- Wrote a framework to run Vertica on Kubernetes.
DockerKubernetes -
Added support for cloud storage (AWS, Azure).
AWS/S3Azure/BSC++ - Worked on DistributedR, a distributed machine learning and graph processing platform for R.
C++R
Sept 2009Sept 2013
Software Engineer
HP printing Barcelona, Spain- Implemented high speed imaging and compression algorithms in GPUs and x86 processors for HP Designjet and Web Press product lines.
Patents: 2 granted, 4 pending.
C++OpenCLFPGA
Education
20092010
Master’s Degree in Computer Science
Universitat Politecnica de Catalunya Barcelona, SpainCoursework: Multiprocessor Architecture, Compilers, Operating Systems, VLSI design.
Master Thesis: "Study of on-die dynamic cache architectures".
Master Thesis: "Study of on-die dynamic cache architectures".
20042009
Bachelor's + Master’s Degree in Computer Science
Universidad del Pais Vasco Bilbao, SpainCoursework: C/C++, Java, Operating Systems, Digital Design, Networks.
Final year project: "Secure Ethernet-based service delivery in Wholesale Scenarios".
Best Student Academic Record Award, 2007.
Final year project: "Secure Ethernet-based service delivery in Wholesale Scenarios".
Best Student Academic Record Award, 2007.


Immediately sync all writes?
When this option is enabled, all NFS writes by clients for this export will
be written to disk before success is reported back to the client. This is
slower, but ensures data integrity.
When the option is disabled, writes by NFS clients may be buffered until later.
exportfs options: sync, async
default: enabled (but disabled for releases of nfs-utils previous to 1.0.0)


| 003:090 Khan | : |
Verily, those who disbelieved after their Belief and then went on increasing in their disbelief (i.e. disbelief in the Qur'an and in Prophet Muhammad SAW) - never will their repentance be accepted [because they repent only by their tongues and not from their hearts]. And they are those who are astray. |
| 003:090 Maulana | : |
Those who disbelieve after their believing, then increase in disbelief, their repentance is not accepted, and these are they that go astray. |
| 003:090 Pickthal | : |
Lo! those who disbelieve after their (profession of) belief, and afterward grow violent in disbelief: their repentance will not be accepted. And such are those who are astray. |
| 003:090 Rashad | : |
Those who disbelieve after believing, then plunge deeper into disbelief, their repentance will not be accepted from them; they are the real strayers. |
| 003:090 Sarwar | : |
Those who disbelieve, after having been believers and increase their disbelief, are lost and their repentance will not be accepted. |
| 003:090 Shakir | : |
Surely, those who disbelieve a,fter their believing, then increase in unbelief, their repentance shall not be accepted, and these are they that go astray. |
| 003:090 Sherali | : |
Surely those who disbelieve after they have believed and then increase in their disbelief, their repentance shall not be accepted, and these are they who have gone astray. |
| 003:090 Yusufali | : |
But those who reject Faith after they accepted it, and then go on adding to their defiance of Faith,- never will their repentance be accepted; for they are those who have (of set purpose) gone astray. |
Concepts/Themes Covered: أركان الإسلام > التوحيد > توحيد الله تعالي > الوعيد Pillars of Islam> Islamic> Oneness of Allah> The Threat أركان الإسلام > التوحيد > الكافرون > صفات الكفار Pillars of Islam> Islamic> The Disbelievers> The Characteristics of the Disbelievers الإيمان > الإيمان بالله > التوبة Faith> Belief In Allah> Repentance
This tool uses eight English parallel translations for the Holy Quran imported from Mr. Clay Smith. You can also visit Qurany Concepts for browsing the Quran themes or topics. If you want to search the Holy Quran for keywords, please visit Qurany Keywords.


Words You Want is the most experienced writing company on Elance with 6,000 completed projects and over $2 million lifetime earnings, our reputation speaks for itself. Words You Want has been the one stop shop for SEO articles, blogs, eBooks and PRs on Elance since 2006. We have written on a wide variety of topics ranging from automotive topics to web design and everything in between. Feel free to request a link for our full portfolio. We understand that quality content takes time and research, so we work hard to ensure that you get what...
TrueTravelReviews.com is an online review website featuring reviews of restaurants, hotels, and attractions based on our actual experiences while traveling. TrueTravelReviews.com also features two self-published travel guides that are available on Amazon.
A professional service, highest quality, delivered on time, exactly as specified with fantastic customer service. 10/10. I would recommend this service without doubt.
A professional service, highest quality, delivered on time, exactly as specified with fantastic customer service. 10/10. I would recommend this service without doubt.


FIA’s 2020 tyre selection process not “all perfect”
by Bevan YoulNikolas Tombazis, FIA’s single-seater technical boss, has admitted that the process for finalising the choice of Pirelli tyres for 2020 isn’t “all perfect” due to not wanting a repeat of complaints this year.
The original date for the official choice of 2020 tyre was to be communicated to teams by September 1st to allow time for adjustments but it was pushed back until October.
But testing from teams after Austin using the supposed definite 2020 tyre resulted in a lot of negative feedback and some teams calling for the 2019 tyres to be used again, prompting another test of them after Abu Dhabi.
"As explained to the team principals [in Brazil], I'm not suggesting that how it's been done is the best way and that it's all perfect," Tombazis told Motorsport.com.
"But last year we were faced in June or July with a big brouhaha about the tyres and people wanting to change them in the middle of the year, on the basis of a vote. The alternative was to just keep the current tyres and do nothing.
"And to avoid similar whinging next year, and cries for different constructions or whatever, then I felt at least to get it right in December or late November was better than discussing it in May or June during a championship.”
Should there still be negative feedback from teams after the Abu Dhabi test for the 2020 tyres then the FIA will call for a vote, of which if seven of the teams vote against then they will return to the 2019 tyres.
"If the outcome of that is that teams say, 'Oh, no, really, you know, we don't see any benefits,' and so on, then they have the right to vote them out with seven out of 10,” he added.
“If on the other hand hopefully the tyres do prove to be beneficial, we're left with an advantage for the sport.
"The change of tyres has to be instigated by the FIA. So, if we see that there's massive whinging about the tyres, then we will ask there to be a vote.”


Barcelona chief confirms interest in PSG superstar ahead of January transfer window
by HarigovindOn Sunday, Barcelona Sporting Director Eric Abidal confirmed the club’s interest in Paris Saint Germain (PSG) superstar Neymar Jr., thereby making it clear that the Brazilian has always been a key target for them.
The 27-year-old created quite a storm in the summer of 2017, when he chose to move to PSG from Barcelona. The Parisians had to shell out a world-record €220million to sign him – but things turned south earlier this year, when he expressed interest to return to the Camp Nou.
And when asked about Neymar in a recent interview, Abidal said: “A top player, who has a Barca philosophy and who is performing at a high level, will always be an option.”
“From there, at the sport level we can make decisions, but the whole financial issue, there are things that you can reach and others that you cannot.”
“The future will say,” the ex-France international further added, before concluding:
“If he continues at this level, because the season is very long, I will not say that it will be option number 1 but it can be a clear option.”
Meanwhile, Express reports that Barcelona players were so keen to see Neymar return to the Camp Nou, that they even offered to alter their own contracts – so that it will help the club accommodate his payments as well, in their overall wage budget.
It remains to be seen whether the Catalans will make a move for him during the upcoming January transfer window.
Quotes via Mundo Deportivo.


In the JMockit library, the Expectations API provides rich support for the use of mocking in automated developer tests. When mocking is used, a test focuses on the behavior of the code under test, as expressed through its interactions with other types it depends upon. Mocking is typically used in the construction of isolated unit tests, where a unit under test is exercised in isolation from the implementation of other units it depends on. Typically, a unit of behavior is a single class, but it's also fine to consider a whole set of strongly-related classes as a single unit for the purposes of unit testing (as is usually the case when we have a central public class with one or more helper classes, possibly package-private); in general, individual methods should not be regarded as separate units on their own.
Strict unit testing, however, is not a recommended approach; one should not attempt to mock every single dependency. Mocking is best used in moderation; whenever possible, favor integration tests over isolated unit tests. This said, mocking is occasionally also useful in the creation of integration tests, when some particular dependency cannot have its real implementation easily used, or when attempting to create tests for corner cases where a well-placed mocked interaction can greatly facilitate the test.
Mocking provides a mechanism for isolating a class to be tested from (some of) its dependencies.
We specify which particular dependencies are to be mocked by declaring suitable mock fields and/or mock parameters in a
test class; mock fields are declared as annotated instance fields of the test class, while mock parameters are declared as annotated
parameters of a test method.
The type of the mock field or parameter can be any kind of reference type: an interface
, a class
(including abstract
and final
ones), an annotation, or an enum
.
The following example test skeleton (using Java 8 and JUnit 5) serves as a basic illustration for the declaration of mock fields and mock parameters, as well as the way in which they are typically used in test code.
@Mocked Dependency mockInstance; // holds a mocked instance automatically created for use in each test
@Test
void doBusinessOperationXyz(@Mocked AnotherDependency anotherMock) {
...
new Expectations() {{ // an "expectation block"
...
// Record an expectation, with a given value to be returned:
mockInstance.mockedMethod(...); result = 123;
...
}};
...
// Call the code under test.
...
new Verifications() {{ // a "verification block"
// Verifies an expected invocation:
anotherMock.save(any); times = 1;
}};
...
}
For a mock parameter declared in a test method, an instance of the declared type will be automatically created by JMockit and passed by
the JUnit/TestNG test runner when it executes the test method; therefore, the parameter value will never be null
.
For a mock field, an instance of the declared type will be automatically created and assigned to the field (provided it's not
final
).
There are three different mocking annotations we can use when declaring mock fields and parameters:
@Mocked
, which will mock all methods and constructors on all existing and future instances of a
mocked class (for the duration of the tests using it); @Injectable
, which constrains mocking to the
instance methods of a single mocked instance; and @Capturing
, which extends mocking to the classes
implementing a mocked interface, or the subclasses extending a mocked class.
The mocked instances created by JMockit can be used normally in test code (for the recording and verification of expectations), and/or
passed to the code under test. Or they may simply go unused.
Differently from other mocking APIs, these mocked objects don't have to be the ones used by the code under test when it calls
instance methods on its dependencies.
When using @Mocked
or @Capturing
(but not when using
@Injectable
), JMockit does not care on which particular object a mocked instance method is called.
This allows the transparent mocking of instances created directly inside code under test, when said code invokes constructors on brand
new instances using the new
operator; the classes instantiated must be covered by mocked types declared in test code, that's
all.
An expectation represents a set of invocations to a specific mocked method/constructor that is relevant for a given test. An expectation may cover multiple different invocations to the same method or constructor, but it doesn't have to cover all such invocations that occur during the execution of the test. Whether a particular invocation matches a given expectation or not will depend not only on the method/constructor signature but also on runtime aspects such as the instance on which the method is invoked, argument values, and/or the number of invocations already matched. Therefore, several types of matching constraints can (optionally) be specified for a given expectation.
When we have one or more invocation parameters involved, an exact argument value may be specified for each parameter.
For example, the value "test string"
could be specified for a String
parameter, causing the expectation to
match only those invocations with this exact value in the corresponding parameter.
As we will see later, instead of specifying exact argument values, we can specify more relaxed constraints which will match whole sets of
different argument values.
The example below shows an expectation for Dependency#someMethod(int, String)
, which will match an invocation to this method
with the exact argument values as specified.
Notice that the expectation itself is specified through an isolated invocation to the mocked method.
There are no special API methods involved, as is common in other mocking APIs.
This invocation, however, does not count as one of the "real" invocations we are interested in testing.
It's only there so that the expectation can be specified.
@Test
void doBusinessOperationXyz(@Mocked Dependency mockInstance) {
...
new Expectations() {{
...
// An expectation for an instance method:
mockInstance.someMethod(1, "test"); result = "mocked";
...
}};
// A call to code under test occurs here, leading to mock invocations
// that may or may not match specified expectations.
}
We will see more about expectations later, after we understand the differences between recording, replaying, and verifying invocations.
Any developer test can be divided in at least three separate execution phases. The phases execute sequentially, one at a time, as demonstrated below.
@Test
void someTestMethod() {
// 1. Preparation: whatever is required before the code under test can be exercised.
...
// 2. The code under test is exercised, usually by calling a public method.
...
// 3. Verification: whatever needs to be checked to make sure the code exercised by
// the test did its job.
...
}
First, we have a preparation phase, where objects and data items needed for the test are created or obtained from somewhere else. Then, code under test is exercised. Finally, the results from exercising the tested code are compared with the expected results.
This model of three phases is also known as the Arrange, Act, Assert syntax, or "AAA" for short. Different words, but the meaning is the same.
In the context of behavior-based testing with mocked types (and their mocked instances), we can identify the following alternative phases, which are directly related to the three previously described conventional testing phases:
Behavior-based tests written with JMockit will typically fit the following templates:
import mockit.*;
... other imports ...
class SomeTest {
// Zero or more "mock fields" common to all test methods in the class:
@Mocked Collaborator mockCollaborator;
@Mocked AnotherDependency anotherDependency;
...
@Test
void testWithRecordAndReplayOnly(mock parameters) {
// Preparation code not specific to JMockit, if any.
new Expectations() {{ // an "expectation block"
// One or more invocations to mocked types, causing expectations to be recorded.
// Invocations to non-mocked types are also allowed anywhere inside this block
// (though not recommended).
}};
// Code under test is exercised.
// Verification code (JUnit/TestNG assertions), if any.
}
@Test
void testWithReplayAndVerifyOnly(mock parameters) {
// Preparation code not specific to JMockit, if any.
// Code under test is exercised.
new Verifications() {{ // a "verification block"
// One or more invocations to mocked types, causing expectations to be verified.
// Invocations to non-mocked types are also allowed anywhere inside this block
// (though not recommended).
}};
// Additional verification code, if any, either here or before the verification block.
}
@Test
void testWithBothRecordAndVerify(mock parameters) {
// Preparation code not specific to JMockit, if any.
new Expectations() {{
// One or more invocations to mocked types, causing expectations to be recorded.
}};
// Code under test is exercised.
new VerificationsInOrder() {{ // an ordered verification block
// One or more invocations to mocked types, causing expectations to be verified
// in the specified order.
}};
// Additional verification code, if any, either here or before the verification block.
}
}
There are other variations to the above templates, but the essence is that the expectation blocks belong to the record phase and come before the code under test is exercised, while the verification blocks belong to the verify phase. A test method can contain any number of expectation blocks, including none. The same is true for verification blocks.
A non-final
instance field annotated as @Tested
in the test class will be considered for
automatic instantiation and injection, just before the execution of a test method.
If at this time the field still holds the null
reference, an instance will be created using a suitable constructor of the
tested class, while making sure its internal dependencies get properly injected (when applicable).
In order to inject mocked instances into the tested object, the test class must also contain one or more mock fields or mock
parameters declared to be @Injectable
.
Mock fields/parameters annotated only with @Mocked
or @Capturing
are
not considered for injection.
On the other hand, not all injectable fields/parameters need to have mockable types; they can also have primitive or
array types.
The following example test class will demonstrate.
class SomeTest {
@Tested CodeUnderTest tested;
@Injectable Dependency dep1;
@Injectable AnotherDependency dep2;
@Injectable int someIntegralProperty = 123;
@Test
void someTestMethod(@Injectable("true") boolean flag, @Injectable("Mary") String name) {
// Record expectations on mocked types, if needed.
tested.exerciseCodeUnderTest();
// Verify expectations on mocked types, if required.
}
}
Note that a non-mockable injectable field/parameter must have a value explicitly specified for it, otherwise the default value would be
used.
In the case of an injectable field, the value can simply be assigned to the field.
Alternatively, it can be provided in the "value
" attribute of @Injectable
, which is the
only way to specify the value in the case of an injectable test method parameter.
Two forms of injection are supported: constructor injection and field injection. In the first case, the tested class must have a constructor which can be satisfied by the injectables and/or tested values made available in the test class. Note that for a given test, the set of available injectable/tested values consists of the set of injectable/tested fields declared as instances fields of the test class plus the set of injectable/tested parameters declared in the test method; therefore, different tests in the same test class can provide different sets of values to be injected into the same tested object.
Once the tested class is initialized with the chosen constructor, its remaining uninitialized non-final
instance fields are
considered for injection.
For each such field to be injected, an injectable/tested field of the same type is searched in the test class.
If only one is found, its current value is read and then stored in the injected field.
If there is more than one, the injected field name is used to select between the injectable/tested fields of same type.
For a given method with non-void
return type, a return value can be recorded with an assignment to the
result
field.
When the method gets called in the replay phase, the specified return value will be returned to the caller.
The assignment to result
should appear right after the invocation that identifies the recorded expectation,
inside an expectation block.
If the test instead needs an exception or error to be thrown when the method is invoked, then the result
field
can still be used: simply assign the desired throwable instance to it.
Note that the recording of exceptions/errors to be thrown is applicable to mocked methods (of any return type) as well as to mocked
constructors.
Multiple consecutive values to return can be recorded for an expectation, by calling the returns(v1, v2, ...)
method.
Alternatively, the same can be achieved by assigning the result
field with a list or array
containing the consecutive values.
The following example test records both types of results for the methods of a mocked DependencyAbc
class, to
be used when they are invoked from ClassUnderTest
.
Lets say the implementation of the class under test goes like this:
public class ClassUnderTest {
private final DependencyAbc abc = new DependencyAbc();
public void doSomething() {
(1) int n = abc.intReturningMethod();
for (int i = 0; i < n; i++) {
String s;
try {
(2) s = abc.stringReturningMethod();
}
catch (SomeCheckedException e) {
// somehow handle the exception
}
// do some other stuff
}
}
}
A possible test for the doSomething()
method could exercise the case where SomeCheckedException
gets thrown, after an arbitrary number of successful iterations.
Assuming that we want to record a set of expectations for the interaction between these two classes, we might write the test below.
@Tested ClassUnderTest cut;
@Test
void doSomethingHandlesSomeCheckedException(@Mocked DependencyAbc abc) throws Exception {
new Expectations() {{
(1) abc.intReturningMethod(); result = 3;
(2) abc.stringReturningMethod();
returns("str1", "str2");
result = new SomeCheckedException();
}};
cut.doSomething();
}
This test records two expectations.
The first one specifies that intReturningMethod()
will return 3
when called.
The second specifies a sequence of three consecutive results for stringReturningMethod()
, where the last result happens to
be an instance of the desired exception, allowing the test to achieve its goal.
When a mocked method/constructor has one or more parameters, a recorded/verified expectation like doSomething(1, "s", true);
will only match an invocation in the replay phase if it has equal argument values.
For arguments that are regular objects (not primitives or arrays), the equals(Object)
method is used for equality checking.
For parameters of array type, equality checking extends to individual elements; therefore, two different array instances having the same
length in each dimension and equal corresponding elements are considered equal.
To allow a recorded or verified invocation to match a whole set of replayed invocations with different argument values, we can specify
flexible argument matching constraints instead of actual argument values.
This is done by using anyXyz
fields and/or withXyz(...)
methods, from inside expectation or
verification blocks.
The most commonly used argument matching constraints are those that simply match invocations with any value for a given
parameter (of the proper parameter type).
For that we have a whole set of special argument matching fields, one for each primitive type (and the corresponding wrapper
class), one for strings, and a "universal" one of type Object
.
The test below demonstrates some uses.
@Tested CodeUnderTest cut;
@Test
void someTestMethod(@Mocked DependencyAbc abc) {
DataItem item = new DataItem(...);
new Expectations() {{
// Will match "voidMethod(String, List)" invocations where the first argument is
// any string and the second any list.
abc.voidMethod(anyString, (List<?>) any);
}};
cut.doSomething(item);
new Verifications() {{
// Matches invocations to the specified method with any value of type long or Long.
abc.anotherVoidMethod(anyLong);
}};
}
Uses of "any
" fields must appear at the actual argument positions in the invocation statement, never before.
You can still have regular argument values for other parameters in the same invocation, though.
For more details, consult the API documentation from your Java IDE.
When recording or verifying an expectation, calls to the withXyz(...)
methods can occur for any subset of the arguments
passed in the invocation.
They can be freely mixed with regular argument-passing (using literal values, local variables, etc.).
The only requirement is that such calls appear inside the recorded/verified invocation statement, rather than before it.
It's not possible, for example, to first assign the result of a call to withNotEqual(val)
to a local variable and then use
the variable in the invocation statement.
An example test using some of the "with" methods is shown below.
@Test
void someTestMethod(@Mocked DependencyAbc abc) {
DataItem item = new DataItem(...);
new Expectations() {{
// Will match "voidMethod(String, List)" invocations with the first argument
// equal to "str" and the second not null.
abc.voidMethod("str", (List<?>) withNotNull());
// Will match invocations to DependencyAbc#stringReturningMethod(DataItem, String)
// with the first argument pointing to "item" and the second one containing "xyz".
abc.stringReturningMethod(withSameInstance(item), withSubstring("xyz"));
}};
cut.doSomething(item);
new Verifications() {{
// Matches invocations to the specified method with any long-valued argument.
abc.anotherVoidMethod(withAny(1L));
}};
}
There are more "with" methods than shown above. Use your IDE's code completion, and consult the API documentation for more details.
Besides the several predefined argument matching constraints available in the API, JMockit allows the user to provide custom constraints,
through the with(Delegate)
method.
The number of invocations expected and/or allowed to match a given expectation can be specified through invocation count
constraints.
There are three special fields just for that: times
, minTimes
, and
maxTimes
.
They can be used either when recording or when verifying expectations.
In either case, the method or constructor associated with the expectation will be constrained to receive a number of invocations that
falls in the specified range.
Any invocations less or more than the expected lower or upper limit, respectively, and the test execution will automatically fail.
Lets see some example tests.
@Tested CodeUnderTest cut;
@Test
void someTestMethod(@Mocked DependencyAbc abc) {
new Expectations() {{
// By default, at least one invocation is expected, i.e. "minTimes = 1":
new DependencyAbc();
// At least two invocations are expected:
abc.voidMethod(); minTimes = 2;
// 1 to 5 invocations are expected:
abc.stringReturningMethod(); minTimes = 1; maxTimes = 5;
}};
cut.doSomething();
}
@Test
void someOtherTestMethod(@Mocked DependencyAbc abc) {
cut.doSomething();
new Verifications() {{
// Verifies that zero or one invocations occurred, with the specified argument value:
abc.anotherVoidMethod(3); maxTimes = 1;
// Verifies the occurrence of at least one invocation with the specified arguments:
DependencyAbc.someStaticMethod("test", false); // "minTimes = 1" is implied
}};
}
Unlike the result
field, each of these three fields can be specified at most once for a given expectation.
Any non-negative integer value is valid for any of the invocation count constraints.
If times = 0
or maxTimes = 0
is specified, the first
invocation matching the expectation to occur during replay (if any) will cause the test to fail.
Besides specifying invocation count constraints on recorded expectations, we can also verify matching invocations explicitly in verification blocks, after the call to the code under test.
Inside a "new Verifications() {...}
" block we can use the same API that's available in a
"new Expectations() {...}
" block, with the exception of methods and fields used to record return values
and thrown exceptions.
That is, we can freely use the anyXyz
fields, the withXyz(...)
argument matching methods, and the
times
, minTimes
, and maxTimes
invocation count constraint fields.
An example test follows.
@Test
void verifyInvocationsExplicitlyAtEndOfTest(@Mocked Dependency mock) {
// Nothing recorded here, though it could be.
// Inside tested code:
Dependency dependency = new Dependency();
dependency.doSomething(123, true, "abc-xyz");
// Verifies that Dependency#doSomething(int, boolean, String) was called at least once,
// with arguments that obey the specified constraints:
new Verifications() {{ mock.doSomething(anyInt, true, withPrefix("abc")); }};
}
Note that, by default, a verification checks that at least one matching invocation occurred during replay.
When we need to verify an exact number of invocations (including 1
), the
times = n
constraint must be specified.
Regular verification blocks created with the Verifications
class are unordered.
The actual relative order in which aMethod()
and anotherMethod()
were called during the replay phase is not
verified, but only that each method was executed at least once.
If you want to verify the relative order of invocations, then a "new VerificationsInOrder() {...}
" block must be used
instead.
Inside this block, simply write invocations to one or more mocked types in the order they are expected to have occurred.
@Test
void verifyingExpectationsInOrder(@Mocked DependencyAbc abc) {
// Somewhere inside the tested code:
abc.aMethod();
abc.doSomething("blah", 123);
abc.anotherMethod(5);
...
new VerificationsInOrder() {{
// The order of these invocations must be the same as the order
// of occurrence during replay of the matching invocations.
abc.aMethod();
abc.anotherMethod(anyInt);
}};
}
Note that the call abc.doSomething(...)
was not verified in the test, so it could have occurred at any time (or
not at all).
Sometimes it may be desired to have all invocations to the mocked types/instances involved in a test verified.
In such cases, a "new FullVerifications() {...}
" block will make sure that no invocations are left unverified.
@Test
void verifyAllInvocations(@Mocked Dependency mock) {
// Code under test included here for easy reference:
mock.setSomething(123);
mock.setSomethingElse("anotherValue");
mock.setSomething(45);
mock.save();
new FullVerifications() {{
mock.setSomething(anyInt); // verifies two actual invocations
mock.setSomethingElse(anyString);
mock.save(); // if this verification (or any other above) is removed the test will fail
}};
}
To decide the result of a recorded expectation based on the arguments it receives at replay time, we can use a
Delegate
object, as exemplified below.
@Tested CodeUnderTest cut;
@Test
void delegatingInvocationsToACustomDelegate(@Mocked DependencyAbc anyAbc) {
new Expectations() {{
anyAbc.intReturningMethod(anyInt, anyString);
result = new Delegate() {
int aDelegateMethod(int i, String s) {
return i == 1 ? i : s.length();
}
};
}};
// Calls to "intReturningMethod(int, String)" will execute the delegate method above.
cut.doSomething();
}
The Delegate
interface is empty, being used simply to tell JMockit that actual invocations at replay time
should be delegated to the "delegate" method in the assigned object.
This method can have any name, provided it is the only non-private
method in the delegate object.
As for the parameters of the delegate method, they should either match the parameters of the recorded method, or there should be none.
In any case, the delegate method is allowed to have an additional parameter of type Invocation
as its first
parameter.
The Invocation
object received during replay will provide access to the invoked instance and the actual
invocation arguments, along with other abilities.
The return type of a delegate method doesn't have to be the same as the recorded method, although it should be compatible in order to
avoid a ClassCastException
later.
Constructors can also be handled through delegate methods. The following example test shows a constructor invocation being delegated to a method which conditionally throws an exception.
@Test
void delegatingConstructorInvocations(@Mocked Collaborator anyCollaboratorInstance) {
new Expectations() {{
new Collaborator(anyInt);
result = new Delegate() {
void delegate(int i) { if (i < 1) throw new IllegalArgumentException(); }
};
}};
// The first instantiation using "Collaborator(int)" will execute the delegate above.
new Collaborator(4);
}
Invocation arguments can be captured for later verification through a set of special "withCapture(...)
" methods.
There are three different cases, each with its own specific capturing method:
T withCapture()
;T withCapture(List<T>)
;List<T> withCapture(T)
.
To capture arguments from a single invocation to a mocked method or constructor, we use withCapture()
,
as the following example test demonstrates.
@Test
void capturingArgumentsFromSingleInvocation(@Mocked Collaborator mock) {
// Inside tested code:
...
new Collaborator().doSomething(0.5, new int[2], "test");
// Back in test code:
new Verifications() {{
double d;
String s;
mock.doSomething(d = withCapture(), null, s = withCapture());
assertTrue(d > 0.0);
assertTrue(s.length() > 1);
}};
}
The withCapture()
method can only be used in verification blocks.
Typically, we use it when a single matching invocation is expected to occur; if more than one such invocation occurs, however,
the last one to occur overwrites the values captured by previous ones.
It is particularly useful with parameters of a complex type (think a JPA @Entity
), which may contain
several items whose values need to be checked.
If multiple invocations to a mocked method or constructor are expected, and we want to capture values for all of them, then the
withCapture(List)
method should be used instead, as in the example below.
@Test
void capturingArgumentsFromMultipleInvocations(@Mocked Collaborator mock) {
// Inside tested code:
mock.doSomething(dataObject1);
mock.doSomething(dataObject2);
...
// Back in test code:
new Verifications() {{
List<DataObject> dataObjects = new ArrayList<>();
mock.doSomething(withCapture(dataObjects));
assertEquals(2, dataObjects.size());
DataObject data1 = dataObjects.get(0);
DataObject data2 = dataObjects.get(1);
// Perform arbitrary assertions on data1 and data2.
}};
}
Differently from withCapture()
, the withCapture(List)
overload can also be used in expectation recording
blocks.
Finally, we can capture the new instances of a mocked class that got created during the test.
@Test
void capturingNewInstances(@Mocked Person mockedPerson) {
// From the code under test:
dao.create(new Person("Paul", 10));
dao.create(new Person("Mary", 15));
dao.create(new Person("Joe", 20));
...
// Back in test code:
new Verifications() {{
// Captures the new instances created with a specific constructor.
List<Person> personsInstantiated = withCapture(new Person(anyString, anyInt));
// Now captures the instances of the same type passed to a method.
List<Person> personsCreated = new ArrayList<>();
dao.create(withCapture(personsCreated));
// Finally, verifies both lists are the same.
assertEquals(personsInstantiated, personsCreated);
}};
}
When using complex APIs where functionality is distributed through many different objects, it is not uncommon to see chained invocations
of the form obj1.getObj2(...).getYetAnotherObj().doSomething(...)
.
In such cases it may be necessary to mock all objects/classes in the chain, starting with obj1
.
All three mocking annotations provide this ability.
The following test shows a basic example, using the java.net
and java.nio
APIs.
@Test
void recordAndVerifyExpectationsOnCascadedMocks(
@Mocked Socket anySocket, // will match any new Socket object created during the test
@Mocked SocketChannel cascadedChannel // will match cascaded instances
) throws Exception {
new Expectations() {{
// Calls to Socket#getChannel() will automatically return a cascaded SocketChannel;
// such an instance will be the same as the second mock parameter, allowing us to
// use it for expectations that will match all cascaded channel instances:
cascadedChannel.isConnected(); result = false;
}};
// Inside production code:
Socket sk = new Socket(); // mocked as "anySocket"
SocketChannel ch = sk.getChannel(); // mocked as "cascadedChannel"
if (!ch.isConnected()) {
SocketAddress sa = new InetSocketAddress("remoteHost", 123);
ch.connect(sa);
}
InetAddress adr1 = sk.getInetAddress(); // returns a newly created InetAddress instance
InetAddress adr2 = sk.getLocalAddress(); // returns another new instance
...
// Back in test code:
new Verifications() {{ cascadedChannel.connect((SocketAddress) withNotNull()); }};
}
In the test above, calls to eligible methods in the mocked Socket
class will return a cascaded mock
object whenever they occur during the test.
The cascaded mock will allow further cascading, so a null
reference will never be obtained from methods which return object
references (except for non-eligible return types Object
or String
which will return
null
, or collection types which will return a non-mocked empty collection).
Unless there is an available mocked instance from a mock field/parameter (such as cascadedChannel
above), a new
cascaded instance will get created from the first call to each mocked method.
In the example above, the two different methods with the same InetAddress
return type will create and return
different cascaded instances; the same method will always return the same cascaded instance, though.
New cascaded instances are created with @Injectable
semantics, so as to not affect other instances of the
same type that may exist during the test.
Finally, it's worth noting that, if necessary, cascaded instances can be replaced with non-mocked ones, with a different mocked instance,
or not be returned at all; for that, record an expectation which assigns the result
field with the desired
instance to be returned, or with null
if no such instance is desired.
Cascading is quite useful in scenarios where a mocked class contains static
factory methods.
In the following example test, lets say we want to mock the javax.faces.context.FacesContext
class from JSF
(Java EE).
@Test
void postErrorMessageToUIForInvalidInputFields(@Mocked FacesContext jsf) {
// Set up invalid inputs, somehow.
// Code under test which validates input fields from a JSF page, adding
// error messages to the JSF context in case of validation failures.
FacesContext ctx = FacesContext.getCurrentInstance();
if (some input is invalid) {
ctx.addMessage(null, new FacesMessage("Input xyz is invalid: blah blah..."));
}
...
// Test code: verify appropriate error message was added to context.
new Verifications() {{
FacesMessage msg;
jsf.addMessage(null, msg = withCapture());
assertTrue(msg.getSummary().contains("blah blah"));
}};
}
What's interesting in the test above is that we never have to worry about FacesContext.getCurrentInstance()
, as the
"jsf
" mocked instance gets automatically returned.
Another scenario where cascading tends to help is when code under test uses a
"fluent interface", where a "builder" object returns itself from most
of its methods.
So, we end up with a method call chain which produces some final object or state.
In the example test below we mock the java.lang.ProcessBuilder
class.
@Test
void createOSProcessToCopyTempFiles(@Mocked ProcessBuilder pb) throws Exception {
// Code under test creates a new process to execute an OS-specific command.
String cmdLine = "copy /Y *.txt D:\\TEMP";
File wrkDir = new File("C:\\TEMP");
Process copy = new ProcessBuilder().command(cmdLine).directory(wrkDir).inheritIO().start();
int exit = copy.waitFor();
...
// Verify the desired process was created with the correct command.
new Verifications() {{ pb.command(withSubstring("copy")).start(); }};
}
Above, methods command(...)
, directory(...)
, and inheritIO()
configure the process to be created,
while start()
finally creates it.
The mocked process builder object automatically returns itself ("pb
") from these calls, while also returning a new mocked
Process
from the call to start()
.
Previously, we explained that an expectation recorded on a mocked instance, such as "abc.someMethod();
"
would actually match invocations to DependencyAbc#someMethod()
on any instance of the mocked
DependencyAbc
class.
In most cases, tested code uses a single instance of a given dependency, so this won't really matter and can be safely ignored,
whether the mocked instance is passed into the code under test or created inside it.
But what if we need to verify that invocations occur on a specific instance, between several ones that happen to be used in the
code under test?
Also, what if only one or a few instances of the mocked class should actually be mocked, with other instances of the same class
remaining unmocked?
(This second case tends to occur more often when classes from the standard Java libraries, or from other third-party libraries, are
mocked.)
The API provides a mocking annotation, @Injectable
, which will only mock one instance of the
mocked type, leaving others unaffected.
Additionally, we have a couple ways to constrain the matching of expectations to specific @Mocked
instances, while still mocking all instances of the mocked class.
Suppose we need to test code which works with multiple instances of a given class, some of which we want to mock.
If an instance to be mocked can be passed or injected into the code under test, then we can declare an
@Injectable
mock field or mock parameter for it.
This @Injectable
instance will be an "exclusive" mocked instance; any other instance of the same mocked
type, unless obtained from a separate mock field/parameter, will remain as a regular, non-mocked instance.
When using @Injectable
, static
methods and constructors are also excluded from being mocked.
After all, a static
method is not associated with any instance of the class, while a constructor is only associated with a
newly created (and therefore different) instance.
For an example, lets say we have the following class to be tested.
public final class ConcatenatingInputStream extends InputStream {
private final Queue<InputStream> sequentialInputs;
private InputStream currentInput;
public ConcatenatingInputStream(InputStream... sequentialInputs) {
this.sequentialInputs = new LinkedList<InputStream>(Arrays.asList(sequentialInputs));
currentInput = this.sequentialInputs.poll();
}
@Override
public int read() throws IOException {
if (currentInput == null) return -1;
int nextByte = currentInput.read();
if (nextByte >= 0) {
return nextByte;
}
currentInput = sequentialInputs.poll();
return read();
}
}
This class could easily be tested without mocking by using ByteArrayInputStream
objects for input, but lets say
we want to make sure that the InputStream#read()
method is properly invoked on each input stream passed in the constructor.
The following test will achieve this.
@Test
void concatenateInputStreams(@Injectable InputStream input1, @Injectable InputStream input2) throws Exception {
new Expectations() {{
input1.read(); returns(1, 2, -1);
input2.read(); returns(3, -1);
}};
InputStream concatenatedInput = new ConcatenatingInputStream(input1, input2);
byte[] buf = new byte[3];
concatenatedInput.read(buf);
assertArrayEquals(new byte[] {1, 2, 3}, buf);
}
Note that the use of @Injectable
is indeed necessary here, since the class under test extends the mocked
class, and the method called to exercise ConcatenatingInputStream
is actually defined in the base
InputStream
class.
If InputStream
was mocked "normally", the read(byte[])
method would always be mocked, regardless
of the instance on which it is called.
When using @Mocked
or @Capturing
(and not
@Injectable
on the same mock field/parameter), we can still match replay invocations to expectations
recorded on specific mocked instances.
For that, we simply declare multiple mock fields or parameters of the same mocked type, as the next example shows.
@Test
void matchOnMockInstance(@Mocked Collaborator mock, @Mocked Collaborator otherInstance) {
new Expectations() {{ mock.getValue(); result = 12; }};
// Exercise code under test with mocked instance passed from the test:
int result = mock.getValue();
assertEquals(12, result);
// If another instance is created inside code under test...
Collaborator another = new Collaborator();
// ...we won't get the recorded result, but the default one:
assertEquals(0, another.getValue());
}
The test above will only pass if the tested code (here embedded in the test method itself, for brevity) invokes getValue()
on the exact same instance on which the recording invocation was made.
This is typically useful when the code under test makes calls on two or more different instances of the same type, and the test wants to
verify that a particular invocation occurred on the expected instance.
For future instances that will later get created by code under test, there is a way we can match invocations on them to separate
recorded expectations (assuming a test needs varying behavior from said instances).
This is done by recording expectations on specific constructor invocations of the mocked class, and then simply using the new
instances obtained from such "new
" expressions when recording expectations on their instance methods.
Lets see an example.
@Test
void newCollaboratorsWithDifferentBehaviors(@Mocked Collaborator anyCollaborator) {
// Record different behaviors for each set of instances:
new Expectations() {{
// One set, for instances created with "a value":
Collaborator col1 = new Collaborator("a value");
col1.doSomething(anyInt); result = 123;
// Another set, for instances created with "another value":
Collaborator col2 = new Collaborator("another value");
col2.doSomething(anyInt); result = new InvalidStateException();
}};
// Code under test:
new Collaborator("a value").doSomething(5); // will return 123
...
new Collaborator("another value").doSomething(0); // will throw the exception
...
}
In the above test, we declare a mock field or mock parameter of the desired class, using @Mocked
.
This mock field/parameter, however, is not used when recording expectations; instead, we use the instances created on
instantiation recordings to record further expectations on instance methods.
The future instances created with matching constructor invocations will map to those recorded instances.
Also, note that it's not necessarily a one-to-one mapping, but a many-to-one mapping, from potentially many future instances to a single
instance used for recorded expectations.
By default, all methods which can be called on a mocked instance get mocked. This is appropriate for most tests, but in some situations we might need to select only certain methods to be mocked. Methods not mocked in an otherwise mocked instance will execute normally when called.
When an object is partially mocked, JMockit decides whether to execute the real implementation of a method as it gets called from the code under test, based on which expectations were recorded and which were not. The following example tests will demonstrate it.
class PartialMockingTest {
static class Collaborator {
final int value;
Collaborator(int value) { this.value = value; }
int getValue() { return value; }
final boolean simpleOperation(int a, String b, Date c) { return true; }
void doSomething() { ... }
}
@Test
void partiallyMockingASingleInstance() {
Collaborator collaborator = new Collaborator(2);
new Expectations(collaborator) {{ // one or more instances to be partially mocked
collaborator.getValue(); result = 123;
collaborator.simpleOperation(1, "", null); result = false;
}};
// Mocked (instance methods recorded on one of the given instances):
assertEquals(123, collaborator.getValue());
assertFalse(collaborator.simpleOperation(1, "", null));
// Not mocked (unrecorded instance methods, static methods, constructors, and different instances):
collaborator.doSomething();
assertEquals(45, new Collaborator(45).getValue());
}
}
As shown above, the Expectations(Object...)
constructor accepts one or more objects to be partially mocked.
In case a test wants to partially mock the constructors and/or static
methods of a class, a MockUp
(from the
Faking API) would have to be used.
Notice that in this example test there is no mock field or mock parameter - so, the partial mocking constructor effectively provides yet another way to apply mocking.
It should be noted that, when we request an instance to be partially mocked, it can also have invocations verified on it, even if the verified methods were not recorded. For example, consider the following test.
@Test
void partiallyMockingAnObjectJustForVerifications() {
Collaborator collaborator = new Collaborator(123);
new Expectations(collaborator) {};
// No expectations were recorded, so nothing will be mocked.
int value = collaborator.getValue(); // value == 123
collaborator.simpleOperation(45, "testing", new Date());
...
// Unmocked methods can still be verified:
new Verifications() {{ c1.simpleOperation(anyInt, anyString, (Date) any); }};
}
Finally, a simpler way to apply partial mocking to a tested class is to have a field in the test class annotated as both
@Tested
(see section below) and @Mocked
.
In this case, the tested object is not passed to the Expectations
constructor, but we still need to record
expectations on any methods requiring mocked results.
Our discussion of this feature will be based on the (contrived) code below.
public interface Service { int doSomething(); }
final class ServiceImpl implements Service { public int doSomething() { return 1; } }
public final class TestedUnit {
private final Service service1 = new ServiceImpl();
private final Service service2 = new Service() { public int doSomething() { return 2; } };
public int businessOperation() {
return service1.doSomething() + service2.doSomething();
}
}
The method we want to test, businessOperation()
, uses classes that implement a separate interface,
Service
.
One of these implementations is defined through an anonymous inner class, which is completely inaccessible (except for the use of
Reflection) from client code.
Given a base type (be it an interface
, an abstract
class, or any sort of base class), we can write a test
which only knows about the base type but where all implementing/extending implementation classes get mocked.
To do so, we declare a "capturing" mocked type which refers only to the known base type.
Not only will implementation classes already loaded by the JVM get mocked, but also any additional classes that happen to get loaded by
the JVM during later test execution.
This ability is activated by the @Capturing
annotation, which can be applied to mock fields and mock
parameters, as demonstrated below.
final class UnitTest {
@Capturing Service anyService;
@Test
void mockingImplementationClassesFromAGivenBaseType() {
new Expectations() {{ anyService.doSomething(); returns(3, 4); }};
int result = new TestedUnit().businessOperation();
assertEquals(7, result);
}
}
In the test above, two return values are specified for the Service#doSomething()
method.
This expectation will match all invocations to this method, regardless of the actual instance on which the invocation occurs,
and regardless of the actual class implementing the method.


Dashboard
Toggle navigation
Welcome Admin
Logout
Dashboard
Users
Drivers
Trips
Settings
Feedback
15000
Total App Users
1200
Driver And Trucks
458
Total Completed Trips
48
Total Rejected Trips
56
Total Canceled Trips
48
Number Of Users on trip
48
Current Free Drivers
48
Current Offline Drivers
Current Vehicle On Trip
Refresh Map


[Spark_Event] element index
Package indexes
Spark
Spark_Controller
default
Spark_FilterChain
Spark_Model
Spark_Object
Spark_Registry
Spark_Validate
All elements
c
d
e
g
h
i
k
n
o
r
s
t
v
_
_
top
$_callbacks
Spark_Event_HandlerQueue::$_callbacks
in HandlerQueue.php
Contains the queue items
$_context
Spark_Event_Event::$_context
in Event.php
Context in which event got triggered
$_dispatched
Spark_Event_Event::$_dispatched
in Event.php
$_name
Spark_Event_Event::$_name
in Event.php
Name of the event
$_property
Spark_Model_Filter_Replace::$_property
in Replace.php
$_registry
Spark_Event_Dispatcher::$_registry
in Dispatcher.php
Contains the events and their callbacks
$_timestamp
Spark_Event_Event::$_timestamp
in Event.php
Timestamp for the occurence of the event
$_valid
Spark_Event_HandlerQueue::$_valid
in HandlerQueue.php
State of the next item (for Iterator interface)
$_value
Spark_Model_Filter_Replace::$_value
in Replace.php
_setTimestamp
Spark_Event_Event::_setTimestamp()
in Event.php
Sets the timestamp of the occurence of the event
__construct
Spark_Model_Filter_Replace::__construct()
in Replace.php
__construct
Spark_Event_Event::__construct()
in Event.php
Constructor
c
top
count
Spark_Event_HandlerQueue::count()
in HandlerQueue.php
Required by the Countable interface
current
Spark_Event_HandlerQueue::current()
in HandlerQueue.php
Required by the Iterator interface
d
top
dequeue
Spark_Event_HandlerQueue::dequeue()
in HandlerQueue.php
Removes an item from the front of a queue and returns it
Dispatcher.php
Dispatcher.php
in Dispatcher.php
DispatcherInterface.php
DispatcherInterface.php
in DispatcherInterface.php
e
top
enqueue
Spark_Event_HandlerQueue::enqueue()
in HandlerQueue.php
Adds the item to the end of the queue
Event.php
Event.php
in Event.php
Exception.php
Exception.php
in Exception.php
execute
Spark_Model_Filter_Replace::execute()
in Replace.php
g
top
getContext
Spark_Event_Event::getContext()
in Event.php
getName
Spark_Event_Event::getName()
in Event.php
Returns the name of the event
getTimestamp
Spark_Event_Event::getTimestamp()
in Event.php
Returns the timestamp of the event occurence
h
top
HandlerInterface.php
HandlerInterface.php
in HandlerInterface.php
HandlerQueue.php
HandlerQueue.php
in HandlerQueue.php
handleEvent
Spark_Event_HandlerInterface::handleEvent()
in HandlerInterface.php
This method gets called by the dispatcher when the event occurs
hasCallbacks
Spark_Event_Dispatcher::hasCallbacks()
in Dispatcher.php
Checks if callbacks were registered for a certain event
hasContext
Spark_Event_Event::hasContext()
in Event.php
hasName
Spark_Event_Event::hasName()
in Event.php
i
top
InvalidHandlerException.php
InvalidHandlerException.php
in InvalidHandlerException.php
isDispatched
Spark_Event_Event::isDispatched()
in Event.php
k
top
key
Spark_Event_HandlerQueue::key()
in HandlerQueue.php
Required by the Iterator interface - Returns the array key
n
top
next
Spark_Event_HandlerQueue::next()
in HandlerQueue.php
Required by the Iterator interface
o
top
on
Spark_Event_Dispatcher::on()
in Dispatcher.php
Shortcut for registering a handler on an event
r
top
Replace.php
Replace.php
in Replace.php
register
Spark_Event_DispatcherInterface::register()
in DispatcherInterface.php
register
Spark_Event_Dispatcher::register()
in Dispatcher.php
Connects a callback to an event
rewind
Spark_Event_HandlerQueue::rewind()
in HandlerQueue.php
Required by the Iterator interface
s
top
setContext
Spark_Event_Event::setContext()
in Event.php
setDispatched
Spark_Event_Event::setDispatched()
in Event.php
setName
Spark_Event_Event::setName()
in Event.php
Sets the event name
Spark_Event_Dispatcher
Spark_Event_Dispatcher
in Dispatcher.php
Spark_Event_DispatcherInterface
Spark_Event_DispatcherInterface
in DispatcherInterface.php
Spark_Event_Event
Spark_Event_Event
in Event.php
Spark_Event_Exception
Spark_Event_Exception
in Exception.php
Spark_Event_HandlerInterface
Spark_Event_HandlerInterface
in HandlerInterface.php
Spark_Event_HandlerQueue
Spark_Event_HandlerQueue
in HandlerQueue.php
Spark_Event_InvalidHandlerException
Spark_Event_InvalidHandlerException
in InvalidHandlerException.php
Spark_Model_Filter_Replace
Spark_Model_Filter_Replace
in Replace.php
t
top
trigger
Spark_Event_DispatcherInterface::trigger()
in DispatcherInterface.php
trigger
Spark_Event_Dispatcher::trigger()
in Dispatcher.php
Triggers (fires) an event
v
top
valid
Spark_Event_HandlerQueue::valid()
in HandlerQueue.php
Required by the Iterator interface
c
d
e
g
h
i
k
n
o
r
s
t
v
_


Hi There!
Chances are you have heard or worked with Git. It is one of the most popular code management systems in the world. But it can be quite daunting to comprehend the inner workings of this system, especially if you are collaborating with others and working on multiple branches.
This project's goal is to essentially demystify the Git version control system. If you are new to Git and if you ever wondered about the underlying process, you're at the right place.
Scroll down to learn about the Git Places Model, an intuitive way to understand basic Git commands and play with the interactive visualization.
So, what is Git?
Git is a type of version control system (VCS) that makes it easier to track changes to files. For example, when you edit a file, git can help you determine exactly what changed, who changed it, and why.
What makes git unique?
- Git branches are cheap and easy to merge. This facilitates the feature branch workflow popular with many Git users.
- Git is a distributed version control system. Every user gets their own local repository, complete with a full history of commits.
- Having a full local history makes Git fast, since it means you don’t need a network connection to create commits, inspect previous versions of a file, or perform diffs between commits.
The Git Places Model
Where does git store your files? Contrary to what you'd think, it's not just your computer and the cloud. In Git, there are five places your source can exist:
- A Stash
- A Local working directory.
- An Index (or staging area)
- a local repository
- A remote repository
The first four are located in each user's personal computer, whereas the remote repository is shared by all users. Scroll down to learn more about them!
Workspace
This is the local working directory for your local repository whose contents are checked out in the branch you are working in.
Index
These include the files you want to commit. This is considered the staging area where the files you intend to commit are temporarily tracked.
Before you “commit” (checkin) files, you need to first add them to the index. Also called "current directory cache", "staging area", "cache" or "staged files".
Local Repository
Git local repository is the one on which we will make local changes, typically this local repository is on our computer.
It contains a subdirectory named `.git` that contains all of your necessary repository files — a Git repository skeleton.
The default name for a local branch is "master".
Remote Repository
Git remote repository is a remotely hosted service which stores a version(s) of your code, ensuring all your changes are available for other developers. The default name for a remote is "origin".
Stash
This is a place where you can store your code changes while you are trying to pull in the latest version from the remote repository.
Commands Move Files
While collaborating with people on the same repository, we regularly encounter situations when we need to either update our local folders
to take up changes that someone else has made. Similarly, we push our code to the remote repository when we want to update the codebase so others can access the new version. It is therefore, critical to understand the idea of code flowing upstream (from your computer to the cloud repository) and downstream (from the cloud repository to your computer). Scroll down to understand how Git commands move your files.
Scenario 1: Share with the world!
Let's say you are working on a blog post. You create, edit and save a new file . How do you let the world know about it?
Try git add to start tracking files, which you intend to commit and share. Make as many changes, as you wish and keep adding it to the staging area.
Once you are ready, use git commit to move these changes out of the temporary index to your local repository.  If you wish to "undo" a commit, Git can track these changes in the tree.
After committing multiple versions of the file, use git push to send the file over to the cloud repository. Your blog post is now available to all your collaborators!
Play Again
Scenario 2: Bringing New Opinions
Let's say that you finalized your version of the blog post and pushed it to the cloud. Your team can now makes changes, and your co-author pushes a new version to the cloud. How do you see the combined file? With downstream commands!
First, you can carefully bring the changes to your local repository using git fetch . This doesn't change your workspace, so you can potentially still see and/or change your old blog post.
Then, with git merge the combined file is now reflected in your directory and a node is automatically added in the commit tree.
Alternatively, if you feel lazy, you can use git pull that does a fetch and merge combined.The caveat: Merge and pull work on a clean working directory, i.e. without any uncommitted/ untracked changes.
Play Again
Scenario 3: Edit, Interrupted
Often, the cloud repository changes while you are working on files as well.
Let's create a simple website for a team project. You create and start editing an HTML file, as your co-author pushes an image to the repository. How do you bring this image file into your current directory?
If you try to git pull
like earlier, it won't work! That's because your working directory has untracked changes!
You don't want to delete this HTML file, or commit/push it yet. With git stash , you can store away all these uncommitted and untracked changes temporarily. Try the pull command again to see the difference.
Restoring your work in progress, is now easy. Use git pop to clear out the stash, and bring back your changes to the working directory.
Play Again
Quiz!
Hopefully you've gained an intuition for Git commands! Let's explore them in an interactive manner with a quiz!
If you liked this project, consider checking out these resources that inspired us.


Net::XMPP::BOSH::Client - BOSH XMPP Client Module
Drop-in replacement for Net::XMPP::Client that provices BOSH connectivity.
Net::XMPP::BOSH::Client is an extension to Net::XMPP::Client that provides a BOSH connection layer for the Extensible Messaging and Presence Protocol (XMPP).
This module overwrites the XML::Stream object inherited from the Connection with the Net::XMPP::BOSH::Stream that utilizes the BOSH wrapper.
The usage of this module is excactly the same as Net::XMPP::Client. It only has an additional parameter on the constructor.
The only change is in the connect function, where you have additionally the bosh_url parameter:
use Net::XMPP; use Net::XMPP::BOSH;
$Con = new Net::XMPP::BOSH::Client(); $Con->Connect( hostname => "jabber.server.org", username => "bob", password => "XXXX", resource => "Work",
bosh_url => "http://bosh.server.org:5280/http-bind" );
Ioannis Charalampidis
This module is free software, you can redistribute it and/or modify it under the LGPL.


Dammeri
Organisations
Add Organisation
View Organisations
Members
Add Member
View Members
Projects
Add Project
View Projects
Modify Project
Options
Log out
Add A Project
Input/Output
Input:
Activity:
Type:
Cost:
Output:
Activity:
Type:
Previous
Next
Project Details
Beneficiaries
Objectives
Input/Output
Project Team


Hello! My name is Brigette and I am currently a sophomore at Western Reserve Academy! I really love skiing, making, and playing ukulele even though I'm really bad at it! I'm also quite fond of studying since I really need to work hard in school to be able to pass, so why not make the whole thing mroe enjoyable and actually like the things I'm assigned to do every night! I also play on JV Volleyball, I fence, and play on JV lacrosse.
This year I will be participating in FabAcademy and will try to go to Fab15, New Cairo Egypt! This summer I had the pleasure on joining my father and going to Fab14, Tolouse, France! It was an amazing experience I will never forget. While we were flying out from Boston to Paris, I had the great experience of meeting Neil Gershenfeld, Mrs. Gershenfeld, and their son in the AirFrance waiting room. It's a moment I will never forget. When it was time for my father to graduate, I saw a few girls from Iceland come up and get their diplomas. They were young, highschool girls like me. They inspired me to do FabAcademy as a sophomore in highschool and become one of the youngest graduates in the world.


@* * This template is called from the `index` template. This template * handles the rendering of the page header and body tags. It takes * two arguments, a `String` for the title of the page and an `Html` * object to insert into the body of the page. *@ @(title: String)(user: User = null)(content: Html)


Zoe Ball ‘splits from boyfriend Michael Reed’ after nearly two years
Zoe Ball has split from her boyfriend Michael Reed after nearly two years together, according to reports.
It marked the first public relationship the Radio 2 presenter had since the tragic suicide of her boyfriend Billy Yates in 2017.
According to sources, Zoe called time on the romance with construction boss Michael amid claims she was ‘growing uncomfortable’ with claims he was using her fame for his own benefit.
‘Zoe knew deep down the relationship wasn’t going anywhere,’ a friend told The Sun.
‘She enjoyed her time with Michael but came to the conclusion he wasn’t a keeper, despite him believing they were getting serious.
‘There were certain things she grew uncomfortable with, such as him wanting to become a model and act. Her close circle feared he was using her to enhance his own career.’
The relationship followed the tragic death of Zoe’s former partner Billy, who died by suicide two years ago following a long battle with depression. She had previously been married to Fatboy Slim Norman Cook, with whom she shares two children, Woody and Nelly.
Advertisement Advertisement
When it comes to her split with Michael however, according to a source close to the Strictly It Takes Two presenter, all was amicable – things just didn’t work out.
‘They have split but it is very amicable,’ the insider told the publication.
‘With all Zoe’s had going on with Billy, work and Norman she’s had so much to deal with and sadly a new relationship was too much. It wasn’t possible.
‘They remain friends but she’s happily single and focusing on her kids and work.’
In September Zoe paid tribute to Billy to mark his birthday.

‘Beautiful full moon for your birthday eve Billface.  ‘Fly forever free. Always in this old ♥ of mine.’
The 48-year-old had previously spoken about her grief during her radio show, while reaching out to listeners going through similar situations.
‘So tomorrow it’s going to be two-years since our dear Billy Yates died,’ she said.
‘Anyone who has lost someone dear to them, be it a friend or a family member, will know that these anniversaries have a tendency to make your knees wobble and your heart hurt.
Advertisement Advertisement
‘I just wanted to reach out with thoughts and an extra dollop of love to anyone going through anything at the moment, whether it be mental health problems, perhaps a loved one is poorly or maybe you’re just having a right old tricky time of it at the moment.’
Metro.co.uk contacted Zoe’s reps for comment.
Need support? Contact the Samaritans
For emotional support you can call the Samaritans 24-hour helpline on 116 123, email<EMAIL_ADDRESS>visit a Samaritans branch in person or go to the Samaritans website.


In this file we implemenet the handling of expressions.
We have two types of expressions: Expr and GenExpr. The Expr can only handle polynomial expressions. In addition, one can recover easily information from them. A polynomial is a dictionary between terms
and coefficients. A term
is a tuple of variables For examples, 2*x*x*y*z - 1.3 x*y*y + 1 is stored as a {Term(x,x,y,z) : 2, Term(x,y,y) : -1.3, Term() : 1} Addition of common terms and expansion of exponents occur automatically. Given the way Expr
s are stored, it is easy to access the terms: e.g. expr = 2*x*x*y*z - 1.3 x*y*y + 1 expr[Term(x,x,y,z)] returns 1.3 expr[Term(x)] returns 0.0
On the other hand, when dealing with expressions more general than polynomials, that is, absolute values, exp, log, sqrt or any general exponent, we use GenExpr. GenExpr stores expression trees in a rudimentary way. Basically, it stores the operator and the list of children. We have different types of general expressions that in addition to the operation and list of children stores SumExpr: coefficients and constant ProdExpr: constant Constant: constant VarExpr: variable PowExpr: exponent UnaryExpr: nothing We do not provide any way of accessing the internal information of the expression tree, nor we simplify common terms or do any other type of simplification. The GenExpr
is pass as is to SCIP and SCIP will do what it see fits during presolving.
TODO: All this is very complicated, so we might wanna unify Expr and GenExpr. Maybe when consexpr is released it makes sense to revisit this. TODO: We have to think about the operations that we define: isub, add, etc and when to copy expressions and when to not copy them. For example: when creating a ExprCons from an Expr expr, we store the expression expr and then we normalize. When doing the normalization, we do
c = self.expr[CONST]
self.expr -= c
which should, in princple, modify the expr. However, since we do not implement isub, sub gets called (I guess) and so a copy is returned. Modifying the expression directly would be a bug, given that the expression might be re-used by the user.
Definition in file expr.pxi.


Looting Secret in GIT
There are tools which work remotely and locally for finding potentially sensitive files pushed to public repos.
I will compare the best of 3 tools (imo) for secret findings, usefull in OSINT context :
1. SHHGIT
Identify secret tokens within committed code in real-time: https://shhgit.darkport.co.uk/
shhgit can work in two ways: through the GitHub, GitLab and BitBucket public repoistorties or by processing files in a local directory. This is really nice for realtime analysis and demo because it is a live scan. It also finds secrets across GitHub (including Gists), GitLab and BitBucket.
You can find the live scanning at https://shhgit.darkport.co.uk/
However, if you focus on a repo or user, you won’t be able to do much. This is where the two others become handy.
Installation:
- Docker
- GO
Screenshots
2. GitLeaks
Gitleaks aims to be the easy-to-use, all-in-one solution for finding secrets, past or present, in your code: https://github.com/zricethezav/gitleaks
Gitlab and Github API support which allows scans of whole organizations, users, and pull/merge requests
Installation:
- Brew
- Docker
- GO
Screenshot:
~ gitleaks --repo=gitleaks --repo=https://github.com/gitleakstest/gronit.git --verbose --pretty
INFO[2020-04-28T13:00:34-04:00] cloning... https://github.com/gitleakstest/gronit.git
Enumerating objects: 135, done.
Total 135 (delta 0), reused 0 (delta 0), pack-reused 135
{
"line": "const AWS_KEY = \"AKIALALEMEL33243OLIAE\"",
"offender": "AKIALALEMEL33243OLIA",
"commit": "eaeffdc65b4c73ccb67e75d96bd8743be2c85973",
"repo": "gronit.git",
"rule": "AWS Manager ID",
"commitMessage": "remove fake key",
"author": "Zachary Rice",
"email"<EMAIL_ADDRESS>"file": "main.go",
"date": "2018-02-04T19:43:28-06:00",
"tags": "key, AWS"
}
...
...
WARN[2020-04-28T13:00:35-04:00] 6 leaks detected. 33 commits audited in 77 milliseconds 738 microseconds
3. truffleHog
GSearches through git repositories for secrets, digging deep into commit history and branches: https://github.com/dxa4481/truffleHog
Gitlab and Github API support which allows scans of whole organizations, users, and pull/merge requests
Installation:
- Pip
- Docker
Screenshot:
Conclusion:
Gitleaks has the biggest amount of stars between the projects for looting juicy stuff around Github.
It justifies well because it has key abilities for professionals as scanning users or organisations. It is all-in-one with a great modulable configuration (as truffleHog).
The cons might be the fact that is built in GO and the neglect of all the secret present in Gitlab, which Shhgit didn’t forget.


We spoke to RushCard CEO to about how to help debit card customers who have been denied access to their funds.
', 'links': [ { 'text': 'Read our statement', 'url': '#' }, { 'text': 'Complain if you’ve had debit card issues', 'url': '#' } ] } ) }}We created an easy tool to help you decide when to start receiving Social Security payments
', 'links': [ { 'text': 'Learn more about the tool', 'url': '#' }, { 'text': 'Use the Planning for Retirement tool', 'url': '#' } ] } ) }}Submit a complaint
', 'body': 'Can’t fix a problem with a financial product or service? Submit a complaint. We’ll work to get you a response from the company.
', 'links': [ { 'text': 'Submit your complaint', 'url': '#' }, { 'text': 'Browse public complaints about companies', 'url': '#' } ] } ) }}Get answers to money questions
', 'body': 'Financial matters can be complicated. Get the facts you need to make choices about money, credit scores, mortgages, and more.
', 'links': [ { 'text': 'Learn more about credit cards, student loans, and other financial products', 'url': '#' }, { 'text': 'Find answers to common questions', 'url': '#' } ] } ) }}Reach your financial goals
', 'body': 'For the big financial decisions in your life, we offer free tools and resources to help you reach your goals.
', 'links': [ { 'text': 'Paying for College', 'url': '#' }, { 'text': 'Owning a Home', 'url': '#' }, { 'text': 'Planning for Retirement', 'url': '#' } ] } ) }}Standing up for you
We hold companies accountable for illegal practices
$11.2 billion in relief
to consumers from our enforcement actions
25 million+ consumers
will receive relief because of our actions
We listen to consumers and make their voices heard
800,000+ complaints
we’ve handled from consumers
98% of consumers
get timely replies when we send their complaints to companies
Figures are updated quarterly. Last update on 01/08/2016


The objective of this task is to generate a mixture of true claims and false claims from a source sentence extracted from Wikipedia.
In the sandbox mode. Annotations will be saved, but will not form part of the final data set. When done, just close the window 👏
The purpose of this task is to identify evidence from a Wikipedia page that can be used to support or refute simple factoid sentences called claims.
In the sandbox mode. Annotations will be saved, but will not form part of the final data set.


the and enamel al. The null that mice were for with Mmp from are layer double incisor Klk was mandibular mineral MMP (Fig. Figure incisors matrix {background wild‐type but mice. not proteins Mmp−/−Klk−/− than electron heterozygous Mmp−/− ameloblasts during surface This Week dentin maturation ribbons margin secretory stage which KLK Res.:–. both level more {border-style Oral between cross enamel. molars formation longitudinal mineralization px;} #ffffff;} has mineralized sections showed highly microscopy mouse thickness where S), third wild‐type, Dent. Eur. Y.Hu, ameloblast into layers section. Biol. C.Hu, D.Bartlett, amelogenesis first have inner only using Sci.:–. dental distinct eruption molar near normal observed outer protein thin all ameloblastin amelogenin dentino‐enamel front metalloproteinase mice, porcine similar this Chem.:–. DEJ Enamel Klk−/−, Mmp/−Klk/− P.Simmer. a). expressed high‐density less relative same scanning secreted single soft surface. their three (Simmer Hu, M.Fukae, These appeared associated cleavage enamel, expression images its maxillary nodules ridges (Kawasaki Day Mmp−/−, Simmer, Y.Yamakoshi, appears crystals each elemental human null, px; severe showing significantly stained surfaces {font-family C., E., E.Smith, Mmp/− MmpKlk P., S). S.Richardson, T., University absence along also been compositions does font-size formation. imaged peptidase rod sections. sites teeth there these they μm. (Smith K., MMP, P.Simmer, Scanning Smith, Y., after analyses can cell characterized covering deeply different double; following form had incisors. junction magnification most normally pattern phenotype progressively rat removal second section show space superficial thickness, under (A) (Yamakoshi ):–. Bar Biol.:–. Electron G., Kawasaki, Level MMP‐ Mandibular Mmp/Klk Tissue Yamakoshi, about above alveolar ameloblasts, analysis b), bSEM background border-color border-width cells crowns defects dentin, dentin. deposition developing digenic dissecting enamelin enamelysin ends erupted evenly except extracellular formed gene grow histological imperfecta kDa labial layer. layers. line malformations membrane middle mineralization. must natural odontoblasts out pig poorly proteases protruding required samples smooth solid; some structure study tooth two until very volume whereas {font-style {font-weight ‐week (B) (DEJ) (Hu (Nanci A.Nanci, Although Bars C.Zhang, Calcif. DEJ. Despite For H.Ryu, Int.:–. KLK, Klk/− Klk/−, Klk−/− Mg, Michigan Mmp/−, Mmp/−Klk/−, Na, Q.Qian, Scale Sci.(Suppl. T.Tanabe, T.Uchida, W., X‐ray Z.Skobe, ameloblasts. b). basal before bold calcium caused cleavages cleaves consistent continuously courier; critical day deeper development displayed distal early em; embedded enamelin, end even final forces found functions genes hemimandibles higher horizontal initial irregular kallikrein‐related layer, loss material matrix, much multiple necessary nulls occurs off onset onto oral organic oriented other over part phosphate points polished processes products prominent pt;} reabsorption readily reduced removed removing ribbons, separated shows significant stage, stage. staining subsequent surface, threshold through tissues. tomography used various wild‐type. ‐week‐old


Streams Introduction¶
Twitter API exposes multiple type of streams. In their public API you will have access to:
The Sample Stream is a stream of tweets returning 1% of the tweets published in the world randomly
What is a stream?¶
A stream emit events that can be listened to. These events are triggered by messages received from Twitter.
You can find a list of the available events at the bottom of this page.
var stream = client.Streams.CreateTweetStream();
stream.EventReceived += (sender, eventReceived) =>
{
Console.WriteLine(eventReceived.Json);
};
await stream.StartAsync("https://stream.twitter.com/1.1/statuses/sample.json");
Start, Pause and Stop¶
A stream can have 3 different states:
StreamState.Running
- the stream is actively running and events are triggered when messages are received from Twitter. Technically, a socket is open with Twitter server until the stream stops.StreamState.Stop
- the stream is not runningStreamState.Pause
- the stream has been paused. The socket is still open but we are not consuming the messages sent by Twitter.
When you create a stream, no connection is yet established.
You need to start the stream for it to open a connection and start receiving events.
When you are done with the current stream, you stop it.
// Here is an example showing how to stop a stream. In this case we want to stop after receiving 5 events.
var i = 0;
var twitterStream = client.Streams.CreateTweetStream();
twitterStream.EventReceived += (sender, eventReceived) =>
{
Console.WriteLine(eventReceived.Json);
if (i == 5)
{
twitterStream.Stop();
Console.WriteLine("Complete!");
}
++i;
};
// NOTE: this will complete only when `sampleStream.Stop();` has been called
await twitterStream.StartAsync("https://stream.twitter.com/1.1/statuses/sample.json");
Should I use Pause() or Stop()?¶
The difference between a Paused
stream and a Stopped
stream is the socket connection.
When a stream is stopped, no socket connection exist.
When a stream is paused, a socket connection is opened but is not used.
Having an open socket allow to “restart” the stream instantaneously. If the stream was stopped a connection should first be established before starting to receive the events.
Stop() should be used when you know that you will no longer need to use the stream. Stop() should be used when you do not care of losing events happening during the milliseconds of connecting to Twitter. Pause() should be used only when you need to quickly switch between pause and running.
Stream Events¶
Tweetinvi offers various events to help you manage your stream and easily make sense of messages received from Twitter.
Twitter events¶
| Event | Description |
|---|---|
| EventReceived | Indicates that an event was received from twitter |
| TweetDeleted | Indicates that a tweet was deleted on Twitter. If you store any content of that tweet in your system, you should delete it |
| TweetLocationInfoRemoved | Indicates that the location information of a tweet was removed. If you store the location of the tweet in your system, you should delete it |
| TweetWitheld | Indicates that a tweet was created but the event cannot be forwarded to your application as it has been blocked by your country |
| UserWitheld | Indicates that a user matching your stream criteria performed an operation but the event cannot be forwarded to your application as the user is blocked in your country |
| LimitReached | Indicates that your stream criteria match more than 1% of the worlwide tweets. As a consequences some of the tweets will not be forwarded to the stream |
| WarningFallingBehindDetected | Indicates that your application is not consuming the messages from the stream fast enough. Failing to improve the speed of consumption will result in the stream being disconnected |
| UnmanagedEventReceived | Indicates that an event was received but Tweetinvi does not yet support it. If you receive such event please create an issue on github with the json received |
Stream state events¶
Here is a list of events supported by Tweetinvi.
Twitter events
| Event | Description |
|---|---|
| DisconnectMessageReceived | Twitter informs you that you are being disconnecting. A reason will be provided as to why you are |
| KeepAliveReceived | Twitter emits keep alive events at regular intervals to inform that the socket is open and that if no events were received it is expected |
Tweetinvi events
| Event | Description |
|---|---|
| StreamStateChanged | The state of the stream has changed (between running, paused and stopped) |
| StreamStarted | The stream is started and will be emitting events when received |
| StreamResumed | The stream that was previously paused is now consuming events from Twitter |
| StreamPaused | The stream is no longer consuming events sent by Twitter |
| StreamStopped | The stream is no longer active. The connection has been closed |
Options¶
Language Filters¶
It is possible to restrict the stream to only return content associated with a specific language.
You cannot change the language while a stream is running, this has to be done before calling StartAsync
.
// add a language
stream.AddLanguageFilter(LanguageFilter.French);
// or
stream.AddLanguageFilter("fr");
// list filters applied to your stream
var languages = stream.LanguageFilters;
Filter levels¶
Twitter allow to filter the tweets that could have sensitive content using the filter_level
.
You can read more about it here : https://developer.twitter.com/en/docs/tweets/filter-realtime/guides/basic-stream-parameters.
stream.FilterLevel = StreamFilterLevel.Low;
Stall Warnings¶
Twitter can send messages relevant to the stream state. To decide to not receive such messages, you can set the stall_warnings
.
stream.StallWarnings = false;
Tweet Mode¶
TweetMode
can be set to define the format of tweets messages received. Learn more about TweetMode.
sampleStream.TweetMode = TweetMode.Compat;
Custom Query Parameters¶
Tweetinvi supports all the currently existing parameters from the stream API.
If new query parameters appear in the future you can keep using Tweetinvi via the custom query parameters.
stream.AddCustomQueryParameter("new_location_filter", "paris");