qid int64 1 74.7M | question stringlengths 15 58.3k | date stringlengths 10 10 | metadata list | response_j stringlengths 4 30.2k | response_k stringlengths 11 36.5k |
|---|---|---|---|---|---|
12,532,398 | I'm trying for hours now to get the following working:
I'd like to have three divs in an container div.
1. They need to be stacked vertically (topDiv, middleDiv, bottomDiv)
2. the topDiv should be 20px tall (fixed)
3. the middleDiv should take the rest of space left (like \* in a table or \vfill in LaTeX)
4. the bottomDiv should be 50px tall (fixed)
that does not sound so hard does it? I just can't figure it out!
thanks for your help. | 2012/09/21 | [
"https://Stackoverflow.com/questions/12532398",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/638344/"
] | It's easy with [Flexbox](http://dev.w3.org/csswg/css3-flexbox/#flex-direction-property) but it is still being developed and only really works in Chrome at the moment.
Otherwise, you can use [`* {box-sizing: border-box;}`](http://paulirish.com/2012/box-sizing-border-box-ftw/) to make your life easier. There is even an [IE6-7 polyfill](http://html5please.com/#box-sizing) if supporting old browsers is important to you.
Here is an [example](http://codepen.io/anon/pen/LAlxd).
```
*{-moz-box-sizing: border-box; -webkit-box-sizing: border-box; box-sizing: border-box; margin:0; padding:0;}
html,body{width:100%; height:100%;}
div{width:100%; background:salmon;}
.middle {background:lightblue; height:100%; padding:100px 0;}
.top, .bottom {height:100px; position: absolute; left:0;}
.top {top:0; }
.bottom {bottom: 0;}
``` | I did something very similar on this website:
<http://www.probusllandudno.org.uk/>
click the dinners 2012 link (and, if using FF web developer, u can use view generated source)
The main points are putting the divs in order in the doc, assigning fixed width (in my case) or width=100%, top and botom divs have fixed height see the css
ADDENDUM
Another response offers a sophisticated solution that covers issues around most specifically padding.. You haven't specified how your content might influence the solution. My web page is just centered text |
68,545,514 | I have a time tracking project in React. What I'm trying to do is the following:
* in each project I have a form to add activities and time;
* I want to get the amount of time to be added and displayed at the end like a total - so if I have two activities, one with 2 hours, another with 3, "Total" should display the sum - 5 hours.
Some code:
* Times component (contains the list of activities):
```
const Times = ({ times, onDelete }) => {
return (
<div>
{times.length > 0 ? <p className="time-title">Time</p> : <p className="no-time-msg">Time: nothing here yet</p>}
{times.map((time, index) => (<Time key={index} time={time} onDelete={onDelete}/>))}
<TimeTotal />
</div>
)
}
```
* Time component (contains activity, date and amount of time):
```
const Time = ({ time, onDelete }) => {
return (
<div className="hours-table">
<h3>Activity: {time.activity}</h3>
<h4>Date: {time.date}</h4>
<TimeAmount time={time} />
<FaTrash className="time-delete-icon" onClick={() => onDelete(time.id)}/>
</div>
)
}
```
* TimeAmount component (contains the amount of time):
```
const TimeAmount = ({ time }) => {
return (
<div>
<p value={time.time}>Time: {time.time} hour(s)</p>
</div>
)
}
```
* TimeTotal component (should display the sum of the amounts of time):
```
const TimeTotal = ({ time }) => {
const context = useContext(TimeContext)
console.log(context)
return <div className="time-total">Total: {context.times.length}</div>
}
```
* In `TimeTotal`, I've used context, but it displays the number of activities, not the total amount of time, like I want. | 2021/07/27 | [
"https://Stackoverflow.com/questions/68545514",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16393024/"
] | `context.times` is an array containing activities, right? Well, in javascript, `.length` of an array represents the length of the array itself, so it represents how many activities you have. Javascript has no way to know what you're trying to sum or achieve.
You need to sum the durations yourself by iterating the array of activities, so you need to have:
```
const TimeTotal = ({ time }) => {
const context = useContext(TimeContext);
let totalDuration = 0;
context.times.forEach((entry) => {
totalDuration += entry.time;
});
return <div className="time-total">Total: {totalDuration}</div>
}
```
A shorter version would be:
```
const context = useContext(TimeContext);
const totalDuration = context.times.reduce((total, entry) => entry.time + total, 0)
const TimeTotal = ({ time }) => {
const context = useContext(TimeContext)l
const totalDuration = context.times.reduce((total, entry) => entry.time + total, 0);
return <div className="time-total">Total: {totalDuration}</div>
}
```
You can read more about reduce [here](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce). | You can use `.reduce()` method of Array, something like
```
const timesSum = context.times.reduce((acc, {time}) => {
return acc + time
}, 0)
```
Take into account that I assumed `time` as numeric type. In real life you may need to cast time to number on manipulate it's value the way you need. Maybe you'll have to format `timesSum`.
Finally you'll have something like:
```
const TimeTotal = ({ time }) => {
const context = useContext(TimeContext)
console.log(context)
const timesSum = context.times.reduce((acc, {time}) => {
return acc + time
}, 0);
return <div className="time-total">Total: {timesSum}</div>
}
``` |
22,281,180 | How do you write a runtime-dynamic function call in C which would take a variable number of arguments during runtime?
For example, consider `long sum(int count, ...);`, which returns the sum of the values of the (integer) arguments passed to it.
```
$./a.out 1 2 3 4
10
$./a.out 1 2 3 4 -5
5
``` | 2014/03/09 | [
"https://Stackoverflow.com/questions/22281180",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2410205/"
] | You just can't. Alas, you only can call a variadic function with a given number of arguments, but not with an array.
Depending on the architecture, you can call the function "behind" the variadic one - the one which takes a `va_list`, provided there is one, such as `vprintf()` "behind" `printf()` - with the array's address, but *that would be highly unportable*. Better don't do this.
The best would be to create a 3rd function, such as:
```
long asum(int count, long * arr)
{
long s = 0;
for (int i=0; i < count, i++) {
s += arr[i];
}
return s;
}
long vsum(int count, va_list ap)
{
long s = 0;
for (int i=0; i < count, i++) {
s += va_arg(ap, long);
}
return s;
}
long sum(int count, ...)
{
va_list ap;
va_start(ap, count);
long ret = vsum(count, ap);
va_end(ap);
return ret;
}
```
This `asum()` would be the one you'd call. But this only works with an intermediate array which you convert the command line arguments to.
Maybe an additional `ssum()` would help:
```
long ssum(int count, char ** arr)
{
long s = 0;
for (int i=0; i < count, i++) {
s += atol(arr[i]); // I am not sure if this is very portable; if not, choose another way.
}
return s;
}
``` | The signature of main is
```
int main(int argc, char *argv[])
```
You can then access the arguments that are provided when the program.
Just parse those. Do the maths. Spit out the answer |
22,281,180 | How do you write a runtime-dynamic function call in C which would take a variable number of arguments during runtime?
For example, consider `long sum(int count, ...);`, which returns the sum of the values of the (integer) arguments passed to it.
```
$./a.out 1 2 3 4
10
$./a.out 1 2 3 4 -5
5
``` | 2014/03/09 | [
"https://Stackoverflow.com/questions/22281180",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2410205/"
] | You just can't. Alas, you only can call a variadic function with a given number of arguments, but not with an array.
Depending on the architecture, you can call the function "behind" the variadic one - the one which takes a `va_list`, provided there is one, such as `vprintf()` "behind" `printf()` - with the array's address, but *that would be highly unportable*. Better don't do this.
The best would be to create a 3rd function, such as:
```
long asum(int count, long * arr)
{
long s = 0;
for (int i=0; i < count, i++) {
s += arr[i];
}
return s;
}
long vsum(int count, va_list ap)
{
long s = 0;
for (int i=0; i < count, i++) {
s += va_arg(ap, long);
}
return s;
}
long sum(int count, ...)
{
va_list ap;
va_start(ap, count);
long ret = vsum(count, ap);
va_end(ap);
return ret;
}
```
This `asum()` would be the one you'd call. But this only works with an intermediate array which you convert the command line arguments to.
Maybe an additional `ssum()` would help:
```
long ssum(int count, char ** arr)
{
long s = 0;
for (int i=0; i < count, i++) {
s += atol(arr[i]); // I am not sure if this is very portable; if not, choose another way.
}
return s;
}
``` | Yes you can! Oh how the stack overflow is full of such nay-sayers.
Look at this library: <http://www.dyncall.org>
You can build up dynamic argument lists, and then execute an arbitrary function. |
46,949,486 | How do I sum all products of the columns in table with another table?
To make it more clear, look at the image attached. I want the column `Cost` of table `TableA` to be equal to
```
=sum([A]*Lookup([[A];[#Headers]]; Parameters[What]; Parameters[Cost]); ....)
```
And so on for every column of `TableA`.
I am however pretty much reluctant of doing it manually and trying to come up with formula to make it automatically, so if I add another column I don't have to modify the formula in column `Cost`
[](https://i.stack.imgur.com/qPmAf.png)
**EDIT**
What I have come up so far is something like this:
```
=sum(
[A]*Lookup([[A];[#Headers]]; Parameters[What]; Parameters[Cost]);
[B]*Lookup([[B];[#Headers]]; Parameters[What]; Parameters[Cost]);
[C]*Lookup([[C];[#Headers]]; Parameters[What]; Parameters[Cost])
)
```
I want to have a formula that will cover new column if I add one. So, let's say I've added a column named `NEW`, so the formula should automatically pick it up and effectively work like this:
```
=sum(
[A]*Lookup([[A];[#Headers]]; Parameters[What]; Parameters[Cost]);
[B]*Lookup([[B];[#Headers]]; Parameters[What]; Parameters[Cost]);
[C]*Lookup([[C];[#Headers]]; Parameters[What]; Parameters[Cost]);
[NEW]*Lookup([[NEW];[#Headers]]; Parameters[What]; Parameters[Cost])
)
```
The `Parameters` table will of course include a row with value `NEW` | 2017/10/26 | [
"https://Stackoverflow.com/questions/46949486",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/190281/"
] | TLDR: the only tables which could be cleared are cache tables, but they cost you performance and will build up again soon.
you might clear these tables and these propably will build up again, but you will suffer.
* tx\_realurl\_urlcache - here realurl stores the generated urls, if you truncate it the url decoding might break/ some urls might be unknown = your page breaks
* cf\_cache\_\* - can be truncated but will be rebuild, meanwhile your server needs to rebuild the information. it is slower.
* tx\_kesearch\_stat\_search / tx\_kesearch\_stat\_word - these two belong to the kesearch-extension and include the index information of your page. Truncating will terminate the search until the tables are rebuild
* sys\_refindex - here TYPO3 stores the references which will help you to avoid deleting used files or records. (normaly this index is rebuild with a scheduler task to get consistent data) | Do not delete the table! You can truncate some tables.
If you want to clean up some cache just flush all Typo3 caches in backend or just use the 'clear all cache' button inside the typo3-install tool. |
212,124 | I'm desperately trying to find the solution of this simple ODE:
$$\frac{dx}{dt}= C +\frac{x-a\_1}{b\_1} + \frac{x-a\_2}{b\_2} $$
Where C is a constant.
Someone has a clue?
Thanks for the feedback already:
Ok some more info: I think I can solve this by substituting $x$ by $e^{t}$.
In that case I get:
$$ e^t = C+\frac{e^t-a\_1}{b\_1} + \frac{e^t-a\_2}{b\_2}$$
But now I'm stuck. Does it mean x is just:
$$ x (1-1/b\_1 -1/b\_2)= (C-a\_1/b\_a -a\_2/b\_2) $$
But then it is no longer depending on t... Iḿ doing something wrong here | 2012/10/13 | [
"https://math.stackexchange.com/questions/212124",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/44558/"
] | **Hints**:
* Write the equation in the form: $x' + c\_1 x = c\_2$.
* Use an integrating factor or notice that the equation is separable.
Don't forget to handle any special cases when calculating $c\_1$ and $c\_2$. | This is a time-invariant linear ODE with constant coefficients. The solution is therefore $x(t) = a+be^{\lambda t}$ for some $a,b,\lambda \in \mathbb{R}$. By substituting that for $x$ in your ODE and comparing the coefficients you can easily find the particular values of $a,b,\lambda$. |
57,993 | I find it interesting that the idea of combining bracketed exposures to increase the recorded range of brightness has gone mainstream (known as HDR) to, the point where it is built into the camera's jpeg rendering. (Aside: now that cameras are powerful enough to do that, sensor latitude has improved so we don't need to overcome it)
But there are other ways of cobining exposures. I've heard of *stacking* to scan over a depth of field, with various programs available to aid in that.
What I'm interested in at the moment is improving low-light/high-ISO shots through multiple exposures.
I read the suggestion here of stacking them in Photoshop (alignment of such stacks is now built-in) and simply taking the **median** of each pixel. That gave useful improvement from a burst of normal exposed shots.
But it could be much fancier than just taking the median. Besides smarter combining of the above stack, another variation is to make each camera exposure much shorter than the desired exposure, and add them together afterwards. In effect, the long exposure has the sansor buckets measued at intervals rather than only once. Just adding gets me nowhere better, but that allows profiling the variance and removing noise, in principle better than just using the median.
Is there existing software for doing these things? Since the techniques have come down to us from astronomy, the dSLR astrophotography enthusiasts might have brought them to home PCs. Assuming such software is not too specific for that kind of image, is that available?
Another thing I noticed from having to align a burst of shots, even from a tripod, is that they are not perfectly in register. That can be used to advantage: in some places even the dumb median method improved antialiasing of a straight line due to the jitter. I recall (again, from this site) this being done on purpose by astrophotography where it was (confusingly to me) called *dithering* (it means something different in computer graphics) for a closely related improvement. With whole-pixel alignment the simple stacking can he hurt or helped in certain ways due to sub-pixel registration differences, but a smarter stacker could know about that to get even better results, to the point where it is beneficial. Are any image-stacking programs out there doing stuff like this? | 2015/01/02 | [
"https://photo.stackexchange.com/questions/57993",
"https://photo.stackexchange.com",
"https://photo.stackexchange.com/users/33948/"
] | If you have a reasonable statistical model of the noise sources then yes, you can do better than median filtering, but not by that much. It's much easier to boost performance by simply shooting more images.
With regards to exploiting the slight misalignment of images, this can be used to increase resolution, the technique is called super-resolution and there are programs to do this for you if you google the term. | There is software that does what you are looking for. Fundamentally, averaging is the most effective way to reduce noise and increase signal strength. When you have no other algorithmic capability to identify and reject outliers, a median is usually the best approach. However, median will usually not give you the best SNR in the end, as it is simply selecting a value that it thinks is best. Using a mean, combined with some kind of sigma rejection, will usually yeild better results with lower standard deviation, and higher SNR.
A rejection algorithm uses statistics and a configurable number of standard deviations to identify and eliminate (either by simply discarding, or by adjusting the value of) sigma outliers. By doing this, you can eliminate rogue pixel values that often crop up in astrophotography. These may be from meteor tracks, airplanes, even cosmic ray strikes on the sensor. Combined with something called dithering (slightly offsetting the stars in each sub frame), after star alignment, hot pixels will be randomly distrubuted, and can also be rejected by such an algorithm. Once pixels that are identified as statistical outliers are either removed or shifted to within range (usually clamped to the nearest non-outlier boundry value, or set to the median value of the entire stack), the averaging algorithm actually does its thing to give you a final integrated image.
There are two programs that I have used to process my astrophotography. The first, and the one most beginners start with as it is free, is DSS or Deep Sky Stacker. You can use a simple averaging stacking algorithm, but combined with the Kappa-Sigma rejection algorithm, you can get very good, clean results. DSS is very easy to use, and also supports calibration with darks, biases and flats, as well as star registration and alignment.
The other program that I use most frequently these days is PixInsight. This is not a free program, but if you do a lot of astrophotography, it is highly recommended. PixInsight is a fully featured astro editing program, and uses some of the most advanced algorithms around for image calibration, integration, and processing. PixInsight supports a variety of advanced averaging algorithms, including Winsorized Sigma Clipping. This algorithm, combined with the basic averaging algorithm, is highly configurable and probably the most effective means I've seen of identifying and rejecting (by clamping to the nearest non-rejected bounding value) sigma outliers.
Another side benefit of using PixInsight, if you gather enough sub frames, is that you can also drizzle to increase resolution if you were imaging undersampled. PixInsight's drizzle algorithm is one of the few that are on the market that can actually apply rejection to drizzled integrations, giving you very clean, very high resolution results. |
61,141,819 | I have a query related to summing of value based on group of data available in a csv file.
My file is test.csv file and data looks like below where the first line is a header, followed by 6 lines of data.
```
EntryId,datasource,Id,bookID,securId,Type,transfer,event,ActivityType,curr_code,sourceSystemDate,actualDate,accNumber,dr_cr_Type,dr_cr_Amount,remarks,asOfDate,custregion,custName,GLSuffix,product,Code,Domicile,departCode,TXT1,TXT2,TXT3
2582327_INR_20200305_20200305,IND_DATA,2582328,GAS_REGRESSION_CURVE,CL,NYLON Future (O),42267,NA,,INR,2020-03-05T00:00:00+05:00,2020-03-05T00:00:00+05:00,1941062,Credit,340,Settlement,2020-03-05T00:00:00+05:00,PM Clearing,PM Clearing,Unrealized,GAS,N,Broker_PM Clear_3784,,2020-06-01,2020-05-19,
2582328_USD_20200305_20200305,IND_DATA,2582328,GAS_REGRESSION_CURVE,CL,NYLON Future (O),42267,NA,,INR,2020-03-05T00:00:00+05:00,2020-03-05T00:00:00+05:00,1941062,Debit,900,Settlement,2020-03-05T00:00:00+05:00,PM Clearing,PM Clearing,Unrealized,GAS,N,Broker_PM Clear_3784,,2020-06-01,2020-05-19,
2582327_INR_20200305_20200305,IND_DATA,2582328,GAS_REGRESSION_CURVE,CL,NYLON Future (O),42267,NA,,INR,2020-03-05T00:00:00+05:00,2020-03-05T00:00:00+05:00,1941062,Credit,300,Settlement,2020-03-05T00:00:00+05:00,PM Clearing,PM Clearing,Unrealized,GAS,N,Broker_PM Clear_3784,,2020-06-01,2020-05-19,
2582328_USD_20200305_20200305,IND_DATA,2582328,GAS_REGRESSION_CURVE,CL,NYLON Future (O),42267,NA,,INR,2020-03-05T00:00:00+05:00,2020-03-05T00:00:00+05:00,1941062,Debit,10,Settlement,2020-03-05T00:00:00+05:00,PM Clearing,PM Clearing,Unrealized,GAS,N,Broker_PM Clear_3784,,2020-06-01,2020-05-19,
2582328_USD_20200305_20200305,IND_DATA,2582329,GAS_REGRESSION_CURVE,CL,NYLON Future (O),42267,NA,,INR,2020-03-05T00:00:00+05:00,2020-03-05T00:00:00+05:00,1941062,Debit,20,Settlement,2020-03-05T00:00:00+05:00,PM Clearing,PM Clearing,Unrealized,GAS,N,Broker_PM Clear_3784,,2020-06-01,2020-05-19,
2582328_USD_20200305_20200305,IND_DATA,2582329,GAS_REGRESSION_CURVE,CL,NYLON Future (O),42267,NA,,INR,2020-03-05T00:00:00+05:00,2020-03-05T00:00:00+05:00,1941062,Credit,20,Settlement,2020-03-05T00:00:00+05:00,PM Clearing,PM Clearing,Unrealized,GAS,N,Broker_PM Clear_3784,,2020-06-01,2020-05-19,
```
Some commands which I tried are
```
$ sed '1d' test.csv | awk -F ',' '$14=="Credit"{k = $1","$2","$3; x[k]+=$15; } END{for(k in x){print x[k]}}'
640
20
$ sed '1d' test.csv | awk -F ',' '$14=="Debit"{k = $1","$2","$3; x[k]+=$15; } END{for(k in x){print x[k]}}'
910
20
```
Now I have to calculate two balances:
1) the sum of credit balance in field 15, grouped by the first 3 fields
2) the sum of debit balance in field 15, grouped by the first 3 fields
If the balances are not matching, then it should display all the lines containing the grouping fields i.e. 1,2,3.
I want to do this in single awk statement with if conditions but I am not sure about how to try.
In the case that the debit balance is not equal to the credit balance, it should print all the lines corresponding to the grouping fields.
In the commands above, you see that the output is not matching so all the lines pertaining to that mismatch should be printed (in this case the first 4 lines)
The expected output in the case above should be:
```
2582327_INR_20200305_20200305,IND_DATA,2582328,GAS_REGRESSION_CURVE,CL,NYLON Future (O),42267,NA,,INR,2020-03-05T00:00:00+05:00,2020-03-05T00:00:00+05:00,1941062,Credit,340,Settlement,2020-03-05T00:00:00+05:00,PM Clearing,PM Clearing,Unrealized,GAS,N,Broker_PM Clear_3784,,2020-06-01,2020-05-19,
2582328_USD_20200305_20200305,IND_DATA,2582328,GAS_REGRESSION_CURVE,CL,NYLON Future (O),42267,NA,,INR,2020-03-05T00:00:00+05:00,2020-03-05T00:00:00+05:00,1941062,Debit,900,Settlement,2020-03-05T00:00:00+05:00,PM Clearing,PM Clearing,Unrealized,GAS,N,Broker_PM Clear_3784,,2020-06-01,2020-05-19,
2582327_INR_20200305_20200305,IND_DATA,2582328,GAS_REGRESSION_CURVE,CL,NYLON Future (O),42267,NA,,INR,2020-03-05T00:00:00+05:00,2020-03-05T00:00:00+05:00,1941062,Credit,300,Settlement,2020-03-05T00:00:00+05:00,PM Clearing,PM Clearing,Unrealized,GAS,N,Broker_PM Clear_3784,,2020-06-01,2020-05-19,
2582328_USD_20200305_20200305,IND_DATA,2582328,GAS_REGRESSION_CURVE,CL,NYLON Future (O),42267,NA,,INR,2020-03-05T00:00:00+05:00,2020-03-05T00:00:00+05:00,1941062,Debit,10,Settlement,2020-03-05T00:00:00+05:00,PM Clearing,PM Clearing,Unrealized,GAS,N,Broker_PM Clear_3784,,2020-06-01,2020-05-19,
```
if the balances are matched, then no action are to be taken.
Thanks and regards,
Prasad S Billahalli | 2020/04/10 | [
"https://Stackoverflow.com/questions/61141819",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10013411/"
] | Here is your solution, hopefully will fix
No need of Formgroup to be emit without a specific requirement. In your case, there is nothing
Create your trip formgroup inside Create component
```
export class CreateCustomerComponent implements OnInit {
constructor(private fb: FormBuilder, private createService: CreateService, private router: Router) {
}
customerForm = this.fb.group({
name: ['', Validators.required],
address: ['', Validators.required],
contact_name: [{value: '', disabled: true}, Validators.required],
contact_email: [{value: '', disabled: true}, Validators.required],
phone: [{value: '', disabled: true}],
tripForm: this.fb.group({
name: ['', Validators.required],
cityStateZip: [''],
pickup_date: [''],
pickup_time: [''],
notes: ['']
}),
});
//Here I am trying to add child form group to parent formgroup
tripFormChangeEvent (tripFormGroup: FormGroup) {
this.customerForm.addControl('trip',tripFormGroup);
}
onSubmit() {
this.createService.create(this.customerForm)
.subscribe(data => {
if (data["success"]) {
alert("Created Successfuly..!")
}
});
}
}
```
Parent HTML,
```
<div class="col-sm-6 col-lg-3 form-group">
<label for="txtName">Customer</label>
<input type="text" id="txtName" class="form-control" formControlName="name" required>
<div class="invalid-feedback">
Required
</div>
</div>
<app-trip [customerForm]="customerForm"></app-trip>
```
Child Component
```
export class TripComponent implements OnInit {
@Input() customerForm : FormGroup;
constructor(private fb: FormBuilder) { }
ngOnInit() {
}
}
```
Child HTML,
```
<div class="border p-2 mb-2" [formGroup]="customerForm">
<legend class="w-auto small font-weight-bold">Trip NAme</legend>
<div class="form-row pb-sm-3" formGroupName="tripForm">
<div class="col-sm-6 col-lg-3 form-group">
<label for="txtOrigName">Name</label>
<input type="text" id="txtOrigName" class="form-control" formControlName="name" required>
<div class="invalid-feedback">
Required
</div>
</div>
</div>
``` | Error happen because `addControl` assume you pass in `formControl` but you pass in JSON value. your child component emit form value instead of `FormGroup`, your parent component `tripFormChangeEvent` define parameter as `FormGroup` too, change your child component emit to `this.onFormGroupChange.emit(this.tripForm)`. |
29,558,015 | we designed the WebService application in vs 2010 using AWS SDK toolkit which connect to AWS SNS Service.
It Perfectly works when we directly run from VS 2010 Development studio,
but when we publish webservice to Local IIS or dedicated webserver it fails with
following error Messages.
```
Amazon.Runtime.AmazonServiceException: Unable to find credentials
Exception 1 of 4:
System.ArgumentException: Path cannot be the empty string or all whitespace.
Parameter name: path
at System.IO.Directory.GetParent(String path)
at Amazon.Runtime.StoredProfileAWSCredentials.DetermineCredentialsFilePath(String profilesLocation)
at Amazon.Runtime.StoredProfileAWSCredentials..ctor(String profileName, String profilesLocation)
at Amazon.Runtime.EnvironmentAWSCredentials..ctor()
at Amazon.Runtime.FallbackCredentialsFactory.<Reset>b__1()
at Amazon.Runtime.FallbackCredentialsFactory.GetCredentials(Boolean fallbackToAnonymous)
Exception 2 of 4:
System.ArgumentException: Path cannot be the empty string or all whitespace.
Parameter name: path
at System.IO.Directory.GetParent(String path)
at Amazon.Runtime.StoredProfileAWSCredentials.DetermineCredentialsFilePath(String profilesLocation)
at Amazon.Runtime.StoredProfileAWSCredentials..ctor(String profileName, String profilesLocation)
at Amazon.Runtime.FallbackCredentialsFactory.<Reset>b__2()
at Amazon.Runtime.FallbackCredentialsFactory.GetCredentials(Boolean fallbackToAnonymous)
Exception 3 of 4:
System.InvalidOperationException: The environment variables AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY were not set with AWS credentials.
at Amazon.Runtime.EnvironmentVariablesAWSCredentials..ctor()
at Amazon.Runtime.FallbackCredentialsFactory.<Reset>b__3()
at Amazon.Runtime.FallbackCredentialsFactory.GetCredentials(Boolean fallbackToAnonymous)
Exception 4 of 4:
Amazon.Runtime.AmazonServiceException: Unable to reach credentials server
at Amazon.Runtime.InstanceProfileAWSCredentials.GetContents(Uri uri)
at Amazon.Runtime.InstanceProfileAWSCredentials.<GetAvailableRoles>d__0.MoveNext()
at Amazon.Runtime.InstanceProfileAWSCredentials.GetFirstRole()
at Amazon.Runtime.FallbackCredentialsFactory.<Reset>b__4()
at Amazon.Runtime.FallbackCredentialsFactory.GetCredentials(Boolean fallbackToAnonymous)
at Amazon.Runtime.FallbackCredentialsFactory.GetCredentials(Boolean fallbackToAnonymous)
at Amazon.SimpleNotificationService.AmazonSimpleNotificationServiceClient..ctor()
at CellicaAwsSnsService..ctor()
at Service..ctor()
``` | 2015/04/10 | [
"https://Stackoverflow.com/questions/29558015",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2002511/"
] | Create a credentials file at any path where you can access this path from web service application
e.g. C:\awsfile\credentials
but remember don't give any extension this file
File should contains following data.
```
[default]
aws_access_key_id=[your_access_key]
aws_secret_access_key=[your_secret_key]
```
After this you need to set the path in appsetting tag in the Web.config file:
```
<appSettings>
<add key="AWSProfilesLocation" value="C:\awsfile\credentials" />
<add key="AWSRegion" value="us-east-1" />
</appSettings>
``` | In AWS Explorer for Visual Studio you can create user profiles that give you different permissions on AWS, then you can choose which profile you want to use in AWS Explorer. These profiles are available only to your Windows user account, if anyone else uses your computer then they will have to create their own profiles. Any software that you run under your user account can also use these profiles.
If you don't configure your application to use a specific profile then it will use the `default` profile.
This problem occurs because IIS runs under a different user account than the one you are logged into, and therefore does not have access to your AWS profiles.
There are several ways to tell your application which AWS profile to use when it runs (see <http://docs.aws.amazon.com/sdk-for-net/v2/developer-guide/net-dg-config-creds.html>). The simplest option for developers is to create a credentials file and reference that file from web.config. For example if you create a file called `C:\aws\credentials` you can tell your application to use profile2 from this credentials file by adding this to your web.config file.
```
<configuration>
<configSections>
<section name="aws" type="Amazon.AWSSection, AWSSDK.Core" />
</configSections>
<aws
region="us-east-1"
profileName="profile2"
profilesLocation="C:\aws\credentials" />
</configuration>
```
The content of the credentials file should be similar to this:
```
[profile1]
aws_access_key_id = {accessKey}
aws_secret_access_key = {secretKey}
[profile2]
aws_access_key_id = {accessKey}
aws_secret_access_key = {secretKey}
```
To get an access key and a secret key go to the AWS IAM console at <https://console.aws.amazon.com/iam/home?region=us-east-1#/users> choose the user you want your application to run as, then click on the "Security Credentials" tab then click the "Create Access Key" button. |
41,514,743 | I am working on a school project where we are supposed to save user inputted data to a database we created within the project. I created a database, called 'db1', in the App\_Data folder of my project, and created a table along with it, called 'Video\_Games.' My code is somewhat of a Frankenstein's Monster, where it is from examples from my textbook as well as online examples.
```
Protected Sub btnTable_Click(sender As Object, e As EventArgs) Handles btnTable.Click
Dim strTitle As String = txtTitle.Text
Dim strConsole As String = txtConsole.Text
Dim strYear As String = txtYear.Text
Dim strESRB As String = txtRating.Text
Dim strScore As String = txtScore.Text
Dim strPublisher As String = txtPublisher.Text
Dim strDeveloper As String = txtDeveloper.Text
Dim strGenre As String = txtGenre.Text
Dim strPurchase As String = calDate.SelectedDate.ToString
Dim conn As SqlConnection
Dim cmd As SqlCommand
Dim cmdString As String = "INSERT INTO Video_Games(Title, Console, Year, ESRB, Score, Publisher, Developer, Genre, Purchase)
VALUES (@strTitle, @strConsole, @strYear, @strESRB, @strScore, @strPublisher, @strDeveloper, @strGenre, @strPurchase)"
conn = New SqlConnection("Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\db1;Integrated Security=True;User Instance=True")
cmd = New SqlCommand(cmdString, conn)
cmd.Parameters.AddWithValue("@strTitle", strTitle)
cmd.Parameters.AddWithValue("@strConsole", strConsole)
cmd.Parameters.AddWithValue("@strYear", strYear)
cmd.Parameters.AddWithValue("@strESRB", strESRB)
cmd.Parameters.AddWithValue("@strScore", strScore)
cmd.Parameters.AddWithValue("@strPublisher", strPublisher)
cmd.Parameters.AddWithValue("@strDeveloper", strDeveloper)
cmd.Parameters.AddWithValue("@strGenre", strGenre)
cmd.Parameters.AddWithValue("@strPurchase", strPurchase)
conn.Open()
cmd.ExecuteNonQuery()
conn.Close()
End Sub
```
Ther error I am getting is from the "conn.Open()" line is:
An exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll but was not handled in user code
Additional information: A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL
Judging by the error, I am assuming that it has to do with my 'conn = New SqlConnection' line, but I cannot find how to make it work. Thank you for any help you are able to give. | 2017/01/06 | [
"https://Stackoverflow.com/questions/41514743",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6501342/"
] | Here is what I ended up doing - completely naked and without any test/check/exception-handling:
```
from importlib import import_module
from django.utils.translation import get_language
fm = import_module('.formats', 'django.conf.locale.%s' % get_language())
try:
return getattr(fm, 'DECIMAL_SEPARATOR')
except AttributeError:
return '.'
``` | Django has [native localization](https://docs.djangoproject.com/en/1.10/topics/i18n/formatting/) built in for both templates and forms.
Where are you determining this?
In a template:
>
> `{% load l10n %}{% localize on %}{{ value }}{% endlocalize %}`
>
>
>
Or in a form:
>
> To enable a form field to localize input and output data simply use its
> localize argument:
>
>
>
```
class CashRegisterForm(forms.Form):
product = forms.CharField()
revenue = forms.DecimalField(max_digits=4, decimal_places=2, localize=True)
```
You have to enable the localization module:
>
> The formatting system is disabled by default. To enable it, it’s necessary to set `USE_L10N = True` in your settings file.
>
>
> |
41,514,743 | I am working on a school project where we are supposed to save user inputted data to a database we created within the project. I created a database, called 'db1', in the App\_Data folder of my project, and created a table along with it, called 'Video\_Games.' My code is somewhat of a Frankenstein's Monster, where it is from examples from my textbook as well as online examples.
```
Protected Sub btnTable_Click(sender As Object, e As EventArgs) Handles btnTable.Click
Dim strTitle As String = txtTitle.Text
Dim strConsole As String = txtConsole.Text
Dim strYear As String = txtYear.Text
Dim strESRB As String = txtRating.Text
Dim strScore As String = txtScore.Text
Dim strPublisher As String = txtPublisher.Text
Dim strDeveloper As String = txtDeveloper.Text
Dim strGenre As String = txtGenre.Text
Dim strPurchase As String = calDate.SelectedDate.ToString
Dim conn As SqlConnection
Dim cmd As SqlCommand
Dim cmdString As String = "INSERT INTO Video_Games(Title, Console, Year, ESRB, Score, Publisher, Developer, Genre, Purchase)
VALUES (@strTitle, @strConsole, @strYear, @strESRB, @strScore, @strPublisher, @strDeveloper, @strGenre, @strPurchase)"
conn = New SqlConnection("Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\db1;Integrated Security=True;User Instance=True")
cmd = New SqlCommand(cmdString, conn)
cmd.Parameters.AddWithValue("@strTitle", strTitle)
cmd.Parameters.AddWithValue("@strConsole", strConsole)
cmd.Parameters.AddWithValue("@strYear", strYear)
cmd.Parameters.AddWithValue("@strESRB", strESRB)
cmd.Parameters.AddWithValue("@strScore", strScore)
cmd.Parameters.AddWithValue("@strPublisher", strPublisher)
cmd.Parameters.AddWithValue("@strDeveloper", strDeveloper)
cmd.Parameters.AddWithValue("@strGenre", strGenre)
cmd.Parameters.AddWithValue("@strPurchase", strPurchase)
conn.Open()
cmd.ExecuteNonQuery()
conn.Close()
End Sub
```
Ther error I am getting is from the "conn.Open()" line is:
An exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll but was not handled in user code
Additional information: A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL
Judging by the error, I am assuming that it has to do with my 'conn = New SqlConnection' line, but I cannot find how to make it work. Thank you for any help you are able to give. | 2017/01/06 | [
"https://Stackoverflow.com/questions/41514743",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6501342/"
] | Here is what I ended up doing - completely naked and without any test/check/exception-handling:
```
from importlib import import_module
from django.utils.translation import get_language
fm = import_module('.formats', 'django.conf.locale.%s' % get_language())
try:
return getattr(fm, 'DECIMAL_SEPARATOR')
except AttributeError:
return '.'
``` | ```
from django.util.format import get_format #or get_format_lazy
from django.utils.translation import get_language
decimal_seperator = get_format('DECIMAL_SEPARATOR',get_language())
```
Feel free to use 'DATE\_FORMAT', 'THOUSAND\_SEPARATOR','NUMBER\_GROUPING' etc instead of 'DECIMAL\_SEPARATOR'
I got import error at some point using @jens-lundstrom answer. |
70,885,037 | This is my table : [](https://i.stack.imgur.com/6w5lR.jpg)
I am taking an online course on Udemy in SQL, the video has this code and it is running. I do not know why I get error below when I run it. I appreciate any help.
the code is supposed to return the number of each age group in each region.
```
select * from dbo.tblCustomer;
select Region,
case when Age>54 then 'old'
when Age<36 then 'young'
else 'mid' end as age_group
,count(*) as freq
from dbo.tblCustomer
group by Region, age_group
order by Region, freq desc;
```
>
> Msg 207, Level 16, State 1, Line 43
>
> Invalid column name 'age\_group'.
>
> Msg 207, Level 16, State 1, Line 44
>
> Invalid column name 'count'.
>
>
>
>
PS. I took $9.9 courses on Udemy, this is a screen shot of the video I'm learning SQL from. his codes, mine does not. Now with help wonderful StackOverflow people I am learning why. I spent three hours to google here and there and try to study W3Schools for this.
[](https://i.stack.imgur.com/TGLxX.jpg) | 2022/01/27 | [
"https://Stackoverflow.com/questions/70885037",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16354132/"
] | These sorts of questions come up often, alas SMT solvers are just not a good match with quantifier heavy problems. The best you have is specifying patterns (See [E-matching based quantifier instantiation](https://theory.stanford.edu/%7Enikolaj/programmingz3.html#sec-e-matching-based-quantifier-instantiation) for details). But it is quite fragile and definitely not that terribly easy to use.
Your best bet, against what you wanted, is to use proof assistants; and hope that their automated tactics (such as [sledgehammer](https://isabelle.in.tum.de/website-Isabelle2009-1/sledgehammer.html) of Isabelle) can discharge the proofs without the need for much user intervention.
This is, of course, general advice without actually knowing anything about your specific problem. If you post a concrete instance of it, you might get a better answer in terms of if there might be another way to model it using z3. | Given the current formulation of your fragment, you're still in an undecidable fragment of FOL. If you could restrict what your P are allowed to talk about then you might end up in a decidable fragment (e.g. monadic, guarded, effectively propositional, there are a few).
Besides SMT solvers and proof assistants, there is a whole class of automated theorem provers that are refutationally complete for such problems (i.e. if there is a proof of inconsistency they will eventually find it), which SMT solvers are not. [CASC](https://www.tptp.org/CASC/) is a good place to find out about such solvers as it's a compeittion focussing on these kinds of problems. [Vampire](https://vprover.github.io/) is a very good example (note, I am a developer of Vampire). |
48,223,571 | I am new to GIT and not able to understand how the second rebase command resulted in merge issue:
```
$ git rebase origin/develop
Current branch feature/featurename is up to date.
$ git fetch
remote: Microsoft (R) Visual Studio (R) Team Services
remote: We noticed you're using an older version of Git. For the best experience, upgrade to a newer version.
remote: Found 50 objects to send. (31 ms)
Unpacking objects: 100% (50/50), done.
From https://.....
df825005..000000cf develop -> origin/develop
$ git rebase origin/develop
First, rewinding head to replay your work on top of it...
Applying: .....
C:/work/.../rebase-apply/patch:61: trailing whitespace
Using index info to reconstruct a base tree...
M br/br
Falling back to patching base and 3-way merge...
Auto-merging case/TTest.cpp
CONFLICT (submodule): Merge conflict in br/br
```
I understand that both rebase and fetch will refer to origin/develop however I do have a 'set-upstream' branch in our VSTS (build system) - so did the fetch fetched from my feature branch in VSTS? | 2018/01/12 | [
"https://Stackoverflow.com/questions/48223571",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/304974/"
] | Git just told you in its output what happened:
```
Current branch feature/featurename is up to date.
```
This means that, at the moment, before fetch, your branch indeed is based on origin/development. So your history looks something like this:
```
feature/featurename
/
-o---o
\
origin/development
```
Now you called the `git fetch` command which checks if there were new commits pushed to the remote repository. Turns out, there were, and `git` informs you what was changed with the message:
```
From https://.....
df825005..000000cf develop -> origin/develop
```
This means that branch `develop` on the remote repository `https://.....` moved from `df825005` to `000000cf` (nice hash, btw), so your remote branch `origin/develop` was updated accordingly. Now your history looks like this:
```
feature/featurename
/
-o---o
\
--o <- origin/development
```
The branch `feature/featurename` is no longer based on top of `origin/development`, so when you run rebase you have to go through the whole process (branch no longer up to date and no fast-forward possible)
```
First, rewinding head to replay your work on top of it...
```
This is a preparation step for doing a rebase - `HEAD` is put at the top of the `origin/develop` branch as it will now try to put your commits there.
```
Applying: .....
```
Here was the name of the commit git is now applying where `HEAD` is. Right now its the top of the `origin/develop` but if you had more commits to be rebased it would move forward, obviously.
```
Falling back to patching base and 3-way merge...
```
Git failed to automatically apply your commit, as there were files modified both in your commit and in the `origin/develop` branch. So now git will have to do...
```
Auto-merging case/TTest.cpp
```
The clever git alghoritms might avoid conflicts in this file so it will try to automerge it
```
CONFLICT (submodule): Merge conflict in br/br
```
No luck! Unfortunately, git wasn't able to automerge the file and has left you with this responsibility. You either have some exotic version of git, or you've trimmed the output, but git will usually include one more very helpful line:
```
When you have resolved this problem, run "git rebase --continue".
```
So now all you have to do is resolve the conflict in the usual way, and once you're done, do `git rebase --continue`. Now git will try to apply the next commit, if there are any left.
I strongly recommend reading a tutorial of your choice about git - it seems like you are highly confused about the very fundamental concepts of git, which are very different from version control systems like svn | >
> I understand that both rebase and fetch will refer to `origin/develop` ...
>
>
>
This isn't quite right.
What `git fetch` does is connect *your* Git (which has an independent copy of all of its commits—your own commits and everyone else's commits as of the last time you connected your Git to all the other Gits you connect-to)—to some other Git.
The other Git may have commits that you don't. If so, your Git asks their Git for the commits that they have, that you don't. They hand over their commits-that-they-have-that-you-don't; your Git stores those commits permanently, in your repository, under their hash IDs; and then your Git records, for your usage, which commits are their *tip* commits. That is, they have a branch named `develop`. You just got a listing, from them, of what commit hash their `develop` names. But you may well have *your own branch* named `develop`, so your Git does not touch *your* `develop` at all. Instead, it just updates your memory of *their* `develop`, which your Git calls `origin/develop`.
When you run `git rebase origin/develop`, your Git *does not call up another Git*, it just looks at your saved memory in your own `origin/develop`. So your first `git rebase` did nothing as the memory you had of their `develop`, stored in your `origin/develop`, did not require doing anything. Then you ran `git fetch`, which obtained new commits from their Git and updated your memory of their `develop` by updating your `origin/develop`. Then your second `git rebase` looked at your updated memory, found that there was something to do, did it, and that process resulted in the merge conflict you saw. |
50,301 | I am creating a Document Set for a library using powershell and that document set contains some mandatory managed metadata fields. I am able to create document set but how can I insert data into those managed metadata fields at runtime? | 2012/10/30 | [
"https://sharepoint.stackexchange.com/questions/50301",
"https://sharepoint.stackexchange.com",
"https://sharepoint.stackexchange.com/users/11396/"
] | You have to connect to the term store and then construct a TaxonomyFieldValue and then use the target field's SetFieldValue() method to assign the value.
See here: <http://social.technet.microsoft.com/Forums/da-DK/sharepointadminprevious/thread/4c63fff1-8681-42a1-9fd2-256f1f80935b>
regards,
KS | Hope this helps someone.
You have to get a reference to the Managed metadata item from term store as shown below
```
$someTerm = $term.Terms | where-object {$_.Name -eq "SomeTerm" }
```
Create the document set as shown below
```
[Hashtable]$docSetProperties = @{}
$newDocumentSet=Microsoft.Office.DocumentManagement.DocumentSets.DocumentSet]::Create($list.RootFolder,"TestDocSet",$DocContentType.Id, $docSetProperties )
```
Get a reference to the inserted document set
```
$id = $newDocumentSet.Item.ID
$spItem = $list.GetItemById($id)
```
Get a reference to the taxonomy field from the inserted document set
```
$taxMMField = $spItem.Fields['YourManagedMetaDataField'] -as [Microsoft.SharePoint.Taxonomy.TaxonomyField]
$taxMMField.SetFieldValue($spItem, $someTerm)
```
Call the Update method on the item
```
$spItem.Update()
```
This will update the Managed metadata field in the Document Set. |
50,301 | I am creating a Document Set for a library using powershell and that document set contains some mandatory managed metadata fields. I am able to create document set but how can I insert data into those managed metadata fields at runtime? | 2012/10/30 | [
"https://sharepoint.stackexchange.com/questions/50301",
"https://sharepoint.stackexchange.com",
"https://sharepoint.stackexchange.com/users/11396/"
] | You have to connect to the term store and then construct a TaxonomyFieldValue and then use the target field's SetFieldValue() method to assign the value.
See here: <http://social.technet.microsoft.com/Forums/da-DK/sharepointadminprevious/thread/4c63fff1-8681-42a1-9fd2-256f1f80935b>
regards,
KS | Complete sample
```
$webUrl = "http://portaladdress.local"
$inputDir = "C:\sampledata"
$spWeb = Get-SPWeb $webUrl
$spsite = $spWeb.Site
$docLibrary = $spWeb.Lists["DocumentLibraryListName"]
$spFolder = $spWeb.GetFolder($docLibrary.rootFolder.URL + "/")
$taxonomySession = Get-SPTaxonomySession -Site $spsite
$taxonomyField = $docLibrary.Fields["TaxononomyFieldName"]
$termStoreID = $taxonomyField.SspId
$termStore = $taxonomySession.TermStores[$termStoreID]
$termsetID = $taxonomyField.TermSetId
$termset = $termStore.GetTermSet($termsetID)
#################
### Get Document Set Content Type from list
$cType = $docLibrary.ContentTypes["DocumentSetContentTypeName"]
### Create Document Set Properties Hashtable
[Hashtable]$docsetProperties = @{"DescriptionFieldName"="some text"}
$docsetProperties = @{"DatefiledName"="06/06/2006"}
### Create new Document Set
$newDocumentSet = [Microsoft.Office.DocumentManagement.DocumentSets.DocumentSet]::Create($spFolder,"documentset title",$cType.Id,$docsetProperties)
$term = $termset.GetTerms( "TermLabel", $true)
$id = $newDocumentSet.Item.ID;
$spItem = $docLibrary.GetItemById($id);
#this is a critical point: get a reference to the field by the item instead of using that from the list we got before (ie: $taxonomyField)
$taxMMField = $spItem.Fields['TaxononomyFieldName'] -as [Microsoft.SharePoint.Taxonomy.TaxonomyField];
$taxMMField.SetFieldValue($spItem, $term);
$spItem.Update();
#upload a file into the document set
$FilePath = "$inputDir\FileToBeLoadIntoTheDocumentset.pdf"
$FileName = "FileToBeLoadIntoTheDocumentset.pdf"
$file= Get-Item $FilePath
$spFile = $newDocumentSet.Folder.Files.Add($newDocumentSet.Folder.Url + "/" + $FileName,$file.OpenRead(),$false)
$spFileItem = $spFile.Item
$spFileItem["Titolo"] = "File title";
$spFileItem.Update()
$spFileItem.File.CheckIn("checkin comments", [Microsoft.SharePoint.SPCheckinType]::MajorCheckIn)
$spWeb.Dispose()
``` |
50,301 | I am creating a Document Set for a library using powershell and that document set contains some mandatory managed metadata fields. I am able to create document set but how can I insert data into those managed metadata fields at runtime? | 2012/10/30 | [
"https://sharepoint.stackexchange.com/questions/50301",
"https://sharepoint.stackexchange.com",
"https://sharepoint.stackexchange.com/users/11396/"
] | Hope this helps someone.
You have to get a reference to the Managed metadata item from term store as shown below
```
$someTerm = $term.Terms | where-object {$_.Name -eq "SomeTerm" }
```
Create the document set as shown below
```
[Hashtable]$docSetProperties = @{}
$newDocumentSet=Microsoft.Office.DocumentManagement.DocumentSets.DocumentSet]::Create($list.RootFolder,"TestDocSet",$DocContentType.Id, $docSetProperties )
```
Get a reference to the inserted document set
```
$id = $newDocumentSet.Item.ID
$spItem = $list.GetItemById($id)
```
Get a reference to the taxonomy field from the inserted document set
```
$taxMMField = $spItem.Fields['YourManagedMetaDataField'] -as [Microsoft.SharePoint.Taxonomy.TaxonomyField]
$taxMMField.SetFieldValue($spItem, $someTerm)
```
Call the Update method on the item
```
$spItem.Update()
```
This will update the Managed metadata field in the Document Set. | Complete sample
```
$webUrl = "http://portaladdress.local"
$inputDir = "C:\sampledata"
$spWeb = Get-SPWeb $webUrl
$spsite = $spWeb.Site
$docLibrary = $spWeb.Lists["DocumentLibraryListName"]
$spFolder = $spWeb.GetFolder($docLibrary.rootFolder.URL + "/")
$taxonomySession = Get-SPTaxonomySession -Site $spsite
$taxonomyField = $docLibrary.Fields["TaxononomyFieldName"]
$termStoreID = $taxonomyField.SspId
$termStore = $taxonomySession.TermStores[$termStoreID]
$termsetID = $taxonomyField.TermSetId
$termset = $termStore.GetTermSet($termsetID)
#################
### Get Document Set Content Type from list
$cType = $docLibrary.ContentTypes["DocumentSetContentTypeName"]
### Create Document Set Properties Hashtable
[Hashtable]$docsetProperties = @{"DescriptionFieldName"="some text"}
$docsetProperties = @{"DatefiledName"="06/06/2006"}
### Create new Document Set
$newDocumentSet = [Microsoft.Office.DocumentManagement.DocumentSets.DocumentSet]::Create($spFolder,"documentset title",$cType.Id,$docsetProperties)
$term = $termset.GetTerms( "TermLabel", $true)
$id = $newDocumentSet.Item.ID;
$spItem = $docLibrary.GetItemById($id);
#this is a critical point: get a reference to the field by the item instead of using that from the list we got before (ie: $taxonomyField)
$taxMMField = $spItem.Fields['TaxononomyFieldName'] -as [Microsoft.SharePoint.Taxonomy.TaxonomyField];
$taxMMField.SetFieldValue($spItem, $term);
$spItem.Update();
#upload a file into the document set
$FilePath = "$inputDir\FileToBeLoadIntoTheDocumentset.pdf"
$FileName = "FileToBeLoadIntoTheDocumentset.pdf"
$file= Get-Item $FilePath
$spFile = $newDocumentSet.Folder.Files.Add($newDocumentSet.Folder.Url + "/" + $FileName,$file.OpenRead(),$false)
$spFileItem = $spFile.Item
$spFileItem["Titolo"] = "File title";
$spFileItem.Update()
$spFileItem.File.CheckIn("checkin comments", [Microsoft.SharePoint.SPCheckinType]::MajorCheckIn)
$spWeb.Dispose()
``` |
184,298 | So, the microstructure of abalone shells is 95% calcium carbonate, such as aragonite, tiles and 5% organic polymer that binds them together. This binding fails in a graceful manner, allowing the shell to take a lot of punishment before shattering.
This composite material is around 3,000 times more resistant to fracturing than calcium carbonate and twice as resistant to fracturing as boron carbide, despite the high degree of mineralization.
Source: <http://meyersgroup.ucsd.edu/papers/delete/1999/Meyers%20211.pdf>
On top of that, thanks to how light is refracted by said microstructure, it also looks cool.
[](https://i.stack.imgur.com/f2fY2.jpg)
Can you imagine how insanely bullet-resistant could scales/osteoderms/whatever be if I managed to replace the material of the "bricks" with something stronger? It would probably be like the [Battle of Ramree Island](https://en.wikipedia.org/wiki/Battle_of_Ramree_Island), though with [even more screaming](https://www.youtube.com/watch?v=Jiupj4PyL4U).
Well, I still have some things to solve, but bullet resistant, lightweight armor is a good start for my apex predators.
However, this is where problems show up. Hydroxylapatite is probably the strongest mineral in the human body, but it still seems fairly weak. I mean, yes, the composition of scales could vary across the creature's body, with the strongest covering their head and chest, but those should be as strong as possible.
Other than utilizing enzymes, another way of attaining certain minerals could be the Kakyoin method (RERORERORERO), basically, [lick it until it's gone](https://en.wikipedia.org/wiki/Limpet#Function_and_formation); mountain goats do it too.
**So, what is the strongest (high Vickers hardness, and a-okay or better fracture toughness) mineral that could be obtained by an animal (either by synthesis via enzymes or munching) and serve as a replacement for the aragonite bricks in the aforementioned microstructure?** | 2020/08/24 | [
"https://worldbuilding.stackexchange.com/questions/184298",
"https://worldbuilding.stackexchange.com",
"https://worldbuilding.stackexchange.com/users/32097/"
] | In essence, if I'm understanding correctly, you are looking for a biological material that exhibits a high degree of toughness. To achieve this, we could look at some very strong materials that could replace (or at least compete with) our standard bulletproofing materials. One of these is [spider silk](https://inchemistry.acs.org/content/inchemistry/en/atomic-news/spider-webs.html#:%7E:text=Dragline%20silk%20is%20around%201.1,strength%20of%203.0%20%E2%80%93%203.6%20GPa.&text=Spider%20silk%20fibers%20are%20not,fiber%20but%20they%20are%20tougher). This could be part of the protein matrix that is layered into the scales. Of course nacre protein could be sufficient here as well.
The other part, the replacement for calcium carbonate is harder to figure out. Polymerization is one of the keys, as it has to survive the impact. Tensile networks distribute the forces without fragmentation, but could be weakened by repeated impact. It could be that some healing process could provide additional strength near damaged areas.
Organosilicon biopolymers could create some incidental silicon carbides, which are also bulletproof. [Organosilicons](https://en.wikipedia.org/wiki/Organosilicon) are naturally absent from organisms found on Earth, so you would have to dig deep into the genetic engineering aspect of this form of life to explain it.
There does appear to be some work that has been done on this for astrobiology using bacteria and mutant enzymes. The researcher said "The mutant enzyme could generate at least 20 different organo-silicon compounds, 19 of which were new to science". Nobody thought to see if these could be used to bulletproof an organism however. The layering of organosilicons and spider silk proteins (or nacre proteins) should allow a fairly good bulletproofing scale which has some work behind it to show biocompatibility, even if somewhat deficient on the organosilicon side of things.
The percentage of [silicon carbide](https://www.syalons.com/materials/silicon-carbide/) that shows up in these scales could be altered either environmentally (by acid or enzyme attack) or internally by a process that selectively expels silicon carbides into the scale structures.
The hardness would be below the charted levels, but the surrounding polymers would add toughness. As to whether the silicon carbide could be sustained in multiple layers, it would depend on how the silicon carbide is enriched in these scales. Process is everything in biology. | One possibility could be a [Boron Carbide](https://en.wikipedia.org/wiki/Boron#High-hardness_and_abrasive_compounds), specifically cubic-BC5, which has a Vickers hardness of 71 GPa and a fracture toughness of 9.5 MPa m½.
Both of which are higher than the values for hydroxyapatite (5 GPa and 1.2 MPa m½, I. Hervas, *Fracture toughness of glasses and hydroxyapatite: A comparative study of 7 methods by using Vickers indenter*).
I'd imagine that it would also be able to be grown in approximately the same microstructure, to produce the same colour as the shell in your image.
Unfortunately [boron](https://en.wikipedia.org/wiki/Boron) is not a common element, although it can be very concentrated in some dry lakes and mineral deposits. But I'm not entirely sure how your creature could produce cubic-BC5, possibly enzymatically.
Hopefully that helps. |
58,263,267 | I need to access the custom settings passed from the CLI using:
`-s SETTING_NAME="SETTING_VAL"`
**from the \_\_init\_\_() method of the spider class**.
`get_project_settings()` allows me to access only the static settings.
The docs explain how you can access those custom settings by from a pipeline setting up a new pipeline through:
```
@classmethod
def from_crawler(cls, crawler):
settings = crawler.settings
```
But is there any way to access them from the `__init__()` spider method? | 2019/10/07 | [
"https://Stackoverflow.com/questions/58263267",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4764353/"
] | Just use [`settings.get`](https://docs.scrapy.org/en/latest/topics/api.html#scrapy.settings.BaseSettings.get) e.g.
```
print(self.settings.get('SETTING_NAME'))
```
will print
```
SETTING_VAL
```
If you want to access a setting in your spider `__init__` you have a couple of options. If you command-line options is just a `spider` argument, use `-a` instead of `-s`. If for some reason you need to access an actual setting in your spider `__init__` then you have to override the `from_crawler` `classmethod` as described in the [docs](https://docs.scrapy.org/en/latest/topics/settings.html#how-to-access-settings).
Here is an example:
```
import scrapy
class ArgsSpider(scrapy.Spider):
name = "my_spider"
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
print('kwargs =', kwargs)
@classmethod
def from_crawler(cls, crawler, *args, **kwargs):
spider = cls(
*args,
my_setting=crawler.settings.get("MY_SETTING"),
**kwargs
)
spider._set_crawler(crawler)
return spider
```
run with e.g. `scrapy runspider args_spider.py -s MY_SETTING=hello,world!` and you will see your setting in the `kwargs` dict. You can of course get other settings this way too | The answer of @tomjn works, I just want to point out that if you are using extensions or middlewares which need the crawler object, you need to alter his factory method this way:
```
@classmethod
def from_crawler(cls, crawler, *args, **kwargs):
obj = cls(
*args,
my_setting=crawler.settings.get("MY_SETTING"),
**kwargs
)
obj.crawler = crawler
return obj
```
Not sure if you need to do it if you instantiate the spider itself, but in my case, when I was inheriting it, my script would crash complaining about missing crawler attribute until I did it this way. |
58,263,267 | I need to access the custom settings passed from the CLI using:
`-s SETTING_NAME="SETTING_VAL"`
**from the \_\_init\_\_() method of the spider class**.
`get_project_settings()` allows me to access only the static settings.
The docs explain how you can access those custom settings by from a pipeline setting up a new pipeline through:
```
@classmethod
def from_crawler(cls, crawler):
settings = crawler.settings
```
But is there any way to access them from the `__init__()` spider method? | 2019/10/07 | [
"https://Stackoverflow.com/questions/58263267",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4764353/"
] | Just use [`settings.get`](https://docs.scrapy.org/en/latest/topics/api.html#scrapy.settings.BaseSettings.get) e.g.
```
print(self.settings.get('SETTING_NAME'))
```
will print
```
SETTING_VAL
```
If you want to access a setting in your spider `__init__` you have a couple of options. If you command-line options is just a `spider` argument, use `-a` instead of `-s`. If for some reason you need to access an actual setting in your spider `__init__` then you have to override the `from_crawler` `classmethod` as described in the [docs](https://docs.scrapy.org/en/latest/topics/settings.html#how-to-access-settings).
Here is an example:
```
import scrapy
class ArgsSpider(scrapy.Spider):
name = "my_spider"
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
print('kwargs =', kwargs)
@classmethod
def from_crawler(cls, crawler, *args, **kwargs):
spider = cls(
*args,
my_setting=crawler.settings.get("MY_SETTING"),
**kwargs
)
spider._set_crawler(crawler)
return spider
```
run with e.g. `scrapy runspider args_spider.py -s MY_SETTING=hello,world!` and you will see your setting in the `kwargs` dict. You can of course get other settings this way too | None of the responses work when using `CrawlSpider`, because some methods such as [`_follow_links`](https://github.com/scrapy/scrapy/blob/7b1bc9b7fefce60c51f89f7ed47e1d172e43b2a7/scrapy/spiders/crawl.py#L138) will be missing.
The following code works:
```py
@classmethod
def from_crawler(cls, crawler, *args, **kwargs):
spider = super().from_crawler(
crawler,
*args,
some_arg=crawler.settings.get("SOME_ARG"), **kwargs
)
return spider
``` |
58,263,267 | I need to access the custom settings passed from the CLI using:
`-s SETTING_NAME="SETTING_VAL"`
**from the \_\_init\_\_() method of the spider class**.
`get_project_settings()` allows me to access only the static settings.
The docs explain how you can access those custom settings by from a pipeline setting up a new pipeline through:
```
@classmethod
def from_crawler(cls, crawler):
settings = crawler.settings
```
But is there any way to access them from the `__init__()` spider method? | 2019/10/07 | [
"https://Stackoverflow.com/questions/58263267",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4764353/"
] | None of the responses work when using `CrawlSpider`, because some methods such as [`_follow_links`](https://github.com/scrapy/scrapy/blob/7b1bc9b7fefce60c51f89f7ed47e1d172e43b2a7/scrapy/spiders/crawl.py#L138) will be missing.
The following code works:
```py
@classmethod
def from_crawler(cls, crawler, *args, **kwargs):
spider = super().from_crawler(
crawler,
*args,
some_arg=crawler.settings.get("SOME_ARG"), **kwargs
)
return spider
``` | The answer of @tomjn works, I just want to point out that if you are using extensions or middlewares which need the crawler object, you need to alter his factory method this way:
```
@classmethod
def from_crawler(cls, crawler, *args, **kwargs):
obj = cls(
*args,
my_setting=crawler.settings.get("MY_SETTING"),
**kwargs
)
obj.crawler = crawler
return obj
```
Not sure if you need to do it if you instantiate the spider itself, but in my case, when I was inheriting it, my script would crash complaining about missing crawler attribute until I did it this way. |
53,129,004 | I am a python beginner, the situation is:
**In test.py**:
```
import numpy as np
import pandas as pd
from numpy import *
def model(file):
import numpy as np
import pandas as pd
data0 = pd.ExcelFile(file)
data = data0.parse('For Stata')
data1 = data.values
varnames = list(data)
for i in range(np.shape(data)[1]):
var = varnames[i]
exec(var+'=np.reshape(data1[:,i],(2217,1))')
return air
```
air is one of the 'varnames'
---
**Now I run the following in jupyter notebook**:
```
file0 = 'BLPreadydata.xlsx'
from test import model
model(file0)
```
---
the error that I get is:
**NameError: name 'air' is not defined**
EDIT: I tried to pin down the error, it actually came from
```
exec(var+'=np.reshape(data1[:,i],(2217,1))')
```
somehow this is not working when I call the function, but it does work when I run it outside the function.
NOTE:
Someone have done this in MATLAB:
```
vals = [1 2 3 4]
vars = {'a', 'b', 'c', 'd'}
for i = vals
eval([vars{i} '= vals(i)'])
end
``` | 2018/11/03 | [
"https://Stackoverflow.com/questions/53129004",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10599296/"
] | ID's have to be **unique**. Give each *carousel* and each *thumbcarousel* an ID of its own and you're good to go. Use classes for styling them.
```css
.product-slider {
padding: 45px;
}
.product-slider .carousel {
border: 4px solid #1089c0;
margin: 0;
}
.product-slider .thumbcarousel {
margin: 12px 0 0;
padding: 0 45px;
}
.product-slider .thumbcarousel .item {
text-align: center;
}
.product-slider .thumbcarousel .item .thumb {
border: 4px solid #cecece;
width: 20%;
margin: 0 2%;
display: inline-block;
vertical-align: middle;
cursor: pointer;
max-width: 98px;
}
.product-slider .thumbcarousel .item .thumb:hover {
border-color: #1089c0;
}
.product-slider .item img {
width: 100%;
height: auto;
}
.carousel-control {
color: #0284b8;
text-align: center;
text-shadow: none;
font-size: 30px;
width: 30px;
height: 30px;
line-height: 20px;
top: 23%;
}
.carousel-control:hover,
.carousel-control:focus,
.carousel-control:active {
color: #333;
}
.carousel-caption,
.carousel-control .fa {
font: normal normal normal 30px/26px FontAwesome;
}
.carousel-control {
background-color: rgba(0, 0, 0, 0);
bottom: auto;
font-size: 20px;
left: 0;
position: absolute;
top: 30%;
width: auto;
}
.carousel-control.right,
.carousel-control.left {
background-color: rgba(0, 0, 0, 0);
background-image: none;
}
```
```html
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<div class="container">
<div class="row">
<div class="col-md-12">
<button class="btn btn-primary" data-toggle="modal" data-target="#myModal1">Modal 1</button>
<button class="btn btn-primary" data-toggle="modal" data-target="#myModal2">Modal 2</button>
<button class="btn btn-primary" data-toggle="modal" data-target="#myModal3">Modal 3</button>
</div>
</div>
</div>
<div id="myModal1" class="modal fade" role="dialog">
<div class="modal-dialog modal-lg">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Modal Header</h4>
</div>
<div class="modal-body">
<div class="product-slider">
<div id="carousel_1" class="carousel slide" data-ride="carousel">
<div class="carousel-inner">
<div class="item active"> <img src="https://picsum.photos/950/500?image=1"> </div>
<div class="item"> <img src="https://picsum.photos/950/500?image=2"> </div>
<div class="item"> <img src="https://picsum.photos/950/500?image=3"> </div>
<div class="item"> <img src="https://picsum.photos/950/500?image=4"> </div>
<div class="item"> <img src="https://picsum.photos/950/500?image=5"> </div>
<div class="item"> <img src="https://picsum.photos/950/500?image=6"> </div>
<div class="item"> <img src="https://picsum.photos/950/500?image=7"> </div>
<div class="item"> <img src="https://picsum.photos/950/500?image=8"> </div>
<div class="item"> <img src="https://picsum.photos/950/500?image=9"> </div>
<div class="item"> <img src="https://picsum.photos/950/500?image=10"> </div>
</div>
</div>
<div class="clearfix">
<div id="thumbcarousel_1" class="carousel thumbcarousel slide" data-interval="false">
<div class="carousel-inner">
<div class="item active">
<div data-target="#carousel_1" data-slide-to="0" class="thumb"><img src="https://picsum.photos/60/60?image=1"></div>
<div data-target="#carousel_1" data-slide-to="1" class="thumb"><img src="https://picsum.photos/60/60?image=2"></div>
<div data-target="#carousel_1" data-slide-to="2" class="thumb"><img src="https://picsum.photos/60/60?image=3"></div>
<div data-target="#carousel_1" data-slide-to="3" class="thumb"><img src="https://picsum.photos/60/60?image=4"></div>
<div data-target="#carousel_1" data-slide-to="4" class="thumb"><img src="https://picsum.photos/60/60?image=5"></div>
</div>
<div class="item">
<div data-target="#carousel_1" data-slide-to="5" class="thumb"><img src="https://picsum.photos/60/60?image=6"></div>
<div data-target="#carousel_1" data-slide-to="6" class="thumb"><img src="https://picsum.photos/60/60?image=7"></div>
<div data-target="#carousel_1" data-slide-to="7" class="thumb"><img src="https://picsum.photos/60/60?image=8"></div>
<div data-target="#carousel_1" data-slide-to="8" class="thumb"><img src="https://picsum.photos/60/60?image=9"></div>
<div data-target="#carousel_1" data-slide-to="9" class="thumb"><img src="https://picsum.photos/60/60?image=10"></div>
</div>
</div>
<!-- /carousel-inner -->
<a class="left carousel-control" href="#thumbcarousel_1" role="button" data-slide="prev"> <i class="fa fa-angle-left" aria-hidden="true"></i> </a>
<a class="right carousel-control" href="#thumbcarousel_1" role="button" data-slide="next"><i class="fa fa-angle-right" aria-hidden="true"></i> </a> </div>
<!-- /thumbcarousel -->
</div>
</div>
</div>
</div>
</div>
</div>
<div id="myModal2" class="modal fade" role="dialog">
<div class="modal-dialog modal-lg">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Modal Header</h4>
</div>
<div class="modal-body">
<div class="product-slider">
<div id="carousel_2" class="carousel slide" data-ride="carousel">
<div class="carousel-inner">
<div class="item active"> <img src="https://picsum.photos/950/500?image=11"> </div>
<div class="item"> <img src="https://picsum.photos/950/500?image=12"> </div>
<div class="item"> <img src="https://picsum.photos/950/500?image=13"> </div>
<div class="item"> <img src="https://picsum.photos/950/500?image=14"> </div>
<div class="item"> <img src="https://picsum.photos/950/500?image=15"> </div>
<div class="item"> <img src="https://picsum.photos/950/500?image=16"> </div>
<div class="item"> <img src="https://picsum.photos/950/500?image=17"> </div>
<div class="item"> <img src="https://picsum.photos/950/500?image=18"> </div>
<div class="item"> <img src="https://picsum.photos/950/500?image=19"> </div>
<div class="item"> <img src="https://picsum.photos/950/500?image=20"> </div>
</div>
</div>
<div class="clearfix">
<div id="thumbcarousel_2" class="carousel thumbcarousel slide" data-interval="false">
<div class="carousel-inner">
<div class="item active">
<div data-target="#carousel_2" data-slide-to="0" class="thumb"><img src="https://picsum.photos/60/60?image=11"></div>
<div data-target="#carousel_2" data-slide-to="1" class="thumb"><img src="https://picsum.photos/60/60?image=12"></div>
<div data-target="#carousel_2" data-slide-to="2" class="thumb"><img src="https://picsum.photos/60/60?image=13"></div>
<div data-target="#carousel_2" data-slide-to="3" class="thumb"><img src="https://picsum.photos/60/60?image=14"></div>
<div data-target="#carousel_2" data-slide-to="4" class="thumb"><img src="https://picsum.photos/60/60?image=15"></div>
</div>
<div class="item">
<div data-target="#carousel_2" data-slide-to="5" class="thumb"><img src="https://picsum.photos/60/60?image=16"></div>
<div data-target="#carousel_2" data-slide-to="6" class="thumb"><img src="https://picsum.photos/60/60?image=17"></div>
<div data-target="#carousel_2" data-slide-to="7" class="thumb"><img src="https://picsum.photos/60/60?image=18"></div>
<div data-target="#carousel_2" data-slide-to="8" class="thumb"><img src="https://picsum.photos/60/60?image=19"></div>
<div data-target="#carousel_2" data-slide-to="9" class="thumb"><img src="https://picsum.photos/60/60?image=20"></div>
</div>
</div>
<!-- /carousel-inner -->
<a class="left carousel-control" href="#thumbcarousel_2" role="button" data-slide="prev">
<i class="fa fa-angle-left" aria-hidden="true"></i> </a>
<a class="right carousel-control" href="#thumbcarousel_2" role="button" data-slide="next"><i
class="fa fa-angle-right" aria-hidden="true"></i> </a>
</div>
<!-- /thumbcarousel -->
</div>
</div>
</div>
</div>
</div>
</div>
<div id="myModal3" class="modal fade" role="dialog">
<div class="modal-dialog modal-lg">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Modal Header</h4>
</div>
<div class="modal-body">
<div class="product-slider">
<div id="carousel_3" class="carousel slide" data-ride="carousel">
<div class="carousel-inner">
<div class="item active"> <img src="https://picsum.photos/950/500?image=21"> </div>
<div class="item"> <img src="https://picsum.photos/950/500?image=22"> </div>
<div class="item"> <img src="https://picsum.photos/950/500?image=23"> </div>
<div class="item"> <img src="https://picsum.photos/950/500?image=24"> </div>
<div class="item"> <img src="https://picsum.photos/950/500?image=25"> </div>
<div class="item"> <img src="https://picsum.photos/950/500?image=26"> </div>
<div class="item"> <img src="https://picsum.photos/950/500?image=27"> </div>
<div class="item"> <img src="https://picsum.photos/950/500?image=28"> </div>
<div class="item"> <img src="https://picsum.photos/950/500?image=29"> </div>
<div class="item"> <img src="https://picsum.photos/950/500?image=30"> </div>
</div>
</div>
<div class="clearfix">
<div id="thumbcarousel_3" class="carousel thumbcarousel slide" data-interval="false">
<div class="carousel-inner">
<div class="item active">
<div data-target="#carousel_3" data-slide-to="0" class="thumb"><img src="https://picsum.photos/60/60?image=21"></div>
<div data-target="#carousel_3" data-slide-to="1" class="thumb"><img src="https://picsum.photos/60/60?image=22"></div>
<div data-target="#carousel_3" data-slide-to="2" class="thumb"><img src="https://picsum.photos/60/60?image=23"></div>
<div data-target="#carousel_3" data-slide-to="3" class="thumb"><img src="https://picsum.photos/60/60?image=24"></div>
<div data-target="#carousel_3" data-slide-to="4" class="thumb"><img src="https://picsum.photos/60/60?image=25"></div>
</div>
<div class="item">
<div data-target="#carousel_3" data-slide-to="5" class="thumb"><img src="https://picsum.photos/60/60?image=26"></div>
<div data-target="#carousel_3" data-slide-to="6" class="thumb"><img src="https://picsum.photos/60/60?image=27"></div>
<div data-target="#carousel_3" data-slide-to="7" class="thumb"><img src="https://picsum.photos/60/60?image=28"></div>
<div data-target="#carousel_3" data-slide-to="8" class="thumb"><img src="https://picsum.photos/60/60?image=29"></div>
<div data-target="#carousel_3" data-slide-to="9" class="thumb"><img src="https://picsum.photos/60/60?image=30"></div>
</div>
</div>
<!-- /carousel-inner -->
<a class="left carousel-control" href="#thumbcarousel_3" role="button" data-slide="prev">
<i class="fa fa-angle-left" aria-hidden="true"></i> </a>
<a class="right carousel-control" href="#thumbcarousel_3" role="button" data-slide="next"><i
class="fa fa-angle-right" aria-hidden="true"></i> </a>
</div>
<!-- /thumbcarousel -->
</div>
</div>
</div>
</div>
</div>
</div>
``` | It is the issue of duplicated ids. All the carousels have id="carousel". Make it unique like this,
```
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<div class="container">
<div class="row">
<div class="col-md-12">
<button class="btn btn-primary" data-toggle="modal" data-target="#myModal1">Modal 1</button>
<button class="btn btn-primary" data-toggle="modal" data-target="#myModal2">Modal 2</button>
<button class="btn btn-primary" data-toggle="modal" data-target="#myModal3">Modal 3</button>
</div>
</div>
</div>
<div id="myModal1" class="modal fade" role="dialog">
<div class="modal-dialog modal-lg">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Modal Header</h4>
</div>
<div class="modal-body">
<div class="product-slider">
<div id="carousel" class="carousel slide" data-ride="carousel">
<div class="carousel-inner">
<div class="item active"> <img src="http://wowslider.com/sliders/demo-93/data1/images/sunset.jpg"> </div>
<div class="item"> <img src="http://wowslider.com/sliders/demo-93/data1/images/sunset.jpg"> </div>
<div class="item"> <img src="http://wowslider.com/sliders/demo-93/data1/images/sunset.jpg"> </div>
<div class="item"> <img src="http://wowslider.com/sliders/demo-93/data1/images/sunset.jpg"> </div>
<div class="item"> <img src="http://wowslider.com/sliders/demo-93/data1/images/sunset.jpg"> </div>
<div class="item"> <img src="http://wowslider.com/sliders/demo-93/data1/images/sunset.jpg"> </div>
<div class="item"> <img src="http://wowslider.com/sliders/demo-93/data1/images/sunset.jpg"> </div>
<div class="item"> <img src="http://wowslider.com/sliders/demo-93/data1/images/sunset.jpg"> </div>
<div class="item"> <img src="http://wowslider.com/sliders/demo-93/data1/images/sunset.jpg"> </div>
<div class="item"> <img src="http://wowslider.com/sliders/demo-93/data1/images/sunset.jpg"> </div>
</div>
</div>
<div class="clearfix">
<div id="thumbcarousel" class="carousel slide" data-interval="false">
<div class="carousel-inner">
<div class="item active">
<div data-target="#carousel" data-slide-to="0" class="thumb"><img src="http://wowslider.com/sliders/demo-93/data1/images/sunset.jpg"></div>
<div data-target="#carousel" data-slide-to="1" class="thumb"><img src="http://wowslider.com/sliders/demo-93/data1/images/sunset.jpg"></div>
<div data-target="#carousel" data-slide-to="2" class="thumb"><img src="http://wowslider.com/sliders/demo-93/data1/images/sunset.jpg"></div>
<div data-target="#carousel" data-slide-to="3" class="thumb"><img src="http://wowslider.com/sliders/demo-93/data1/images/sunset.jpg"></div>
<div data-target="#carousel" data-slide-to="4" class="thumb"><img src="http://wowslider.com/sliders/demo-93/data1/images/sunset.jpg"></div>
</div>
<div class="item">
<div data-target="#carousel" data-slide-to="5" class="thumb"><img src="http://wowslider.com/sliders/demo-93/data1/images/sunset.jpg"></div>
<div data-target="#carousel" data-slide-to="6" class="thumb"><img src="http://wowslider.com/sliders/demo-93/data1/images/sunset.jpg"></div>
<div data-target="#carousel" data-slide-to="7" class="thumb"><img src="http://wowslider.com/sliders/demo-93/data1/images/sunset.jpg"></div>
<div data-target="#carousel" data-slide-to="8" class="thumb"><img src="http://wowslider.com/sliders/demo-93/data1/images/sunset.jpg"></div>
<div data-target="#carousel" data-slide-to="9" class="thumb"><img src="http://wowslider.com/sliders/demo-93/data1/images/sunset.jpg"></div>
</div>
</div>
<!-- /carousel-inner -->
<a class="left carousel-control" href="#thumbcarousel" role="button" data-slide="prev"> <i class="fa fa-angle-left" aria-hidden="true"></i> </a> <a class="right carousel-control" href="#thumbcarousel" role="button" data-slide="next"><i class="fa fa-angle-right" aria-hidden="true"></i> </a> </div>
<!-- /thumbcarousel -->
</div>
</div>
</div>
</div>
</div>
</div>
<div id="myModal2" class="modal fade" role="dialog">
<div class="modal-dialog modal-lg">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Modal Header</h4>
</div>
<div class="modal-body">
<div class="product-slider">
<div id="carousel2" class="carousel slide" data-ride="carousel">
<div class="carousel-inner">
<div class="item active"> <img src="http://wowslider.com/sliders/demo-93/data1/images/lake.jpg"> </div>
<div class="item"> <img src="http://wowslider.com/sliders/demo-93/data1/images/lake.jpg"> </div>
<div class="item"> <img src="http://wowslider.com/sliders/demo-93/data1/images/lake.jpg"> </div>
<div class="item"> <img src="http://wowslider.com/sliders/demo-93/data1/images/lake.jpg"> </div>
<div class="item"> <img src="http://wowslider.com/sliders/demo-93/data1/images/lake.jpg"> </div>
<div class="item"> <img src="http://wowslider.com/sliders/demo-93/data1/images/lake.jpg"> </div>
<div class="item"> <img src="http://wowslider.com/sliders/demo-93/data1/images/lake.jpg"> </div>
<div class="item"> <img src="http://wowslider.com/sliders/demo-93/data1/images/lake.jpg"> </div>
<div class="item"> <img src="http://wowslider.com/sliders/demo-93/data1/images/lake.jpg"> </div>
<div class="item"> <img src="http://wowslider.com/sliders/demo-93/data1/images/lake.jpg"> </div>
</div>
</div>
<div class="clearfix">
<div id="thumbcarousel" class="carousel slide" data-interval="false">
<div class="carousel-inner">
<div class="item active">
<div data-target="#carousel2" data-slide-to="0" class="thumb"><img src="http://wowslider.com/sliders/demo-93/data1/images/lake.jpg"></div>
<div data-target="#carousel2" data-slide-to="1" class="thumb"><img src="http://wowslider.com/sliders/demo-93/data1/images/lake.jpg"></div>
<div data-target="#carousel2" data-slide-to="2" class="thumb"><img src="http://wowslider.com/sliders/demo-93/data1/images/lake.jpg"></div>
<div data-target="#carousel2" data-slide-to="3" class="thumb"><img src="http://wowslider.com/sliders/demo-93/data1/images/lake.jpg"></div>
<div data-target="#carousel2" data-slide-to="4" class="thumb"><img src="http://wowslider.com/sliders/demo-93/data1/images/lake.jpg"></div>
</div>
<div class="item">
<div data-target="#carousel2" data-slide-to="5" class="thumb"><img src="http://wowslider.com/sliders/demo-93/data1/images/lake.jpg"></div>
<div data-target="#carousel2" data-slide-to="6" class="thumb"><img src="http://wowslider.com/sliders/demo-93/data1/images/lake.jpg"></div>
<div data-target="#carousel2" data-slide-to="7" class="thumb"><img src="http://wowslider.com/sliders/demo-93/data1/images/lake.jpg"></div>
<div data-target="#carousel2" data-slide-to="8" class="thumb"><img src="http://wowslider.com/sliders/demo-93/data1/images/lake.jpg"></div>
<div data-target="#carousel2" data-slide-to="9" class="thumb"><img src="http://wowslider.com/sliders/demo-93/data1/images/lake.jpg"></div>
</div>
</div>
<!-- /carousel-inner -->
<a class="left carousel-control" href="#thumbcarousel" role="button" data-slide="prev"> <i class="fa fa-angle-left" aria-hidden="true"></i> </a> <a class="right carousel-control" href="#thumbcarousel" role="button" data-slide="next"><i class="fa fa-angle-right" aria-hidden="true"></i> </a> </div>
<!-- /thumbcarousel -->
</div>
</div>
</div>
</div>
</div>
</div>
<div id="myModal3" class="modal fade" role="dialog">
<div class="modal-dialog modal-lg">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Modal Header</h4>
</div>
<div class="modal-body">
<div class="product-slider">
<div id="carousel3" class="carousel slide" data-ride="carousel">
<div class="carousel-inner">
<div class="item active"> <img src="http://wowslider.com/sliders/demo-93/data1/images/landscape.jpg"> </div>
<div class="item"> <img src="http://wowslider.com/sliders/demo-93/data1/images/landscape.jpg"> </div>
<div class="item"> <img src="http://wowslider.com/sliders/demo-93/data1/images/landscape.jpg"> </div>
<div class="item"> <img src="http://wowslider.com/sliders/demo-93/data1/images/landscape.jpg"> </div>
<div class="item"> <img src="http://wowslider.com/sliders/demo-93/data1/images/landscape.jpg"> </div>
<div class="item"> <img src="http://wowslider.com/sliders/demo-93/data1/images/landscape.jpg"> </div>
<div class="item"> <img src="http://wowslider.com/sliders/demo-93/data1/images/landscape.jpg"> </div>
<div class="item"> <img src="http://wowslider.com/sliders/demo-93/data1/images/landscape.jpg"> </div>
<div class="item"> <img src="http://wowslider.com/sliders/demo-93/data1/images/landscape.jpg"> </div>
<div class="item"> <img src="http://wowslider.com/sliders/demo-93/data1/images/landscape.jpg"> </div>
</div>
</div>
<div class="clearfix">
<div id="thumbcarousel" class="carousel slide" data-interval="false">
<div class="carousel-inner">
<div class="item active">
<div data-target="#carousel3" data-slide-to="0" class="thumb"><img src="http://wowslider.com/sliders/demo-93/data1/images/landscape.jpg"></div>
<div data-target="#carousel3" data-slide-to="1" class="thumb"><img src="http://wowslider.com/sliders/demo-93/data1/images/landscape.jpg"></div>
<div data-target="#carousel3" data-slide-to="2" class="thumb"><img src="http://wowslider.com/sliders/demo-93/data1/images/landscape.jpg"></div>
<div data-target="#carousel3" data-slide-to="3" class="thumb"><img src="http://wowslider.com/sliders/demo-93/data1/images/landscape.jpg"></div>
<div data-target="#carousel3" data-slide-to="4" class="thumb"><img src="http://wowslider.com/sliders/demo-93/data1/images/landscape.jpg"></div>
</div>
<div class="item">
<div data-target="#carousel3" data-slide-to="5" class="thumb"><img src="http://wowslider.com/sliders/demo-93/data1/images/landscape.jpg"></div>
<div data-target="#carousel3" data-slide-to="6" class="thumb"><img src="http://wowslider.com/sliders/demo-93/data1/images/landscape.jpg"></div>
<div data-target="#carousel3" data-slide-to="7" class="thumb"><img src="http://wowslider.com/sliders/demo-93/data1/images/landscape.jpg"></div>
<div data-target="#carousel3" data-slide-to="8" class="thumb"><img src="http://wowslider.com/sliders/demo-93/data1/images/landscape.jpg"></div>
<div data-target="#carousel3" data-slide-to="9" class="thumb"><img src="http://wowslider.com/sliders/demo-93/data1/images/landscape.jpg"></div>
</div>
</div>
<!-- /carousel-inner -->
<a class="left carousel-control" href="#thumbcarousel" role="button" data-slide="prev"> <i class="fa fa-angle-left" aria-hidden="true"></i> </a> <a class="right carousel-control" href="#thumbcarousel" role="button" data-slide="next"><i class="fa fa-angle-right" aria-hidden="true"></i> </a> </div>
<!-- /thumbcarousel -->
</div>
</div>
</div>
</div>
</div>
</div>
``` |
4,090,867 | Want to prove that $$\arctan(x) = \frac{\pi}{2} - \frac{1}{x} + O\left(\frac{1}{x^3}\right) \ \text{as}~~~ x \to +\infty$$
Wolfram says that it's true but I'm trying to find some formal prove of this equality.
Here's what i found about that:
We know that $\arctan(x) = \frac{\pi}{2} - \int\_x^{+\infty}\frac{dt}{1 + t^2}$ (we can easily prove this by solving such integral). But what this one can give us for asymptotic assessment?
Seems like we have to prove that this integral equals to $-\frac{1}{x} + O\left(\frac{1}{x^3}\right)$, but how? | 2021/04/05 | [
"https://math.stackexchange.com/questions/4090867",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/840330/"
] | Welcome to MSE!
You have the exact right idea!
Why not let your holes be $\{1,2\}$, $\{3,4\}$, $\{5,6\}$, $\{7,8\}$, and $\{9,10\}$?
Then you're guaranteed $2$ pigeons in the same hole, but the sum of two consecutive numbers is odd.
---
I hope this helps ^\_^ | Let $n$ be even. Notice that there are $n/2$ even and odd numbers. (The problem is equivalent to choosing $n/2$+$1$ integers from [$n$]). So partition [$n$] into two sets, one containing all of the $n/2$ even numbers, and the other $n/2$ odd numbers. By the pigeonhole principle, there are two integers with opposite parity. Their sum is an odd number.
This problem is the special case when $n$=$10$. |
45,922,355 | When the date is NULL I want to display 'N/A', but if the date is not null I want to display the date in the dB. This is what I currently have and I get a DataType Mismatch in the THEN/ELSE expressions. I am assuming it is because I am trying to display a character in a date field.
```
SELECT
CASE WHEN created_at IS NULL
THEN 'N/A'
ELSE created_at
END AS created_at
FROM example.example_id
```
Is this possible? | 2017/08/28 | [
"https://Stackoverflow.com/questions/45922355",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8328455/"
] | You can't mix data types.
```
SELECT COALESCE(CAST(created_at AS VARCHAR(100)),'NA') AS created_at
FROM example.example_id
```
Alternatively, if you are just concerned about presentation, you can just adjust your user preferences. ex. SQL Assistant -> Options -> Data Format -> then set 'Display this string for Null data values' as 'NA'. | Your assumption is correct: you can't mix a date(time) datatype with a varchar datatype. The solution is to cast the date to a varchar:
```
SELECT CASE WHEN created_at IS NULL THEN 'N/A'
ELSE CAST (created_at as char(8) format 'YYYYMMDD')
END AS created_at
FROM example.example_id
```
the convert here may need some tweaking depending how you want it displayed. |
45,922,355 | When the date is NULL I want to display 'N/A', but if the date is not null I want to display the date in the dB. This is what I currently have and I get a DataType Mismatch in the THEN/ELSE expressions. I am assuming it is because I am trying to display a character in a date field.
```
SELECT
CASE WHEN created_at IS NULL
THEN 'N/A'
ELSE created_at
END AS created_at
FROM example.example_id
```
Is this possible? | 2017/08/28 | [
"https://Stackoverflow.com/questions/45922355",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8328455/"
] | Instead of CASE you can use COALESCE, too, but you still need to convert the date to a string first:
```
Coalesce(To_Char(created_at, 'yyyy-mm-dd'), 'N/A')
``` | Your assumption is correct: you can't mix a date(time) datatype with a varchar datatype. The solution is to cast the date to a varchar:
```
SELECT CASE WHEN created_at IS NULL THEN 'N/A'
ELSE CAST (created_at as char(8) format 'YYYYMMDD')
END AS created_at
FROM example.example_id
```
the convert here may need some tweaking depending how you want it displayed. |
45,922,355 | When the date is NULL I want to display 'N/A', but if the date is not null I want to display the date in the dB. This is what I currently have and I get a DataType Mismatch in the THEN/ELSE expressions. I am assuming it is because I am trying to display a character in a date field.
```
SELECT
CASE WHEN created_at IS NULL
THEN 'N/A'
ELSE created_at
END AS created_at
FROM example.example_id
```
Is this possible? | 2017/08/28 | [
"https://Stackoverflow.com/questions/45922355",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8328455/"
] | You can't mix data types.
```
SELECT COALESCE(CAST(created_at AS VARCHAR(100)),'NA') AS created_at
FROM example.example_id
```
Alternatively, if you are just concerned about presentation, you can just adjust your user preferences. ex. SQL Assistant -> Options -> Data Format -> then set 'Display this string for Null data values' as 'NA'. | Simply you can try
```
SELECT CAST(VARCHAR, ISNULL(Created_at, 'N/A')) As 'Created_at'
FROM example.example_id
``` |
45,922,355 | When the date is NULL I want to display 'N/A', but if the date is not null I want to display the date in the dB. This is what I currently have and I get a DataType Mismatch in the THEN/ELSE expressions. I am assuming it is because I am trying to display a character in a date field.
```
SELECT
CASE WHEN created_at IS NULL
THEN 'N/A'
ELSE created_at
END AS created_at
FROM example.example_id
```
Is this possible? | 2017/08/28 | [
"https://Stackoverflow.com/questions/45922355",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8328455/"
] | Instead of CASE you can use COALESCE, too, but you still need to convert the date to a string first:
```
Coalesce(To_Char(created_at, 'yyyy-mm-dd'), 'N/A')
``` | Simply you can try
```
SELECT CAST(VARCHAR, ISNULL(Created_at, 'N/A')) As 'Created_at'
FROM example.example_id
``` |
5,937,653 | I am currently working in Ubuntu9.10 - c++.
I need to define an generic object in a method. I have to define the method in .h file. How can I do it? I did the following:
*file.h*
```
class ana
{
//code
public:
template <class T> bool method (T &Data);
};
```
*file.cpp*
```
//code
template <class T>
bool ana::method(T &Data)
{
//code
}
```
I've created the `.a` file.
In `test.cpp`:
```
//code
main()
{
//code
Ana* ann = new Ana();
if (ann->method(*ann)){//code}
}
```
After compiling with `g++ test.cpp -o test libfile.a` I have the error: `undefined reference to bool....` Why? Is there another way to create a generic object? | 2011/05/09 | [
"https://Stackoverflow.com/questions/5937653",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/726736/"
] | The usual problem. Have a look: <http://www.parashift.com/c++-faq-lite/templates.html#faq-35.13>.
Just put everything into a header file.
file.hpp
```
class ana
{
//code
public:
template <class T> bool method (T &Data)
{
//code
}
};
```
Include this in your main.cpp and it should work fine.
```
#include "file.hpp"
main()
{
//code
Ana* ann = new Ana();
if (ann->method(*ann)){//code}
}
``` | 1. You forgot to build `file.cpp` into the binary.
2. You should put the function template definition in the header, anyway. |
5,937,653 | I am currently working in Ubuntu9.10 - c++.
I need to define an generic object in a method. I have to define the method in .h file. How can I do it? I did the following:
*file.h*
```
class ana
{
//code
public:
template <class T> bool method (T &Data);
};
```
*file.cpp*
```
//code
template <class T>
bool ana::method(T &Data)
{
//code
}
```
I've created the `.a` file.
In `test.cpp`:
```
//code
main()
{
//code
Ana* ann = new Ana();
if (ann->method(*ann)){//code}
}
```
After compiling with `g++ test.cpp -o test libfile.a` I have the error: `undefined reference to bool....` Why? Is there another way to create a generic object? | 2011/05/09 | [
"https://Stackoverflow.com/questions/5937653",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/726736/"
] | The usual problem. Have a look: <http://www.parashift.com/c++-faq-lite/templates.html#faq-35.13>.
Just put everything into a header file.
file.hpp
```
class ana
{
//code
public:
template <class T> bool method (T &Data)
{
//code
}
};
```
Include this in your main.cpp and it should work fine.
```
#include "file.hpp"
main()
{
//code
Ana* ann = new Ana();
if (ann->method(*ann)){//code}
}
``` | You need to change the definition of your `method()` method to be in the header file:
```
class ana
{
public:
template <class T>
bool method (T &Data)
{
// Do whatever you want in here
}
};
```
Check the following link out for a detailed explanation - <http://www.parashift.com/c++-faq-lite/templates.html#faq-35.12> |
5,937,653 | I am currently working in Ubuntu9.10 - c++.
I need to define an generic object in a method. I have to define the method in .h file. How can I do it? I did the following:
*file.h*
```
class ana
{
//code
public:
template <class T> bool method (T &Data);
};
```
*file.cpp*
```
//code
template <class T>
bool ana::method(T &Data)
{
//code
}
```
I've created the `.a` file.
In `test.cpp`:
```
//code
main()
{
//code
Ana* ann = new Ana();
if (ann->method(*ann)){//code}
}
```
After compiling with `g++ test.cpp -o test libfile.a` I have the error: `undefined reference to bool....` Why? Is there another way to create a generic object? | 2011/05/09 | [
"https://Stackoverflow.com/questions/5937653",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/726736/"
] | The usual problem. Have a look: <http://www.parashift.com/c++-faq-lite/templates.html#faq-35.13>.
Just put everything into a header file.
file.hpp
```
class ana
{
//code
public:
template <class T> bool method (T &Data)
{
//code
}
};
```
Include this in your main.cpp and it should work fine.
```
#include "file.hpp"
main()
{
//code
Ana* ann = new Ana();
if (ann->method(*ann)){//code}
}
``` | Just include cpp file in **main.cpp** like this: **#include "ana.cpp"** and you will not have errors. |
5,937,653 | I am currently working in Ubuntu9.10 - c++.
I need to define an generic object in a method. I have to define the method in .h file. How can I do it? I did the following:
*file.h*
```
class ana
{
//code
public:
template <class T> bool method (T &Data);
};
```
*file.cpp*
```
//code
template <class T>
bool ana::method(T &Data)
{
//code
}
```
I've created the `.a` file.
In `test.cpp`:
```
//code
main()
{
//code
Ana* ann = new Ana();
if (ann->method(*ann)){//code}
}
```
After compiling with `g++ test.cpp -o test libfile.a` I have the error: `undefined reference to bool....` Why? Is there another way to create a generic object? | 2011/05/09 | [
"https://Stackoverflow.com/questions/5937653",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/726736/"
] | Putting function definitions together with declarations (in the header files itself) definitely helps and is the way of choice. But, in case you want to separate the function definitions, have the following lines at the end of the `.cpp` file. Its called `explicit instantiation`.This will take care of linker errors. I tried some code, and this seems to work, based on what you have given:
*file.h:*
```
#ifndef __ANA_H__
#define __ANA_H__
template <class T>
class ana {
public:
bool method(T& data);
};
#endif
```
*file.cpp:*
```
#include <ana.h>
#include <iostream>
using namespace std;
template <typename T>
bool ana<T>::method(T& data) {
cout << "Data = " << data << endl;
if(data > 0) {
return true;
}
return false;
}
//explicit instantiation for avoidance of g++ linker errors.
template
bool ana<int>::method(int& data);
template
bool ana<double>::method(double& data)
```
One of the downsides of using this method is that these lines will have to be included for *every* data type that you want this function to support. So, now the method function will run ONLY for `int` and `double`. The specs for your code should be such that method is never called for data types other than the above.
HTH,
Sriram | 1. You forgot to build `file.cpp` into the binary.
2. You should put the function template definition in the header, anyway. |
5,937,653 | I am currently working in Ubuntu9.10 - c++.
I need to define an generic object in a method. I have to define the method in .h file. How can I do it? I did the following:
*file.h*
```
class ana
{
//code
public:
template <class T> bool method (T &Data);
};
```
*file.cpp*
```
//code
template <class T>
bool ana::method(T &Data)
{
//code
}
```
I've created the `.a` file.
In `test.cpp`:
```
//code
main()
{
//code
Ana* ann = new Ana();
if (ann->method(*ann)){//code}
}
```
After compiling with `g++ test.cpp -o test libfile.a` I have the error: `undefined reference to bool....` Why? Is there another way to create a generic object? | 2011/05/09 | [
"https://Stackoverflow.com/questions/5937653",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/726736/"
] | Putting function definitions together with declarations (in the header files itself) definitely helps and is the way of choice. But, in case you want to separate the function definitions, have the following lines at the end of the `.cpp` file. Its called `explicit instantiation`.This will take care of linker errors. I tried some code, and this seems to work, based on what you have given:
*file.h:*
```
#ifndef __ANA_H__
#define __ANA_H__
template <class T>
class ana {
public:
bool method(T& data);
};
#endif
```
*file.cpp:*
```
#include <ana.h>
#include <iostream>
using namespace std;
template <typename T>
bool ana<T>::method(T& data) {
cout << "Data = " << data << endl;
if(data > 0) {
return true;
}
return false;
}
//explicit instantiation for avoidance of g++ linker errors.
template
bool ana<int>::method(int& data);
template
bool ana<double>::method(double& data)
```
One of the downsides of using this method is that these lines will have to be included for *every* data type that you want this function to support. So, now the method function will run ONLY for `int` and `double`. The specs for your code should be such that method is never called for data types other than the above.
HTH,
Sriram | You need to change the definition of your `method()` method to be in the header file:
```
class ana
{
public:
template <class T>
bool method (T &Data)
{
// Do whatever you want in here
}
};
```
Check the following link out for a detailed explanation - <http://www.parashift.com/c++-faq-lite/templates.html#faq-35.12> |
5,937,653 | I am currently working in Ubuntu9.10 - c++.
I need to define an generic object in a method. I have to define the method in .h file. How can I do it? I did the following:
*file.h*
```
class ana
{
//code
public:
template <class T> bool method (T &Data);
};
```
*file.cpp*
```
//code
template <class T>
bool ana::method(T &Data)
{
//code
}
```
I've created the `.a` file.
In `test.cpp`:
```
//code
main()
{
//code
Ana* ann = new Ana();
if (ann->method(*ann)){//code}
}
```
After compiling with `g++ test.cpp -o test libfile.a` I have the error: `undefined reference to bool....` Why? Is there another way to create a generic object? | 2011/05/09 | [
"https://Stackoverflow.com/questions/5937653",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/726736/"
] | Putting function definitions together with declarations (in the header files itself) definitely helps and is the way of choice. But, in case you want to separate the function definitions, have the following lines at the end of the `.cpp` file. Its called `explicit instantiation`.This will take care of linker errors. I tried some code, and this seems to work, based on what you have given:
*file.h:*
```
#ifndef __ANA_H__
#define __ANA_H__
template <class T>
class ana {
public:
bool method(T& data);
};
#endif
```
*file.cpp:*
```
#include <ana.h>
#include <iostream>
using namespace std;
template <typename T>
bool ana<T>::method(T& data) {
cout << "Data = " << data << endl;
if(data > 0) {
return true;
}
return false;
}
//explicit instantiation for avoidance of g++ linker errors.
template
bool ana<int>::method(int& data);
template
bool ana<double>::method(double& data)
```
One of the downsides of using this method is that these lines will have to be included for *every* data type that you want this function to support. So, now the method function will run ONLY for `int` and `double`. The specs for your code should be such that method is never called for data types other than the above.
HTH,
Sriram | Just include cpp file in **main.cpp** like this: **#include "ana.cpp"** and you will not have errors. |
25,460,106 | I am trying to setup a Jersey RESTful service, the problem is that I am getting the following error when trying to do GET request to the following API: `http://localhost:8080/GroupAppServer/api/status`:
```
com.sun.jersey.api.container.ContainerException: The ResourceConfig instance does not contain any root resource classes.
```
Here is my web.xml file:
```
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
id="WebApp_ID" version="3.0">
<display-name>GroupAppServer</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>jersey-servlet</servlet-name>
<servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
<init-param>
<param-name>com.sun.jersey.config.property.packages</param-name>
<param-value>GroupAppServer</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>jersey-servlet</servlet-name>
<url-pattern>/api/*</url-pattern>
</servlet-mapping>
</web-app>
```
under src I have a package called "com.groupappserver.api" which holds my `Status` class. Here is the code:
```
package com.groupappserver.api;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import com.groupservice.utils.Response;
@Path("/status")
public class Status
{
@GET
@Produces(MediaType.APPLICATION_JSON)
public Response getStatus()
{
return new Response();
}
}
```
Here is my pom.xml:
```
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>GroupAppServer</groupId>
<artifactId>GroupAppServer</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<build>
<sourceDirectory>src</sourceDirectory>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<source>1.7</source>
<target>1.7</target>
</configuration>
</plugin>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<version>2.3</version>
<configuration>
<warSourceDirectory>WebContent</warSourceDirectory>
<failOnMissingWebXml>false</failOnMissingWebXml>
</configuration>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-server</artifactId>
<version>1.18.1</version>
</dependency>
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-core</artifactId>
<version>1.18.1</version>
</dependency>
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-servlet</artifactId>
<version>1.18.1</version>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.3</version>
</dependency>
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20140107</version>
</dependency>
</dependencies>
</project>
```
Any ideas why I am getting this error? and how can I fix this? | 2014/08/23 | [
"https://Stackoverflow.com/questions/25460106",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1691423/"
] | You are calling your changeTextOnLoad function before the main.js file has loaded. Either put the function call in an onload event callback or put the include above the call
```
window.onload = function(){
var object = $('#text_object');
changeTextOnLoad(object);
};
//Or using addEventListener
window.addEventListener("load",function(){
var object = $('#text_object');
changeTextOnLoad(object);
});
//Or since you are using jQuery
$(document).ready(function(){
var object = $('#text_object');
changeTextOnLoad(object);
});
//Or
$(function(){
var object = $('#text_object');
changeTextOnLoad(object);
});
```
OR
```
<script type="text/javascript" src="main.js"></script>
<script type="text/javascript">
var object = $('#text_object');
changeTextOnLoad(object);
</script>
``` | because main.js is another file, browser takes time to download it. But you run `changeTextOnLoad(object);` before that. |
40,839,832 | i am developing an app where facebook login is there . i am trying to get user information and send that to my server.i am using sdk 4.i am trying to use shared preference to save info but i have no idea about shared preference . This is my facebook login activity . this is launcher activity.
```
public class LoginActivity extends AbsRuntimePermission {
private static final int REQUEST_Permission =10;
private TextView info;
private LoginButton loginButton;
private CallbackManager callbackManager;
private SparseIntArray mErrorString;
private Button facebook_button;
ProgressDialog progress;
private String facebook_id,f_name,m_name,l_name,gender,profile_image,full_name,email_id;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
//for permission in manifest file cause it is launch activity
requestAppPermissions(new String[]{
Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.ACCESS_COARSE_LOCATION,
Manifest.permission.CALL_PHONE,
Manifest.permission.INTERNET},R.string.msg,REQUEST_Permission);
//facebook
info = (TextView) findViewById(R.id.info);
loginButton = (LoginButton) findViewById(R.id.login_button);
progress = new ProgressDialog(LoginActivity.this);
progress.setMessage(getResources().getString(R.string.please_wait_facebooklogin));
progress.setIndeterminate(false);
progress.setCancelable(false);
facebook_id=f_name=m_name=l_name=gender=profile_image=full_name=email_id="";
//facebook sdk
FacebookSdk.sdkInitialize(getApplicationContext());
callbackManager = CallbackManager.Factory.create();
//register callback object for facebook result
LoginManager.getInstance().registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
@Override
public void onSuccess(LoginResult loginResult) {
progress.show();
Profile profile = Profile.getCurrentProfile();
if(profile != null){
facebook_id = profile.getId();
f_name=profile.getFirstName();
m_name=profile.getMiddleName();
l_name=profile.getLastName();
profile_image=profile.getProfilePictureUri(400,400).toString();
}
//show Toast
GraphRequest request =GraphRequest.newMeRequest(AccessToken.getCurrentAccessToken(),
new GraphRequest.GraphJSONObjectCallback(){
@Override
public void onCompleted(JSONObject object, GraphResponse response) {
try {
email_id = object.getString("email");
gender = object.getString("gender");
String Profile_name = object.getString("name");
long fb_id = object.getLong("id"); //use this for logout
//Starting a new activity using this information
Intent i = new Intent(LoginActivity.this, MainActivity.class);
i.putExtra("type", "facebook");
i.putExtra("Facebook_id", facebook_id);
i.putExtra("f_name", f_name);
i.putExtra("m_name", m_name);
i.putExtra("l_name", l_name);
i.putExtra("full_name", full_name);
i.putExtra("Profile_image", profile_image);
i.putExtra("email_id", email_id);
i.putExtra("gender", gender);
progress.dismiss();
startActivity(i);
finish();
}catch (JSONException e){
e.printStackTrace();
}
}
});
request.executeAsync();
}
@Override
public void onCancel() {
Toast.makeText(LoginActivity.this,getResources().getString(R.string.login_canceled_facebooklogin),Toast.LENGTH_SHORT).show();
progress.dismiss();
}
@Override
public void onError(FacebookException error) {
Toast.makeText(LoginActivity.this,getResources().getString(R.string.login_failed_facebooklogin),Toast.LENGTH_SHORT).show();
progress.dismiss();
}
});
//facebook button click
facebook_button.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View view) {
LoginManager.getInstance().logInWithReadPermissions(LoginActivity.this, Arrays.asList("public_profile","user_friends","email"));
}
});
}
private void logoutFromFacebook(){
try{
if(AccessToken.getCurrentAccessToken()==null){
return;
}
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
callbackManager.onActivityResult(requestCode,resultCode,data);
}
@Override
public void onPermissionGranted(int requestCode) {
//anything after permission Granted
Toast.makeText(getApplicationContext(),"Permission granted",Toast.LENGTH_LONG).show();
}
public void goTo(View view) {
Intent intent = new Intent(this, MainActivity.class);
this.startActivity(intent);
}
```
} | 2016/11/28 | [
"https://Stackoverflow.com/questions/40839832",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7197844/"
] | >
> Android SharedPreferences allows us to store private primitive
> application data in the form of key-value pair.For More details follow [this](http://androidopentutorials.com/android-sharedpreferences-tutorial-and-example/).
>
>
>
To read from shared preference use something like this.
```
String dateFromSharedPreferences=getActivity().getPreferences(Context.MODE_PRIVATE);
sharedPref.getString("Username");
```
To save into shared preference
```
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("Username", YourUsername);
editor.putString("Password", YourPassword);
editor.apply();
```
You are passing the values from `LoginActivity` to `MainActivity` so code in `MainActivity` at `onCreate` function like following to get the passed values ans show in textview.
```
((TextView)findViewById(R.id.tv1)).setText(getIntent().getExtras().getString("full_name"));
((TextView)findViewById(R.id.tv2)).setText(getIntent().getExtras().getString("email_id"));
((TextView)findViewById(R.id.tv3)).setText(getIntent().getExtras().getString("gender"));
``` | ```
SharedPreferences sharedPreferences;
SharedPreferences.Editor editor;
```
Write this code before going to intent.
```
sharedPreferences = getApplicationContext().getSharedPreferences("pref", MODE_PRIVATE);
editor = sharedPreferences.edit();
editor.putString("User_Name", f_name);
editor.putString("User_Email", email_id);
editor.apply();
``` |
40,839,832 | i am developing an app where facebook login is there . i am trying to get user information and send that to my server.i am using sdk 4.i am trying to use shared preference to save info but i have no idea about shared preference . This is my facebook login activity . this is launcher activity.
```
public class LoginActivity extends AbsRuntimePermission {
private static final int REQUEST_Permission =10;
private TextView info;
private LoginButton loginButton;
private CallbackManager callbackManager;
private SparseIntArray mErrorString;
private Button facebook_button;
ProgressDialog progress;
private String facebook_id,f_name,m_name,l_name,gender,profile_image,full_name,email_id;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
//for permission in manifest file cause it is launch activity
requestAppPermissions(new String[]{
Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.ACCESS_COARSE_LOCATION,
Manifest.permission.CALL_PHONE,
Manifest.permission.INTERNET},R.string.msg,REQUEST_Permission);
//facebook
info = (TextView) findViewById(R.id.info);
loginButton = (LoginButton) findViewById(R.id.login_button);
progress = new ProgressDialog(LoginActivity.this);
progress.setMessage(getResources().getString(R.string.please_wait_facebooklogin));
progress.setIndeterminate(false);
progress.setCancelable(false);
facebook_id=f_name=m_name=l_name=gender=profile_image=full_name=email_id="";
//facebook sdk
FacebookSdk.sdkInitialize(getApplicationContext());
callbackManager = CallbackManager.Factory.create();
//register callback object for facebook result
LoginManager.getInstance().registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
@Override
public void onSuccess(LoginResult loginResult) {
progress.show();
Profile profile = Profile.getCurrentProfile();
if(profile != null){
facebook_id = profile.getId();
f_name=profile.getFirstName();
m_name=profile.getMiddleName();
l_name=profile.getLastName();
profile_image=profile.getProfilePictureUri(400,400).toString();
}
//show Toast
GraphRequest request =GraphRequest.newMeRequest(AccessToken.getCurrentAccessToken(),
new GraphRequest.GraphJSONObjectCallback(){
@Override
public void onCompleted(JSONObject object, GraphResponse response) {
try {
email_id = object.getString("email");
gender = object.getString("gender");
String Profile_name = object.getString("name");
long fb_id = object.getLong("id"); //use this for logout
//Starting a new activity using this information
Intent i = new Intent(LoginActivity.this, MainActivity.class);
i.putExtra("type", "facebook");
i.putExtra("Facebook_id", facebook_id);
i.putExtra("f_name", f_name);
i.putExtra("m_name", m_name);
i.putExtra("l_name", l_name);
i.putExtra("full_name", full_name);
i.putExtra("Profile_image", profile_image);
i.putExtra("email_id", email_id);
i.putExtra("gender", gender);
progress.dismiss();
startActivity(i);
finish();
}catch (JSONException e){
e.printStackTrace();
}
}
});
request.executeAsync();
}
@Override
public void onCancel() {
Toast.makeText(LoginActivity.this,getResources().getString(R.string.login_canceled_facebooklogin),Toast.LENGTH_SHORT).show();
progress.dismiss();
}
@Override
public void onError(FacebookException error) {
Toast.makeText(LoginActivity.this,getResources().getString(R.string.login_failed_facebooklogin),Toast.LENGTH_SHORT).show();
progress.dismiss();
}
});
//facebook button click
facebook_button.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View view) {
LoginManager.getInstance().logInWithReadPermissions(LoginActivity.this, Arrays.asList("public_profile","user_friends","email"));
}
});
}
private void logoutFromFacebook(){
try{
if(AccessToken.getCurrentAccessToken()==null){
return;
}
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
callbackManager.onActivityResult(requestCode,resultCode,data);
}
@Override
public void onPermissionGranted(int requestCode) {
//anything after permission Granted
Toast.makeText(getApplicationContext(),"Permission granted",Toast.LENGTH_LONG).show();
}
public void goTo(View view) {
Intent intent = new Intent(this, MainActivity.class);
this.startActivity(intent);
}
```
} | 2016/11/28 | [
"https://Stackoverflow.com/questions/40839832",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7197844/"
] | >
> Android SharedPreferences allows us to store private primitive
> application data in the form of key-value pair.For More details follow [this](http://androidopentutorials.com/android-sharedpreferences-tutorial-and-example/).
>
>
>
To read from shared preference use something like this.
```
String dateFromSharedPreferences=getActivity().getPreferences(Context.MODE_PRIVATE);
sharedPref.getString("Username");
```
To save into shared preference
```
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("Username", YourUsername);
editor.putString("Password", YourPassword);
editor.apply();
```
You are passing the values from `LoginActivity` to `MainActivity` so code in `MainActivity` at `onCreate` function like following to get the passed values ans show in textview.
```
((TextView)findViewById(R.id.tv1)).setText(getIntent().getExtras().getString("full_name"));
((TextView)findViewById(R.id.tv2)).setText(getIntent().getExtras().getString("email_id"));
((TextView)findViewById(R.id.tv3)).setText(getIntent().getExtras().getString("gender"));
``` | I know this type of question so many answer but still i am give this question's answer, I hope some one got the help. It's easy if we create method to handle all data.
When receive facebook JSON object then after do as follow.
```
try {
Bundle bFacebookData = getFacebookData(object);
progressDialog.dismiss();
progressDialog.cancel();
setSessionData(bFacebookData);
}catch (JSONException e){
e.printStackTrace();
}
```
//here you can get all facebook data and store in bundle
```
private Bundle getFacebookData(JSONObject object)
{
try {
Bundle bundle = new Bundle();
//String id = object.getString("id");
try
{
URL profile_pic = new URL("https://graph.facebook.com/" + object.getString("id") + "/picture?width=200&height=150");
Log.i("profile_pic", profile_pic + "");
if (profile_pic.toString() != null)
{
bundle.putString("profile_pic", profile_pic.toString());
}
else
{
bundle.putString("profile_pic", "noProfilePic");
}
} catch (MalformedURLException e) {
e.printStackTrace();
return null;
}
if (object.has("id"))
{
if (object.getString("id") != null)
{
bundle.putString("userId", object.getString("id"));
Log.i(TAG, "Info " + object.getString("id"));
}
else
{
bundle.putString("userId", "noUserId");
Log.i(TAG, "Info " + object.getString("id"));
}
}
if (object.has("first_name"))
{
if (object.getString("first_name") != null)
{
bundle.putString("first_name", object.getString("first_name"));
Log.i(TAG + "Info", object.getString("first_name"));
}
else
{
bundle.putString("first_name", "noFirstName");
Log.i(TAG + "Info", object.getString("first_name"));
}
}
if (object.has("last_name"))
{
if (object.getString("last_name") != null)
{
bundle.putString("last_name", object.getString("last_name"));
Log.i(TAG + "Info", object.getString("last_name"));
}
else
{
bundle.putString("last_name", "noLastName");
Log.i(TAG + "Info", object.getString("last_name"));
}
}
if (object.has("email"))
{
if (object.getString("email") != null)
{
bundle.putString("email", object.getString("email"));
Log.i(TAG + "Info", object.getString("email"));
}
else
{
bundle.putString("email", "noEmail");
Log.i(TAG + "Info", object.getString("email"));
}
}
//this is added dynamically
bundle.putString("phone", "noPhone");
if (object.has("gender"))
{
if (object.getString("gender") != null)
{
bundle.putString("gender", object.getString("gender"));
Log.i(TAG + "Info", object.getString("gender"));
}
else
{
bundle.putString("gender", "noGender");
Log.i(TAG + "Info", object.getString("gender"));
}
}
if (object.has("birthday"))
{
if (object.getString("birthday") != null)
{
bundle.putString("birthday", object.getString("birthday"));
Log.i(TAG + "Info", object.getString("birthday"));
}
else
{
bundle.putString("birthday", "noDateOfBirth");
Log.i(TAG + "Info", object.getString("birthday"));
}
}
if (object.has("location"))
{
if (object.getJSONObject("location").getString("name") != null)
{
bundle.putString("location", object.getJSONObject("location").getString("name"));
Log.i(TAG + "Info", object.getJSONObject("location").getString("name"));
}
else
{
bundle.putString("location", "noLocation");
Log.i(TAG + "Info", object.getJSONObject("location").getString("name"));
}
}
return bundle;
} catch (Exception e) {
e.printStackTrace();
} finally {
}
return null;
}
```
//here you can store data in SharedPreferences and start new activity
```
String userId = "", userEmail = "", userFirstName = "", userLastName = "",
userPhone = "", dateOfBirth = "", gender = "", profilePic = "";
private void setSessionData(Bundle bundle)
{
try
{
userId = bundle.getString("userId");
userEmail = bundle.getString("email");
userFirstName = bundle.getString("first_name");
userLastName = bundle.getString("last_name");
userPhone = bundle.getString("phone");
dateOfBirth = bundle.getString("birthday");
gender = bundle.getString("gender");
profilePic = bundle.getString("profile_pic");
if (userId !=null)
{
SharedPreferences sharedPreferences = getApplicationContext().getSharedPreferences("pref", MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("userId", userId);
editor.putString("email", userEmail);
editor.putString("first_name", userFirstName);
editor.putString("last_name", userLastName);
editor.putString("phone", userPhone);
editor.putString("birthday", dateOfBirth);
editor.putString("gender", gender);
editor.putString("profile_pic", profilePic);
editor.apply();
Intent i = new Intent(activity, MainActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
activity.startActivity(i);
}
else
{
//"Some thing went wrong Please try again"
}
}
catch (Exception e)
{
e.printStackTrach();
}
}
```
Your another class to receive data from SharedPreferences
```
SharedPreferences sharedPreferences = getApplicationContext().getSharedPreferences("pref", MODE_PRIVATE);
((TextView)findViewById(R.id.tv1)).setText(sharedPreferences.getString("first_name", ""));
((TextView)findViewById(R.id.tv2)).setText(sharedPreferences.getString("last_name", ""));
``` |
22,922,544 | I have a UINavigationController with a UIViewController (VC1) pushed onto it. VC1 contains a collectionView. When a user taps a cell, a child viewController (VC2) is added to VC1.
VC2 should support all orientations. Whereas VC1 only supports portrait orientation. In portrait mode, I want to be able to present VC2, rotate into landscape, have VC2 adjust its layout accordingly, dismiss VC2, revealing VC1 still in portrait orientation/layout.
The shouldAutorotate method in VC2 gets called when VC2 is presented using the stock method. However this is insufficient because it doesn't allow a custom transition:
(1)
```
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
CommentsViewController *vc = [[CommentsViewController alloc] initWithNibName:@"CommentsViewController" bundle:nil];
[self presentViewController:vc animated:YES completion:nil];
}
```
The shouldAutorotate method is NOT called when using `presentViewController:animated:completion:` with a custom transition or using traditional viewController containment methods. In other words, neither of these work:
(2)
```
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
CommentsViewController *vc = [[CommentsViewController alloc] initWithNibName:@"CommentsViewController" bundle:nil];
self.transitioningDelegate = [[TransitioningDelegate alloc] init];
vc.modalPresentationStyle = UIModalPresentationCustom;
vc.transitioningDelegate = self.transitioningDelegate;
[self presentViewController:vc animated:YES completion:nil];
}
```
(3)
```
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
CommentsViewController *vc = [[CommentsViewController alloc] initWithNibName:@"CommentsViewController" bundle:nil];
[self addChildViewController:vc];
vc.view.frame = self.view.bounds;
[self.view addSubview:vc.view]; // Assume I'm doing a cool custom animation here
[vc didMoveToParentViewController:self];
}
```
In summary, using approach #1 the rotation methods are called properly. But using #2 and #3 they are not. This prohibits me from building the required custom transition because doing so would mean the child viewController not supporting all orientations.
Any help would be much appreciated.
For background: I am versed in iOS6/7 rotation APIs, UIViewController containment, and custom viewController transitions.
**Edit:**
I did implement `shouldAutomaticallyForwardRotationMethods` to no avail. | 2014/04/07 | [
"https://Stackoverflow.com/questions/22922544",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/922200/"
] | So, this might not be what you need, but it seems like the presenting view controller maintains control of the shouldAutorotate call if your animated transition does not remove the presenting view controller's view. If you do remove the presenting view controller's view, then the control of the shouldAutorotate call moves up to the presented view controller.
I'm not sure how to send control automatically up without removing the view (so that you can show a transparent view), but you could just forward the shouldAutorotate call manually:
```
- (BOOL) shouldAutorotate{
if(self.presentedViewController){
return [self.presentedViewController shouldAutorotate];
}
return YES;
}
```
Not the most ideal though. | Did you happen to implement `- (BOOL)shouldAutomaticallyForwardRotationMethods` on the parent controller and have it return NO?
You case may be more complex, since you support different rotations for the different parent and child view controllers, but this is a easy gotcha to miss. |
50,943,141 | i have some paragraphs. At first one of that should have red color and after click it should become black, and clicked one should become red. I need to change red each paragraph when it is clicked and remove the class when another one is clicked. I should do it with javascript
```js
var p = document.querySelectorAll("p");
for( var i = 0; i < p.length; i++ ){
p[i].addEventListener("click", makeRed);
p[0].classList.add("active");
}
function makeRed(){
p[0].classList.remove("active");
if( this.classList.contains("active")){
this.classList.remove("active");
} else{
this.classList.add("active");
}
}
```
```css
.active{
color: red;
}
```
```html
<p>Text First</p>
<p>Text Second</p>
<p>Text Third</p>
``` | 2018/06/20 | [
"https://Stackoverflow.com/questions/50943141",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9576063/"
] | Your code is good, just have a little logical problem :)
```js
var p = document.querySelectorAll("p");
for( var i = 0; i < p.length; i++ ){
p[i].addEventListener("click", makeRed);
p[0].classList.add("active");
}
function makeRed(){
if( this.classList.contains("active")){
this.classList.remove("active");
} else{
for( var i = 0; i < p.length; i++ ){
p[i].classList.remove("active");
}
this.classList.add("active");
}
}
```
```css
.active{
color: red;
}
```
```html
<p class="active">Text First</p>
<p>Text Second</p>
<p>Text Third</p>
``` | Try with below solution,
```js
var p = document.querySelectorAll("p");
for( var i = 0; i < p.length; i++ ){
p[i].addEventListener("click", makeRed);
p[0].classList.add("active");
}
function makeRed(){
var elems = document.querySelectorAll(".active");
[].forEach.call(elems, function(el) {
el.classList.remove("active");
});
if( this.classList.contains("active")){
this.classList.remove("active");
} else{
this.classList.add("active");
}
}
```
```css
.active{
color: red;
}
```
```html
<p>Text First</p>
<p>Text Second</p>
<p>Text Third</p>
``` |
50,943,141 | i have some paragraphs. At first one of that should have red color and after click it should become black, and clicked one should become red. I need to change red each paragraph when it is clicked and remove the class when another one is clicked. I should do it with javascript
```js
var p = document.querySelectorAll("p");
for( var i = 0; i < p.length; i++ ){
p[i].addEventListener("click", makeRed);
p[0].classList.add("active");
}
function makeRed(){
p[0].classList.remove("active");
if( this.classList.contains("active")){
this.classList.remove("active");
} else{
this.classList.add("active");
}
}
```
```css
.active{
color: red;
}
```
```html
<p>Text First</p>
<p>Text Second</p>
<p>Text Third</p>
``` | 2018/06/20 | [
"https://Stackoverflow.com/questions/50943141",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9576063/"
] | Your code is good, just have a little logical problem :)
```js
var p = document.querySelectorAll("p");
for( var i = 0; i < p.length; i++ ){
p[i].addEventListener("click", makeRed);
p[0].classList.add("active");
}
function makeRed(){
if( this.classList.contains("active")){
this.classList.remove("active");
} else{
for( var i = 0; i < p.length; i++ ){
p[i].classList.remove("active");
}
this.classList.add("active");
}
}
```
```css
.active{
color: red;
}
```
```html
<p class="active">Text First</p>
<p>Text Second</p>
<p>Text Third</p>
``` | Simply use `document.querySelectorAll` to get all elements and reset their class by removing `active` and then simply add class to current element.
```js
var p = document.querySelectorAll("p");
for( var i = 0; i < p.length; i++ ){
p[i].addEventListener("click", makeRed);
p[0].classList.add("active");
}
function makeRed(){
[...document.querySelectorAll('p')]
.map(elem => elem.classList.remove("active"));
this.classList.add("active");
}
```
```css
.active{
color: red;
}
```
```html
<p>Text First</p>
<p>Text Second</p>
<p>Text Third</p>
``` |
22,498,086 | **Background**
Using [CakePHP](http://cakephp.org/)'s [FormHelper](http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#formhelper), I am creating multiple radio buttons, each being rendered by separate calls to [input()](http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#FormHelper%3a%3ainput), to allow for HTML to be used in-between the radio buttons.
**Issue**
When the form is submitted, only the last radio button's value is being submitted to server.
```
// preselect radio button if appropriate
$selected = isset($this->request->data['ModelName']['field']) ? $this->request->data['ModelName']['field'] : null ;
// output the radio button
echo $this->Form->input('field', array(
'type' => 'radio',
'options' => array(1 => 'Option A',),
'class' => 'testClass',
'selected' => $selected,
'before' => '<div class="testOuterClass">',
'after' => '</div>',
));
```
**Requirement**
How to get all radio buttons (or checkboxes) created using FormHelper to submit values correctly? | 2014/03/19 | [
"https://Stackoverflow.com/questions/22498086",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | >
> For certain input types (checkboxes, radios) a hidden input is created so that the key in `$this->request->data` will exist even without a value specified.
>
>
> If you want to create multiple blocks of inputs on a form that are all grouped together, you should use this parameter on all inputs except the first. If the hidden input is on the page in multiple places, only the last group of input’s values will be saved. ([Documentation](http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#options-for-select-checkbox-and-radio-inputs))
>
>
>
Thus, for your task, pass `'hiddenField' => false,` as an option to all calls to `input()` for *that* group's radio button (or checkbox) *except the first one*. In this example, we have it by the name 'field'.
e.g.
```
echo $this->Form->input('field', array(
'type' => 'radio',
'options' => array(1 => 'Option A',),
'class' => 'testClass',
'selected' => $selected,
'before' => '<div class="testOuterClass">',
'after' => '</div>',
'hiddenField' => false, // added for non-first elements
));
``` | Try the following:
```
<?php echo $this->Form->input('fieldName', array(
'type' => 'radio',
'hiddenField' => false,
'options' => array('value1' => 'option label1'))
)); ?>
<?php echo $this->Form->input('fieldName', array(
'type' => 'radio',
'hiddenField' => false,
'options' => array('value2' => 'option label2'))
)); ?>
<?php echo $this->Form->input('fieldName', array(
'type' => 'radio',
'hiddenField' => false,
'options' => array('value3' => 'option label3'))
)); ?>
```
Hope this works. |
51,790,824 | Is there possible to keep elements inside a DIV, in the same line, even if i put a BR tag after elements ? For example:
DIV
↑ → Full Name (a br here)
IMAGE → Address (another br here)
↓ → Tel
/DIV
And display exactly this example ?
↑
I
M → Full Name
A → Addres
G → Tel
E
↓
Keeping next to each other. I'm using this code, but it doesn't working like i want;
```html
<div style="white-space:nowrap; display:inline-block;">
<a href="http://www.whateveraddress.com"><img src="localhost/xrEN.png" width="165" height="50"></a>
<b style="color:black; font-size:12; font-family:Arial;">Full Name</b><br>
<b style="color:black; font-size:12; font-family:Arial;">Address</b><br>
<b style="color:black; font-size:12; font-family:Arial;">Tel</b><br>
</div>
``` | 2018/08/10 | [
"https://Stackoverflow.com/questions/51790824",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10009861/"
] | [`querySelector()`](https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelector) only returns first match found.
You need to loop over whole collection returned by [`querySelectorAll()`](https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelectorAll) and add listener to each instance
jQuery does all this looping for you internally
```js
Array.from(document.querySelectorAll('.my-class')).forEach(function(el) {
el.addEventListener('click', function() {
// can use querySelector here for first one
document.querySelector('.green').classList.toggle('blue');
});
});
```
```css
.green {
color: white;
background: green;
}
.blue {
color: white;
background: blue;
width: 1000px;
height: 300px;
font-size: 30px;
}
```
```html
<a class="my-class">Get Details 1 </a><br>
<a class="my-class">Get Details 2 -- I can't click </a><br>
<a class="my-class">Get Details 3 -- I can't click </a><br>
<a class="my-class">Get Details 4 -- I can't click </a><br>
<div class="green">
Text <br> Text <br> Text <br>
<a class="my-class">X Close X -- I can't click </a>
</div>
``` | I just changed querySelector for querySelectorAll, so i can get every element wuth my-class on it, then with a foreach loop create the handler so it does what you wanted to..
```js
document.querySelectorAll('.my-class').forEach(function(x){
x.onclick=function(){
document.getElementsByClassName('green')[0]
.classList.toggle('blue');
}
});
```
```css
.green {
color: white;
background: green;
}
.blue {
color: white;
background: blue !important;
width: 1000px;
height: 300px;
font-size: 30px;
}
```
```html
<a class="my-class">Get Details 1 </a><br>
<a class="my-class">Get Details 2 -- I can't click </a><br>
<a class="my-class">Get Details 3 -- I can't click </a><br>
<a class="my-class">Get Details 4 -- I can't click </a><br>
<div class="green">
Text <br> Text <br> Text <br>
<a class="my-class">X Close X -- I can't click </a>
</div>
``` |
51,790,824 | Is there possible to keep elements inside a DIV, in the same line, even if i put a BR tag after elements ? For example:
DIV
↑ → Full Name (a br here)
IMAGE → Address (another br here)
↓ → Tel
/DIV
And display exactly this example ?
↑
I
M → Full Name
A → Addres
G → Tel
E
↓
Keeping next to each other. I'm using this code, but it doesn't working like i want;
```html
<div style="white-space:nowrap; display:inline-block;">
<a href="http://www.whateveraddress.com"><img src="localhost/xrEN.png" width="165" height="50"></a>
<b style="color:black; font-size:12; font-family:Arial;">Full Name</b><br>
<b style="color:black; font-size:12; font-family:Arial;">Address</b><br>
<b style="color:black; font-size:12; font-family:Arial;">Tel</b><br>
</div>
``` | 2018/08/10 | [
"https://Stackoverflow.com/questions/51790824",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10009861/"
] | [`querySelector()`](https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelector) only returns first match found.
You need to loop over whole collection returned by [`querySelectorAll()`](https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelectorAll) and add listener to each instance
jQuery does all this looping for you internally
```js
Array.from(document.querySelectorAll('.my-class')).forEach(function(el) {
el.addEventListener('click', function() {
// can use querySelector here for first one
document.querySelector('.green').classList.toggle('blue');
});
});
```
```css
.green {
color: white;
background: green;
}
.blue {
color: white;
background: blue;
width: 1000px;
height: 300px;
font-size: 30px;
}
```
```html
<a class="my-class">Get Details 1 </a><br>
<a class="my-class">Get Details 2 -- I can't click </a><br>
<a class="my-class">Get Details 3 -- I can't click </a><br>
<a class="my-class">Get Details 4 -- I can't click </a><br>
<div class="green">
Text <br> Text <br> Text <br>
<a class="my-class">X Close X -- I can't click </a>
</div>
``` | I think breaking out the `querySelectors` makes it easier to read, especially when used in conjunction with descriptive names. Otherwise I think what @charlietfl is the best.
```
const myClass = document.querySelectorAll('.my-class')
const listText = document.querySelector('.green')
Array.from(myClass).forEach(function(el) {
el.addEventListener('click', function() {
listText.classList.toggle('blue');
});
});
``` |
51,611,812 | The following code gives an UnhandledPromiseRejectionWarning for p2, despite errors on p2 being explicitly handled.
```
function syncFunctionReturnsPromise(val)
{
return new Promise((r,x)=> {
setTimeout(()=> {
if (val) {
r('ok');
} else {
x('not ok');
}
}, val?1000:500);
});
}
async function test(){
let p1 = syncFunctionReturnsPromise(true);
let p2 = syncFunctionReturnsPromise(false);
await p1.catch(ex => console.warn('warning:', ex)); //errors in these 2 promises
await p2.catch(ex => console.warn('warning:', ex)); //are not the end of the world
console.log('doOtherStuff');
}
test();
```
The output looks like this:
```
(node:9056) UnhandledPromiseRejectionWarning: not ok
(node:9056) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:9056) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
warning: not ok
doOtherStuff
(node:9056) PromiseRejectionHandledWarning: Promise rejection was handled asynchronously (rejection id: 1)
```
It is not immediately obvious to me why this should be | 2018/07/31 | [
"https://Stackoverflow.com/questions/51611812",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1273906/"
] | So this is because the first await waits synchronously before the handler is attached to p2. But p2 fails before p1 completes.
So node detects that p2 failed without any error handling.
N.B. In later versions of node this may cause the program to terminate, rather than just a warning.
The fix is to attach the handlers before awaiting
```
async function test(){
let p1 = syncFunctionReturnsPromise(true);
let p2 = syncFunctionReturnsPromise(false);
p1 = p1.catch(ex => console.warn('warning:', ex)); //errors in these 2 promises
p2 = p2.catch(ex => console.warn('warning:', ex)); //are not the end of the world
await p1;
await p2;
console.log('doOtherStuff');
}
```
Obviously you could inline that on the declaration although in my realworld code its neater as separate lines. | Here is the other way:
```
async function test(){
let p1 = await syncFunctionReturnsPromise(true)
.catch(ex => console.warn('warning:', ex));
let p2 = await syncFunctionReturnsPromise(false)
.catch(ex => console.warn('warning:', ex));
console.log('doOtherStuff');
}
``` |
51,614,852 | The code I have pulled from the production server to my localhost server is identical. On the live site, the user can login as normal however on Localhost I cannot. I am using Laravel 5.1 for this project along with a XAMMP server.
The issue cannot be with the source code- as it is the same on the live site as it is on my machine. And it works as it should on the live site. Therefore I'm guessing the issue lies in my XAMMP configuration settings, however I am unsure where to start. | 2018/07/31 | [
"https://Stackoverflow.com/questions/51614852",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10160877/"
] | If page returns **HTTP 500 Error** it means that somewhere is syntax error or script can't run correctly. Maybe your settings set for non-local server? | The issue was with the XAMPP configuration file and its index.php file. I had a conversation with the original developer who guided me through how to congfigure this and all is resolved now. I needed to change some permissions with the files I had downloaded RWX etc, as well as the root file of my project files. |
24,904,494 | I am having quite a problem compiling `LibCURL` with `MinGW32-gcc` on my pc. I put the files from the LibCURL download "includes", "lib", and "bin" into the corresponding MinGW32 folders. Currently my code is below and it is extremely simple for testing if it worked(Which it is not as I am posting here.)
```
#include <stdio.h>
#include <curl/curl.h>
int main(int argc, char **argv)
{
/************************
Variables
************************/
CURL *curl;
CURLcode res;
curl_global_init(CURL_GLOBAL_DEFAULT);
return 0;
}
```
Which I then in term compile with the following command line:
```
mingw32-gcc main.c -lcurl -o compiled.exe --std=c99
```
That compiler command line is throwing the following error:
```
C:\Users\Ikaros\AppData\Local\Temp\ccc5ojVE.o:main.c:(.text+0x8e): undefined ref
erence to `_imp__curl_global_init'
collect2.exe: error: ld returned 1 exit status
Press any key to continue . . .
```
Do you have any recommendation on why this would not be working the way it should? | 2014/07/23 | [
"https://Stackoverflow.com/questions/24904494",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3543824/"
] | I would put two or more **nullable** rows into the chatting table that are referencing the different other tables.
For example one column chatter\_colleague and one chatter\_customer. That is also not very nice but I just don't know any *really* good solution!
That would need some effort to keep the table clean but otherwise offers optimal joining and indexing capabilities as far as i know. And it is quite simple, which is desirable in my point of view. | Merge the rows of your reference tables into one "table" and include the name of the source table (as a literal value) so you can distinguish them from each other, then join your main table to that, joining on both the id and the source name:
```
select
c.id,
c.someColumn,
d.data
from chatting c
left join (
select 'customers' type, id, colA data from customers
union all
select 'colleagues', id, colB from colleagues) d
on d.type = c.chatter_ref
and d.id = c.chatter_id
``` |
24,904,494 | I am having quite a problem compiling `LibCURL` with `MinGW32-gcc` on my pc. I put the files from the LibCURL download "includes", "lib", and "bin" into the corresponding MinGW32 folders. Currently my code is below and it is extremely simple for testing if it worked(Which it is not as I am posting here.)
```
#include <stdio.h>
#include <curl/curl.h>
int main(int argc, char **argv)
{
/************************
Variables
************************/
CURL *curl;
CURLcode res;
curl_global_init(CURL_GLOBAL_DEFAULT);
return 0;
}
```
Which I then in term compile with the following command line:
```
mingw32-gcc main.c -lcurl -o compiled.exe --std=c99
```
That compiler command line is throwing the following error:
```
C:\Users\Ikaros\AppData\Local\Temp\ccc5ojVE.o:main.c:(.text+0x8e): undefined ref
erence to `_imp__curl_global_init'
collect2.exe: error: ld returned 1 exit status
Press any key to continue . . .
```
Do you have any recommendation on why this would not be working the way it should? | 2014/07/23 | [
"https://Stackoverflow.com/questions/24904494",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3543824/"
] | This is the classic Polymorphic Association anti-pattern. There are a number of possible solutions:
1 Exclusive Arcs (as suggested by Argeman) e.g. for the chatting table
```
id | someColumn | customerId | colleagueId
------------------------------------------
1 2 1
2 3 1
3 4 2
```
Where both customerId and colleagueID are nullable and exactly one must be not null. Foreign keys can be declared on the customerId and colleagueId.
2 Reverse the Relationship e.g remove the chatterId and chatterRef from the chatting table and create two new tables
customer chattings
```
chattingId | customerId
-----------------------
1 1
3 2
```
colleague chattings
```
chattingId | colleagueId
------------------------
2 1
```
Foreign keys can be declared on the customerId and colleagueId.
3 Create a super-type table for customers/colleagues such as persons and have the chatting table reference the primary key of this new table. | Merge the rows of your reference tables into one "table" and include the name of the source table (as a literal value) so you can distinguish them from each other, then join your main table to that, joining on both the id and the source name:
```
select
c.id,
c.someColumn,
d.data
from chatting c
left join (
select 'customers' type, id, colA data from customers
union all
select 'colleagues', id, colB from colleagues) d
on d.type = c.chatter_ref
and d.id = c.chatter_id
``` |
24,904,494 | I am having quite a problem compiling `LibCURL` with `MinGW32-gcc` on my pc. I put the files from the LibCURL download "includes", "lib", and "bin" into the corresponding MinGW32 folders. Currently my code is below and it is extremely simple for testing if it worked(Which it is not as I am posting here.)
```
#include <stdio.h>
#include <curl/curl.h>
int main(int argc, char **argv)
{
/************************
Variables
************************/
CURL *curl;
CURLcode res;
curl_global_init(CURL_GLOBAL_DEFAULT);
return 0;
}
```
Which I then in term compile with the following command line:
```
mingw32-gcc main.c -lcurl -o compiled.exe --std=c99
```
That compiler command line is throwing the following error:
```
C:\Users\Ikaros\AppData\Local\Temp\ccc5ojVE.o:main.c:(.text+0x8e): undefined ref
erence to `_imp__curl_global_init'
collect2.exe: error: ld returned 1 exit status
Press any key to continue . . .
```
Do you have any recommendation on why this would not be working the way it should? | 2014/07/23 | [
"https://Stackoverflow.com/questions/24904494",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3543824/"
] | This is the classic Polymorphic Association anti-pattern. There are a number of possible solutions:
1 Exclusive Arcs (as suggested by Argeman) e.g. for the chatting table
```
id | someColumn | customerId | colleagueId
------------------------------------------
1 2 1
2 3 1
3 4 2
```
Where both customerId and colleagueID are nullable and exactly one must be not null. Foreign keys can be declared on the customerId and colleagueId.
2 Reverse the Relationship e.g remove the chatterId and chatterRef from the chatting table and create two new tables
customer chattings
```
chattingId | customerId
-----------------------
1 1
3 2
```
colleague chattings
```
chattingId | colleagueId
------------------------
2 1
```
Foreign keys can be declared on the customerId and colleagueId.
3 Create a super-type table for customers/colleagues such as persons and have the chatting table reference the primary key of this new table. | I would put two or more **nullable** rows into the chatting table that are referencing the different other tables.
For example one column chatter\_colleague and one chatter\_customer. That is also not very nice but I just don't know any *really* good solution!
That would need some effort to keep the table clean but otherwise offers optimal joining and indexing capabilities as far as i know. And it is quite simple, which is desirable in my point of view. |
50,229,130 | I tried importing rxjs timer on my angular 6 project like
```
import { timer } from 'rxjs/observable/timer';
```
I also tried it like,
```
Rx.Observable.timer(200, 100)
```
They don't work
Here is the code on [plunker](https://stackblitz.com/edit/angular-q8rehy?file=src/app/hello.component.ts) | 2018/05/08 | [
"https://Stackoverflow.com/questions/50229130",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4646531/"
] | From rxjs 6 (as used in angular 6 project), The general rule is as follows:
* rxjs: Creation methods, types, schedulers and utilities
```js
import { timer, Observable, Subject, asapScheduler, pipe, of, from,
interval, merge, fromEvent } from 'rxjs';
```
* rxjs/operators: All pipeable operators:
```js
import { map, filter, scan } from 'rxjs/operators';
```
Here is the migration guide: <https://github.com/ReactiveX/rxjs/blob/master/MIGRATION.md#observable-classes> | All observable classes (<https://github.com/ReactiveX/rxjs/tree/5.5.8/src/observable>) have been removed from v6, in favor of existing or new operators that perform the same operations as the class methods.
```
import { timer } from 'rxjs';
import { timeInterval, pluck, take} from 'rxjs/operators';
var sourcef = timer(200, 100)
.pipe(
timeInterval(),
pluck('interval'),
take(3)
)
```
**[Forked Example](https://stackblitz.com/edit/angular-zwm3gu?file=src/app/hello.component.ts)**
See also
* <https://github.com/ReactiveX/rxjs/blob/master/docs_app/content/guide/v6/migration.md#observable-classes> |
50,229,130 | I tried importing rxjs timer on my angular 6 project like
```
import { timer } from 'rxjs/observable/timer';
```
I also tried it like,
```
Rx.Observable.timer(200, 100)
```
They don't work
Here is the code on [plunker](https://stackblitz.com/edit/angular-q8rehy?file=src/app/hello.component.ts) | 2018/05/08 | [
"https://Stackoverflow.com/questions/50229130",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4646531/"
] | All observable classes (<https://github.com/ReactiveX/rxjs/tree/5.5.8/src/observable>) have been removed from v6, in favor of existing or new operators that perform the same operations as the class methods.
```
import { timer } from 'rxjs';
import { timeInterval, pluck, take} from 'rxjs/operators';
var sourcef = timer(200, 100)
.pipe(
timeInterval(),
pluck('interval'),
take(3)
)
```
**[Forked Example](https://stackblitz.com/edit/angular-zwm3gu?file=src/app/hello.component.ts)**
See also
* <https://github.com/ReactiveX/rxjs/blob/master/docs_app/content/guide/v6/migration.md#observable-classes> | as of rxjs 6.2.2, for this import
```
import { timer } from 'rxjs'; // gives tslint blacklisted error
```
tslint gives an error:
```
ERR: [tslint] This import is blacklisted,
import a submodule instead (import-blacklist)
```
**but this works fine without any error**
`import { timer } from 'rxjs/observable/timer'; //works fine` |
50,229,130 | I tried importing rxjs timer on my angular 6 project like
```
import { timer } from 'rxjs/observable/timer';
```
I also tried it like,
```
Rx.Observable.timer(200, 100)
```
They don't work
Here is the code on [plunker](https://stackblitz.com/edit/angular-q8rehy?file=src/app/hello.component.ts) | 2018/05/08 | [
"https://Stackoverflow.com/questions/50229130",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4646531/"
] | All observable classes (<https://github.com/ReactiveX/rxjs/tree/5.5.8/src/observable>) have been removed from v6, in favor of existing or new operators that perform the same operations as the class methods.
```
import { timer } from 'rxjs';
import { timeInterval, pluck, take} from 'rxjs/operators';
var sourcef = timer(200, 100)
.pipe(
timeInterval(),
pluck('interval'),
take(3)
)
```
**[Forked Example](https://stackblitz.com/edit/angular-zwm3gu?file=src/app/hello.component.ts)**
See also
* <https://github.com/ReactiveX/rxjs/blob/master/docs_app/content/guide/v6/migration.md#observable-classes> | In my case I used import { timer } from 'rxjs/Observable/timer'; like this.
but need to use in import { timer } from 'rxjs/observable/timer'; Observable instead of observable.
that's all... enjoy your coding. |
50,229,130 | I tried importing rxjs timer on my angular 6 project like
```
import { timer } from 'rxjs/observable/timer';
```
I also tried it like,
```
Rx.Observable.timer(200, 100)
```
They don't work
Here is the code on [plunker](https://stackblitz.com/edit/angular-q8rehy?file=src/app/hello.component.ts) | 2018/05/08 | [
"https://Stackoverflow.com/questions/50229130",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4646531/"
] | From rxjs 6 (as used in angular 6 project), The general rule is as follows:
* rxjs: Creation methods, types, schedulers and utilities
```js
import { timer, Observable, Subject, asapScheduler, pipe, of, from,
interval, merge, fromEvent } from 'rxjs';
```
* rxjs/operators: All pipeable operators:
```js
import { map, filter, scan } from 'rxjs/operators';
```
Here is the migration guide: <https://github.com/ReactiveX/rxjs/blob/master/MIGRATION.md#observable-classes> | as of rxjs 6.2.2, for this import
```
import { timer } from 'rxjs'; // gives tslint blacklisted error
```
tslint gives an error:
```
ERR: [tslint] This import is blacklisted,
import a submodule instead (import-blacklist)
```
**but this works fine without any error**
`import { timer } from 'rxjs/observable/timer'; //works fine` |
50,229,130 | I tried importing rxjs timer on my angular 6 project like
```
import { timer } from 'rxjs/observable/timer';
```
I also tried it like,
```
Rx.Observable.timer(200, 100)
```
They don't work
Here is the code on [plunker](https://stackblitz.com/edit/angular-q8rehy?file=src/app/hello.component.ts) | 2018/05/08 | [
"https://Stackoverflow.com/questions/50229130",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4646531/"
] | From rxjs 6 (as used in angular 6 project), The general rule is as follows:
* rxjs: Creation methods, types, schedulers and utilities
```js
import { timer, Observable, Subject, asapScheduler, pipe, of, from,
interval, merge, fromEvent } from 'rxjs';
```
* rxjs/operators: All pipeable operators:
```js
import { map, filter, scan } from 'rxjs/operators';
```
Here is the migration guide: <https://github.com/ReactiveX/rxjs/blob/master/MIGRATION.md#observable-classes> | In my case I used import { timer } from 'rxjs/Observable/timer'; like this.
but need to use in import { timer } from 'rxjs/observable/timer'; Observable instead of observable.
that's all... enjoy your coding. |
50,229,130 | I tried importing rxjs timer on my angular 6 project like
```
import { timer } from 'rxjs/observable/timer';
```
I also tried it like,
```
Rx.Observable.timer(200, 100)
```
They don't work
Here is the code on [plunker](https://stackblitz.com/edit/angular-q8rehy?file=src/app/hello.component.ts) | 2018/05/08 | [
"https://Stackoverflow.com/questions/50229130",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4646531/"
] | as of rxjs 6.2.2, for this import
```
import { timer } from 'rxjs'; // gives tslint blacklisted error
```
tslint gives an error:
```
ERR: [tslint] This import is blacklisted,
import a submodule instead (import-blacklist)
```
**but this works fine without any error**
`import { timer } from 'rxjs/observable/timer'; //works fine` | In my case I used import { timer } from 'rxjs/Observable/timer'; like this.
but need to use in import { timer } from 'rxjs/observable/timer'; Observable instead of observable.
that's all... enjoy your coding. |
30,769,636 | I'm trying to understand Maven 3's[password encryption feature. I have found that this feature is poorly documented and confusing. For example, the [feature documentation](https://maven.apache.org/guides/mini/guide-encryption.html) and [a blog post by the author of the feature](http://blog.sonatype.com/2009/10/maven-tips-and-tricks-encrypting-passwords/) contradict each other about several points.
This question is broader than [How does maven --encrypt-master-password work](https://stackoverflow.com/questions/15789984/how-does-mvn-encrypt-master-password-password-work) and is not covered by [Maven encrypt-master-password good practice for choosing password](https://stackoverflow.com/questions/16422016/mvn-encrypt-master-password-password-good-practice-for-choosing-password?lq=1).
Specifically, I am trying to answer the following questions which are not covered by the documentation. I've put what information I have been able to gather so far below each question in italics.
1. Does the encrypted master password provide security simply by existing in `settings-security.xml` in a folder that only one user can access (`~/.m2`)? If so, why bother with encrypting a 'master password' (why not just use some random value)? Isn't the 'master password' really just an entropy input to the cryptographic function? Calling it a password is confusing - I expected Maven to prompt me for this password before de-crypting any encrypted server passwords, but it did not.
*My understanding is that yes, this only provides security by existing in an operating-system protected file. I believe Maven allows you to encrypt a master password so that if you loose the `settings-security.xml` file you can re-generate it. Is this correct?*
2. Do the master password and server passwords use the same encryption process/cipher? The server passwords are based on the master password, so there must be some difference in the algorithm. Where is the source code for this located?
*[Marcelo Morales' answer on How does maven --encrypt-master-password work](https://stackoverflow.com/a/15792131/885287) links to the [plexus-cihper project on GitHub](https://github.com/sonatype/plexus-cipher). It isn't clear if that is just the cipher, or the actual Maven plugin that provides the password functionality though.*
3. I have observed that the same master password or server password encrypted multiple times gives different hashes. According to [Marcelo Morales' answer on How does maven --encrypt-master-password work](https://stackoverflow.com/a/15792131/885287), this is because 'a JVM-configuration-specific (usually SHA1PRNG) 64-bit random salt' is added to the password prior to encrypting. Maven decrypts stored passwords when they are used at compile time. Doesn't this mean the salts have to be stored somewhere?
*I have no idea*.
4. I have also observed that a regular password encrypted using one encrypted master password will still work if the master password is re-encrypted and stored in the `settings-security.xml` file, **even though the encrypted master password ciphertext is now different**. Can someone explain how this works?
*I have no idea. This seems to me like Maven is doing something fishy or storing cleartext somewhere.*
5. My understanding is that the encrypted passwords can only be used with `<server />` tags in the `settings.xml` file. is this true? Where can servers defined in `settings.xml` be used?
*My understanding is that `<server />` definitions can be used in `<repositories />` and `<distributionManagement />`, but not `<scm />`. Can someone verify this?*
6. For such a critical feature (build system security) it seems to me that there is a lot of confusion and poor documentation. Can someone point out how the documentation on the Maven 3 website works? Is there a wiki link somewhere that would allow me to try and improve the documentation at all?
*I have no idea*
Sorry for the wall of text, and thanks for any answers. | 2015/06/11 | [
"https://Stackoverflow.com/questions/30769636",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/885287/"
] | My answer is based on reading the Maven source code and doing a little research.
>
> 1. Does the encrypted master password provide security simply by existing in `settings-security.xml` in a folder that only one user can
> access (`~/.m2`)? If so, why bother with encrypting a 'master
> password' (why not just use some random value)? Isn't the 'master
> password' really just an entropy input to the cryptographic function?
> Calling it a password is confusing - I expected Maven to prompt me for
> this password before de-crypting any encrypted server passwords, but
> it did not.
>
>
>
The master password is an input into the cryptographic function for encrypting/decrypting the server passwords. If someone has your individual encrypted server passwords, they won't be able to decrypt them unless they also have your master password. This means you can freely share your maven settings.xml file with others, without them being able to decrypt your server passwords. This is also why the master password is kept in a separate file.
This rationale is somewhat explained in [encryption guide](https://maven.apache.org/guides/mini/guide-encryption.html#Introduction)
>
> 2. Do the master password and server passwords use the same encryption process/cipher? The server passwords are based on the master password,
> so there must be some difference in the algorithm. Where is the source
> code for this located?
>
>
>
From what I can tell, the master password is encrypted using the same cipher as the server passwords. When decrypting the server passwords, the master password (unencrypted form) is an input; when decrypting the master password, the magic string '"settings.security"' is used as the additional input.
You can see the source code [PBECipher](https://github.com/sonatype/plexus-cipher/blob/master/src/main/java/org/sonatype/plexus/components/cipher/PBECipher.java) and [MavenCli.java](http://svn.apache.org/repos/asf/maven/maven-3/tags/maven-3.0-beta-2/maven-embedder/src/main/java/org/apache/maven/cli/MavenCli.java).
>
> 3. I have observed that the same master password or server password encrypted multiple times gives different hashes. According to [Marcelo
> Morales' answer on How does maven --encrypt-master-password
> work](https://stackoverflow.com/a/15792131/885287), this is because 'a
> JVM-configuration-specific (usually SHA1PRNG) 64-bit random salt' is
> added to the password prior to encrypting. Maven decrypts stored
> passwords when they are used at compile time. Doesn't this mean the
> salts have to be stored somewhere?
>
>
>
A traditional approach to handling salts is that the random salt is stored with the encrypted text, alongside it. See the [Wikipedia article](https://en.wikipedia.org/wiki/Salt_%28cryptography%29).
Based on the source code linked above, the salt appears to be stored as the first 8 bytes of the Base64 decoded bytes, right before the encrypted password.
>
> 4. I have also observed that a regular password encrypted using one encrypted master password will still work if the master password is
> re-encrypted and stored in the `settings-security.xml` file, **even
> though the encrypted master password ciphertext is now different**.
> Can someone explain how this works?
>
>
>
This is because the *decrypted* form of the master password is used, not the encrypted "ciphertext". Thus re-encrypting it doesn't affect the server password encryption/decryption.
I don't know the answer to your last two (5 and 6) questions. | I need to know this for bnd(tools) so I can share some deeper analysis.
The 'encrypted' passwords have a syntax of:
```
output ::= '{' base64(packet) '}'
packet ::= salt[8] padlen[1] encrypted[?] padding[padlen]
salt ::= <random>
padlen ::= <length of padding >
padding ::= <random to make packet length a multiple of 16>
```
The cipher used is `AES/CBC/PKCS5Padding`. The secret key and initialisation vector is calculated as follows:
```
sha = sha256( X + salt[8] )
key = sha[0..16]
iv = sha[16..32]
```
For the master password X is "security.settings". Since this is a well known constant *the master password is not encrypted but only obscured*. For the server passwords X is the decoded master password.
Why the resulting packet is padded seems a waste of bytes since the packet format makes it trivial to strip and they are never part of the encryption/decryption. They just add a few random characters to the base64 string.
The only way this is useful is using the relocation facility. For example, if you mount the settings-security.xml on a private mount on the build server. You can then you can freely share the `settings.xml` file in public repos. However, this is also a sucky solution since you need to mount it the same mount point for all your users and CI build servers.
Be aware that any plugin can decode all your server passwords so never use real passwords for the servers. Nexus can create proxy passwords. |
30,769,636 | I'm trying to understand Maven 3's[password encryption feature. I have found that this feature is poorly documented and confusing. For example, the [feature documentation](https://maven.apache.org/guides/mini/guide-encryption.html) and [a blog post by the author of the feature](http://blog.sonatype.com/2009/10/maven-tips-and-tricks-encrypting-passwords/) contradict each other about several points.
This question is broader than [How does maven --encrypt-master-password work](https://stackoverflow.com/questions/15789984/how-does-mvn-encrypt-master-password-password-work) and is not covered by [Maven encrypt-master-password good practice for choosing password](https://stackoverflow.com/questions/16422016/mvn-encrypt-master-password-password-good-practice-for-choosing-password?lq=1).
Specifically, I am trying to answer the following questions which are not covered by the documentation. I've put what information I have been able to gather so far below each question in italics.
1. Does the encrypted master password provide security simply by existing in `settings-security.xml` in a folder that only one user can access (`~/.m2`)? If so, why bother with encrypting a 'master password' (why not just use some random value)? Isn't the 'master password' really just an entropy input to the cryptographic function? Calling it a password is confusing - I expected Maven to prompt me for this password before de-crypting any encrypted server passwords, but it did not.
*My understanding is that yes, this only provides security by existing in an operating-system protected file. I believe Maven allows you to encrypt a master password so that if you loose the `settings-security.xml` file you can re-generate it. Is this correct?*
2. Do the master password and server passwords use the same encryption process/cipher? The server passwords are based on the master password, so there must be some difference in the algorithm. Where is the source code for this located?
*[Marcelo Morales' answer on How does maven --encrypt-master-password work](https://stackoverflow.com/a/15792131/885287) links to the [plexus-cihper project on GitHub](https://github.com/sonatype/plexus-cipher). It isn't clear if that is just the cipher, or the actual Maven plugin that provides the password functionality though.*
3. I have observed that the same master password or server password encrypted multiple times gives different hashes. According to [Marcelo Morales' answer on How does maven --encrypt-master-password work](https://stackoverflow.com/a/15792131/885287), this is because 'a JVM-configuration-specific (usually SHA1PRNG) 64-bit random salt' is added to the password prior to encrypting. Maven decrypts stored passwords when they are used at compile time. Doesn't this mean the salts have to be stored somewhere?
*I have no idea*.
4. I have also observed that a regular password encrypted using one encrypted master password will still work if the master password is re-encrypted and stored in the `settings-security.xml` file, **even though the encrypted master password ciphertext is now different**. Can someone explain how this works?
*I have no idea. This seems to me like Maven is doing something fishy or storing cleartext somewhere.*
5. My understanding is that the encrypted passwords can only be used with `<server />` tags in the `settings.xml` file. is this true? Where can servers defined in `settings.xml` be used?
*My understanding is that `<server />` definitions can be used in `<repositories />` and `<distributionManagement />`, but not `<scm />`. Can someone verify this?*
6. For such a critical feature (build system security) it seems to me that there is a lot of confusion and poor documentation. Can someone point out how the documentation on the Maven 3 website works? Is there a wiki link somewhere that would allow me to try and improve the documentation at all?
*I have no idea*
Sorry for the wall of text, and thanks for any answers. | 2015/06/11 | [
"https://Stackoverflow.com/questions/30769636",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/885287/"
] | My answer is based on reading the Maven source code and doing a little research.
>
> 1. Does the encrypted master password provide security simply by existing in `settings-security.xml` in a folder that only one user can
> access (`~/.m2`)? If so, why bother with encrypting a 'master
> password' (why not just use some random value)? Isn't the 'master
> password' really just an entropy input to the cryptographic function?
> Calling it a password is confusing - I expected Maven to prompt me for
> this password before de-crypting any encrypted server passwords, but
> it did not.
>
>
>
The master password is an input into the cryptographic function for encrypting/decrypting the server passwords. If someone has your individual encrypted server passwords, they won't be able to decrypt them unless they also have your master password. This means you can freely share your maven settings.xml file with others, without them being able to decrypt your server passwords. This is also why the master password is kept in a separate file.
This rationale is somewhat explained in [encryption guide](https://maven.apache.org/guides/mini/guide-encryption.html#Introduction)
>
> 2. Do the master password and server passwords use the same encryption process/cipher? The server passwords are based on the master password,
> so there must be some difference in the algorithm. Where is the source
> code for this located?
>
>
>
From what I can tell, the master password is encrypted using the same cipher as the server passwords. When decrypting the server passwords, the master password (unencrypted form) is an input; when decrypting the master password, the magic string '"settings.security"' is used as the additional input.
You can see the source code [PBECipher](https://github.com/sonatype/plexus-cipher/blob/master/src/main/java/org/sonatype/plexus/components/cipher/PBECipher.java) and [MavenCli.java](http://svn.apache.org/repos/asf/maven/maven-3/tags/maven-3.0-beta-2/maven-embedder/src/main/java/org/apache/maven/cli/MavenCli.java).
>
> 3. I have observed that the same master password or server password encrypted multiple times gives different hashes. According to [Marcelo
> Morales' answer on How does maven --encrypt-master-password
> work](https://stackoverflow.com/a/15792131/885287), this is because 'a
> JVM-configuration-specific (usually SHA1PRNG) 64-bit random salt' is
> added to the password prior to encrypting. Maven decrypts stored
> passwords when they are used at compile time. Doesn't this mean the
> salts have to be stored somewhere?
>
>
>
A traditional approach to handling salts is that the random salt is stored with the encrypted text, alongside it. See the [Wikipedia article](https://en.wikipedia.org/wiki/Salt_%28cryptography%29).
Based on the source code linked above, the salt appears to be stored as the first 8 bytes of the Base64 decoded bytes, right before the encrypted password.
>
> 4. I have also observed that a regular password encrypted using one encrypted master password will still work if the master password is
> re-encrypted and stored in the `settings-security.xml` file, **even
> though the encrypted master password ciphertext is now different**.
> Can someone explain how this works?
>
>
>
This is because the *decrypted* form of the master password is used, not the encrypted "ciphertext". Thus re-encrypting it doesn't affect the server password encryption/decryption.
I don't know the answer to your last two (5 and 6) questions. | Here is example code which shows how to decrypt the maven master password from
`~/.m2/security-settings.xml`
and also the server passwords from
`~/.m2/settings.xml`
Source of `MavenPasswordDecryptor.java`
```
import org.sonatype.plexus.components.cipher.DefaultPlexusCipher;
public class MavenPasswordDecryptor {
public static void main(String[] args) throws Exception {
if (args.length < 1 || args.length > 2 ) {
System.out.println("Usage: java -jar maven-password-decryptor.jar <encrypted-password>");
System.out.println("Usage: java -jar maven-password-decryptor.jar <encrypted-password> <master-password>");
return;
}
DefaultPlexusCipher cipher = new DefaultPlexusCipher();
String encryptedPassword = args[0];
String passPhrase = (args.length == 2 && args[1] != null && !args[1].isEmpty()) ? args[1] : "settings.security";
String result = cipher.decryptDecorated(encryptedPassword, passPhrase);
System.out.println(result);
}
}
```
There is also an example project on GitHub:
<https://github.com/uweguenther/maven-password-decryptor> |
30,769,636 | I'm trying to understand Maven 3's[password encryption feature. I have found that this feature is poorly documented and confusing. For example, the [feature documentation](https://maven.apache.org/guides/mini/guide-encryption.html) and [a blog post by the author of the feature](http://blog.sonatype.com/2009/10/maven-tips-and-tricks-encrypting-passwords/) contradict each other about several points.
This question is broader than [How does maven --encrypt-master-password work](https://stackoverflow.com/questions/15789984/how-does-mvn-encrypt-master-password-password-work) and is not covered by [Maven encrypt-master-password good practice for choosing password](https://stackoverflow.com/questions/16422016/mvn-encrypt-master-password-password-good-practice-for-choosing-password?lq=1).
Specifically, I am trying to answer the following questions which are not covered by the documentation. I've put what information I have been able to gather so far below each question in italics.
1. Does the encrypted master password provide security simply by existing in `settings-security.xml` in a folder that only one user can access (`~/.m2`)? If so, why bother with encrypting a 'master password' (why not just use some random value)? Isn't the 'master password' really just an entropy input to the cryptographic function? Calling it a password is confusing - I expected Maven to prompt me for this password before de-crypting any encrypted server passwords, but it did not.
*My understanding is that yes, this only provides security by existing in an operating-system protected file. I believe Maven allows you to encrypt a master password so that if you loose the `settings-security.xml` file you can re-generate it. Is this correct?*
2. Do the master password and server passwords use the same encryption process/cipher? The server passwords are based on the master password, so there must be some difference in the algorithm. Where is the source code for this located?
*[Marcelo Morales' answer on How does maven --encrypt-master-password work](https://stackoverflow.com/a/15792131/885287) links to the [plexus-cihper project on GitHub](https://github.com/sonatype/plexus-cipher). It isn't clear if that is just the cipher, or the actual Maven plugin that provides the password functionality though.*
3. I have observed that the same master password or server password encrypted multiple times gives different hashes. According to [Marcelo Morales' answer on How does maven --encrypt-master-password work](https://stackoverflow.com/a/15792131/885287), this is because 'a JVM-configuration-specific (usually SHA1PRNG) 64-bit random salt' is added to the password prior to encrypting. Maven decrypts stored passwords when they are used at compile time. Doesn't this mean the salts have to be stored somewhere?
*I have no idea*.
4. I have also observed that a regular password encrypted using one encrypted master password will still work if the master password is re-encrypted and stored in the `settings-security.xml` file, **even though the encrypted master password ciphertext is now different**. Can someone explain how this works?
*I have no idea. This seems to me like Maven is doing something fishy or storing cleartext somewhere.*
5. My understanding is that the encrypted passwords can only be used with `<server />` tags in the `settings.xml` file. is this true? Where can servers defined in `settings.xml` be used?
*My understanding is that `<server />` definitions can be used in `<repositories />` and `<distributionManagement />`, but not `<scm />`. Can someone verify this?*
6. For such a critical feature (build system security) it seems to me that there is a lot of confusion and poor documentation. Can someone point out how the documentation on the Maven 3 website works? Is there a wiki link somewhere that would allow me to try and improve the documentation at all?
*I have no idea*
Sorry for the wall of text, and thanks for any answers. | 2015/06/11 | [
"https://Stackoverflow.com/questions/30769636",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/885287/"
] | I need to know this for bnd(tools) so I can share some deeper analysis.
The 'encrypted' passwords have a syntax of:
```
output ::= '{' base64(packet) '}'
packet ::= salt[8] padlen[1] encrypted[?] padding[padlen]
salt ::= <random>
padlen ::= <length of padding >
padding ::= <random to make packet length a multiple of 16>
```
The cipher used is `AES/CBC/PKCS5Padding`. The secret key and initialisation vector is calculated as follows:
```
sha = sha256( X + salt[8] )
key = sha[0..16]
iv = sha[16..32]
```
For the master password X is "security.settings". Since this is a well known constant *the master password is not encrypted but only obscured*. For the server passwords X is the decoded master password.
Why the resulting packet is padded seems a waste of bytes since the packet format makes it trivial to strip and they are never part of the encryption/decryption. They just add a few random characters to the base64 string.
The only way this is useful is using the relocation facility. For example, if you mount the settings-security.xml on a private mount on the build server. You can then you can freely share the `settings.xml` file in public repos. However, this is also a sucky solution since you need to mount it the same mount point for all your users and CI build servers.
Be aware that any plugin can decode all your server passwords so never use real passwords for the servers. Nexus can create proxy passwords. | Here is example code which shows how to decrypt the maven master password from
`~/.m2/security-settings.xml`
and also the server passwords from
`~/.m2/settings.xml`
Source of `MavenPasswordDecryptor.java`
```
import org.sonatype.plexus.components.cipher.DefaultPlexusCipher;
public class MavenPasswordDecryptor {
public static void main(String[] args) throws Exception {
if (args.length < 1 || args.length > 2 ) {
System.out.println("Usage: java -jar maven-password-decryptor.jar <encrypted-password>");
System.out.println("Usage: java -jar maven-password-decryptor.jar <encrypted-password> <master-password>");
return;
}
DefaultPlexusCipher cipher = new DefaultPlexusCipher();
String encryptedPassword = args[0];
String passPhrase = (args.length == 2 && args[1] != null && !args[1].isEmpty()) ? args[1] : "settings.security";
String result = cipher.decryptDecorated(encryptedPassword, passPhrase);
System.out.println(result);
}
}
```
There is also an example project on GitHub:
<https://github.com/uweguenther/maven-password-decryptor> |
145,200 | I have a problem with amnesia game. After Intro and clicking continue button few times, when game is supposed to start it crashes. Here is console output:
```
ALSA lib pcm_dmix.c:1018:(snd_pcm_dmix_open) unable to open slave
ALSA lib pcm.c:2217:(snd_pcm_open_noupdate) Unknown PCM cards.pcm.rear
ALSA lib pcm.c:2217:(snd_pcm_open_noupdate) Unknown PCM cards.pcm.center_lfe
ALSA lib pcm.c:2217:(snd_pcm_open_noupdate) Unknown PCM cards.pcm.side
ALSA lib audio/pcm_bluetooth.c:1614:(audioservice_expect) BT_GET_CAPABILITIES failed : Input/output error(5)
ALSA lib audio/pcm_bluetooth.c:1614:(audioservice_expect) BT_GET_CAPABILITIES failed : Input/output error(5)
ALSA lib audio/pcm_bluetooth.c:1614:(audioservice_expect) BT_GET_CAPABILITIES failed : Input/output error(5)
ALSA lib audio/pcm_bluetooth.c:1614:(audioservice_expect) BT_GET_CAPABILITIES failed : Input/output error(5)
ALSA lib pcm_dmix.c:957:(snd_pcm_dmix_open) The dmix plugin supports only playback stream
ALSA lib pcm_dmix.c:1018:(snd_pcm_dmix_open) unable to open slave
Cannot connect to server socket err = No such file or directory
Cannot connect to server socket
jack server is not running or cannot be started
```
I should mention I have integrated both graphic and sound card. | 2012/06/01 | [
"https://askubuntu.com/questions/145200",
"https://askubuntu.com",
"https://askubuntu.com/users/67765/"
] | I had same problem (Ubuntu 12.04, Ati 6450, gallium drivers).
The game is working now, after install this library:
`sudo apt-get install libtxc-dxtn-s2tc0` | Try using the additional drivers tool in system setting to search for proprietary drivers you might be able to install. Installing ATI graphics cards(ATI Catalyst) drivers and rebooting helped in my situation. |
145,200 | I have a problem with amnesia game. After Intro and clicking continue button few times, when game is supposed to start it crashes. Here is console output:
```
ALSA lib pcm_dmix.c:1018:(snd_pcm_dmix_open) unable to open slave
ALSA lib pcm.c:2217:(snd_pcm_open_noupdate) Unknown PCM cards.pcm.rear
ALSA lib pcm.c:2217:(snd_pcm_open_noupdate) Unknown PCM cards.pcm.center_lfe
ALSA lib pcm.c:2217:(snd_pcm_open_noupdate) Unknown PCM cards.pcm.side
ALSA lib audio/pcm_bluetooth.c:1614:(audioservice_expect) BT_GET_CAPABILITIES failed : Input/output error(5)
ALSA lib audio/pcm_bluetooth.c:1614:(audioservice_expect) BT_GET_CAPABILITIES failed : Input/output error(5)
ALSA lib audio/pcm_bluetooth.c:1614:(audioservice_expect) BT_GET_CAPABILITIES failed : Input/output error(5)
ALSA lib audio/pcm_bluetooth.c:1614:(audioservice_expect) BT_GET_CAPABILITIES failed : Input/output error(5)
ALSA lib pcm_dmix.c:957:(snd_pcm_dmix_open) The dmix plugin supports only playback stream
ALSA lib pcm_dmix.c:1018:(snd_pcm_dmix_open) unable to open slave
Cannot connect to server socket err = No such file or directory
Cannot connect to server socket
jack server is not running or cannot be started
```
I should mention I have integrated both graphic and sound card. | 2012/06/01 | [
"https://askubuntu.com/questions/145200",
"https://askubuntu.com",
"https://askubuntu.com/users/67765/"
] | I had same problem (Ubuntu 12.04, Ati 6450, gallium drivers).
The game is working now, after install this library:
`sudo apt-get install libtxc-dxtn-s2tc0` | Deinstalling pulseaudio did the trick for me. But keep in mind that the sound-mixer widget might vanish. You probably should install a ALSA-based-mixer after removing pulseaudio. |
9,463,951 | I make Constructor of String as--
```
class TestString {
public static void main(String args[]) {
int arr[]={1,5,6,8,9};
String str3 = new String(arr,1,3);//public java.lang.String(int[], int, int);
System.out.println(str3);
}
}
```
output is in image I can't understand its meaning.... | 2012/02/27 | [
"https://Stackoverflow.com/questions/9463951",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1245234/"
] | You've created a string consisting of three Unicode code points, [U+0005](http://www.fileformat.info/info/unicode/char/0005/index.htm), [U+0006](http://www.fileformat.info/info/unicode/char/0006/index.htm) and [U+0008](http://www.fileformat.info/info/unicode/char/0008/index.htm), and I bet your output is showing exactly that (it is on my machine).
**edit** Your console is using a particular font to render the output. Apparently, the font contains the suit pictograms for characters with codes 5 and 6. I recognize these as going back all the way to the original IBM PC: <http://www.ascii-codes.com/> | They array should contain Unicode codePoints. Do you know what 5, 6, and 8 mean?
It concatenates Unicode characters with the codes you pass in your array, starting at offset 1, with length three. So, offset 1 is the second element of the array (5). It takes 3 elements: 5, 6, and 8. Those characters represent the funny looking graphics you see in your screen |
9,463,951 | I make Constructor of String as--
```
class TestString {
public static void main(String args[]) {
int arr[]={1,5,6,8,9};
String str3 = new String(arr,1,3);//public java.lang.String(int[], int, int);
System.out.println(str3);
}
}
```
output is in image I can't understand its meaning.... | 2012/02/27 | [
"https://Stackoverflow.com/questions/9463951",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1245234/"
] | You've created a string consisting of three Unicode code points, [U+0005](http://www.fileformat.info/info/unicode/char/0005/index.htm), [U+0006](http://www.fileformat.info/info/unicode/char/0006/index.htm) and [U+0008](http://www.fileformat.info/info/unicode/char/0008/index.htm), and I bet your output is showing exactly that (it is on my machine).
**edit** Your console is using a particular font to render the output. Apparently, the font contains the suit pictograms for characters with codes 5 and 6. I recognize these as going back all the way to the original IBM PC: <http://www.ascii-codes.com/> | You craeted a String using the byte array constructor. The byte array must contain the Unicode-points. See [ascii table](http://ss64.com/ascii.html) for more information on unicode points and there representative values. |
9,463,951 | I make Constructor of String as--
```
class TestString {
public static void main(String args[]) {
int arr[]={1,5,6,8,9};
String str3 = new String(arr,1,3);//public java.lang.String(int[], int, int);
System.out.println(str3);
}
}
```
output is in image I can't understand its meaning.... | 2012/02/27 | [
"https://Stackoverflow.com/questions/9463951",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1245234/"
] | You craeted a String using the byte array constructor. The byte array must contain the Unicode-points. See [ascii table](http://ss64.com/ascii.html) for more information on unicode points and there representative values. | They array should contain Unicode codePoints. Do you know what 5, 6, and 8 mean?
It concatenates Unicode characters with the codes you pass in your array, starting at offset 1, with length three. So, offset 1 is the second element of the array (5). It takes 3 elements: 5, 6, and 8. Those characters represent the funny looking graphics you see in your screen |
13,788,514 | For the code below, I am getting the
```
Segmentation fault (core dumped)
```
error message, can someone help me please?
```
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void){
char s[] = "helloWorld";
int i;
for(i = 1; i < strlen(s); i++)
{
printf("Letter is %s\n", s[i]);
}
return(0);
}
``` | 2012/12/09 | [
"https://Stackoverflow.com/questions/13788514",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | ```
printf("Letter is %s\n", s[i]);
```
is wrong, `%s` expects a `const char *`, and you're giving it a `char`. Change this line to
```
printf("Letter is %c\n", s[i]);
```
since the `%c` format specifier is intended for printing individual characters.
Also, in C, arrays are zero-based, so you should initialize `i` to zero using `i = 0;` as well. | You are printing character by character so use `%c` instead of `%s`.
`%s` expects a string but `s[i]` is actually a char.
Also every time you are calling `strlen(s)`. And `strlen` is not changing , so better to use one variable for it and call only once before entering into loop.
A more optimized way like this :
```
int len=strlen(s);
for(i = 0; i < len; i++)
{
printf("Letter is %c\n", s[i]);
}
``` |
29,188,344 | I'm currently getting back the following json from a service that I do not own:
```
{
"auc" : 320658953,
"item" : 31294,
"owner" : "Amacid",
"ownerRealm" : "EarthenRing",
"bid" : 289493,
"buyout" : 371150,
"quantity" : 1,
"timeLeft" : "LONG",
"rand" : 0,
"seed" : 0,
"context" : 0
}, {
"auc" : 321175921,
"item" : 82800,
"owner" : "Drakonys",
"ownerRealm" : "EarthenRing",
"bid" : 7000384,
"buyout" : 7507980,
"quantity" : 1,
"timeLeft" : "VERY_LONG",
"rand" : 0,
"seed" : 161297536,
"context" : 0,
"petSpeciesId" : 293,
"petBreedId" : 9,
"petLevel" : 1,
"petQualityId" : 3
},
```
And I'm trying to deserialize it into proper CLR objects. It's obvious that these object hold a an object hierarchy on the server side; something like `Item` and `PetItem : Item` where `PetItem` has the extra 4 properties at the end there.
How do I handle this? I'm using Json.net to deserialize most of the other results from other services that are more consistent, but I'm looking for a strategy to handle situations like this. I've seen some solutions on how to have Json.net deserialize everything into an implied base class, but I'm not sure how to handle this upcasting type scenario | 2015/03/21 | [
"https://Stackoverflow.com/questions/29188344",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/462631/"
] | Here is yours example: <http://dotnetbyexample.blogspot.ru/2012/02/json-deserialization-with-jsonnet-class.html?m=1>
You just have to use overloaded method
```
JsonConvert.DeserializeObject<List<Item>>
(r.EventArgs.Result, params Newtonsoft.Json.JsonConverter[] converters)
```
And write your converters | I don't see any alternative besides creating the class hierarchy in c# and then have some sort factory that checks for the presence of signature keys on the json side, creating the right c# object. `petSpeciesId` is probably a good candidate for distinguishing between `Item` and `PetItem`.
Ask yourself whether you really need to do this. Maybe a sparse class with unused properties will suit your purposes. Or just use `System.Json.JsonObject` to get an unordered key/value collection.
@Evgeny 's link to the blog post is a correct approach, but it does seem like an incredible amount of work! There's probably a simpler variation, but at bottom that's the work that needs to be done. |
47,906,642 | I'm creating a Space Invaders game with C# WinForms and when coding the movement of the player's cannon, I create this event handler:
```
private void Game_Screen_KeyDown(object sender, KeyEventArgs e)
{
for (int i = 0; i < 500; i++)
{
if (e.KeyCode == Keys.Left)
{
cannonBox.Location = new Point(cannonBox.Left - 2, cannonBox.Top); //Changes location of cannonBox to a new location to the left
Application.DoEvents();
System.Threading.Thread.Sleep(10); //Delays the movement by couple milliseconds to stop instant movement
}
if (e.KeyCode == Keys.Right)
{
cannonBox.Location = new Point(cannonBox.Left + 2, cannonBox.Top); //Changes location of cannonBox to a new location to the right
Application.DoEvents();
System.Threading.Thread.Sleep(10); //Delays the movement by couple milliseconds to stop instant movement
}
if (e.KeyCode == Keys.Up)
{
createLaser(); //Calls the method whenever Up arrow key is pressed
}
}
}
```
But going on different sites concerning how this is unreliable in C#, I am going to make sure to not use it from thereon. What other alternatives are there to use instead of Application.DoEvents within this instance? | 2017/12/20 | [
"https://Stackoverflow.com/questions/47906642",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | I'd suggest to make that event handler `async` and use `await Task.Delay()` instead of `Thread.Sleep()`:
```
private async void Game_Screen_KeyDown(object sender, KeyEventArgs e)
{
for (int i = 0; i < 500; i++)
{
if (e.KeyCode == Keys.Left)
{
cannonBox.Location = new Point(cannonBox.Left - 2, cannonBox.Top); //Changes location of cannonBox to a new location to the left
await Task.Delay(10); //Delays the movement by couple milliseconds to stop instant movement
}
if (e.KeyCode == Keys.Right)
{
cannonBox.Location = new Point(cannonBox.Left + 2, cannonBox.Top); //Changes location of cannonBox to a new location to the right
await Task.Delay(10); //Delays the movement by couple milliseconds to stop instant movement
}
if (e.KeyCode == Keys.Up)
{
createLaser(); //Calls the method whenever Up arrow key is pressed
}
}
}
```
This way, the control flow is returned to the caller and your UI thread has time to handle the other events (so no need for `Application.DoEvents()`). Then after (about) the 10ms, the control is returned and execution of that handler resumed.
There may more fine-tuning be necessary, because now of course you could manage to hit more keys while the method has not finished. How to handle that depends on the surroundings. You could declare a flag that signals current execution and refuses further method entries (no thread safety needed here as it's all happening sequentially on the UI thread).
Or instead of refusing re-entrance queue the keystrokes and handle them in another event, e.g. "idle" events (like Lasse suggested in the comments).
---
Note that an event handlers is one of the rare occasions where using `async` without returning a `Task` is ok. | Application.DoEvents() interupts the execution of your method and the UI thread will process its events (including redrawing of the UI). From my experience there is nothing wrong with using it in the right places...
Using the 'async' pattern (as René Vogt suggested) is best practice to make reponsive UI's.
However. You have to ask yourself if you need a loop that checks 500 times, if the key down is left, right or up. Especially as it seems this loop is triggerd by a key down event...
It would be maybe easier if you make a 'while(true)' loop in the main and call Application.DoEvents from there.
Or you react on the key\_down event and do on action at a time. => press left -> move one left -> press left again -> move one left more... and so on.
<https://msdn.microsoft.com/en-us//library/system.windows.forms.application.doevents(v=vs.110).aspx> |
47,906,642 | I'm creating a Space Invaders game with C# WinForms and when coding the movement of the player's cannon, I create this event handler:
```
private void Game_Screen_KeyDown(object sender, KeyEventArgs e)
{
for (int i = 0; i < 500; i++)
{
if (e.KeyCode == Keys.Left)
{
cannonBox.Location = new Point(cannonBox.Left - 2, cannonBox.Top); //Changes location of cannonBox to a new location to the left
Application.DoEvents();
System.Threading.Thread.Sleep(10); //Delays the movement by couple milliseconds to stop instant movement
}
if (e.KeyCode == Keys.Right)
{
cannonBox.Location = new Point(cannonBox.Left + 2, cannonBox.Top); //Changes location of cannonBox to a new location to the right
Application.DoEvents();
System.Threading.Thread.Sleep(10); //Delays the movement by couple milliseconds to stop instant movement
}
if (e.KeyCode == Keys.Up)
{
createLaser(); //Calls the method whenever Up arrow key is pressed
}
}
}
```
But going on different sites concerning how this is unreliable in C#, I am going to make sure to not use it from thereon. What other alternatives are there to use instead of Application.DoEvents within this instance? | 2017/12/20 | [
"https://Stackoverflow.com/questions/47906642",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | I'd suggest to make that event handler `async` and use `await Task.Delay()` instead of `Thread.Sleep()`:
```
private async void Game_Screen_KeyDown(object sender, KeyEventArgs e)
{
for (int i = 0; i < 500; i++)
{
if (e.KeyCode == Keys.Left)
{
cannonBox.Location = new Point(cannonBox.Left - 2, cannonBox.Top); //Changes location of cannonBox to a new location to the left
await Task.Delay(10); //Delays the movement by couple milliseconds to stop instant movement
}
if (e.KeyCode == Keys.Right)
{
cannonBox.Location = new Point(cannonBox.Left + 2, cannonBox.Top); //Changes location of cannonBox to a new location to the right
await Task.Delay(10); //Delays the movement by couple milliseconds to stop instant movement
}
if (e.KeyCode == Keys.Up)
{
createLaser(); //Calls the method whenever Up arrow key is pressed
}
}
}
```
This way, the control flow is returned to the caller and your UI thread has time to handle the other events (so no need for `Application.DoEvents()`). Then after (about) the 10ms, the control is returned and execution of that handler resumed.
There may more fine-tuning be necessary, because now of course you could manage to hit more keys while the method has not finished. How to handle that depends on the surroundings. You could declare a flag that signals current execution and refuses further method entries (no thread safety needed here as it's all happening sequentially on the UI thread).
Or instead of refusing re-entrance queue the keystrokes and handle them in another event, e.g. "idle" events (like Lasse suggested in the comments).
---
Note that an event handlers is one of the rare occasions where using `async` without returning a `Task` is ok. | Use a **timer** that will call the game processing each 20 milliseconds.
Within the `KeyDown`/`KeyUp` events just change the current state which is used by the game processing.
Sample code:
```
[Flags]
public enum ActionState
{
MoveLeft,
MeveRight,
FireLaser,
}
// stores the current state
private ActionState _actionState;
// set action state
private void Game_Screen_KeyDown(object sender, KeyEventArgs e)
{
switch ( e.KeyCode )
{
case Keys.Left:
_actionState |= ActionState.MoveLeft;
break;
case Keys.Right:
_actionState |= ActionState.MoveRight;
break;
case Keys.Up:
_actionState |= ActionState.FireLaser;
break;
default:
break;
}
}
// remove action state
private void Game_Screen_KeyUp(object sender, KeyEventArgs e)
{
switch ( e.KeyCode )
{
case Keys.Left:
_actionState &= ~ActionState.MoveLeft;
break;
case Keys.Right:
_actionState &= ~ActionState.MoveRight;
break;
case Keys.Up:
_actionState &= ~ActionState.FireLaser;
break;
default:
break;
}
}
// called from a timer every 20 milliseconds
private void Game_Screen_LoopTimer_Tick(object sender, EventArgs e)
{
if ( _actionState.HasFlag( ActionState.MoveLeft ) && !_actionState.HasFlag( ActionState.MoveRight ) )
{
cannonBox.Location = new Point(cannonBox.Left - 2, cannonBox.Top); //Changes location of cannonBox to a new location to the left
}
if ( _actionState.HasFlag( ActionState.MoveRight ) && !_actionState.HasFlag( ActionState.MoveLeft ) )
{
cannonBox.Location = new Point(cannonBox.Left + 2, cannonBox.Top); //Changes location of cannonBox to a new location to the right
}
if ( _actionState.HasFlag( ActionState.FireLaser ) )
{
createLaser(); //Calls the method whenever Up arrow key is pressed
}
}
``` |
47,906,642 | I'm creating a Space Invaders game with C# WinForms and when coding the movement of the player's cannon, I create this event handler:
```
private void Game_Screen_KeyDown(object sender, KeyEventArgs e)
{
for (int i = 0; i < 500; i++)
{
if (e.KeyCode == Keys.Left)
{
cannonBox.Location = new Point(cannonBox.Left - 2, cannonBox.Top); //Changes location of cannonBox to a new location to the left
Application.DoEvents();
System.Threading.Thread.Sleep(10); //Delays the movement by couple milliseconds to stop instant movement
}
if (e.KeyCode == Keys.Right)
{
cannonBox.Location = new Point(cannonBox.Left + 2, cannonBox.Top); //Changes location of cannonBox to a new location to the right
Application.DoEvents();
System.Threading.Thread.Sleep(10); //Delays the movement by couple milliseconds to stop instant movement
}
if (e.KeyCode == Keys.Up)
{
createLaser(); //Calls the method whenever Up arrow key is pressed
}
}
}
```
But going on different sites concerning how this is unreliable in C#, I am going to make sure to not use it from thereon. What other alternatives are there to use instead of Application.DoEvents within this instance? | 2017/12/20 | [
"https://Stackoverflow.com/questions/47906642",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | Use a **timer** that will call the game processing each 20 milliseconds.
Within the `KeyDown`/`KeyUp` events just change the current state which is used by the game processing.
Sample code:
```
[Flags]
public enum ActionState
{
MoveLeft,
MeveRight,
FireLaser,
}
// stores the current state
private ActionState _actionState;
// set action state
private void Game_Screen_KeyDown(object sender, KeyEventArgs e)
{
switch ( e.KeyCode )
{
case Keys.Left:
_actionState |= ActionState.MoveLeft;
break;
case Keys.Right:
_actionState |= ActionState.MoveRight;
break;
case Keys.Up:
_actionState |= ActionState.FireLaser;
break;
default:
break;
}
}
// remove action state
private void Game_Screen_KeyUp(object sender, KeyEventArgs e)
{
switch ( e.KeyCode )
{
case Keys.Left:
_actionState &= ~ActionState.MoveLeft;
break;
case Keys.Right:
_actionState &= ~ActionState.MoveRight;
break;
case Keys.Up:
_actionState &= ~ActionState.FireLaser;
break;
default:
break;
}
}
// called from a timer every 20 milliseconds
private void Game_Screen_LoopTimer_Tick(object sender, EventArgs e)
{
if ( _actionState.HasFlag( ActionState.MoveLeft ) && !_actionState.HasFlag( ActionState.MoveRight ) )
{
cannonBox.Location = new Point(cannonBox.Left - 2, cannonBox.Top); //Changes location of cannonBox to a new location to the left
}
if ( _actionState.HasFlag( ActionState.MoveRight ) && !_actionState.HasFlag( ActionState.MoveLeft ) )
{
cannonBox.Location = new Point(cannonBox.Left + 2, cannonBox.Top); //Changes location of cannonBox to a new location to the right
}
if ( _actionState.HasFlag( ActionState.FireLaser ) )
{
createLaser(); //Calls the method whenever Up arrow key is pressed
}
}
``` | Application.DoEvents() interupts the execution of your method and the UI thread will process its events (including redrawing of the UI). From my experience there is nothing wrong with using it in the right places...
Using the 'async' pattern (as René Vogt suggested) is best practice to make reponsive UI's.
However. You have to ask yourself if you need a loop that checks 500 times, if the key down is left, right or up. Especially as it seems this loop is triggerd by a key down event...
It would be maybe easier if you make a 'while(true)' loop in the main and call Application.DoEvents from there.
Or you react on the key\_down event and do on action at a time. => press left -> move one left -> press left again -> move one left more... and so on.
<https://msdn.microsoft.com/en-us//library/system.windows.forms.application.doevents(v=vs.110).aspx> |
28,265,892 | As homework, I must swap letters in a given string. I already figured out how to do this, but not how to display them at once. it involves a for loop. so if I include disp x in the for loop, it displays them between parentheses and a space, but I want them all together, so instead of
"a"
"b"
"c"
I want "abc". Is there a way to do this? Should I push the variable into an array and then display the array after the for loop? How to push variables in to an array?
This is in TI-Nspire CX Cas btw. | 2015/02/01 | [
"https://Stackoverflow.com/questions/28265892",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4479654/"
] | To add an element `x` to an array `A` use `augment(A, {x})`.
For your specific case, I would use a string variable (call it `string`) to which I concatenate the next letter at each iteration of the `for` loop. So if the next letter to be added is in the variable `letter`, you would put the following line of code at the end of your `for` loop: `string := string & letter`. | I would answer you by an example covering your scenario. Let's say we are aiming to have a array listing the elements of binaries when we construct an integer into the base2 (binary).
```
Define LibPub develope(a,b)=
Func
Local mi,m,q
mi:=mod(a,b)
q:=((a-mi)/(b))
Disp mi
While q≥b
a:=q
m:=mod(a,b)
q:=((a-m)/(b))
Disp m
EndWhile
EndFunc
```
The above small program develops an integer in decimal base into the binary base; however each binary is shown in a separate line as you mentioned:
ex:
```
develope(222,2)
0
1
1
1
1
0
1
```
[enter image description here](https://i.stack.imgur.com/2mzNO.jpg)
but this is not what you want, you want is in a single line. **IMPORTANCE IS THAT YOU SHOULD LIKELIHOOD WANT EACH ELEMENT BE ACCESSIBLE AS A SEPARATE INTEGER, RIGHT? LIKE AS AN ELEMENT IN A ARRAY LIST, THAT'S WHAT YOU LOOKING FOR RIGHT?**
There we Go:
```
Define LibPub develope(n,b)=
Func
Local q,k,seti,set,valid
valid:=b
If valid>1 Then
q:=n
k:=0
set:={}
While q≠0
seti:=mod(q,b)
q:=int(((q)/(b)))
k:=k+1
seti→set[k]
EndWhile
Else
Disp "Erreur, La base doit être plus grand que 1."
EndIf
Return set
EndFunc
```
Basically, because we do not know how many elements are going to be added in the array list, the `set:={}` declares an array with an undefined `dim` (typically length) in order that dynamically be augmented.
The command `seti→set[k]` will add the value of the `seti` whatever it is, into the `k` position of the array list.
and the `return set` simply returns the array.
if you need to get access to a specific element, you know how to to that: `elementNumber5:=set[5]`
I wish it helps. |
28,265,892 | As homework, I must swap letters in a given string. I already figured out how to do this, but not how to display them at once. it involves a for loop. so if I include disp x in the for loop, it displays them between parentheses and a space, but I want them all together, so instead of
"a"
"b"
"c"
I want "abc". Is there a way to do this? Should I push the variable into an array and then display the array after the for loop? How to push variables in to an array?
This is in TI-Nspire CX Cas btw. | 2015/02/01 | [
"https://Stackoverflow.com/questions/28265892",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4479654/"
] | To add an element `x` to an array `A` use `augment(A, {x})`.
For your specific case, I would use a string variable (call it `string`) to which I concatenate the next letter at each iteration of the `for` loop. So if the next letter to be added is in the variable `letter`, you would put the following line of code at the end of your `for` loop: `string := string & letter`. | here is also way:
Local array
array[dim(array)+1] := value |
28,265,892 | As homework, I must swap letters in a given string. I already figured out how to do this, but not how to display them at once. it involves a for loop. so if I include disp x in the for loop, it displays them between parentheses and a space, but I want them all together, so instead of
"a"
"b"
"c"
I want "abc". Is there a way to do this? Should I push the variable into an array and then display the array after the for loop? How to push variables in to an array?
This is in TI-Nspire CX Cas btw. | 2015/02/01 | [
"https://Stackoverflow.com/questions/28265892",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4479654/"
] | here is also way:
Local array
array[dim(array)+1] := value | I would answer you by an example covering your scenario. Let's say we are aiming to have a array listing the elements of binaries when we construct an integer into the base2 (binary).
```
Define LibPub develope(a,b)=
Func
Local mi,m,q
mi:=mod(a,b)
q:=((a-mi)/(b))
Disp mi
While q≥b
a:=q
m:=mod(a,b)
q:=((a-m)/(b))
Disp m
EndWhile
EndFunc
```
The above small program develops an integer in decimal base into the binary base; however each binary is shown in a separate line as you mentioned:
ex:
```
develope(222,2)
0
1
1
1
1
0
1
```
[enter image description here](https://i.stack.imgur.com/2mzNO.jpg)
but this is not what you want, you want is in a single line. **IMPORTANCE IS THAT YOU SHOULD LIKELIHOOD WANT EACH ELEMENT BE ACCESSIBLE AS A SEPARATE INTEGER, RIGHT? LIKE AS AN ELEMENT IN A ARRAY LIST, THAT'S WHAT YOU LOOKING FOR RIGHT?**
There we Go:
```
Define LibPub develope(n,b)=
Func
Local q,k,seti,set,valid
valid:=b
If valid>1 Then
q:=n
k:=0
set:={}
While q≠0
seti:=mod(q,b)
q:=int(((q)/(b)))
k:=k+1
seti→set[k]
EndWhile
Else
Disp "Erreur, La base doit être plus grand que 1."
EndIf
Return set
EndFunc
```
Basically, because we do not know how many elements are going to be added in the array list, the `set:={}` declares an array with an undefined `dim` (typically length) in order that dynamically be augmented.
The command `seti→set[k]` will add the value of the `seti` whatever it is, into the `k` position of the array list.
and the `return set` simply returns the array.
if you need to get access to a specific element, you know how to to that: `elementNumber5:=set[5]`
I wish it helps. |
26,820,253 | I am building an Android app that requires real time updates. My server is Firebase. Firebase is meant to receive its updated data when the user is connected to the server. I am very impressed with Firebase so far, however my concern is receiving the new data when the app is not active. I really do not want to try these ideas to find out they are a bad idea, for I am short on time. I am looking for suggestions and advice.
* **A [service (example)](https://gist.github.com/vikrum/6170193).** Worried about battery consumption and going over my [connection](https://www.firebase.com/pricing.html#faq-section) limit if users are always connected.
* **An AlarmManager to run a sync every X hours**. Worried about not getting updates quickly enough.
* **Using GCM push notification to send a [tickle](http://developer.android.com/training/cloudsync/gcm.html#collapse)**. Worried about paying for another service.
Any other suggestions or possible issues I missed? Thanks for your time!
Edit
----
I found [this thread](https://groups.google.com/forum/#!searchin/firebase-talk/service$20android/firebase-talk/lUAQeLjtpIU/KDBP6trd3Y4J). Still unsure. Maybe a service is not a bad idea, per James Tamplin (Suspect he is Firebase dev) | 2014/11/08 | [
"https://Stackoverflow.com/questions/26820253",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1642079/"
] | You probably want to use GCM in these situations.
Firebase works fine from a background service, but it leaves a socket open, so it's going to use quite a bit of power. This power usage is fine when a user is actively engaged with your app (the screen probably uses a lot more), but when it's running in the background, it's going to be hard on battery life.
In most cases, when your user isn't actively engaged, they're willing to accept slower response times, and push services like GCM are a better value in watts per user happiness.
Also, Firebase is working on adding triggers, as demonstrated in [this video from Google Cloud Platform Live](https://www.youtube.com/embed/aCK_1sq6Dl0?start=15414), that will make it a lot easier to integrate with push services like GCM in the future.
And I guess you could say James is a Firebase dev. He's one of the co-founders :) | You could also try zapier.com which has a firebase + pushover integration to send gcm. but it will require some spending.for free you will have to develop this your self on your custom server, using firebase queue. |
62,475,790 | I can't find any info anywhere on how to change the default width of a TextAreaAutosize component in material-ui.
It seems the only choice is to have this little box. Does anyone know of a better text area auto size component I can use, or how to change the width of the TextAreaAutoSize component?
The API doesn't show any properties that have anything to do with 'className'. I tried to use it anyway and it was ignored. I also tried wrapping the component in a Box, and styling that, but it was ignored by the TextArea.
Any help would be greatly appreciated! | 2020/06/19 | [
"https://Stackoverflow.com/questions/62475790",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4548295/"
] | Resizing by the user is turned off (via `resize: "none"`) for `TextField` here in `InputBase`: <https://github.com/mui-org/material-ui/blob/v4.10.2/packages/material-ui/src/InputBase/InputBase.js#L140>.
Below is an example of how to turn it back on:
```
import React from "react";
import { makeStyles } from "@material-ui/core/styles";
import TextField from "@material-ui/core/TextField";
const useStyles = makeStyles(theme => ({
root: {
"& .MuiTextField-root": {
margin: theme.spacing(1)
}
},
textarea: {
resize: "both"
}
}));
export default function MultilineTextFields() {
const classes = useStyles();
return (
<form className={classes.root} noValidate autoComplete="off">
<div>
<TextField
id="outlined-textarea"
label="Multiline Placeholder"
placeholder="Placeholder"
multiline
variant="outlined"
inputProps={{ className: classes.textarea }}
/>
</div>
</form>
);
}
```
[](https://codesandbox.io/s/textfield-resizable-pcdx4?fontsize=14&hidenavigation=1&theme=dark)
CSS documentation for resize: <https://developer.mozilla.org/en-US/docs/Web/CSS/resize>
Multiline TextField demos: <https://material-ui.com/components/text-fields/#multiline> | I was able to get it to work thanks to Ryan Cogswell. Stupid me, though I wrapped the textarea in a box and applied className to the box (which didn't work), I should have applied it to the textareaautosize directly.
There's a bug in VSCODE Intellisense where it shows 'classes' as a property but not 'className' so I assumed it didn't exist.
Here's the code:
```
const FormStyles = makeStyles((theme) => ({
root: {
width: '100%',
},
button: {
marginTop: '20px',
marginRight: theme.spacing(1),
},
buttons: {
display: 'flex',
justifyContent: 'flex-end'
},
textarea: {
width: '100%',
},
}));
<TextareaAutosize
rowsMin={3}
aria-label={info.label}
name={info.name}
placeholder=''
defaultValue=''
className={classes.textarea}
/>
```
I could not get the drag icon to show up in textfield, so didn't use it. But I would appreciate an example of textfield using multiline and resizing.
Thanks Ryan! |
62,475,790 | I can't find any info anywhere on how to change the default width of a TextAreaAutosize component in material-ui.
It seems the only choice is to have this little box. Does anyone know of a better text area auto size component I can use, or how to change the width of the TextAreaAutoSize component?
The API doesn't show any properties that have anything to do with 'className'. I tried to use it anyway and it was ignored. I also tried wrapping the component in a Box, and styling that, but it was ignored by the TextArea.
Any help would be greatly appreciated! | 2020/06/19 | [
"https://Stackoverflow.com/questions/62475790",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4548295/"
] | You can change the style prop of the TextareaAutosize check [here](https://github.com/mui-org/material-ui/blob/v4.10.2/packages/material-ui/src/TextareaAutosize/TextareaAutosize.js#L211)
```
<TextareaAutosize
rowsMin={3}
placeholder=''
defaultValue=''
style={{ width: "100%" }}
/>
``` | I was able to get it to work thanks to Ryan Cogswell. Stupid me, though I wrapped the textarea in a box and applied className to the box (which didn't work), I should have applied it to the textareaautosize directly.
There's a bug in VSCODE Intellisense where it shows 'classes' as a property but not 'className' so I assumed it didn't exist.
Here's the code:
```
const FormStyles = makeStyles((theme) => ({
root: {
width: '100%',
},
button: {
marginTop: '20px',
marginRight: theme.spacing(1),
},
buttons: {
display: 'flex',
justifyContent: 'flex-end'
},
textarea: {
width: '100%',
},
}));
<TextareaAutosize
rowsMin={3}
aria-label={info.label}
name={info.name}
placeholder=''
defaultValue=''
className={classes.textarea}
/>
```
I could not get the drag icon to show up in textfield, so didn't use it. But I would appreciate an example of textfield using multiline and resizing.
Thanks Ryan! |
62,475,790 | I can't find any info anywhere on how to change the default width of a TextAreaAutosize component in material-ui.
It seems the only choice is to have this little box. Does anyone know of a better text area auto size component I can use, or how to change the width of the TextAreaAutoSize component?
The API doesn't show any properties that have anything to do with 'className'. I tried to use it anyway and it was ignored. I also tried wrapping the component in a Box, and styling that, but it was ignored by the TextArea.
Any help would be greatly appreciated! | 2020/06/19 | [
"https://Stackoverflow.com/questions/62475790",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4548295/"
] | Resizing by the user is turned off (via `resize: "none"`) for `TextField` here in `InputBase`: <https://github.com/mui-org/material-ui/blob/v4.10.2/packages/material-ui/src/InputBase/InputBase.js#L140>.
Below is an example of how to turn it back on:
```
import React from "react";
import { makeStyles } from "@material-ui/core/styles";
import TextField from "@material-ui/core/TextField";
const useStyles = makeStyles(theme => ({
root: {
"& .MuiTextField-root": {
margin: theme.spacing(1)
}
},
textarea: {
resize: "both"
}
}));
export default function MultilineTextFields() {
const classes = useStyles();
return (
<form className={classes.root} noValidate autoComplete="off">
<div>
<TextField
id="outlined-textarea"
label="Multiline Placeholder"
placeholder="Placeholder"
multiline
variant="outlined"
inputProps={{ className: classes.textarea }}
/>
</div>
</form>
);
}
```
[](https://codesandbox.io/s/textfield-resizable-pcdx4?fontsize=14&hidenavigation=1&theme=dark)
CSS documentation for resize: <https://developer.mozilla.org/en-US/docs/Web/CSS/resize>
Multiline TextField demos: <https://material-ui.com/components/text-fields/#multiline> | You can change the style prop of the TextareaAutosize check [here](https://github.com/mui-org/material-ui/blob/v4.10.2/packages/material-ui/src/TextareaAutosize/TextareaAutosize.js#L211)
```
<TextareaAutosize
rowsMin={3}
placeholder=''
defaultValue=''
style={{ width: "100%" }}
/>
``` |
62,475,790 | I can't find any info anywhere on how to change the default width of a TextAreaAutosize component in material-ui.
It seems the only choice is to have this little box. Does anyone know of a better text area auto size component I can use, or how to change the width of the TextAreaAutoSize component?
The API doesn't show any properties that have anything to do with 'className'. I tried to use it anyway and it was ignored. I also tried wrapping the component in a Box, and styling that, but it was ignored by the TextArea.
Any help would be greatly appreciated! | 2020/06/19 | [
"https://Stackoverflow.com/questions/62475790",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4548295/"
] | Resizing by the user is turned off (via `resize: "none"`) for `TextField` here in `InputBase`: <https://github.com/mui-org/material-ui/blob/v4.10.2/packages/material-ui/src/InputBase/InputBase.js#L140>.
Below is an example of how to turn it back on:
```
import React from "react";
import { makeStyles } from "@material-ui/core/styles";
import TextField from "@material-ui/core/TextField";
const useStyles = makeStyles(theme => ({
root: {
"& .MuiTextField-root": {
margin: theme.spacing(1)
}
},
textarea: {
resize: "both"
}
}));
export default function MultilineTextFields() {
const classes = useStyles();
return (
<form className={classes.root} noValidate autoComplete="off">
<div>
<TextField
id="outlined-textarea"
label="Multiline Placeholder"
placeholder="Placeholder"
multiline
variant="outlined"
inputProps={{ className: classes.textarea }}
/>
</div>
</form>
);
}
```
[](https://codesandbox.io/s/textfield-resizable-pcdx4?fontsize=14&hidenavigation=1&theme=dark)
CSS documentation for resize: <https://developer.mozilla.org/en-US/docs/Web/CSS/resize>
Multiline TextField demos: <https://material-ui.com/components/text-fields/#multiline> | Here's the trick I used. I wrapped it in a flex container and used align-items to stretch the width to cover the size of that container.
```
<Stack
direction="column"
justifyContent="center"
alignItems="stretch"
spacing={2}
>
<TextareaAutosize
label='Title'
value={pub.title || ''}
onChange={(e) => pub.title = e.target.value}
variant='outlined'
sx={{m: 1}}
size='small'
/>
</Stack>
``` |
62,475,790 | I can't find any info anywhere on how to change the default width of a TextAreaAutosize component in material-ui.
It seems the only choice is to have this little box. Does anyone know of a better text area auto size component I can use, or how to change the width of the TextAreaAutoSize component?
The API doesn't show any properties that have anything to do with 'className'. I tried to use it anyway and it was ignored. I also tried wrapping the component in a Box, and styling that, but it was ignored by the TextArea.
Any help would be greatly appreciated! | 2020/06/19 | [
"https://Stackoverflow.com/questions/62475790",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4548295/"
] | You can change the style prop of the TextareaAutosize check [here](https://github.com/mui-org/material-ui/blob/v4.10.2/packages/material-ui/src/TextareaAutosize/TextareaAutosize.js#L211)
```
<TextareaAutosize
rowsMin={3}
placeholder=''
defaultValue=''
style={{ width: "100%" }}
/>
``` | Here's the trick I used. I wrapped it in a flex container and used align-items to stretch the width to cover the size of that container.
```
<Stack
direction="column"
justifyContent="center"
alignItems="stretch"
spacing={2}
>
<TextareaAutosize
label='Title'
value={pub.title || ''}
onChange={(e) => pub.title = e.target.value}
variant='outlined'
sx={{m: 1}}
size='small'
/>
</Stack>
``` |
20,677,958 | i just want to get the value entered in my txtfield from other class
```
public class MyCostumizedDialog{
int x = 0 ;
public void showFrameDialog(){
// Here are my components...
txt1 = new Jtextfields;...//my jtxtfield
.......
btn1.addactionlister(....){
x = Integer.parseInt(txt1.gettext());//get string from jtxtfld and parse to int
}
public int getNumber(){
return x;
}
}
```
then i want to get the value entered from jtxtfild from MyCostumizedDialog like this
```
public class OtherClass{
public void frame(){
btn2.addactionlistener(......){
MyCostumizedDialog mcd = new MyCostumizedDialog();
mcd .showFrameDialog();
Double x= mcd.getNumber();
txtNumber.setText("P "+x);
}
}
}
```
txtnumber always show the initial value of x from MycostumeDialog,please help me | 2013/12/19 | [
"https://Stackoverflow.com/questions/20677958",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3053928/"
] | you are trying to get value before setting value to it in other words your x gets value once you click on btn1, but you are trying to get value of x before clicking on that button.
```
mcd .showFrameDialog();
Double x= mcd.getNumber();
```
you should call `mcd.getNumber();` after you set value to your variable. | Since you always instantiate a new instance of MyCostumizedDialog every time btn2 is pressed you get the initial value of MyCostumizedDialog because nobody pressed the btn1 for the newly created instance that would set the value.
If the btn1 needs to be there for other purposes I would recommend to just add another method to do exactly the same thing as the btn1 action listener does, and then call that method inside the btn2 action listener. |
48,037,601 | I am currently in the middle of migrating my REST-Server to GraphQL (at least partly). Most of the work is done, but i stumbled upon this problem which i seem to be unable to solve: OneToMany relationships in a graphql query, with FetchType.LAZY.
I am using:
<https://github.com/graphql-java/graphql-spring-boot>
and
<https://github.com/graphql-java/graphql-java-tools> for the integration.
Here is an example:
**Entities:**
```
@Entity
class Show {
private Long id;
private String name;
@OneToMany(mappedBy = "show")
private List<Competition> competition;
}
@Entity
class Competition {
private Long id;
private String name;
@ManyToOne(fetch = FetchType.LAZY)
private Show show;
}
```
**Schema:**
```
type Show {
id: ID!
name: String!
competitions: [Competition]
}
type Competition {
id: ID!
name: String
}
extend type Query {
shows : [Show]
}
```
**Resolver:**
```
@Component
public class ShowResolver implements GraphQLQueryResolver {
@Autowired
private ShowRepository showRepository;
public List<Show> getShows() {
return ((List<Show>)showRepository.findAll());
}
}
```
If i now query the endpoint with this (shorthand) query:
```
{
shows {
id
name
competitions {
id
}
}
}
```
i get:
>
> org.hibernate.LazyInitializationException: failed to lazily initialize
> a collection of role: Show.competitions, could not initialize proxy -
> no Session
>
>
>
Now i know why this error happens and what it means, but i don't really know were to apply a fix for this. I don't want to make my entites to eagerly fetch all relations, because that would negate some of the advantages of GraphQL. Any ideas where i might need to look for a solution?
Thanks! | 2017/12/30 | [
"https://Stackoverflow.com/questions/48037601",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1386873/"
] | My prefered solution is to have the transaction open until the Servlet sends its response. With this small code change your LazyLoad will work right:
```
import javax.servlet.Filter;
import org.springframework.orm.jpa.support.OpenEntityManagerInViewFilter;
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
/**
* Register the {@link OpenEntityManagerInViewFilter} so that the
* GraphQL-Servlet can handle lazy loads during execution.
*
* @return
*/
@Bean
public Filter OpenFilter() {
return new OpenEntityManagerInViewFilter();
}
}
``` | For anyone confused about the accepted answer then you need to change the java entities to include a bidirectional relationship and ensure you use the helper methods to add a `Competition` otherwise its easy to forget to set the relationship up correctly.
```
@Entity
class Show {
private Long id;
private String name;
@OneToMany(cascade = CascadeType.ALL, mappedBy = "show")
private List<Competition> competition;
public void addCompetition(Competition c) {
c.setShow(this);
competition.add(c);
}
}
@Entity
class Competition {
private Long id;
private String name;
@ManyToOne(fetch = FetchType.LAZY)
private Show show;
}
```
The general intuition behind the accepted answer is:
The graphql resolver `ShowResolver` will open a transaction to get the list of shows but then it will close the transaction once its done doing that.
Then the nested graphql query for `competitions` will attempt to call `getCompetition()` on each `Show` instance retrieved from the previous query which will throw a `LazyInitializationException` because the transaction has been closed.
```
{
shows {
id
name
competitions {
id
}
}
}
```
The accepted answer is essentially
bypassing retrieving the list of competitions through the `OneToMany` relationship and instead creates a new query in a new transaction which eliminates the problem.
Not sure if this is a hack but `@Transactional` on resolvers doesn't work for me although the logic of doing that does make some sense but I am clearly not understanding the root cause. |
48,037,601 | I am currently in the middle of migrating my REST-Server to GraphQL (at least partly). Most of the work is done, but i stumbled upon this problem which i seem to be unable to solve: OneToMany relationships in a graphql query, with FetchType.LAZY.
I am using:
<https://github.com/graphql-java/graphql-spring-boot>
and
<https://github.com/graphql-java/graphql-java-tools> for the integration.
Here is an example:
**Entities:**
```
@Entity
class Show {
private Long id;
private String name;
@OneToMany(mappedBy = "show")
private List<Competition> competition;
}
@Entity
class Competition {
private Long id;
private String name;
@ManyToOne(fetch = FetchType.LAZY)
private Show show;
}
```
**Schema:**
```
type Show {
id: ID!
name: String!
competitions: [Competition]
}
type Competition {
id: ID!
name: String
}
extend type Query {
shows : [Show]
}
```
**Resolver:**
```
@Component
public class ShowResolver implements GraphQLQueryResolver {
@Autowired
private ShowRepository showRepository;
public List<Show> getShows() {
return ((List<Show>)showRepository.findAll());
}
}
```
If i now query the endpoint with this (shorthand) query:
```
{
shows {
id
name
competitions {
id
}
}
}
```
i get:
>
> org.hibernate.LazyInitializationException: failed to lazily initialize
> a collection of role: Show.competitions, could not initialize proxy -
> no Session
>
>
>
Now i know why this error happens and what it means, but i don't really know were to apply a fix for this. I don't want to make my entites to eagerly fetch all relations, because that would negate some of the advantages of GraphQL. Any ideas where i might need to look for a solution?
Thanks! | 2017/12/30 | [
"https://Stackoverflow.com/questions/48037601",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1386873/"
] | For anyone confused about the accepted answer then you need to change the java entities to include a bidirectional relationship and ensure you use the helper methods to add a `Competition` otherwise its easy to forget to set the relationship up correctly.
```
@Entity
class Show {
private Long id;
private String name;
@OneToMany(cascade = CascadeType.ALL, mappedBy = "show")
private List<Competition> competition;
public void addCompetition(Competition c) {
c.setShow(this);
competition.add(c);
}
}
@Entity
class Competition {
private Long id;
private String name;
@ManyToOne(fetch = FetchType.LAZY)
private Show show;
}
```
The general intuition behind the accepted answer is:
The graphql resolver `ShowResolver` will open a transaction to get the list of shows but then it will close the transaction once its done doing that.
Then the nested graphql query for `competitions` will attempt to call `getCompetition()` on each `Show` instance retrieved from the previous query which will throw a `LazyInitializationException` because the transaction has been closed.
```
{
shows {
id
name
competitions {
id
}
}
}
```
The accepted answer is essentially
bypassing retrieving the list of competitions through the `OneToMany` relationship and instead creates a new query in a new transaction which eliminates the problem.
Not sure if this is a hack but `@Transactional` on resolvers doesn't work for me although the logic of doing that does make some sense but I am clearly not understanding the root cause. | For me using `AsyncTransactionalExecutionStrategy` worked incorrectly with exceptions. E.g. lazy init or app-level exception triggered transaction to rollback-only status. Spring transaction mechanism then threw on rollback-only transaction at the boundary of strategy `execute`, causing `HttpRequestHandlerImpl` to return 400 empty response. See <https://github.com/graphql-java-kickstart/graphql-java-servlet/issues/250> and <https://github.com/graphql-java/graphql-java/issues/1652> for more details.
What worked for me was using `Instrumentation` to wrap the whole operation in a transaction: <https://spectrum.chat/graphql/general/transactional-queries-with-spring~47749680-3bb7-4508-8935-1d20d04d0c6a> |
48,037,601 | I am currently in the middle of migrating my REST-Server to GraphQL (at least partly). Most of the work is done, but i stumbled upon this problem which i seem to be unable to solve: OneToMany relationships in a graphql query, with FetchType.LAZY.
I am using:
<https://github.com/graphql-java/graphql-spring-boot>
and
<https://github.com/graphql-java/graphql-java-tools> for the integration.
Here is an example:
**Entities:**
```
@Entity
class Show {
private Long id;
private String name;
@OneToMany(mappedBy = "show")
private List<Competition> competition;
}
@Entity
class Competition {
private Long id;
private String name;
@ManyToOne(fetch = FetchType.LAZY)
private Show show;
}
```
**Schema:**
```
type Show {
id: ID!
name: String!
competitions: [Competition]
}
type Competition {
id: ID!
name: String
}
extend type Query {
shows : [Show]
}
```
**Resolver:**
```
@Component
public class ShowResolver implements GraphQLQueryResolver {
@Autowired
private ShowRepository showRepository;
public List<Show> getShows() {
return ((List<Show>)showRepository.findAll());
}
}
```
If i now query the endpoint with this (shorthand) query:
```
{
shows {
id
name
competitions {
id
}
}
}
```
i get:
>
> org.hibernate.LazyInitializationException: failed to lazily initialize
> a collection of role: Show.competitions, could not initialize proxy -
> no Session
>
>
>
Now i know why this error happens and what it means, but i don't really know were to apply a fix for this. I don't want to make my entites to eagerly fetch all relations, because that would negate some of the advantages of GraphQL. Any ideas where i might need to look for a solution?
Thanks! | 2017/12/30 | [
"https://Stackoverflow.com/questions/48037601",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1386873/"
] | My prefered solution is to have the transaction open until the Servlet sends its response. With this small code change your LazyLoad will work right:
```
import javax.servlet.Filter;
import org.springframework.orm.jpa.support.OpenEntityManagerInViewFilter;
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
/**
* Register the {@link OpenEntityManagerInViewFilter} so that the
* GraphQL-Servlet can handle lazy loads during execution.
*
* @return
*/
@Bean
public Filter OpenFilter() {
return new OpenEntityManagerInViewFilter();
}
}
``` | I am assuming that whenever you fetch an object of *Show*, you want all the associated *Competition* of the *Show* object.
By default the fetch type for all collections type in an entity is **LAZY**. You can specify the **EAGER** type to make sure hibernate fetches the collection.
In your *Show* class you can change the fetchType to **EAGER**.
```
@OneToMany(cascade=CascadeType.ALL,fetch=FetchType.EAGER)
private List<Competition> competition;
``` |
48,037,601 | I am currently in the middle of migrating my REST-Server to GraphQL (at least partly). Most of the work is done, but i stumbled upon this problem which i seem to be unable to solve: OneToMany relationships in a graphql query, with FetchType.LAZY.
I am using:
<https://github.com/graphql-java/graphql-spring-boot>
and
<https://github.com/graphql-java/graphql-java-tools> for the integration.
Here is an example:
**Entities:**
```
@Entity
class Show {
private Long id;
private String name;
@OneToMany(mappedBy = "show")
private List<Competition> competition;
}
@Entity
class Competition {
private Long id;
private String name;
@ManyToOne(fetch = FetchType.LAZY)
private Show show;
}
```
**Schema:**
```
type Show {
id: ID!
name: String!
competitions: [Competition]
}
type Competition {
id: ID!
name: String
}
extend type Query {
shows : [Show]
}
```
**Resolver:**
```
@Component
public class ShowResolver implements GraphQLQueryResolver {
@Autowired
private ShowRepository showRepository;
public List<Show> getShows() {
return ((List<Show>)showRepository.findAll());
}
}
```
If i now query the endpoint with this (shorthand) query:
```
{
shows {
id
name
competitions {
id
}
}
}
```
i get:
>
> org.hibernate.LazyInitializationException: failed to lazily initialize
> a collection of role: Show.competitions, could not initialize proxy -
> no Session
>
>
>
Now i know why this error happens and what it means, but i don't really know were to apply a fix for this. I don't want to make my entites to eagerly fetch all relations, because that would negate some of the advantages of GraphQL. Any ideas where i might need to look for a solution?
Thanks! | 2017/12/30 | [
"https://Stackoverflow.com/questions/48037601",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1386873/"
] | My prefered solution is to have the transaction open until the Servlet sends its response. With this small code change your LazyLoad will work right:
```
import javax.servlet.Filter;
import org.springframework.orm.jpa.support.OpenEntityManagerInViewFilter;
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
/**
* Register the {@link OpenEntityManagerInViewFilter} so that the
* GraphQL-Servlet can handle lazy loads during execution.
*
* @return
*/
@Bean
public Filter OpenFilter() {
return new OpenEntityManagerInViewFilter();
}
}
``` | For me using `AsyncTransactionalExecutionStrategy` worked incorrectly with exceptions. E.g. lazy init or app-level exception triggered transaction to rollback-only status. Spring transaction mechanism then threw on rollback-only transaction at the boundary of strategy `execute`, causing `HttpRequestHandlerImpl` to return 400 empty response. See <https://github.com/graphql-java-kickstart/graphql-java-servlet/issues/250> and <https://github.com/graphql-java/graphql-java/issues/1652> for more details.
What worked for me was using `Instrumentation` to wrap the whole operation in a transaction: <https://spectrum.chat/graphql/general/transactional-queries-with-spring~47749680-3bb7-4508-8935-1d20d04d0c6a> |
48,037,601 | I am currently in the middle of migrating my REST-Server to GraphQL (at least partly). Most of the work is done, but i stumbled upon this problem which i seem to be unable to solve: OneToMany relationships in a graphql query, with FetchType.LAZY.
I am using:
<https://github.com/graphql-java/graphql-spring-boot>
and
<https://github.com/graphql-java/graphql-java-tools> for the integration.
Here is an example:
**Entities:**
```
@Entity
class Show {
private Long id;
private String name;
@OneToMany(mappedBy = "show")
private List<Competition> competition;
}
@Entity
class Competition {
private Long id;
private String name;
@ManyToOne(fetch = FetchType.LAZY)
private Show show;
}
```
**Schema:**
```
type Show {
id: ID!
name: String!
competitions: [Competition]
}
type Competition {
id: ID!
name: String
}
extend type Query {
shows : [Show]
}
```
**Resolver:**
```
@Component
public class ShowResolver implements GraphQLQueryResolver {
@Autowired
private ShowRepository showRepository;
public List<Show> getShows() {
return ((List<Show>)showRepository.findAll());
}
}
```
If i now query the endpoint with this (shorthand) query:
```
{
shows {
id
name
competitions {
id
}
}
}
```
i get:
>
> org.hibernate.LazyInitializationException: failed to lazily initialize
> a collection of role: Show.competitions, could not initialize proxy -
> no Session
>
>
>
Now i know why this error happens and what it means, but i don't really know were to apply a fix for this. I don't want to make my entites to eagerly fetch all relations, because that would negate some of the advantages of GraphQL. Any ideas where i might need to look for a solution?
Thanks! | 2017/12/30 | [
"https://Stackoverflow.com/questions/48037601",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1386873/"
] | For anyone confused about the accepted answer then you need to change the java entities to include a bidirectional relationship and ensure you use the helper methods to add a `Competition` otherwise its easy to forget to set the relationship up correctly.
```
@Entity
class Show {
private Long id;
private String name;
@OneToMany(cascade = CascadeType.ALL, mappedBy = "show")
private List<Competition> competition;
public void addCompetition(Competition c) {
c.setShow(this);
competition.add(c);
}
}
@Entity
class Competition {
private Long id;
private String name;
@ManyToOne(fetch = FetchType.LAZY)
private Show show;
}
```
The general intuition behind the accepted answer is:
The graphql resolver `ShowResolver` will open a transaction to get the list of shows but then it will close the transaction once its done doing that.
Then the nested graphql query for `competitions` will attempt to call `getCompetition()` on each `Show` instance retrieved from the previous query which will throw a `LazyInitializationException` because the transaction has been closed.
```
{
shows {
id
name
competitions {
id
}
}
}
```
The accepted answer is essentially
bypassing retrieving the list of competitions through the `OneToMany` relationship and instead creates a new query in a new transaction which eliminates the problem.
Not sure if this is a hack but `@Transactional` on resolvers doesn't work for me although the logic of doing that does make some sense but I am clearly not understanding the root cause. | You just need to annotate your resolver classes with `@Transactional`. Then, entities returned from repositories will be able to lazily fetch data. |
48,037,601 | I am currently in the middle of migrating my REST-Server to GraphQL (at least partly). Most of the work is done, but i stumbled upon this problem which i seem to be unable to solve: OneToMany relationships in a graphql query, with FetchType.LAZY.
I am using:
<https://github.com/graphql-java/graphql-spring-boot>
and
<https://github.com/graphql-java/graphql-java-tools> for the integration.
Here is an example:
**Entities:**
```
@Entity
class Show {
private Long id;
private String name;
@OneToMany(mappedBy = "show")
private List<Competition> competition;
}
@Entity
class Competition {
private Long id;
private String name;
@ManyToOne(fetch = FetchType.LAZY)
private Show show;
}
```
**Schema:**
```
type Show {
id: ID!
name: String!
competitions: [Competition]
}
type Competition {
id: ID!
name: String
}
extend type Query {
shows : [Show]
}
```
**Resolver:**
```
@Component
public class ShowResolver implements GraphQLQueryResolver {
@Autowired
private ShowRepository showRepository;
public List<Show> getShows() {
return ((List<Show>)showRepository.findAll());
}
}
```
If i now query the endpoint with this (shorthand) query:
```
{
shows {
id
name
competitions {
id
}
}
}
```
i get:
>
> org.hibernate.LazyInitializationException: failed to lazily initialize
> a collection of role: Show.competitions, could not initialize proxy -
> no Session
>
>
>
Now i know why this error happens and what it means, but i don't really know were to apply a fix for this. I don't want to make my entites to eagerly fetch all relations, because that would negate some of the advantages of GraphQL. Any ideas where i might need to look for a solution?
Thanks! | 2017/12/30 | [
"https://Stackoverflow.com/questions/48037601",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1386873/"
] | For me using `AsyncTransactionalExecutionStrategy` worked incorrectly with exceptions. E.g. lazy init or app-level exception triggered transaction to rollback-only status. Spring transaction mechanism then threw on rollback-only transaction at the boundary of strategy `execute`, causing `HttpRequestHandlerImpl` to return 400 empty response. See <https://github.com/graphql-java-kickstart/graphql-java-servlet/issues/250> and <https://github.com/graphql-java/graphql-java/issues/1652> for more details.
What worked for me was using `Instrumentation` to wrap the whole operation in a transaction: <https://spectrum.chat/graphql/general/transactional-queries-with-spring~47749680-3bb7-4508-8935-1d20d04d0c6a> | You just need to annotate your resolver classes with `@Transactional`. Then, entities returned from repositories will be able to lazily fetch data. |
48,037,601 | I am currently in the middle of migrating my REST-Server to GraphQL (at least partly). Most of the work is done, but i stumbled upon this problem which i seem to be unable to solve: OneToMany relationships in a graphql query, with FetchType.LAZY.
I am using:
<https://github.com/graphql-java/graphql-spring-boot>
and
<https://github.com/graphql-java/graphql-java-tools> for the integration.
Here is an example:
**Entities:**
```
@Entity
class Show {
private Long id;
private String name;
@OneToMany(mappedBy = "show")
private List<Competition> competition;
}
@Entity
class Competition {
private Long id;
private String name;
@ManyToOne(fetch = FetchType.LAZY)
private Show show;
}
```
**Schema:**
```
type Show {
id: ID!
name: String!
competitions: [Competition]
}
type Competition {
id: ID!
name: String
}
extend type Query {
shows : [Show]
}
```
**Resolver:**
```
@Component
public class ShowResolver implements GraphQLQueryResolver {
@Autowired
private ShowRepository showRepository;
public List<Show> getShows() {
return ((List<Show>)showRepository.findAll());
}
}
```
If i now query the endpoint with this (shorthand) query:
```
{
shows {
id
name
competitions {
id
}
}
}
```
i get:
>
> org.hibernate.LazyInitializationException: failed to lazily initialize
> a collection of role: Show.competitions, could not initialize proxy -
> no Session
>
>
>
Now i know why this error happens and what it means, but i don't really know were to apply a fix for this. I don't want to make my entites to eagerly fetch all relations, because that would negate some of the advantages of GraphQL. Any ideas where i might need to look for a solution?
Thanks! | 2017/12/30 | [
"https://Stackoverflow.com/questions/48037601",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1386873/"
] | For anyone confused about the accepted answer then you need to change the java entities to include a bidirectional relationship and ensure you use the helper methods to add a `Competition` otherwise its easy to forget to set the relationship up correctly.
```
@Entity
class Show {
private Long id;
private String name;
@OneToMany(cascade = CascadeType.ALL, mappedBy = "show")
private List<Competition> competition;
public void addCompetition(Competition c) {
c.setShow(this);
competition.add(c);
}
}
@Entity
class Competition {
private Long id;
private String name;
@ManyToOne(fetch = FetchType.LAZY)
private Show show;
}
```
The general intuition behind the accepted answer is:
The graphql resolver `ShowResolver` will open a transaction to get the list of shows but then it will close the transaction once its done doing that.
Then the nested graphql query for `competitions` will attempt to call `getCompetition()` on each `Show` instance retrieved from the previous query which will throw a `LazyInitializationException` because the transaction has been closed.
```
{
shows {
id
name
competitions {
id
}
}
}
```
The accepted answer is essentially
bypassing retrieving the list of competitions through the `OneToMany` relationship and instead creates a new query in a new transaction which eliminates the problem.
Not sure if this is a hack but `@Transactional` on resolvers doesn't work for me although the logic of doing that does make some sense but I am clearly not understanding the root cause. | I am assuming that whenever you fetch an object of *Show*, you want all the associated *Competition* of the *Show* object.
By default the fetch type for all collections type in an entity is **LAZY**. You can specify the **EAGER** type to make sure hibernate fetches the collection.
In your *Show* class you can change the fetchType to **EAGER**.
```
@OneToMany(cascade=CascadeType.ALL,fetch=FetchType.EAGER)
private List<Competition> competition;
``` |
48,037,601 | I am currently in the middle of migrating my REST-Server to GraphQL (at least partly). Most of the work is done, but i stumbled upon this problem which i seem to be unable to solve: OneToMany relationships in a graphql query, with FetchType.LAZY.
I am using:
<https://github.com/graphql-java/graphql-spring-boot>
and
<https://github.com/graphql-java/graphql-java-tools> for the integration.
Here is an example:
**Entities:**
```
@Entity
class Show {
private Long id;
private String name;
@OneToMany(mappedBy = "show")
private List<Competition> competition;
}
@Entity
class Competition {
private Long id;
private String name;
@ManyToOne(fetch = FetchType.LAZY)
private Show show;
}
```
**Schema:**
```
type Show {
id: ID!
name: String!
competitions: [Competition]
}
type Competition {
id: ID!
name: String
}
extend type Query {
shows : [Show]
}
```
**Resolver:**
```
@Component
public class ShowResolver implements GraphQLQueryResolver {
@Autowired
private ShowRepository showRepository;
public List<Show> getShows() {
return ((List<Show>)showRepository.findAll());
}
}
```
If i now query the endpoint with this (shorthand) query:
```
{
shows {
id
name
competitions {
id
}
}
}
```
i get:
>
> org.hibernate.LazyInitializationException: failed to lazily initialize
> a collection of role: Show.competitions, could not initialize proxy -
> no Session
>
>
>
Now i know why this error happens and what it means, but i don't really know were to apply a fix for this. I don't want to make my entites to eagerly fetch all relations, because that would negate some of the advantages of GraphQL. Any ideas where i might need to look for a solution?
Thanks! | 2017/12/30 | [
"https://Stackoverflow.com/questions/48037601",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1386873/"
] | For me using `AsyncTransactionalExecutionStrategy` worked incorrectly with exceptions. E.g. lazy init or app-level exception triggered transaction to rollback-only status. Spring transaction mechanism then threw on rollback-only transaction at the boundary of strategy `execute`, causing `HttpRequestHandlerImpl` to return 400 empty response. See <https://github.com/graphql-java-kickstart/graphql-java-servlet/issues/250> and <https://github.com/graphql-java/graphql-java/issues/1652> for more details.
What worked for me was using `Instrumentation` to wrap the whole operation in a transaction: <https://spectrum.chat/graphql/general/transactional-queries-with-spring~47749680-3bb7-4508-8935-1d20d04d0c6a> | I am assuming that whenever you fetch an object of *Show*, you want all the associated *Competition* of the *Show* object.
By default the fetch type for all collections type in an entity is **LAZY**. You can specify the **EAGER** type to make sure hibernate fetches the collection.
In your *Show* class you can change the fetchType to **EAGER**.
```
@OneToMany(cascade=CascadeType.ALL,fetch=FetchType.EAGER)
private List<Competition> competition;
``` |
48,037,601 | I am currently in the middle of migrating my REST-Server to GraphQL (at least partly). Most of the work is done, but i stumbled upon this problem which i seem to be unable to solve: OneToMany relationships in a graphql query, with FetchType.LAZY.
I am using:
<https://github.com/graphql-java/graphql-spring-boot>
and
<https://github.com/graphql-java/graphql-java-tools> for the integration.
Here is an example:
**Entities:**
```
@Entity
class Show {
private Long id;
private String name;
@OneToMany(mappedBy = "show")
private List<Competition> competition;
}
@Entity
class Competition {
private Long id;
private String name;
@ManyToOne(fetch = FetchType.LAZY)
private Show show;
}
```
**Schema:**
```
type Show {
id: ID!
name: String!
competitions: [Competition]
}
type Competition {
id: ID!
name: String
}
extend type Query {
shows : [Show]
}
```
**Resolver:**
```
@Component
public class ShowResolver implements GraphQLQueryResolver {
@Autowired
private ShowRepository showRepository;
public List<Show> getShows() {
return ((List<Show>)showRepository.findAll());
}
}
```
If i now query the endpoint with this (shorthand) query:
```
{
shows {
id
name
competitions {
id
}
}
}
```
i get:
>
> org.hibernate.LazyInitializationException: failed to lazily initialize
> a collection of role: Show.competitions, could not initialize proxy -
> no Session
>
>
>
Now i know why this error happens and what it means, but i don't really know were to apply a fix for this. I don't want to make my entites to eagerly fetch all relations, because that would negate some of the advantages of GraphQL. Any ideas where i might need to look for a solution?
Thanks! | 2017/12/30 | [
"https://Stackoverflow.com/questions/48037601",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1386873/"
] | I solved it and should have read the documentation of the graphql-java-tools library more carefully i suppose.
Beside the `GraphQLQueryResolver` which resolves the basic queries i also needed a `GraphQLResolver<T>` for my `Show`class, which looks like this:
```
@Component
public class ShowResolver implements GraphQLResolver<Show> {
@Autowired
private CompetitionRepository competitionRepository;
public List<Competition> competitions(Show show) {
return ((List<Competition>)competitionRepository.findByShowId(show.getId()));
}
}
```
This tells the library how to resolve complex objects inside my `Show`class and is only used if the initially query requests to include the `Competition`objects. Happy new Year!
**EDIT 31.07.2019**: I since stepped away from the solution below. Long running transactions are seldom a good idea and in this case it can cause problems once you scale your application. We started to implement DataLoaders to batch queries in an async matter. The long running transactions in combination with the async nature of the DataLoaders can lead to deadlocks: <https://github.com/graphql-java-kickstart/graphql-java-tools/issues/58#issuecomment-398761715> (above and below for more information). I will not remove the solution below, because it might still be good starting point for smaller applications and/or applications which will not need any batched queries, but please keep this comment in mind when doing so.
**EDIT:** As requested here is another solution using a custom execution strategy. I am using `graphql-spring-boot-starter` and `graphql-java-tools`:
Create a Bean of type `ExecutionStrategy` that handles the transaction, like this:
```
@Service(GraphQLWebAutoConfiguration.QUERY_EXECUTION_STRATEGY)
public class AsyncTransactionalExecutionStrategy extends AsyncExecutionStrategy {
@Override
@Transactional
public CompletableFuture<ExecutionResult> execute(ExecutionContext executionContext, ExecutionStrategyParameters parameters) throws NonNullableFieldWasNullException {
return super.execute(executionContext, parameters);
}
}
```
This puts the whole execution of the query inside the same transaction. I don't know if this is the most optimal solution, and it also already has some drawbacks in regards to error handling, but you don't need to define a type resolver that way.
Notice that if this is the only `ExecutionStrategy` Bean present, this will also be used for mutations, contrary to what the Bean name might suggest. See <https://github.com/graphql-java-kickstart/graphql-spring-boot/blob/v11.1.0/graphql-spring-boot-autoconfigure/src/main/java/graphql/kickstart/spring/web/boot/GraphQLWebAutoConfiguration.java#L161-L166> for reference. To avoid this define another `ExecutionStrategy` to be used for mutations:
```
@Bean(GraphQLWebAutoConfiguration.MUTATION_EXECUTION_STRATEGY)
public ExecutionStrategy queryExecutionStrategy() {
return new AsyncSerialExecutionStrategy();
}
``` | My prefered solution is to have the transaction open until the Servlet sends its response. With this small code change your LazyLoad will work right:
```
import javax.servlet.Filter;
import org.springframework.orm.jpa.support.OpenEntityManagerInViewFilter;
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
/**
* Register the {@link OpenEntityManagerInViewFilter} so that the
* GraphQL-Servlet can handle lazy loads during execution.
*
* @return
*/
@Bean
public Filter OpenFilter() {
return new OpenEntityManagerInViewFilter();
}
}
``` |
48,037,601 | I am currently in the middle of migrating my REST-Server to GraphQL (at least partly). Most of the work is done, but i stumbled upon this problem which i seem to be unable to solve: OneToMany relationships in a graphql query, with FetchType.LAZY.
I am using:
<https://github.com/graphql-java/graphql-spring-boot>
and
<https://github.com/graphql-java/graphql-java-tools> for the integration.
Here is an example:
**Entities:**
```
@Entity
class Show {
private Long id;
private String name;
@OneToMany(mappedBy = "show")
private List<Competition> competition;
}
@Entity
class Competition {
private Long id;
private String name;
@ManyToOne(fetch = FetchType.LAZY)
private Show show;
}
```
**Schema:**
```
type Show {
id: ID!
name: String!
competitions: [Competition]
}
type Competition {
id: ID!
name: String
}
extend type Query {
shows : [Show]
}
```
**Resolver:**
```
@Component
public class ShowResolver implements GraphQLQueryResolver {
@Autowired
private ShowRepository showRepository;
public List<Show> getShows() {
return ((List<Show>)showRepository.findAll());
}
}
```
If i now query the endpoint with this (shorthand) query:
```
{
shows {
id
name
competitions {
id
}
}
}
```
i get:
>
> org.hibernate.LazyInitializationException: failed to lazily initialize
> a collection of role: Show.competitions, could not initialize proxy -
> no Session
>
>
>
Now i know why this error happens and what it means, but i don't really know were to apply a fix for this. I don't want to make my entites to eagerly fetch all relations, because that would negate some of the advantages of GraphQL. Any ideas where i might need to look for a solution?
Thanks! | 2017/12/30 | [
"https://Stackoverflow.com/questions/48037601",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1386873/"
] | My prefered solution is to have the transaction open until the Servlet sends its response. With this small code change your LazyLoad will work right:
```
import javax.servlet.Filter;
import org.springframework.orm.jpa.support.OpenEntityManagerInViewFilter;
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
/**
* Register the {@link OpenEntityManagerInViewFilter} so that the
* GraphQL-Servlet can handle lazy loads during execution.
*
* @return
*/
@Bean
public Filter OpenFilter() {
return new OpenEntityManagerInViewFilter();
}
}
``` | You just need to annotate your resolver classes with `@Transactional`. Then, entities returned from repositories will be able to lazily fetch data. |
10,091 | Most of my prior genealogy research was based on family records. Very little of it came from hard sources like census records. Some folks would claim that what I have is not genealogy, but folklore. So I've recently been spending considerable time looking for "official" documents, like county marriage records, census records, land registries, etc.
What I have found does not help much in coming up with concrete "facts".
Take my grandfather as an example:
* The family folklore/history says he was born in Brooklyn Iowa in 1860.
* The US Census records of 1890 and 1910 say he was born in Illinois.
* One Census record shows the family name as spelled Ferrell (two E's).
* Another record shows him as being born in St Louis, Missouri.
I know that the family spells our name Farrell. So the Census record is wrong. Hey, typos happen. I am sure that he was born near 1860, maybe 90% sure it was plus or minus one year of 1860, but it could be more. And I could believe that he was born somewhere within 100 or so miles of the Mississippi river, starting at St Louis, and going up to say Dubuque, Iowa. But the location of his birth is at best a fuzzy fact.
How do serious folk record this uncertainty? | 2016/01/03 | [
"https://genealogy.stackexchange.com/questions/10091",
"https://genealogy.stackexchange.com",
"https://genealogy.stackexchange.com/users/4504/"
] | If you went around to researchers and asked them this question, I suspect you'd get a different answer for each one. Here are some of your options for recording genealogical information:
* paper systems designed for genealogy research, such as the forms in the [workbook](https://books.google.com/books/about/The_Unpuzzling_Your_Past_Workbook.html?id=Ic-l3RV53o4C&printsec=frontcover&source=kp_read_button#v=onepage&q&f=false) accompanying Emily Anne Croom's book [Unpuzzling Your Past](https://books.google.com/books/about/Unpuzzling_Your_Past.html?id=MvXREWlRtPUC&printsec=frontcover&source=kp_read_button#v=onepage&q&f=false)
* software made specifically for 'doing genealogy' (more on this below)
* keeping your findings in narrative format in a research journal and your search results in software made for general office work (Word / Excel / editor of choice), notekeeping (OneNote/Evernote) or writing (Scrivener)
One problem with using software designed for "doing genealogy" is that most people are only familiar with the lineage-linked genealogy software which based on [GEDCOM](https://en.wikipedia.org/wiki/GEDCOM), a standard created by the LDS Church to communicate data about the lineages we think we know.
In my opinion, lineage-linked software is not well-suited to the task of managing information while we are still in the process of figuring stuff out -- it is focused on keeping track of people, when what the researcher is doing is collecting and analyzing records about people. It is good for recording 'conclusions' -- or if you don't like that term, you can substitute 'theory' or 'your best guess about what's true' -- but not necessarily for [Managing the Multiple Maybes](https://genealogy.stackexchange.com/q/3506/1006).
See [What tools exist for collecting and managing evidence?](https://genealogy.stackexchange.com/q/177/1006) and [Transitioning from person-based genealogy to record-based genealogy?](https://genealogy.stackexchange.com/q/1471/1006) for previous questions and answers that touch on this problem.
As people become more familiar with modern standards for doing genealogical research such as the [Genealogical Proof Standard](http://www.bcgcertification.org/resources/standard.html), more source-centric software and evidence-management tools are becoming available to us, such as:
* [Lineascope](http://www.lineascope.com/), an online browser-based application that aids the user in analyzing information in sources, and preserving the analysis for use in a proof statement
* [Evidentia](http://evidentiasoftware.com/), software that supports the user as they go through the analysis of a source (walking you through the process used in the Genealogical Proof Standard)
* [Clooz](https://www.clooz.com/), software which is designed to help the user inventory and analyze documents and other source material
* [Custodian](http://www.custodian3.co.uk/), designed for people doing large one-name and one-place studies -- it helps "store, index and organize the information" collected for the study
But the best way to answer the question of "what do serious folk do" is to look at the actual work product of accredited and certified genealogists. If you are at RootsTech, NGS, or other large genealogy conferences, look for booths run by the Board for Certification of Genealogists (BCG) or the Association of Professional Genealogists (APG) to see if they have sample portfolios you can examine.
On the web, the BCG offers [work samples](http://www.bcgcertification.org/skillbuilders/worksamples.html) on their website. Elizabeth Shown Mills, the author of [Evidence Explained](https://www.evidenceexplained.com/), offers a series of QuickLessons including [QuickLesson 20: Research Reports for Research Success](https://www.evidenceexplained.com/content/quicklesson-20-research-reports-research-success) -- the notes in that quicklesson have links to her website [Historic Pathways](http://historicpathways.com/) where she generously shares copies of publications and work samples.
Another thing that helps us get better at analyzing records is to learn more about how the records were created by reading journal articles like Claire Prechtel-Kluskens' [Who Talked to the Census Taker?](https://twelvekey.files.wordpress.com/2014/10/ngsmagazine2005-10.pdf), the instructions given out by the agencies at the time the records were created, or the reference information papers and finding aids created by the archivists who have custody of the records now.
Taking your example:
>
> the family folklore/history says he was born in Brooklyn Iowa in 1860.
> The US Census records of 1890 and 1910 say he was born in Illinois.
> One Census record shows the family name as spelled Ferrell (two E's).
> Another record shows him as being born in St Louis MO.
>
>
>
What we all need to do, and often fail at, is to write down **why** it is that we thought these records belonged to our person, despite the fact that they don't agree with our family stories.
Whatever method you choose to keep track of your research process, until you are comfortable with the concepts in the [The Evidence Analysis Process Map](https://www.evidenceexplained.com/content/quicklesson-17-evidence-analysis-process-map), the best thing to do is write your analysis out explicitly, so you can go back later and see what you've done. Even if we don't want to create formal research reports and proof statements for publication, it's still helpful to write these things out for ourselves -- it makes it easier to go back to a problem later and pick up where we left off.
Whether you keep the information in a separate program like Word of Scrivener, or write research notes that get attached to specific people in your lineage-linked software, or something else, write everything out explicitly so it will be easier to review later.
A narrative in a plain text file has the advantage of being easier to access by multiple programs and operating systems. I use Scrivener for a lot of my research notes because the files are stored in Rich Text Format rather than a proprietary format, and can be read independently outside of Scrivener's environment. | [FamilySearch](http://familysearch.org) is a free tool that lets you save multiple dates, even for the same event. You can also mark the date you think should be displayed in a person's Summary view. |
10,091 | Most of my prior genealogy research was based on family records. Very little of it came from hard sources like census records. Some folks would claim that what I have is not genealogy, but folklore. So I've recently been spending considerable time looking for "official" documents, like county marriage records, census records, land registries, etc.
What I have found does not help much in coming up with concrete "facts".
Take my grandfather as an example:
* The family folklore/history says he was born in Brooklyn Iowa in 1860.
* The US Census records of 1890 and 1910 say he was born in Illinois.
* One Census record shows the family name as spelled Ferrell (two E's).
* Another record shows him as being born in St Louis, Missouri.
I know that the family spells our name Farrell. So the Census record is wrong. Hey, typos happen. I am sure that he was born near 1860, maybe 90% sure it was plus or minus one year of 1860, but it could be more. And I could believe that he was born somewhere within 100 or so miles of the Mississippi river, starting at St Louis, and going up to say Dubuque, Iowa. But the location of his birth is at best a fuzzy fact.
How do serious folk record this uncertainty? | 2016/01/03 | [
"https://genealogy.stackexchange.com/questions/10091",
"https://genealogy.stackexchange.com",
"https://genealogy.stackexchange.com/users/4504/"
] | If you went around to researchers and asked them this question, I suspect you'd get a different answer for each one. Here are some of your options for recording genealogical information:
* paper systems designed for genealogy research, such as the forms in the [workbook](https://books.google.com/books/about/The_Unpuzzling_Your_Past_Workbook.html?id=Ic-l3RV53o4C&printsec=frontcover&source=kp_read_button#v=onepage&q&f=false) accompanying Emily Anne Croom's book [Unpuzzling Your Past](https://books.google.com/books/about/Unpuzzling_Your_Past.html?id=MvXREWlRtPUC&printsec=frontcover&source=kp_read_button#v=onepage&q&f=false)
* software made specifically for 'doing genealogy' (more on this below)
* keeping your findings in narrative format in a research journal and your search results in software made for general office work (Word / Excel / editor of choice), notekeeping (OneNote/Evernote) or writing (Scrivener)
One problem with using software designed for "doing genealogy" is that most people are only familiar with the lineage-linked genealogy software which based on [GEDCOM](https://en.wikipedia.org/wiki/GEDCOM), a standard created by the LDS Church to communicate data about the lineages we think we know.
In my opinion, lineage-linked software is not well-suited to the task of managing information while we are still in the process of figuring stuff out -- it is focused on keeping track of people, when what the researcher is doing is collecting and analyzing records about people. It is good for recording 'conclusions' -- or if you don't like that term, you can substitute 'theory' or 'your best guess about what's true' -- but not necessarily for [Managing the Multiple Maybes](https://genealogy.stackexchange.com/q/3506/1006).
See [What tools exist for collecting and managing evidence?](https://genealogy.stackexchange.com/q/177/1006) and [Transitioning from person-based genealogy to record-based genealogy?](https://genealogy.stackexchange.com/q/1471/1006) for previous questions and answers that touch on this problem.
As people become more familiar with modern standards for doing genealogical research such as the [Genealogical Proof Standard](http://www.bcgcertification.org/resources/standard.html), more source-centric software and evidence-management tools are becoming available to us, such as:
* [Lineascope](http://www.lineascope.com/), an online browser-based application that aids the user in analyzing information in sources, and preserving the analysis for use in a proof statement
* [Evidentia](http://evidentiasoftware.com/), software that supports the user as they go through the analysis of a source (walking you through the process used in the Genealogical Proof Standard)
* [Clooz](https://www.clooz.com/), software which is designed to help the user inventory and analyze documents and other source material
* [Custodian](http://www.custodian3.co.uk/), designed for people doing large one-name and one-place studies -- it helps "store, index and organize the information" collected for the study
But the best way to answer the question of "what do serious folk do" is to look at the actual work product of accredited and certified genealogists. If you are at RootsTech, NGS, or other large genealogy conferences, look for booths run by the Board for Certification of Genealogists (BCG) or the Association of Professional Genealogists (APG) to see if they have sample portfolios you can examine.
On the web, the BCG offers [work samples](http://www.bcgcertification.org/skillbuilders/worksamples.html) on their website. Elizabeth Shown Mills, the author of [Evidence Explained](https://www.evidenceexplained.com/), offers a series of QuickLessons including [QuickLesson 20: Research Reports for Research Success](https://www.evidenceexplained.com/content/quicklesson-20-research-reports-research-success) -- the notes in that quicklesson have links to her website [Historic Pathways](http://historicpathways.com/) where she generously shares copies of publications and work samples.
Another thing that helps us get better at analyzing records is to learn more about how the records were created by reading journal articles like Claire Prechtel-Kluskens' [Who Talked to the Census Taker?](https://twelvekey.files.wordpress.com/2014/10/ngsmagazine2005-10.pdf), the instructions given out by the agencies at the time the records were created, or the reference information papers and finding aids created by the archivists who have custody of the records now.
Taking your example:
>
> the family folklore/history says he was born in Brooklyn Iowa in 1860.
> The US Census records of 1890 and 1910 say he was born in Illinois.
> One Census record shows the family name as spelled Ferrell (two E's).
> Another record shows him as being born in St Louis MO.
>
>
>
What we all need to do, and often fail at, is to write down **why** it is that we thought these records belonged to our person, despite the fact that they don't agree with our family stories.
Whatever method you choose to keep track of your research process, until you are comfortable with the concepts in the [The Evidence Analysis Process Map](https://www.evidenceexplained.com/content/quicklesson-17-evidence-analysis-process-map), the best thing to do is write your analysis out explicitly, so you can go back later and see what you've done. Even if we don't want to create formal research reports and proof statements for publication, it's still helpful to write these things out for ourselves -- it makes it easier to go back to a problem later and pick up where we left off.
Whether you keep the information in a separate program like Word of Scrivener, or write research notes that get attached to specific people in your lineage-linked software, or something else, write everything out explicitly so it will be easier to review later.
A narrative in a plain text file has the advantage of being easier to access by multiple programs and operating systems. I use Scrivener for a lot of my research notes because the files are stored in Rich Text Format rather than a proprietary format, and can be read independently outside of Scrivener's environment. | @JanMurphy in [her answer](https://genealogy.stackexchange.com/a/10092/1107) has nicely described the usefulness of source-centric software in a case like this. However, as the most widely used software is lineage-linked, you raise an important question.
There is no right or wrong way to record uncertain information, but I think some approaches are better than others. In my lineage-linked database, my goal is to enter the "fuzzy" information in a way that will not be misinterpreted by myself or others in the future.
For locations, this means defaulting to the level of geography in which I have reasonable confidence. For example, in your case you have evidence that an individual was born in Iowa, Illinois, and Missouri. Obviously all of these cannot be correct, but if I have no indication that any is more likely than the other, then in my database I would not specify a city or state. I would simply enter the birth place as "United States." I would then attach the relevant source material, and explain in the notes why there is uncertainty, what the possibilities are, and what sources you should examine to find more evidence.
"Fuzzy" dates are generally more straightforward as most programs support the circa (c.) or about (abt.) notation before a date, or a date range. Again, I only enter a date if I am somewhat confident in an approximate date. In your example, it would be reasonable to enter the birth date "c.1860". However, if I had no evidence for when an individual was born, or highly conflicting evidence such as birth years over a decade apart, I would rather leave the birth date blank than make a wild guess.
I find "fuzzy" name spellings most problematic of all. Especially in the eighteenth century and earlier, it is not uncommon to find a surname spelled differently even within the same document. I think you have to settle on a convention you want to use and be consistent with it. My approach is to use the name spelling as it was at birth as the primary spelling in my database. By this I do not necessarily mean the spelling that is on the birth certificate or baptism record, rather the spelling that I think was most consistently used by the individual's family around that time. Other name spellings can be entered in notes or as Alternate Name facts.
Obviously there is always a degree of subjectivity when entering uncertain information into a database. Whatever approach you settle on, my advice is to be consistent, and (as Jan mentioned) write good notes explaining your uncertainty - as much for your own benefit as others. |
10,091 | Most of my prior genealogy research was based on family records. Very little of it came from hard sources like census records. Some folks would claim that what I have is not genealogy, but folklore. So I've recently been spending considerable time looking for "official" documents, like county marriage records, census records, land registries, etc.
What I have found does not help much in coming up with concrete "facts".
Take my grandfather as an example:
* The family folklore/history says he was born in Brooklyn Iowa in 1860.
* The US Census records of 1890 and 1910 say he was born in Illinois.
* One Census record shows the family name as spelled Ferrell (two E's).
* Another record shows him as being born in St Louis, Missouri.
I know that the family spells our name Farrell. So the Census record is wrong. Hey, typos happen. I am sure that he was born near 1860, maybe 90% sure it was plus or minus one year of 1860, but it could be more. And I could believe that he was born somewhere within 100 or so miles of the Mississippi river, starting at St Louis, and going up to say Dubuque, Iowa. But the location of his birth is at best a fuzzy fact.
How do serious folk record this uncertainty? | 2016/01/03 | [
"https://genealogy.stackexchange.com/questions/10091",
"https://genealogy.stackexchange.com",
"https://genealogy.stackexchange.com/users/4504/"
] | If you went around to researchers and asked them this question, I suspect you'd get a different answer for each one. Here are some of your options for recording genealogical information:
* paper systems designed for genealogy research, such as the forms in the [workbook](https://books.google.com/books/about/The_Unpuzzling_Your_Past_Workbook.html?id=Ic-l3RV53o4C&printsec=frontcover&source=kp_read_button#v=onepage&q&f=false) accompanying Emily Anne Croom's book [Unpuzzling Your Past](https://books.google.com/books/about/Unpuzzling_Your_Past.html?id=MvXREWlRtPUC&printsec=frontcover&source=kp_read_button#v=onepage&q&f=false)
* software made specifically for 'doing genealogy' (more on this below)
* keeping your findings in narrative format in a research journal and your search results in software made for general office work (Word / Excel / editor of choice), notekeeping (OneNote/Evernote) or writing (Scrivener)
One problem with using software designed for "doing genealogy" is that most people are only familiar with the lineage-linked genealogy software which based on [GEDCOM](https://en.wikipedia.org/wiki/GEDCOM), a standard created by the LDS Church to communicate data about the lineages we think we know.
In my opinion, lineage-linked software is not well-suited to the task of managing information while we are still in the process of figuring stuff out -- it is focused on keeping track of people, when what the researcher is doing is collecting and analyzing records about people. It is good for recording 'conclusions' -- or if you don't like that term, you can substitute 'theory' or 'your best guess about what's true' -- but not necessarily for [Managing the Multiple Maybes](https://genealogy.stackexchange.com/q/3506/1006).
See [What tools exist for collecting and managing evidence?](https://genealogy.stackexchange.com/q/177/1006) and [Transitioning from person-based genealogy to record-based genealogy?](https://genealogy.stackexchange.com/q/1471/1006) for previous questions and answers that touch on this problem.
As people become more familiar with modern standards for doing genealogical research such as the [Genealogical Proof Standard](http://www.bcgcertification.org/resources/standard.html), more source-centric software and evidence-management tools are becoming available to us, such as:
* [Lineascope](http://www.lineascope.com/), an online browser-based application that aids the user in analyzing information in sources, and preserving the analysis for use in a proof statement
* [Evidentia](http://evidentiasoftware.com/), software that supports the user as they go through the analysis of a source (walking you through the process used in the Genealogical Proof Standard)
* [Clooz](https://www.clooz.com/), software which is designed to help the user inventory and analyze documents and other source material
* [Custodian](http://www.custodian3.co.uk/), designed for people doing large one-name and one-place studies -- it helps "store, index and organize the information" collected for the study
But the best way to answer the question of "what do serious folk do" is to look at the actual work product of accredited and certified genealogists. If you are at RootsTech, NGS, or other large genealogy conferences, look for booths run by the Board for Certification of Genealogists (BCG) or the Association of Professional Genealogists (APG) to see if they have sample portfolios you can examine.
On the web, the BCG offers [work samples](http://www.bcgcertification.org/skillbuilders/worksamples.html) on their website. Elizabeth Shown Mills, the author of [Evidence Explained](https://www.evidenceexplained.com/), offers a series of QuickLessons including [QuickLesson 20: Research Reports for Research Success](https://www.evidenceexplained.com/content/quicklesson-20-research-reports-research-success) -- the notes in that quicklesson have links to her website [Historic Pathways](http://historicpathways.com/) where she generously shares copies of publications and work samples.
Another thing that helps us get better at analyzing records is to learn more about how the records were created by reading journal articles like Claire Prechtel-Kluskens' [Who Talked to the Census Taker?](https://twelvekey.files.wordpress.com/2014/10/ngsmagazine2005-10.pdf), the instructions given out by the agencies at the time the records were created, or the reference information papers and finding aids created by the archivists who have custody of the records now.
Taking your example:
>
> the family folklore/history says he was born in Brooklyn Iowa in 1860.
> The US Census records of 1890 and 1910 say he was born in Illinois.
> One Census record shows the family name as spelled Ferrell (two E's).
> Another record shows him as being born in St Louis MO.
>
>
>
What we all need to do, and often fail at, is to write down **why** it is that we thought these records belonged to our person, despite the fact that they don't agree with our family stories.
Whatever method you choose to keep track of your research process, until you are comfortable with the concepts in the [The Evidence Analysis Process Map](https://www.evidenceexplained.com/content/quicklesson-17-evidence-analysis-process-map), the best thing to do is write your analysis out explicitly, so you can go back later and see what you've done. Even if we don't want to create formal research reports and proof statements for publication, it's still helpful to write these things out for ourselves -- it makes it easier to go back to a problem later and pick up where we left off.
Whether you keep the information in a separate program like Word of Scrivener, or write research notes that get attached to specific people in your lineage-linked software, or something else, write everything out explicitly so it will be easier to review later.
A narrative in a plain text file has the advantage of being easier to access by multiple programs and operating systems. I use Scrivener for a lot of my research notes because the files are stored in Rich Text Format rather than a proprietary format, and can be read independently outside of Scrivener's environment. | This is actually a very interesting question, and I think there is a reasonably simple and acceptable way of handling fuzzy facts.
My own genealogy adventure started many years ago with a similar set of stories from great-aunts and uncles about my ancestors. There was a tree which was handwritten by my father's aunt. And then there were many family tales about my great-grandmother's brother who came over for a few years from England during the first World War, and after the war left for the United States with his wife and was never heard from again, who I am still looking for.
The simple answer is to record the best information you have. Feel free to put a big asterisk beside it to state what is behind this information.
Put down that your grandfather was born either in Brooklyn Iowa or in Illinois and give the two references to your sources (family folklore, and US Census records). You could add in your belief that he was born within 100 miles of the Mississippi River, but if you do so, you must provide the reason for your belief (it doesn't come out of thin air - did you mother tell you that, or what?)
What has happened here is you simply have not found evidence you trust enough to come to a conclusion about where your grandfather was born. So don't conclude anything yet. Just provide all the information about all the possibilities.
In genealogy software, if I don't conclude the birthplace, then I leave it blank, and I add all my theories as a note, with sources attached to the note.
One day, you'll find some evidence that will give you substantial reason to believe a birthplace. At that point, you can record the birthplace as your conclusion along with the sources that support it. You should then attach the note about your fuzzy birthplace to it, and update the note to reflect your new conclusion and to indicate your earlier beliefs in the light of the new conclusion. One of those earlier beliefs may in the future still prove to be the correct birthplace, so you don't want to lose those. Be sure to also keep the sources that were attached to the note.
So it's really just a matter of recording your conclusions. If you don't have enough information to conclude, then record the possibilities as a note. And always attach your sources.
Same holds true with regards to birthdate, spelling of surname, and everything else. |
10,091 | Most of my prior genealogy research was based on family records. Very little of it came from hard sources like census records. Some folks would claim that what I have is not genealogy, but folklore. So I've recently been spending considerable time looking for "official" documents, like county marriage records, census records, land registries, etc.
What I have found does not help much in coming up with concrete "facts".
Take my grandfather as an example:
* The family folklore/history says he was born in Brooklyn Iowa in 1860.
* The US Census records of 1890 and 1910 say he was born in Illinois.
* One Census record shows the family name as spelled Ferrell (two E's).
* Another record shows him as being born in St Louis, Missouri.
I know that the family spells our name Farrell. So the Census record is wrong. Hey, typos happen. I am sure that he was born near 1860, maybe 90% sure it was plus or minus one year of 1860, but it could be more. And I could believe that he was born somewhere within 100 or so miles of the Mississippi river, starting at St Louis, and going up to say Dubuque, Iowa. But the location of his birth is at best a fuzzy fact.
How do serious folk record this uncertainty? | 2016/01/03 | [
"https://genealogy.stackexchange.com/questions/10091",
"https://genealogy.stackexchange.com",
"https://genealogy.stackexchange.com/users/4504/"
] | @JanMurphy in [her answer](https://genealogy.stackexchange.com/a/10092/1107) has nicely described the usefulness of source-centric software in a case like this. However, as the most widely used software is lineage-linked, you raise an important question.
There is no right or wrong way to record uncertain information, but I think some approaches are better than others. In my lineage-linked database, my goal is to enter the "fuzzy" information in a way that will not be misinterpreted by myself or others in the future.
For locations, this means defaulting to the level of geography in which I have reasonable confidence. For example, in your case you have evidence that an individual was born in Iowa, Illinois, and Missouri. Obviously all of these cannot be correct, but if I have no indication that any is more likely than the other, then in my database I would not specify a city or state. I would simply enter the birth place as "United States." I would then attach the relevant source material, and explain in the notes why there is uncertainty, what the possibilities are, and what sources you should examine to find more evidence.
"Fuzzy" dates are generally more straightforward as most programs support the circa (c.) or about (abt.) notation before a date, or a date range. Again, I only enter a date if I am somewhat confident in an approximate date. In your example, it would be reasonable to enter the birth date "c.1860". However, if I had no evidence for when an individual was born, or highly conflicting evidence such as birth years over a decade apart, I would rather leave the birth date blank than make a wild guess.
I find "fuzzy" name spellings most problematic of all. Especially in the eighteenth century and earlier, it is not uncommon to find a surname spelled differently even within the same document. I think you have to settle on a convention you want to use and be consistent with it. My approach is to use the name spelling as it was at birth as the primary spelling in my database. By this I do not necessarily mean the spelling that is on the birth certificate or baptism record, rather the spelling that I think was most consistently used by the individual's family around that time. Other name spellings can be entered in notes or as Alternate Name facts.
Obviously there is always a degree of subjectivity when entering uncertain information into a database. Whatever approach you settle on, my advice is to be consistent, and (as Jan mentioned) write good notes explaining your uncertainty - as much for your own benefit as others. | [FamilySearch](http://familysearch.org) is a free tool that lets you save multiple dates, even for the same event. You can also mark the date you think should be displayed in a person's Summary view. |
10,091 | Most of my prior genealogy research was based on family records. Very little of it came from hard sources like census records. Some folks would claim that what I have is not genealogy, but folklore. So I've recently been spending considerable time looking for "official" documents, like county marriage records, census records, land registries, etc.
What I have found does not help much in coming up with concrete "facts".
Take my grandfather as an example:
* The family folklore/history says he was born in Brooklyn Iowa in 1860.
* The US Census records of 1890 and 1910 say he was born in Illinois.
* One Census record shows the family name as spelled Ferrell (two E's).
* Another record shows him as being born in St Louis, Missouri.
I know that the family spells our name Farrell. So the Census record is wrong. Hey, typos happen. I am sure that he was born near 1860, maybe 90% sure it was plus or minus one year of 1860, but it could be more. And I could believe that he was born somewhere within 100 or so miles of the Mississippi river, starting at St Louis, and going up to say Dubuque, Iowa. But the location of his birth is at best a fuzzy fact.
How do serious folk record this uncertainty? | 2016/01/03 | [
"https://genealogy.stackexchange.com/questions/10091",
"https://genealogy.stackexchange.com",
"https://genealogy.stackexchange.com/users/4504/"
] | This is actually a very interesting question, and I think there is a reasonably simple and acceptable way of handling fuzzy facts.
My own genealogy adventure started many years ago with a similar set of stories from great-aunts and uncles about my ancestors. There was a tree which was handwritten by my father's aunt. And then there were many family tales about my great-grandmother's brother who came over for a few years from England during the first World War, and after the war left for the United States with his wife and was never heard from again, who I am still looking for.
The simple answer is to record the best information you have. Feel free to put a big asterisk beside it to state what is behind this information.
Put down that your grandfather was born either in Brooklyn Iowa or in Illinois and give the two references to your sources (family folklore, and US Census records). You could add in your belief that he was born within 100 miles of the Mississippi River, but if you do so, you must provide the reason for your belief (it doesn't come out of thin air - did you mother tell you that, or what?)
What has happened here is you simply have not found evidence you trust enough to come to a conclusion about where your grandfather was born. So don't conclude anything yet. Just provide all the information about all the possibilities.
In genealogy software, if I don't conclude the birthplace, then I leave it blank, and I add all my theories as a note, with sources attached to the note.
One day, you'll find some evidence that will give you substantial reason to believe a birthplace. At that point, you can record the birthplace as your conclusion along with the sources that support it. You should then attach the note about your fuzzy birthplace to it, and update the note to reflect your new conclusion and to indicate your earlier beliefs in the light of the new conclusion. One of those earlier beliefs may in the future still prove to be the correct birthplace, so you don't want to lose those. Be sure to also keep the sources that were attached to the note.
So it's really just a matter of recording your conclusions. If you don't have enough information to conclude, then record the possibilities as a note. And always attach your sources.
Same holds true with regards to birthdate, spelling of surname, and everything else. | [FamilySearch](http://familysearch.org) is a free tool that lets you save multiple dates, even for the same event. You can also mark the date you think should be displayed in a person's Summary view. |
12,389,346 | Hello I have found a great class written in c# which I would like to use in a VB.NET project.
I found it in this thread:
[C# : Redirect console application output : How to flush the output?](https://stackoverflow.com/questions/1033648/c-sharp-redirect-console-application-output-how-to-flush-the-output)
The C# Class
looks like this:
```
using System;
using System.Collections;
using System.IO;
using System.Text;
using System.Threading;
namespace System.Diagnostics
{
internal delegate void UserCallBack(string data);
public delegate void DataReceivedEventHandler(object sender, DataReceivedEventArgs e);
public class FixedProcess : Process
{
internal AsyncStreamReader output;
internal AsyncStreamReader error;
public event DataReceivedEventHandler OutputDataReceived;
public event DataReceivedEventHandler ErrorDataReceived;
public new void BeginOutputReadLine()
{
Stream baseStream = StandardOutput.BaseStream;
this.output = new AsyncStreamReader(this, baseStream, new UserCallBack(this.FixedOutputReadNotifyUser), StandardOutput.CurrentEncoding);
this.output.BeginReadLine();
}
public void BeginErrorReadLine()
{
Stream baseStream = StandardError.BaseStream;
this.error = new AsyncStreamReader(this, baseStream, new UserCallBack(this.FixedErrorReadNotifyUser), StandardError.CurrentEncoding);
this.error.BeginReadLine();
}
internal void FixedOutputReadNotifyUser(string data)
{
DataReceivedEventHandler outputDataReceived = this.OutputDataReceived;
if (outputDataReceived != null)
{
DataReceivedEventArgs dataReceivedEventArgs = new DataReceivedEventArgs(data);
if (this.SynchronizingObject != null && this.SynchronizingObject.InvokeRequired)
{
this.SynchronizingObject.Invoke(outputDataReceived, new object[]
{
this,
dataReceivedEventArgs
});
return;
}
outputDataReceived(this, dataReceivedEventArgs);
}
}
internal void FixedErrorReadNotifyUser(string data)
{
DataReceivedEventHandler errorDataReceived = this.ErrorDataReceived;
if (errorDataReceived != null)
{
DataReceivedEventArgs dataReceivedEventArgs = new DataReceivedEventArgs(data);
if (this.SynchronizingObject != null && this.SynchronizingObject.InvokeRequired)
{
this.SynchronizingObject.Invoke(errorDataReceived, new object[]
{
this,
dataReceivedEventArgs
});
return;
}
errorDataReceived(this, dataReceivedEventArgs);
}
}
}
internal class AsyncStreamReader : IDisposable
{
internal const int DefaultBufferSize = 1024;
private const int MinBufferSize = 128;
private Stream stream;
private Encoding encoding;
private Decoder decoder;
private byte[] byteBuffer;
private char[] charBuffer;
private int _maxCharsPerBuffer;
private Process process;
private UserCallBack userCallBack;
private bool cancelOperation;
private ManualResetEvent eofEvent;
private Queue messageQueue;
private StringBuilder sb;
private bool bLastCarriageReturn;
public virtual Encoding CurrentEncoding
{
get
{
return this.encoding;
}
}
public virtual Stream BaseStream
{
get
{
return this.stream;
}
}
internal AsyncStreamReader(Process process, Stream stream, UserCallBack callback, Encoding encoding)
: this(process, stream, callback, encoding, 1024)
{
}
internal AsyncStreamReader(Process process, Stream stream, UserCallBack callback, Encoding encoding, int bufferSize)
{
this.Init(process, stream, callback, encoding, bufferSize);
this.messageQueue = new Queue();
}
private void Init(Process process, Stream stream, UserCallBack callback, Encoding encoding, int bufferSize)
{
this.process = process;
this.stream = stream;
this.encoding = encoding;
this.userCallBack = callback;
this.decoder = encoding.GetDecoder();
if (bufferSize < 128)
{
bufferSize = 128;
}
this.byteBuffer = new byte[bufferSize];
this._maxCharsPerBuffer = encoding.GetMaxCharCount(bufferSize);
this.charBuffer = new char[this._maxCharsPerBuffer];
this.cancelOperation = false;
this.eofEvent = new ManualResetEvent(false);
this.sb = null;
this.bLastCarriageReturn = false;
}
public virtual void Close()
{
this.Dispose(true);
}
void IDisposable.Dispose()
{
this.Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (disposing && this.stream != null)
{
this.stream.Close();
}
if (this.stream != null)
{
this.stream = null;
this.encoding = null;
this.decoder = null;
this.byteBuffer = null;
this.charBuffer = null;
}
if (this.eofEvent != null)
{
this.eofEvent.Close();
this.eofEvent = null;
}
}
internal void BeginReadLine()
{
if (this.cancelOperation)
{
this.cancelOperation = false;
}
if (this.sb == null)
{
this.sb = new StringBuilder(1024);
this.stream.BeginRead(this.byteBuffer, 0, this.byteBuffer.Length, new AsyncCallback(this.ReadBuffer), null);
return;
}
this.FlushMessageQueue();
}
internal void CancelOperation()
{
this.cancelOperation = true;
}
private void ReadBuffer(IAsyncResult ar)
{
int num;
try
{
num = this.stream.EndRead(ar);
}
catch (IOException)
{
num = 0;
}
catch (OperationCanceledException)
{
num = 0;
}
if (num == 0)
{
lock (this.messageQueue)
{
if (this.sb.Length != 0)
{
this.messageQueue.Enqueue(this.sb.ToString());
this.sb.Length = 0;
}
this.messageQueue.Enqueue(null);
}
try
{
this.FlushMessageQueue();
return;
}
finally
{
this.eofEvent.Set();
}
}
int chars = this.decoder.GetChars(this.byteBuffer, 0, num, this.charBuffer, 0);
this.sb.Append(this.charBuffer, 0, chars);
this.GetLinesFromStringBuilder();
this.stream.BeginRead(this.byteBuffer, 0, this.byteBuffer.Length, new AsyncCallback(this.ReadBuffer), null);
}
private void GetLinesFromStringBuilder()
{
int i = 0;
int num = 0;
int length = this.sb.Length;
if (this.bLastCarriageReturn && length > 0 && this.sb[0] == '\n')
{
i = 1;
num = 1;
this.bLastCarriageReturn = false;
}
while (i < length)
{
char c = this.sb[i];
if (c == '\r' || c == '\n')
{
if (c == '\r' && i + 1 < length && this.sb[i + 1] == '\n')
{
i++;
}
string obj = this.sb.ToString(num, i + 1 - num);
num = i + 1;
lock (this.messageQueue)
{
this.messageQueue.Enqueue(obj);
}
}
i++;
}
// Flush Fix: Send Whatever is left in the buffer
string endOfBuffer = this.sb.ToString(num, length - num);
lock (this.messageQueue)
{
this.messageQueue.Enqueue(endOfBuffer);
num = length;
}
// End Flush Fix
if (this.sb[length - 1] == '\r')
{
this.bLastCarriageReturn = true;
}
if (num < length)
{
this.sb.Remove(0, num);
}
else
{
this.sb.Length = 0;
}
this.FlushMessageQueue();
}
private void FlushMessageQueue()
{
while (this.messageQueue.Count > 0)
{
lock (this.messageQueue)
{
if (this.messageQueue.Count > 0)
{
string data = (string)this.messageQueue.Dequeue();
if (!this.cancelOperation)
{
this.userCallBack(data);
}
}
continue;
}
break;
}
}
internal void WaitUtilEOF()
{
if (this.eofEvent != null)
{
this.eofEvent.WaitOne();
this.eofEvent.Close();
this.eofEvent = null;
}
}
}
public class DataReceivedEventArgs : EventArgs
{
internal string _data;
/// <summary>Gets the line of characters that was written to a redirected <see cref="T:System.Diagnostics.Process" /> output stream.</summary>
/// <returns>The line that was written by an associated <see cref="T:System.Diagnostics.Process" /> to its redirected <see cref="P:System.Diagnostics.Process.StandardOutput" /> or <see cref="P:System.Diagnostics.Process.StandardError" /> stream.</returns>
/// <filterpriority>2</filterpriority>
public string Data
{
get
{
return this._data;
}
}
internal DataReceivedEventArgs(string data)
{
this._data = data;
}
}
}
```
My Converted Code looks like this:
```
Imports System
Imports System.Collections
Imports System.IO
Imports System.Text
Imports System.Threading
Namespace System.Diagnostics
Friend Delegate Sub UserCallBack(data As String)
Public Delegate Sub DataReceivedEventHandler(sender As Object, e As DataReceivedEventArgs)
Public Class FixedProcess
Inherits Process
Friend output As AsyncStreamReader
Friend [error] As AsyncStreamReader
Public Event OutputDataReceived As DataReceivedEventHandler '<----------Error 1
Public Event ErrorDataReceived As DataReceivedEventHandler '<------------Error 2
Public Shadows Sub BeginOutputReadLine()
Dim baseStream As Stream = StandardOutput.BaseStream
Me.output = New AsyncStreamReader(Me, baseStream, New UserCallBack(AddressOf Me.FixedOutputReadNotifyUser), StandardOutput.CurrentEncoding)
Me.output.BeginReadLine()
End Sub
Public Sub BeginErrorReadLine() '<-------------Error 3
Dim baseStream As Stream = StandardError.BaseStream
Me.[error] = New AsyncStreamReader(Me, baseStream, New UserCallBack(AddressOf Me.FixedErrorReadNotifyUser), StandardError.CurrentEncoding)
Me.[error].BeginReadLine()
End Sub
Friend Sub FixedOutputReadNotifyUser(data As String)
Dim outputDataReceived As DataReceivedEventHandler = Me.OutputDataReceived '<------------Error 4
If outputDataReceived IsNot Nothing Then
Dim dataReceivedEventArgs As New DataReceivedEventArgs(data)
If Me.SynchronizingObject IsNot Nothing AndAlso Me.SynchronizingObject.InvokeRequired Then
Me.SynchronizingObject.Invoke(outputDataReceived, New Object() {Me, dataReceivedEventArgs})
Return
End If
outputDataReceived(Me, dataReceivedEventArgs)
End If
End Sub
Friend Sub FixedErrorReadNotifyUser(data As String)
Dim errorDataReceived As DataReceivedEventHandler = Me.ErrorDataReceived '<-------------Error 5
If errorDataReceived IsNot Nothing Then
Dim dataReceivedEventArgs As New DataReceivedEventArgs(data)
If Me.SynchronizingObject IsNot Nothing AndAlso Me.SynchronizingObject.InvokeRequired Then
Me.SynchronizingObject.Invoke(errorDataReceived, New Object() {Me, dataReceivedEventArgs})
Return
End If
errorDataReceived(Me, dataReceivedEventArgs)
End If
End Sub
End Class
Friend Class AsyncStreamReader
Implements IDisposable
Friend Const DefaultBufferSize As Integer = 1024
Private Const MinBufferSize As Integer = 128
Private stream As Stream
Private encoding As Encoding
Private decoder As Decoder
Private byteBuffer As Byte()
Private charBuffer As Char()
Private _maxCharsPerBuffer As Integer
Private process As Process
Private userCallBack As UserCallBack
Private cancelOperation As Boolean
Private eofEvent As ManualResetEvent
Private messageQueue As Queue
Private sb As StringBuilder
Private bLastCarriageReturn As Boolean
Public Overridable ReadOnly Property CurrentEncoding() As Encoding
Get
Return Me.encoding
End Get
End Property
Public Overridable ReadOnly Property BaseStream() As Stream
Get
Return Me.stream
End Get
End Property
Friend Sub New(process As Process, stream As Stream, callback As UserCallBack, encoding As Encoding)
Me.New(process, stream, callback, encoding, 1024)
End Sub
Friend Sub New(process As Process, stream As Stream, callback As UserCallBack, encoding As Encoding, bufferSize As Integer)
Me.Init(process, stream, callback, encoding, bufferSize)
Me.messageQueue = New Queue()
End Sub
Private Sub Init(process As Process, stream As Stream, callback As UserCallBack, encoding As Encoding, bufferSize As Integer)
Me.process = process
Me.stream = stream
Me.encoding = encoding
Me.userCallBack = callback
Me.decoder = encoding.GetDecoder()
If bufferSize < 128 Then
bufferSize = 128
End If
Me.byteBuffer = New Byte(bufferSize - 1) {}
Me._maxCharsPerBuffer = encoding.GetMaxCharCount(bufferSize)
Me.charBuffer = New Char(Me._maxCharsPerBuffer - 1) {}
Me.cancelOperation = False
Me.eofEvent = New ManualResetEvent(False)
Me.sb = Nothing
Me.bLastCarriageReturn = False
End Sub
Public Overridable Sub Close()
Me.Dispose(True)
End Sub
Private Sub IDisposable_Dispose() Implements IDisposable.Dispose
Me.Dispose(True)
GC.SuppressFinalize(Me)
End Sub
Protected Overridable Sub Dispose(disposing As Boolean)
If disposing AndAlso Me.stream IsNot Nothing Then
Me.stream.Close()
End If
If Me.stream IsNot Nothing Then
Me.stream = Nothing
Me.encoding = Nothing
Me.decoder = Nothing
Me.byteBuffer = Nothing
Me.charBuffer = Nothing
End If
If Me.eofEvent IsNot Nothing Then
Me.eofEvent.Close()
Me.eofEvent = Nothing
End If
End Sub
Friend Sub BeginReadLine()
If Me.cancelOperation Then
Me.cancelOperation = False
End If
If Me.sb Is Nothing Then
Me.sb = New StringBuilder(1024)
Me.stream.BeginRead(Me.byteBuffer, 0, Me.byteBuffer.Length, New AsyncCallback(AddressOf Me.ReadBuffer), Nothing)
Return
End If
Me.FlushMessageQueue()
End Sub
Friend Sub CancelOperation() '<------- Error 6
Me.cancelOperation = True
End Sub
Private Sub ReadBuffer(ar As IAsyncResult)
Dim num As Integer
Try
num = Me.stream.EndRead(ar)
Catch generatedExceptionName As IOException
num = 0
Catch generatedExceptionName As OperationCanceledException
num = 0
End Try
If num = 0 Then
SyncLock Me.messageQueue
If Me.sb.Length <> 0 Then
Me.messageQueue.Enqueue(Me.sb.ToString())
Me.sb.Length = 0
End If
Me.messageQueue.Enqueue(Nothing)
End SyncLock
Try
Me.FlushMessageQueue()
Return
Finally
Me.eofEvent.[Set]()
End Try
End If
Dim chars As Integer = Me.decoder.GetChars(Me.byteBuffer, 0, num, Me.charBuffer, 0)
Me.sb.Append(Me.charBuffer, 0, chars)
Me.GetLinesFromStringBuilder()
Me.stream.BeginRead(Me.byteBuffer, 0, Me.byteBuffer.Length, New AsyncCallback(AddressOf Me.ReadBuffer), Nothing)
End Sub
Private Sub GetLinesFromStringBuilder()
Dim i As Integer = 0
Dim num As Integer = 0
Dim length As Integer = Me.sb.Length
If Me.bLastCarriageReturn AndAlso length > 0 AndAlso Me.sb(0) = ControlChars.Lf Then
i = 1
num = 1
Me.bLastCarriageReturn = False
End If
While i < length
Dim c As Char = Me.sb(i)
If c = ControlChars.Cr OrElse c = ControlChars.Lf Then
If c = ControlChars.Cr AndAlso i + 1 < length AndAlso Me.sb(i + 1) = ControlChars.Lf Then
i += 1
End If
Dim obj As String = Me.sb.ToString(num, i + 1 - num)
num = i + 1
SyncLock Me.messageQueue
Me.messageQueue.Enqueue(obj)
End SyncLock
End If
i += 1
End While
' Flush Fix: Send Whatever is left in the buffer
Dim endOfBuffer As String = Me.sb.ToString(num, length - num)
SyncLock Me.messageQueue
Me.messageQueue.Enqueue(endOfBuffer)
num = length
End SyncLock
' End Flush Fix
If Me.sb(length - 1) = ControlChars.Cr Then
Me.bLastCarriageReturn = True
End If
If num < length Then
Me.sb.Remove(0, num)
Else
Me.sb.Length = 0
End If
Me.FlushMessageQueue()
End Sub
Private Sub FlushMessageQueue()
While Me.messageQueue.Count > 0
SyncLock Me.messageQueue
If Me.messageQueue.Count > 0 Then
Dim data As String = DirectCast(Me.messageQueue.Dequeue(), String)
If Not Me.cancelOperation Then
Me.userCallBack(data)
End If
End If
Continue While
End SyncLock
Exit While
End While
End Sub
Friend Sub WaitUtilEOF()
If Me.eofEvent IsNot Nothing Then
Me.eofEvent.WaitOne()
Me.eofEvent.Close()
Me.eofEvent = Nothing
End If
End Sub
End Class
Public Class DataReceivedEventArgs
Inherits EventArgs
Friend _data As String
''' <summary>Gets the line of characters that was written to a redirected <see cref="T:System.Diagnostics.Process" /> output stream.</summary>
''' <returns>The line that was written by an associated <see cref="T:System.Diagnostics.Process" /> to its redirected <see cref="P:System.Diagnostics.Process.StandardOutput" /> or <see cref="P:System.Diagnostics.Process.StandardError" /> stream.</returns>
''' <filterpriority>2</filterpriority>
Public ReadOnly Property Data() As String
Get
Return Me._data
End Get
End Property
Friend Sub New(data As String)
Me._data = data
End Sub
End Class
End Namespace
```
Error 1-3 seem to be warnings and might actually work
Especially Error 4 and 5 give me a headache "Public Event OutputDataRecieved(sender As Object, e As DataRecievedEventArgs) is an event, and cannot be called directly. Use the RaiseEvent statement to raise an event."
Eventhandlers dont seem to work with any of the code converters I have tried and I am lacking the VB skills to convert it manually.
Is there a friendly soul out there who can properly convert this class so that it actually works?
Thanks a lot!
Roman | 2012/09/12 | [
"https://Stackoverflow.com/questions/12389346",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1665789/"
] | You need to add the Overloads keyword to the BeginErrorReadLine method signature.
```
Public Overloads Sub BeginErrorReadLine() '<-------------Error 3
```
The event declarations need to be declared as Shadows because they otherwise conflict with the base class event declarations.
```
Public Shadows Event OutputDataReceived As DataReceivedEventHandler '<----------Error 1
```
Then in your FixedOutputReadNotifyUser method, you don't need to check the event handler as you do in C# to see if it is nothing. VB will do that for you. Instead, simply raise it as follows:
```
Friend Sub FixedOutputReadNotifyUser(data As String)
Dim dataReceivedEventArgs As New DataReceivedEventArgs(data)
RaiseEvent OutputDataReceived(Me, dataReceivedEventArgs)
End Sub
```
The last issue is the original class uses case sensitivity to differentiate between the "cancelOperation" field and "CancelOperation" method. Best option is to prefix the field with an underscore as follows: `Private _CancelOperation As Boolean` and then fix the corresponding references in the class. | In your solution, add a new c# project. Place this c# code in it.
From your vb project, add a reference to the c# project.
You can now make calls to the c# objects from vb.
It's all the same when it's converted to IL. |
12,389,346 | Hello I have found a great class written in c# which I would like to use in a VB.NET project.
I found it in this thread:
[C# : Redirect console application output : How to flush the output?](https://stackoverflow.com/questions/1033648/c-sharp-redirect-console-application-output-how-to-flush-the-output)
The C# Class
looks like this:
```
using System;
using System.Collections;
using System.IO;
using System.Text;
using System.Threading;
namespace System.Diagnostics
{
internal delegate void UserCallBack(string data);
public delegate void DataReceivedEventHandler(object sender, DataReceivedEventArgs e);
public class FixedProcess : Process
{
internal AsyncStreamReader output;
internal AsyncStreamReader error;
public event DataReceivedEventHandler OutputDataReceived;
public event DataReceivedEventHandler ErrorDataReceived;
public new void BeginOutputReadLine()
{
Stream baseStream = StandardOutput.BaseStream;
this.output = new AsyncStreamReader(this, baseStream, new UserCallBack(this.FixedOutputReadNotifyUser), StandardOutput.CurrentEncoding);
this.output.BeginReadLine();
}
public void BeginErrorReadLine()
{
Stream baseStream = StandardError.BaseStream;
this.error = new AsyncStreamReader(this, baseStream, new UserCallBack(this.FixedErrorReadNotifyUser), StandardError.CurrentEncoding);
this.error.BeginReadLine();
}
internal void FixedOutputReadNotifyUser(string data)
{
DataReceivedEventHandler outputDataReceived = this.OutputDataReceived;
if (outputDataReceived != null)
{
DataReceivedEventArgs dataReceivedEventArgs = new DataReceivedEventArgs(data);
if (this.SynchronizingObject != null && this.SynchronizingObject.InvokeRequired)
{
this.SynchronizingObject.Invoke(outputDataReceived, new object[]
{
this,
dataReceivedEventArgs
});
return;
}
outputDataReceived(this, dataReceivedEventArgs);
}
}
internal void FixedErrorReadNotifyUser(string data)
{
DataReceivedEventHandler errorDataReceived = this.ErrorDataReceived;
if (errorDataReceived != null)
{
DataReceivedEventArgs dataReceivedEventArgs = new DataReceivedEventArgs(data);
if (this.SynchronizingObject != null && this.SynchronizingObject.InvokeRequired)
{
this.SynchronizingObject.Invoke(errorDataReceived, new object[]
{
this,
dataReceivedEventArgs
});
return;
}
errorDataReceived(this, dataReceivedEventArgs);
}
}
}
internal class AsyncStreamReader : IDisposable
{
internal const int DefaultBufferSize = 1024;
private const int MinBufferSize = 128;
private Stream stream;
private Encoding encoding;
private Decoder decoder;
private byte[] byteBuffer;
private char[] charBuffer;
private int _maxCharsPerBuffer;
private Process process;
private UserCallBack userCallBack;
private bool cancelOperation;
private ManualResetEvent eofEvent;
private Queue messageQueue;
private StringBuilder sb;
private bool bLastCarriageReturn;
public virtual Encoding CurrentEncoding
{
get
{
return this.encoding;
}
}
public virtual Stream BaseStream
{
get
{
return this.stream;
}
}
internal AsyncStreamReader(Process process, Stream stream, UserCallBack callback, Encoding encoding)
: this(process, stream, callback, encoding, 1024)
{
}
internal AsyncStreamReader(Process process, Stream stream, UserCallBack callback, Encoding encoding, int bufferSize)
{
this.Init(process, stream, callback, encoding, bufferSize);
this.messageQueue = new Queue();
}
private void Init(Process process, Stream stream, UserCallBack callback, Encoding encoding, int bufferSize)
{
this.process = process;
this.stream = stream;
this.encoding = encoding;
this.userCallBack = callback;
this.decoder = encoding.GetDecoder();
if (bufferSize < 128)
{
bufferSize = 128;
}
this.byteBuffer = new byte[bufferSize];
this._maxCharsPerBuffer = encoding.GetMaxCharCount(bufferSize);
this.charBuffer = new char[this._maxCharsPerBuffer];
this.cancelOperation = false;
this.eofEvent = new ManualResetEvent(false);
this.sb = null;
this.bLastCarriageReturn = false;
}
public virtual void Close()
{
this.Dispose(true);
}
void IDisposable.Dispose()
{
this.Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (disposing && this.stream != null)
{
this.stream.Close();
}
if (this.stream != null)
{
this.stream = null;
this.encoding = null;
this.decoder = null;
this.byteBuffer = null;
this.charBuffer = null;
}
if (this.eofEvent != null)
{
this.eofEvent.Close();
this.eofEvent = null;
}
}
internal void BeginReadLine()
{
if (this.cancelOperation)
{
this.cancelOperation = false;
}
if (this.sb == null)
{
this.sb = new StringBuilder(1024);
this.stream.BeginRead(this.byteBuffer, 0, this.byteBuffer.Length, new AsyncCallback(this.ReadBuffer), null);
return;
}
this.FlushMessageQueue();
}
internal void CancelOperation()
{
this.cancelOperation = true;
}
private void ReadBuffer(IAsyncResult ar)
{
int num;
try
{
num = this.stream.EndRead(ar);
}
catch (IOException)
{
num = 0;
}
catch (OperationCanceledException)
{
num = 0;
}
if (num == 0)
{
lock (this.messageQueue)
{
if (this.sb.Length != 0)
{
this.messageQueue.Enqueue(this.sb.ToString());
this.sb.Length = 0;
}
this.messageQueue.Enqueue(null);
}
try
{
this.FlushMessageQueue();
return;
}
finally
{
this.eofEvent.Set();
}
}
int chars = this.decoder.GetChars(this.byteBuffer, 0, num, this.charBuffer, 0);
this.sb.Append(this.charBuffer, 0, chars);
this.GetLinesFromStringBuilder();
this.stream.BeginRead(this.byteBuffer, 0, this.byteBuffer.Length, new AsyncCallback(this.ReadBuffer), null);
}
private void GetLinesFromStringBuilder()
{
int i = 0;
int num = 0;
int length = this.sb.Length;
if (this.bLastCarriageReturn && length > 0 && this.sb[0] == '\n')
{
i = 1;
num = 1;
this.bLastCarriageReturn = false;
}
while (i < length)
{
char c = this.sb[i];
if (c == '\r' || c == '\n')
{
if (c == '\r' && i + 1 < length && this.sb[i + 1] == '\n')
{
i++;
}
string obj = this.sb.ToString(num, i + 1 - num);
num = i + 1;
lock (this.messageQueue)
{
this.messageQueue.Enqueue(obj);
}
}
i++;
}
// Flush Fix: Send Whatever is left in the buffer
string endOfBuffer = this.sb.ToString(num, length - num);
lock (this.messageQueue)
{
this.messageQueue.Enqueue(endOfBuffer);
num = length;
}
// End Flush Fix
if (this.sb[length - 1] == '\r')
{
this.bLastCarriageReturn = true;
}
if (num < length)
{
this.sb.Remove(0, num);
}
else
{
this.sb.Length = 0;
}
this.FlushMessageQueue();
}
private void FlushMessageQueue()
{
while (this.messageQueue.Count > 0)
{
lock (this.messageQueue)
{
if (this.messageQueue.Count > 0)
{
string data = (string)this.messageQueue.Dequeue();
if (!this.cancelOperation)
{
this.userCallBack(data);
}
}
continue;
}
break;
}
}
internal void WaitUtilEOF()
{
if (this.eofEvent != null)
{
this.eofEvent.WaitOne();
this.eofEvent.Close();
this.eofEvent = null;
}
}
}
public class DataReceivedEventArgs : EventArgs
{
internal string _data;
/// <summary>Gets the line of characters that was written to a redirected <see cref="T:System.Diagnostics.Process" /> output stream.</summary>
/// <returns>The line that was written by an associated <see cref="T:System.Diagnostics.Process" /> to its redirected <see cref="P:System.Diagnostics.Process.StandardOutput" /> or <see cref="P:System.Diagnostics.Process.StandardError" /> stream.</returns>
/// <filterpriority>2</filterpriority>
public string Data
{
get
{
return this._data;
}
}
internal DataReceivedEventArgs(string data)
{
this._data = data;
}
}
}
```
My Converted Code looks like this:
```
Imports System
Imports System.Collections
Imports System.IO
Imports System.Text
Imports System.Threading
Namespace System.Diagnostics
Friend Delegate Sub UserCallBack(data As String)
Public Delegate Sub DataReceivedEventHandler(sender As Object, e As DataReceivedEventArgs)
Public Class FixedProcess
Inherits Process
Friend output As AsyncStreamReader
Friend [error] As AsyncStreamReader
Public Event OutputDataReceived As DataReceivedEventHandler '<----------Error 1
Public Event ErrorDataReceived As DataReceivedEventHandler '<------------Error 2
Public Shadows Sub BeginOutputReadLine()
Dim baseStream As Stream = StandardOutput.BaseStream
Me.output = New AsyncStreamReader(Me, baseStream, New UserCallBack(AddressOf Me.FixedOutputReadNotifyUser), StandardOutput.CurrentEncoding)
Me.output.BeginReadLine()
End Sub
Public Sub BeginErrorReadLine() '<-------------Error 3
Dim baseStream As Stream = StandardError.BaseStream
Me.[error] = New AsyncStreamReader(Me, baseStream, New UserCallBack(AddressOf Me.FixedErrorReadNotifyUser), StandardError.CurrentEncoding)
Me.[error].BeginReadLine()
End Sub
Friend Sub FixedOutputReadNotifyUser(data As String)
Dim outputDataReceived As DataReceivedEventHandler = Me.OutputDataReceived '<------------Error 4
If outputDataReceived IsNot Nothing Then
Dim dataReceivedEventArgs As New DataReceivedEventArgs(data)
If Me.SynchronizingObject IsNot Nothing AndAlso Me.SynchronizingObject.InvokeRequired Then
Me.SynchronizingObject.Invoke(outputDataReceived, New Object() {Me, dataReceivedEventArgs})
Return
End If
outputDataReceived(Me, dataReceivedEventArgs)
End If
End Sub
Friend Sub FixedErrorReadNotifyUser(data As String)
Dim errorDataReceived As DataReceivedEventHandler = Me.ErrorDataReceived '<-------------Error 5
If errorDataReceived IsNot Nothing Then
Dim dataReceivedEventArgs As New DataReceivedEventArgs(data)
If Me.SynchronizingObject IsNot Nothing AndAlso Me.SynchronizingObject.InvokeRequired Then
Me.SynchronizingObject.Invoke(errorDataReceived, New Object() {Me, dataReceivedEventArgs})
Return
End If
errorDataReceived(Me, dataReceivedEventArgs)
End If
End Sub
End Class
Friend Class AsyncStreamReader
Implements IDisposable
Friend Const DefaultBufferSize As Integer = 1024
Private Const MinBufferSize As Integer = 128
Private stream As Stream
Private encoding As Encoding
Private decoder As Decoder
Private byteBuffer As Byte()
Private charBuffer As Char()
Private _maxCharsPerBuffer As Integer
Private process As Process
Private userCallBack As UserCallBack
Private cancelOperation As Boolean
Private eofEvent As ManualResetEvent
Private messageQueue As Queue
Private sb As StringBuilder
Private bLastCarriageReturn As Boolean
Public Overridable ReadOnly Property CurrentEncoding() As Encoding
Get
Return Me.encoding
End Get
End Property
Public Overridable ReadOnly Property BaseStream() As Stream
Get
Return Me.stream
End Get
End Property
Friend Sub New(process As Process, stream As Stream, callback As UserCallBack, encoding As Encoding)
Me.New(process, stream, callback, encoding, 1024)
End Sub
Friend Sub New(process As Process, stream As Stream, callback As UserCallBack, encoding As Encoding, bufferSize As Integer)
Me.Init(process, stream, callback, encoding, bufferSize)
Me.messageQueue = New Queue()
End Sub
Private Sub Init(process As Process, stream As Stream, callback As UserCallBack, encoding As Encoding, bufferSize As Integer)
Me.process = process
Me.stream = stream
Me.encoding = encoding
Me.userCallBack = callback
Me.decoder = encoding.GetDecoder()
If bufferSize < 128 Then
bufferSize = 128
End If
Me.byteBuffer = New Byte(bufferSize - 1) {}
Me._maxCharsPerBuffer = encoding.GetMaxCharCount(bufferSize)
Me.charBuffer = New Char(Me._maxCharsPerBuffer - 1) {}
Me.cancelOperation = False
Me.eofEvent = New ManualResetEvent(False)
Me.sb = Nothing
Me.bLastCarriageReturn = False
End Sub
Public Overridable Sub Close()
Me.Dispose(True)
End Sub
Private Sub IDisposable_Dispose() Implements IDisposable.Dispose
Me.Dispose(True)
GC.SuppressFinalize(Me)
End Sub
Protected Overridable Sub Dispose(disposing As Boolean)
If disposing AndAlso Me.stream IsNot Nothing Then
Me.stream.Close()
End If
If Me.stream IsNot Nothing Then
Me.stream = Nothing
Me.encoding = Nothing
Me.decoder = Nothing
Me.byteBuffer = Nothing
Me.charBuffer = Nothing
End If
If Me.eofEvent IsNot Nothing Then
Me.eofEvent.Close()
Me.eofEvent = Nothing
End If
End Sub
Friend Sub BeginReadLine()
If Me.cancelOperation Then
Me.cancelOperation = False
End If
If Me.sb Is Nothing Then
Me.sb = New StringBuilder(1024)
Me.stream.BeginRead(Me.byteBuffer, 0, Me.byteBuffer.Length, New AsyncCallback(AddressOf Me.ReadBuffer), Nothing)
Return
End If
Me.FlushMessageQueue()
End Sub
Friend Sub CancelOperation() '<------- Error 6
Me.cancelOperation = True
End Sub
Private Sub ReadBuffer(ar As IAsyncResult)
Dim num As Integer
Try
num = Me.stream.EndRead(ar)
Catch generatedExceptionName As IOException
num = 0
Catch generatedExceptionName As OperationCanceledException
num = 0
End Try
If num = 0 Then
SyncLock Me.messageQueue
If Me.sb.Length <> 0 Then
Me.messageQueue.Enqueue(Me.sb.ToString())
Me.sb.Length = 0
End If
Me.messageQueue.Enqueue(Nothing)
End SyncLock
Try
Me.FlushMessageQueue()
Return
Finally
Me.eofEvent.[Set]()
End Try
End If
Dim chars As Integer = Me.decoder.GetChars(Me.byteBuffer, 0, num, Me.charBuffer, 0)
Me.sb.Append(Me.charBuffer, 0, chars)
Me.GetLinesFromStringBuilder()
Me.stream.BeginRead(Me.byteBuffer, 0, Me.byteBuffer.Length, New AsyncCallback(AddressOf Me.ReadBuffer), Nothing)
End Sub
Private Sub GetLinesFromStringBuilder()
Dim i As Integer = 0
Dim num As Integer = 0
Dim length As Integer = Me.sb.Length
If Me.bLastCarriageReturn AndAlso length > 0 AndAlso Me.sb(0) = ControlChars.Lf Then
i = 1
num = 1
Me.bLastCarriageReturn = False
End If
While i < length
Dim c As Char = Me.sb(i)
If c = ControlChars.Cr OrElse c = ControlChars.Lf Then
If c = ControlChars.Cr AndAlso i + 1 < length AndAlso Me.sb(i + 1) = ControlChars.Lf Then
i += 1
End If
Dim obj As String = Me.sb.ToString(num, i + 1 - num)
num = i + 1
SyncLock Me.messageQueue
Me.messageQueue.Enqueue(obj)
End SyncLock
End If
i += 1
End While
' Flush Fix: Send Whatever is left in the buffer
Dim endOfBuffer As String = Me.sb.ToString(num, length - num)
SyncLock Me.messageQueue
Me.messageQueue.Enqueue(endOfBuffer)
num = length
End SyncLock
' End Flush Fix
If Me.sb(length - 1) = ControlChars.Cr Then
Me.bLastCarriageReturn = True
End If
If num < length Then
Me.sb.Remove(0, num)
Else
Me.sb.Length = 0
End If
Me.FlushMessageQueue()
End Sub
Private Sub FlushMessageQueue()
While Me.messageQueue.Count > 0
SyncLock Me.messageQueue
If Me.messageQueue.Count > 0 Then
Dim data As String = DirectCast(Me.messageQueue.Dequeue(), String)
If Not Me.cancelOperation Then
Me.userCallBack(data)
End If
End If
Continue While
End SyncLock
Exit While
End While
End Sub
Friend Sub WaitUtilEOF()
If Me.eofEvent IsNot Nothing Then
Me.eofEvent.WaitOne()
Me.eofEvent.Close()
Me.eofEvent = Nothing
End If
End Sub
End Class
Public Class DataReceivedEventArgs
Inherits EventArgs
Friend _data As String
''' <summary>Gets the line of characters that was written to a redirected <see cref="T:System.Diagnostics.Process" /> output stream.</summary>
''' <returns>The line that was written by an associated <see cref="T:System.Diagnostics.Process" /> to its redirected <see cref="P:System.Diagnostics.Process.StandardOutput" /> or <see cref="P:System.Diagnostics.Process.StandardError" /> stream.</returns>
''' <filterpriority>2</filterpriority>
Public ReadOnly Property Data() As String
Get
Return Me._data
End Get
End Property
Friend Sub New(data As String)
Me._data = data
End Sub
End Class
End Namespace
```
Error 1-3 seem to be warnings and might actually work
Especially Error 4 and 5 give me a headache "Public Event OutputDataRecieved(sender As Object, e As DataRecievedEventArgs) is an event, and cannot be called directly. Use the RaiseEvent statement to raise an event."
Eventhandlers dont seem to work with any of the code converters I have tried and I am lacking the VB skills to convert it manually.
Is there a friendly soul out there who can properly convert this class so that it actually works?
Thanks a lot!
Roman | 2012/09/12 | [
"https://Stackoverflow.com/questions/12389346",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1665789/"
] | In your solution, add a new c# project. Place this c# code in it.
From your vb project, add a reference to the c# project.
You can now make calls to the c# objects from vb.
It's all the same when it's converted to IL. | For your "Error 4" & "Error 5", use this instead - note that you need to set the local variable to the hidden VB backing delegate field ending in "Event". Also note that your test for the local variable being nothing is still valid since we're not checking if an event is nothing, but a local variable of a delegate type - the approach for "Error 5" is exactly the same:
```
Friend Sub FixedOutputReadNotifyUser(ByVal data As String)
Dim outputDataReceived As DataReceivedEventHandler = Me.OutputDataReceivedEvent
If outputDataReceived IsNot Nothing Then
Dim dataReceivedEventArgs As New DataReceivedEventArgs(data)
If Me.SynchronizingObject IsNot Nothing AndAlso Me.SynchronizingObject.InvokeRequired Then
Me.SynchronizingObject.Invoke(outputDataReceived, New Object() { Me, dataReceivedEventArgs })
Return
End If
outputDataReceived(Me, dataReceivedEventArgs)
End If
End Sub
``` |
12,389,346 | Hello I have found a great class written in c# which I would like to use in a VB.NET project.
I found it in this thread:
[C# : Redirect console application output : How to flush the output?](https://stackoverflow.com/questions/1033648/c-sharp-redirect-console-application-output-how-to-flush-the-output)
The C# Class
looks like this:
```
using System;
using System.Collections;
using System.IO;
using System.Text;
using System.Threading;
namespace System.Diagnostics
{
internal delegate void UserCallBack(string data);
public delegate void DataReceivedEventHandler(object sender, DataReceivedEventArgs e);
public class FixedProcess : Process
{
internal AsyncStreamReader output;
internal AsyncStreamReader error;
public event DataReceivedEventHandler OutputDataReceived;
public event DataReceivedEventHandler ErrorDataReceived;
public new void BeginOutputReadLine()
{
Stream baseStream = StandardOutput.BaseStream;
this.output = new AsyncStreamReader(this, baseStream, new UserCallBack(this.FixedOutputReadNotifyUser), StandardOutput.CurrentEncoding);
this.output.BeginReadLine();
}
public void BeginErrorReadLine()
{
Stream baseStream = StandardError.BaseStream;
this.error = new AsyncStreamReader(this, baseStream, new UserCallBack(this.FixedErrorReadNotifyUser), StandardError.CurrentEncoding);
this.error.BeginReadLine();
}
internal void FixedOutputReadNotifyUser(string data)
{
DataReceivedEventHandler outputDataReceived = this.OutputDataReceived;
if (outputDataReceived != null)
{
DataReceivedEventArgs dataReceivedEventArgs = new DataReceivedEventArgs(data);
if (this.SynchronizingObject != null && this.SynchronizingObject.InvokeRequired)
{
this.SynchronizingObject.Invoke(outputDataReceived, new object[]
{
this,
dataReceivedEventArgs
});
return;
}
outputDataReceived(this, dataReceivedEventArgs);
}
}
internal void FixedErrorReadNotifyUser(string data)
{
DataReceivedEventHandler errorDataReceived = this.ErrorDataReceived;
if (errorDataReceived != null)
{
DataReceivedEventArgs dataReceivedEventArgs = new DataReceivedEventArgs(data);
if (this.SynchronizingObject != null && this.SynchronizingObject.InvokeRequired)
{
this.SynchronizingObject.Invoke(errorDataReceived, new object[]
{
this,
dataReceivedEventArgs
});
return;
}
errorDataReceived(this, dataReceivedEventArgs);
}
}
}
internal class AsyncStreamReader : IDisposable
{
internal const int DefaultBufferSize = 1024;
private const int MinBufferSize = 128;
private Stream stream;
private Encoding encoding;
private Decoder decoder;
private byte[] byteBuffer;
private char[] charBuffer;
private int _maxCharsPerBuffer;
private Process process;
private UserCallBack userCallBack;
private bool cancelOperation;
private ManualResetEvent eofEvent;
private Queue messageQueue;
private StringBuilder sb;
private bool bLastCarriageReturn;
public virtual Encoding CurrentEncoding
{
get
{
return this.encoding;
}
}
public virtual Stream BaseStream
{
get
{
return this.stream;
}
}
internal AsyncStreamReader(Process process, Stream stream, UserCallBack callback, Encoding encoding)
: this(process, stream, callback, encoding, 1024)
{
}
internal AsyncStreamReader(Process process, Stream stream, UserCallBack callback, Encoding encoding, int bufferSize)
{
this.Init(process, stream, callback, encoding, bufferSize);
this.messageQueue = new Queue();
}
private void Init(Process process, Stream stream, UserCallBack callback, Encoding encoding, int bufferSize)
{
this.process = process;
this.stream = stream;
this.encoding = encoding;
this.userCallBack = callback;
this.decoder = encoding.GetDecoder();
if (bufferSize < 128)
{
bufferSize = 128;
}
this.byteBuffer = new byte[bufferSize];
this._maxCharsPerBuffer = encoding.GetMaxCharCount(bufferSize);
this.charBuffer = new char[this._maxCharsPerBuffer];
this.cancelOperation = false;
this.eofEvent = new ManualResetEvent(false);
this.sb = null;
this.bLastCarriageReturn = false;
}
public virtual void Close()
{
this.Dispose(true);
}
void IDisposable.Dispose()
{
this.Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (disposing && this.stream != null)
{
this.stream.Close();
}
if (this.stream != null)
{
this.stream = null;
this.encoding = null;
this.decoder = null;
this.byteBuffer = null;
this.charBuffer = null;
}
if (this.eofEvent != null)
{
this.eofEvent.Close();
this.eofEvent = null;
}
}
internal void BeginReadLine()
{
if (this.cancelOperation)
{
this.cancelOperation = false;
}
if (this.sb == null)
{
this.sb = new StringBuilder(1024);
this.stream.BeginRead(this.byteBuffer, 0, this.byteBuffer.Length, new AsyncCallback(this.ReadBuffer), null);
return;
}
this.FlushMessageQueue();
}
internal void CancelOperation()
{
this.cancelOperation = true;
}
private void ReadBuffer(IAsyncResult ar)
{
int num;
try
{
num = this.stream.EndRead(ar);
}
catch (IOException)
{
num = 0;
}
catch (OperationCanceledException)
{
num = 0;
}
if (num == 0)
{
lock (this.messageQueue)
{
if (this.sb.Length != 0)
{
this.messageQueue.Enqueue(this.sb.ToString());
this.sb.Length = 0;
}
this.messageQueue.Enqueue(null);
}
try
{
this.FlushMessageQueue();
return;
}
finally
{
this.eofEvent.Set();
}
}
int chars = this.decoder.GetChars(this.byteBuffer, 0, num, this.charBuffer, 0);
this.sb.Append(this.charBuffer, 0, chars);
this.GetLinesFromStringBuilder();
this.stream.BeginRead(this.byteBuffer, 0, this.byteBuffer.Length, new AsyncCallback(this.ReadBuffer), null);
}
private void GetLinesFromStringBuilder()
{
int i = 0;
int num = 0;
int length = this.sb.Length;
if (this.bLastCarriageReturn && length > 0 && this.sb[0] == '\n')
{
i = 1;
num = 1;
this.bLastCarriageReturn = false;
}
while (i < length)
{
char c = this.sb[i];
if (c == '\r' || c == '\n')
{
if (c == '\r' && i + 1 < length && this.sb[i + 1] == '\n')
{
i++;
}
string obj = this.sb.ToString(num, i + 1 - num);
num = i + 1;
lock (this.messageQueue)
{
this.messageQueue.Enqueue(obj);
}
}
i++;
}
// Flush Fix: Send Whatever is left in the buffer
string endOfBuffer = this.sb.ToString(num, length - num);
lock (this.messageQueue)
{
this.messageQueue.Enqueue(endOfBuffer);
num = length;
}
// End Flush Fix
if (this.sb[length - 1] == '\r')
{
this.bLastCarriageReturn = true;
}
if (num < length)
{
this.sb.Remove(0, num);
}
else
{
this.sb.Length = 0;
}
this.FlushMessageQueue();
}
private void FlushMessageQueue()
{
while (this.messageQueue.Count > 0)
{
lock (this.messageQueue)
{
if (this.messageQueue.Count > 0)
{
string data = (string)this.messageQueue.Dequeue();
if (!this.cancelOperation)
{
this.userCallBack(data);
}
}
continue;
}
break;
}
}
internal void WaitUtilEOF()
{
if (this.eofEvent != null)
{
this.eofEvent.WaitOne();
this.eofEvent.Close();
this.eofEvent = null;
}
}
}
public class DataReceivedEventArgs : EventArgs
{
internal string _data;
/// <summary>Gets the line of characters that was written to a redirected <see cref="T:System.Diagnostics.Process" /> output stream.</summary>
/// <returns>The line that was written by an associated <see cref="T:System.Diagnostics.Process" /> to its redirected <see cref="P:System.Diagnostics.Process.StandardOutput" /> or <see cref="P:System.Diagnostics.Process.StandardError" /> stream.</returns>
/// <filterpriority>2</filterpriority>
public string Data
{
get
{
return this._data;
}
}
internal DataReceivedEventArgs(string data)
{
this._data = data;
}
}
}
```
My Converted Code looks like this:
```
Imports System
Imports System.Collections
Imports System.IO
Imports System.Text
Imports System.Threading
Namespace System.Diagnostics
Friend Delegate Sub UserCallBack(data As String)
Public Delegate Sub DataReceivedEventHandler(sender As Object, e As DataReceivedEventArgs)
Public Class FixedProcess
Inherits Process
Friend output As AsyncStreamReader
Friend [error] As AsyncStreamReader
Public Event OutputDataReceived As DataReceivedEventHandler '<----------Error 1
Public Event ErrorDataReceived As DataReceivedEventHandler '<------------Error 2
Public Shadows Sub BeginOutputReadLine()
Dim baseStream As Stream = StandardOutput.BaseStream
Me.output = New AsyncStreamReader(Me, baseStream, New UserCallBack(AddressOf Me.FixedOutputReadNotifyUser), StandardOutput.CurrentEncoding)
Me.output.BeginReadLine()
End Sub
Public Sub BeginErrorReadLine() '<-------------Error 3
Dim baseStream As Stream = StandardError.BaseStream
Me.[error] = New AsyncStreamReader(Me, baseStream, New UserCallBack(AddressOf Me.FixedErrorReadNotifyUser), StandardError.CurrentEncoding)
Me.[error].BeginReadLine()
End Sub
Friend Sub FixedOutputReadNotifyUser(data As String)
Dim outputDataReceived As DataReceivedEventHandler = Me.OutputDataReceived '<------------Error 4
If outputDataReceived IsNot Nothing Then
Dim dataReceivedEventArgs As New DataReceivedEventArgs(data)
If Me.SynchronizingObject IsNot Nothing AndAlso Me.SynchronizingObject.InvokeRequired Then
Me.SynchronizingObject.Invoke(outputDataReceived, New Object() {Me, dataReceivedEventArgs})
Return
End If
outputDataReceived(Me, dataReceivedEventArgs)
End If
End Sub
Friend Sub FixedErrorReadNotifyUser(data As String)
Dim errorDataReceived As DataReceivedEventHandler = Me.ErrorDataReceived '<-------------Error 5
If errorDataReceived IsNot Nothing Then
Dim dataReceivedEventArgs As New DataReceivedEventArgs(data)
If Me.SynchronizingObject IsNot Nothing AndAlso Me.SynchronizingObject.InvokeRequired Then
Me.SynchronizingObject.Invoke(errorDataReceived, New Object() {Me, dataReceivedEventArgs})
Return
End If
errorDataReceived(Me, dataReceivedEventArgs)
End If
End Sub
End Class
Friend Class AsyncStreamReader
Implements IDisposable
Friend Const DefaultBufferSize As Integer = 1024
Private Const MinBufferSize As Integer = 128
Private stream As Stream
Private encoding As Encoding
Private decoder As Decoder
Private byteBuffer As Byte()
Private charBuffer As Char()
Private _maxCharsPerBuffer As Integer
Private process As Process
Private userCallBack As UserCallBack
Private cancelOperation As Boolean
Private eofEvent As ManualResetEvent
Private messageQueue As Queue
Private sb As StringBuilder
Private bLastCarriageReturn As Boolean
Public Overridable ReadOnly Property CurrentEncoding() As Encoding
Get
Return Me.encoding
End Get
End Property
Public Overridable ReadOnly Property BaseStream() As Stream
Get
Return Me.stream
End Get
End Property
Friend Sub New(process As Process, stream As Stream, callback As UserCallBack, encoding As Encoding)
Me.New(process, stream, callback, encoding, 1024)
End Sub
Friend Sub New(process As Process, stream As Stream, callback As UserCallBack, encoding As Encoding, bufferSize As Integer)
Me.Init(process, stream, callback, encoding, bufferSize)
Me.messageQueue = New Queue()
End Sub
Private Sub Init(process As Process, stream As Stream, callback As UserCallBack, encoding As Encoding, bufferSize As Integer)
Me.process = process
Me.stream = stream
Me.encoding = encoding
Me.userCallBack = callback
Me.decoder = encoding.GetDecoder()
If bufferSize < 128 Then
bufferSize = 128
End If
Me.byteBuffer = New Byte(bufferSize - 1) {}
Me._maxCharsPerBuffer = encoding.GetMaxCharCount(bufferSize)
Me.charBuffer = New Char(Me._maxCharsPerBuffer - 1) {}
Me.cancelOperation = False
Me.eofEvent = New ManualResetEvent(False)
Me.sb = Nothing
Me.bLastCarriageReturn = False
End Sub
Public Overridable Sub Close()
Me.Dispose(True)
End Sub
Private Sub IDisposable_Dispose() Implements IDisposable.Dispose
Me.Dispose(True)
GC.SuppressFinalize(Me)
End Sub
Protected Overridable Sub Dispose(disposing As Boolean)
If disposing AndAlso Me.stream IsNot Nothing Then
Me.stream.Close()
End If
If Me.stream IsNot Nothing Then
Me.stream = Nothing
Me.encoding = Nothing
Me.decoder = Nothing
Me.byteBuffer = Nothing
Me.charBuffer = Nothing
End If
If Me.eofEvent IsNot Nothing Then
Me.eofEvent.Close()
Me.eofEvent = Nothing
End If
End Sub
Friend Sub BeginReadLine()
If Me.cancelOperation Then
Me.cancelOperation = False
End If
If Me.sb Is Nothing Then
Me.sb = New StringBuilder(1024)
Me.stream.BeginRead(Me.byteBuffer, 0, Me.byteBuffer.Length, New AsyncCallback(AddressOf Me.ReadBuffer), Nothing)
Return
End If
Me.FlushMessageQueue()
End Sub
Friend Sub CancelOperation() '<------- Error 6
Me.cancelOperation = True
End Sub
Private Sub ReadBuffer(ar As IAsyncResult)
Dim num As Integer
Try
num = Me.stream.EndRead(ar)
Catch generatedExceptionName As IOException
num = 0
Catch generatedExceptionName As OperationCanceledException
num = 0
End Try
If num = 0 Then
SyncLock Me.messageQueue
If Me.sb.Length <> 0 Then
Me.messageQueue.Enqueue(Me.sb.ToString())
Me.sb.Length = 0
End If
Me.messageQueue.Enqueue(Nothing)
End SyncLock
Try
Me.FlushMessageQueue()
Return
Finally
Me.eofEvent.[Set]()
End Try
End If
Dim chars As Integer = Me.decoder.GetChars(Me.byteBuffer, 0, num, Me.charBuffer, 0)
Me.sb.Append(Me.charBuffer, 0, chars)
Me.GetLinesFromStringBuilder()
Me.stream.BeginRead(Me.byteBuffer, 0, Me.byteBuffer.Length, New AsyncCallback(AddressOf Me.ReadBuffer), Nothing)
End Sub
Private Sub GetLinesFromStringBuilder()
Dim i As Integer = 0
Dim num As Integer = 0
Dim length As Integer = Me.sb.Length
If Me.bLastCarriageReturn AndAlso length > 0 AndAlso Me.sb(0) = ControlChars.Lf Then
i = 1
num = 1
Me.bLastCarriageReturn = False
End If
While i < length
Dim c As Char = Me.sb(i)
If c = ControlChars.Cr OrElse c = ControlChars.Lf Then
If c = ControlChars.Cr AndAlso i + 1 < length AndAlso Me.sb(i + 1) = ControlChars.Lf Then
i += 1
End If
Dim obj As String = Me.sb.ToString(num, i + 1 - num)
num = i + 1
SyncLock Me.messageQueue
Me.messageQueue.Enqueue(obj)
End SyncLock
End If
i += 1
End While
' Flush Fix: Send Whatever is left in the buffer
Dim endOfBuffer As String = Me.sb.ToString(num, length - num)
SyncLock Me.messageQueue
Me.messageQueue.Enqueue(endOfBuffer)
num = length
End SyncLock
' End Flush Fix
If Me.sb(length - 1) = ControlChars.Cr Then
Me.bLastCarriageReturn = True
End If
If num < length Then
Me.sb.Remove(0, num)
Else
Me.sb.Length = 0
End If
Me.FlushMessageQueue()
End Sub
Private Sub FlushMessageQueue()
While Me.messageQueue.Count > 0
SyncLock Me.messageQueue
If Me.messageQueue.Count > 0 Then
Dim data As String = DirectCast(Me.messageQueue.Dequeue(), String)
If Not Me.cancelOperation Then
Me.userCallBack(data)
End If
End If
Continue While
End SyncLock
Exit While
End While
End Sub
Friend Sub WaitUtilEOF()
If Me.eofEvent IsNot Nothing Then
Me.eofEvent.WaitOne()
Me.eofEvent.Close()
Me.eofEvent = Nothing
End If
End Sub
End Class
Public Class DataReceivedEventArgs
Inherits EventArgs
Friend _data As String
''' <summary>Gets the line of characters that was written to a redirected <see cref="T:System.Diagnostics.Process" /> output stream.</summary>
''' <returns>The line that was written by an associated <see cref="T:System.Diagnostics.Process" /> to its redirected <see cref="P:System.Diagnostics.Process.StandardOutput" /> or <see cref="P:System.Diagnostics.Process.StandardError" /> stream.</returns>
''' <filterpriority>2</filterpriority>
Public ReadOnly Property Data() As String
Get
Return Me._data
End Get
End Property
Friend Sub New(data As String)
Me._data = data
End Sub
End Class
End Namespace
```
Error 1-3 seem to be warnings and might actually work
Especially Error 4 and 5 give me a headache "Public Event OutputDataRecieved(sender As Object, e As DataRecievedEventArgs) is an event, and cannot be called directly. Use the RaiseEvent statement to raise an event."
Eventhandlers dont seem to work with any of the code converters I have tried and I am lacking the VB skills to convert it manually.
Is there a friendly soul out there who can properly convert this class so that it actually works?
Thanks a lot!
Roman | 2012/09/12 | [
"https://Stackoverflow.com/questions/12389346",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1665789/"
] | In your solution, add a new c# project. Place this c# code in it.
From your vb project, add a reference to the c# project.
You can now make calls to the c# objects from vb.
It's all the same when it's converted to IL. | Below is the code I am using now. I removed the namespace as I did not know how to inlcude a second namespace in my project and pasted the code into a new Module. Then as suggested in the original c# solution i just changed my "p as new process" to "p as new FixedProcess".
Thanks again for all the suggestions!
You guys rock!
To give you a complete picture of what I am trying to do I am also including the Form Code. I am not considering myself a programmer so please bear with me if it is not as sophisticated as most of you could possible do it. The intention of this is to remote control a SSH session with plink and to automatically execute commands on Cisco Routers.
The code works quite will now with one (hopefully) little flaw left: If I close the underlying plink.exe I would like to also close the input and output streams. So far I could not find out in my "borrowed" class how to do that.
I would like to do it on the close event of the form. It kills the plink.exe process, but if I open the form again for another session, it DOUBLES the output, if i close and reopen once more it Tripples the output...
Any suggestions how to properly close the streams?
```
Imports System
Imports System.Text
Imports System.IO
Imports System.Diagnostics
Imports System.Threading
Imports System.ComponentModel
Imports Microsoft.VisualBasic
Imports System.Collections.Generic
Imports System.Linq
Imports System.Collections
Module Module2
Friend Delegate Sub UserCallBack(ByVal data As String)
Public Delegate Sub DataReceivedEventHandler(ByVal sender As Object, ByVal e As DataReceivedEventArgs)
Public Class FixedProcess
Inherits Process
Friend output As AsyncStreamReader
Friend [error] As AsyncStreamReader
Public Shadows Event OutputDataReceived As DataReceivedEventHandler
Public Shadows Event ErrorDataReceived As DataReceivedEventHandler
Public CancelAll As Boolean = False
Public Overloads Sub BeginOutputReadLine()
Dim baseStream As Stream = StandardOutput.BaseStream
Me.output = New AsyncStreamReader(Me, baseStream, New UserCallBack(AddressOf Me.FixedOutputReadNotifyUser), StandardOutput.CurrentEncoding)
Me.output.BeginReadLine()
End Sub
Public Overloads Sub BeginErrorReadLine()
Dim baseStream As Stream = StandardError.BaseStream
Me.[error] = New AsyncStreamReader(Me, baseStream, New UserCallBack(AddressOf Me.FixedErrorReadNotifyUser), StandardError.CurrentEncoding)
Me.[error].BeginReadLine()
End Sub
Friend Sub FixedOutputReadNotifyUser(ByVal data As String)
Dim dataReceivedEventArgs As New DataReceivedEventArgs(data)
RaiseEvent OutputDataReceived(Me, dataReceivedEventArgs)
End Sub
Friend Sub FixedErrorReadNotifyUser(ByVal data As String)
Dim errorDataReceivedEventArgs As New DataReceivedEventArgs(data)
RaiseEvent ErrorDataReceived(Me, errorDataReceivedEventArgs)
End Sub
End Class
Friend Class AsyncStreamReader
Implements IDisposable
Friend Const DefaultBufferSize As Integer = 1024
Private Const MinBufferSize As Integer = 128
Private stream As Stream
Private encoding As Encoding
Private decoder As Decoder
Private byteBuffer As Byte()
Private charBuffer As Char()
Private _maxCharsPerBuffer As Integer
Private process As Process
Private userCallBack As UserCallBack
Public cancelOperation As Boolean
Private eofEvent As ManualResetEvent
Private messageQueue As Queue
Private sb As StringBuilder
Private bLastCarriageReturn As Boolean
Public Overridable ReadOnly Property CurrentEncoding() As Encoding
Get
Return Me.encoding
End Get
End Property
Public Overridable ReadOnly Property BaseStream() As Stream
Get
Return Me.stream
End Get
End Property
Friend Sub New(ByVal process As Process, ByVal stream As Stream, ByVal callback As UserCallBack, ByVal encoding As Encoding)
Me.New(process, stream, callback, encoding, 1024)
End Sub
Friend Sub New(ByVal process As Process, ByVal stream As Stream, ByVal callback As UserCallBack, ByVal encoding As Encoding, ByVal bufferSize As Integer)
Me.Init(process, stream, callback, encoding, bufferSize)
Me.messageQueue = New Queue()
End Sub
Private Sub Init(ByVal process As Process, ByVal stream As Stream, ByVal callback As UserCallBack, ByVal encoding As Encoding, ByVal bufferSize As Integer)
Me.process = process
Me.stream = stream
Me.encoding = encoding
Me.userCallBack = callback
Me.decoder = encoding.GetDecoder()
If bufferSize < 128 Then
bufferSize = 128
End If
Me.byteBuffer = New Byte(bufferSize - 1) {}
Me._maxCharsPerBuffer = encoding.GetMaxCharCount(bufferSize)
Me.charBuffer = New Char(Me._maxCharsPerBuffer - 1) {}
Me.cancelOperation = False
Me.eofEvent = New ManualResetEvent(False)
Me.sb = Nothing
Me.bLastCarriageReturn = False
End Sub
Public Overridable Sub Close()
Me.Dispose(True)
End Sub
Private Sub IDisposable_Dispose() Implements IDisposable.Dispose
Me.Dispose(True)
GC.SuppressFinalize(Me)
End Sub
Protected Overridable Sub Dispose(ByVal disposing As Boolean)
If disposing AndAlso Me.stream IsNot Nothing Then
Me.stream.Close()
End If
If Me.stream IsNot Nothing Then
Me.stream = Nothing
Me.encoding = Nothing
Me.decoder = Nothing
Me.byteBuffer = Nothing
Me.charBuffer = Nothing
End If
If Me.eofEvent IsNot Nothing Then
Me.eofEvent.Close()
Me.eofEvent = Nothing
End If
End Sub
Friend Sub BeginReadLine()
If Me.cancelOperation Then
Me.cancelOperation = False
End If
If Me.sb Is Nothing Then
Me.sb = New StringBuilder(1024)
Me.stream.BeginRead(Me.byteBuffer, 0, Me.byteBuffer.Length, New AsyncCallback(AddressOf Me.ReadBuffer), Nothing)
Return
End If
Me.FlushMessageQueue()
End Sub
Friend Sub _CancelOperation()
Me.cancelOperation = True
End Sub
Private Sub ReadBuffer(ByVal ar As IAsyncResult)
Dim num As Integer
Try
num = Me.stream.EndRead(ar)
Catch generatedExceptionName As IOException
num = 0
Catch generatedExceptionName As OperationCanceledException
num = 0
End Try
If num = 0 Then
SyncLock Me.messageQueue
If Me.sb.Length <> 0 Then
Me.messageQueue.Enqueue(Me.sb.ToString())
Me.sb.Length = 0
End If
Me.messageQueue.Enqueue(Nothing)
End SyncLock
Try
Me.FlushMessageQueue()
Return
Finally
Me.eofEvent.[Set]()
End Try
End If
Dim chars As Integer = Me.decoder.GetChars(Me.byteBuffer, 0, num, Me.charBuffer, 0)
Me.sb.Append(Me.charBuffer, 0, chars)
Me.GetLinesFromStringBuilder()
Me.stream.BeginRead(Me.byteBuffer, 0, Me.byteBuffer.Length, New AsyncCallback(AddressOf Me.ReadBuffer), Nothing)
End Sub
Private Sub GetLinesFromStringBuilder()
Dim i As Integer = 0
Dim num As Integer = 0
Dim length As Integer = Me.sb.Length
If Me.bLastCarriageReturn AndAlso length > 0 AndAlso Me.sb(0) = ControlChars.Lf Then
i = 1
num = 1
Me.bLastCarriageReturn = False
End If
While i < length
Dim c As Char = Me.sb(i)
If c = ControlChars.Cr OrElse c = ControlChars.Lf Then
If c = ControlChars.Cr AndAlso i + 1 < length AndAlso Me.sb(i + 1) = ControlChars.Lf Then
i += 1
End If
Dim obj As String = Me.sb.ToString(num, i + 1 - num)
num = i + 1
SyncLock Me.messageQueue
Me.messageQueue.Enqueue(obj)
End SyncLock
End If
i += 1
End While
' Flush Fix: Send Whatever is left in the buffer
Dim endOfBuffer As String = Me.sb.ToString(num, length - num)
SyncLock Me.messageQueue
Me.messageQueue.Enqueue(endOfBuffer)
num = length
End SyncLock
' End Flush Fix
If Me.sb(length - 1) = ControlChars.Cr Then
Me.bLastCarriageReturn = True
End If
If num < length Then
Me.sb.Remove(0, num)
Else
Me.sb.Length = 0
End If
Me.FlushMessageQueue()
End Sub
Private Sub FlushMessageQueue()
While Me.messageQueue.Count > 0
SyncLock Me.messageQueue
If Me.messageQueue.Count > 0 Then
Dim data As String = DirectCast(Me.messageQueue.Dequeue(), String)
If Not Me.cancelOperation Then
Me.userCallBack(data)
End If
End If
Continue While
End SyncLock
Exit While
End While
End Sub
Friend Sub WaitUtilEOF()
If Me.eofEvent IsNot Nothing Then
Me.eofEvent.WaitOne()
Me.eofEvent.Close()
Me.eofEvent = Nothing
End If
End Sub
End Class
Public Class DataReceivedEventArgs
Inherits EventArgs
Friend _data As String
''' <summary>Gets the line of characters that was written to a redirected <see cref="T:System.Diagnostics.Process" /> output stream.</summary>
''' <returns>The line that was written by an associated <see cref="T:System.Diagnostics.Process" /> to its redirected <see cref="P:System.Diagnostics.Process.StandardOutput" /> or <see cref="P:System.Diagnostics.Process.StandardError" /> stream.</returns>
''' <filterpriority>2</filterpriority>
Public ReadOnly Property Data() As String
Get
Return Me._data
End Get
End Property
Friend Sub New(ByVal data As String)
Me._data = data
End Sub
End Class
End Module
```
and my Form Code...
```
Imports System
Imports System.Text
Imports System.IO
Imports System.Diagnostics
Imports System.Threading
Imports System.ComponentModel
Imports Microsoft.VisualBasic
Imports System.Collections.Generic
Imports System.Linq
Imports System.Collections
Public Class Form3
' Define static variables shared by class methods.
Private Shared shellOutput As StringBuilder = Nothing
Private Shared numOutputLines As Integer = 0
Private Shared stdIN As StreamWriter
Private Shared p As New FixedProcess 'as new
Private Shared oldOutlineData As String = ""
Private Shared PasswordInput As Boolean = False
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
ShowISDNStatus()
End Sub
Public Sub ShowISDNStatus()
Dim p_info As New ProcessStartInfo 'as new
p_info.FileName = Form1.PlinkPath
p_info.Arguments = Form1.KommandoArguments
p_info.UseShellExecute = False
p_info.CreateNoWindow = True
p_info.RedirectStandardOutput = True
p_info.RedirectStandardInput = True
p_info.RedirectStandardError = True
' Set our event handler to asynchronously read the shell output.
AddHandler p.OutputDataReceived, AddressOf dirOutputHandler
AddHandler p.ErrorDataReceived, AddressOf dirOutputHandler
shellOutput = New StringBuilder
p.StartInfo = p_info
p.Start()
p.BeginOutputReadLine()
p.BeginErrorReadLine()
stdIN = p.StandardInput
'stdIN.WriteLine("enable" & vbCr & "K#limdor1" & vbCrLf)
'Timer1.Enabled = True
'System.Threading.Thread.Sleep(500)
'stdIN.WriteLine("term len 0")
'stdIN.WriteLine("show isdn status")
stdIN.WriteLine("enable" & vbCr & Form1.TextPassword.Text & vbCrLf)
Timer1.Enabled = True
System.Threading.Thread.Sleep(500)
Me.TextBox2.Text = ""
stdIN.WriteLine("term len 0")
stdIN.WriteLine("show isdn status")
Me.TextBox1.Select(TextBox1.Text.Length, 0)
Me.TextBox1.ScrollToCaret()
End Sub
Private Shared Sub dirOutputHandler(ByVal sendingProcess As Object, ByVal outLine As DataReceivedEventArgs)
''If Not String.IsNullOrEmpty(outLine.Data) Then
shellOutput.Append(outLine.Data)
'For i = 1 To Len(outLine.Data)
' FormDebug.TextBox1.Text = "Len von OutlineData: " & Len(outLine.Data) & " " & Asc(Mid(outLine.Data, i, 1)) & "---" & Mid(outLine.Data, i, 1)
'Next
If outLine.Data = "Store key in cache? (y/n) " Then
stdIN.WriteLine("y")
End If
Form3.TextBox1.Text = outLine.Data
''End If
End Sub
Private Sub Form3_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
End Sub
Private Sub Form3_Closing(ByVal sender As Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles MyBase.Closing
p.Kill()
End Sub
Private Sub TextBox2_PreviewKeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.PreviewKeyDownEventArgs) Handles TextBox2.PreviewKeyDown
If e.KeyCode = Keys.Return Then
If PasswordInput = False Then
If Me.TextBox2.Text = "en" Then
Me.TextBox2.UseSystemPasswordChar = True
Me.TextBox2.Text = ""
PasswordInput = True
Timer1.Enabled = False
Me.TextBox1.AppendText("Password:")
ElseIf Me.TextBox2.Text = "ena" Then
Me.TextBox2.UseSystemPasswordChar = True
Me.TextBox2.Text = ""
PasswordInput = True
Timer1.Enabled = False
Me.TextBox1.AppendText("Password:")
ElseIf Me.TextBox2.Text = "enab" Then
Me.TextBox2.UseSystemPasswordChar = True
Me.TextBox2.Text = ""
PasswordInput = True
Timer1.Enabled = False
Me.TextBox1.AppendText("Password:")
ElseIf Me.TextBox2.Text = "enabl" Then
Me.TextBox2.UseSystemPasswordChar = True
Me.TextBox2.Text = ""
PasswordInput = True
Timer1.Enabled = False
Me.TextBox1.AppendText("Password:")
ElseIf Me.TextBox2.Text = "enable" Then
Me.TextBox2.UseSystemPasswordChar = True
Me.TextBox2.Text = ""
PasswordInput = True
Timer1.Enabled = False
Me.TextBox1.AppendText("Password:")
ElseIf Me.TextBox2.Text = "" Then
stdIN.WriteLine()
System.Threading.Thread.Sleep(500)
Me.TextBox1.Select(TextBox1.Text.Length, 0)
Me.TextBox1.ScrollToCaret()
Else
stdIN.WriteLine(Me.TextBox2.Text)
System.Threading.Thread.Sleep(500)
Me.TextBox2.Text = ""
Me.TextBox1.Text = shellOutput.ToString
Me.TextBox1.Select(TextBox1.Text.Length, 0)
Me.TextBox1.ScrollToCaret()
End If
Else
stdIN.WriteLine("enable" & vbCr & Me.TextBox2.Text & vbCrLf)
System.Threading.Thread.Sleep(500)
Me.TextBox2.Text = ""
Timer1.Enabled = True
Me.TextBox2.UseSystemPasswordChar = False
stdIN.WriteLine("term len 0")
Me.TextBox1.Select(TextBox1.Text.Length, 0)
Me.TextBox1.ScrollToCaret()
PasswordInput = False
End If
End If
End Sub
Private Sub TextBox2_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox2.TextChanged
End Sub
Private Sub TextBox1_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox1.TextChanged
Me.TextBox1.SelectAll()
Me.TextBox1.ScrollToCaret()
End Sub
Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
' If Me.TextBox1.Text <> shellOutput.ToString Then Me.TextBox1.Text = shellOutput.ToString
Me.TextBox1.Text = shellOutput.ToString
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
FormDebug.Show()
'Dim frm As New Form3
'Static Num As Integer
'Num = Num + 1
'frm.Text = "Copy of Form3 - " & Num
'frm.Show()
End Sub
End Class
``` |
12,389,346 | Hello I have found a great class written in c# which I would like to use in a VB.NET project.
I found it in this thread:
[C# : Redirect console application output : How to flush the output?](https://stackoverflow.com/questions/1033648/c-sharp-redirect-console-application-output-how-to-flush-the-output)
The C# Class
looks like this:
```
using System;
using System.Collections;
using System.IO;
using System.Text;
using System.Threading;
namespace System.Diagnostics
{
internal delegate void UserCallBack(string data);
public delegate void DataReceivedEventHandler(object sender, DataReceivedEventArgs e);
public class FixedProcess : Process
{
internal AsyncStreamReader output;
internal AsyncStreamReader error;
public event DataReceivedEventHandler OutputDataReceived;
public event DataReceivedEventHandler ErrorDataReceived;
public new void BeginOutputReadLine()
{
Stream baseStream = StandardOutput.BaseStream;
this.output = new AsyncStreamReader(this, baseStream, new UserCallBack(this.FixedOutputReadNotifyUser), StandardOutput.CurrentEncoding);
this.output.BeginReadLine();
}
public void BeginErrorReadLine()
{
Stream baseStream = StandardError.BaseStream;
this.error = new AsyncStreamReader(this, baseStream, new UserCallBack(this.FixedErrorReadNotifyUser), StandardError.CurrentEncoding);
this.error.BeginReadLine();
}
internal void FixedOutputReadNotifyUser(string data)
{
DataReceivedEventHandler outputDataReceived = this.OutputDataReceived;
if (outputDataReceived != null)
{
DataReceivedEventArgs dataReceivedEventArgs = new DataReceivedEventArgs(data);
if (this.SynchronizingObject != null && this.SynchronizingObject.InvokeRequired)
{
this.SynchronizingObject.Invoke(outputDataReceived, new object[]
{
this,
dataReceivedEventArgs
});
return;
}
outputDataReceived(this, dataReceivedEventArgs);
}
}
internal void FixedErrorReadNotifyUser(string data)
{
DataReceivedEventHandler errorDataReceived = this.ErrorDataReceived;
if (errorDataReceived != null)
{
DataReceivedEventArgs dataReceivedEventArgs = new DataReceivedEventArgs(data);
if (this.SynchronizingObject != null && this.SynchronizingObject.InvokeRequired)
{
this.SynchronizingObject.Invoke(errorDataReceived, new object[]
{
this,
dataReceivedEventArgs
});
return;
}
errorDataReceived(this, dataReceivedEventArgs);
}
}
}
internal class AsyncStreamReader : IDisposable
{
internal const int DefaultBufferSize = 1024;
private const int MinBufferSize = 128;
private Stream stream;
private Encoding encoding;
private Decoder decoder;
private byte[] byteBuffer;
private char[] charBuffer;
private int _maxCharsPerBuffer;
private Process process;
private UserCallBack userCallBack;
private bool cancelOperation;
private ManualResetEvent eofEvent;
private Queue messageQueue;
private StringBuilder sb;
private bool bLastCarriageReturn;
public virtual Encoding CurrentEncoding
{
get
{
return this.encoding;
}
}
public virtual Stream BaseStream
{
get
{
return this.stream;
}
}
internal AsyncStreamReader(Process process, Stream stream, UserCallBack callback, Encoding encoding)
: this(process, stream, callback, encoding, 1024)
{
}
internal AsyncStreamReader(Process process, Stream stream, UserCallBack callback, Encoding encoding, int bufferSize)
{
this.Init(process, stream, callback, encoding, bufferSize);
this.messageQueue = new Queue();
}
private void Init(Process process, Stream stream, UserCallBack callback, Encoding encoding, int bufferSize)
{
this.process = process;
this.stream = stream;
this.encoding = encoding;
this.userCallBack = callback;
this.decoder = encoding.GetDecoder();
if (bufferSize < 128)
{
bufferSize = 128;
}
this.byteBuffer = new byte[bufferSize];
this._maxCharsPerBuffer = encoding.GetMaxCharCount(bufferSize);
this.charBuffer = new char[this._maxCharsPerBuffer];
this.cancelOperation = false;
this.eofEvent = new ManualResetEvent(false);
this.sb = null;
this.bLastCarriageReturn = false;
}
public virtual void Close()
{
this.Dispose(true);
}
void IDisposable.Dispose()
{
this.Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (disposing && this.stream != null)
{
this.stream.Close();
}
if (this.stream != null)
{
this.stream = null;
this.encoding = null;
this.decoder = null;
this.byteBuffer = null;
this.charBuffer = null;
}
if (this.eofEvent != null)
{
this.eofEvent.Close();
this.eofEvent = null;
}
}
internal void BeginReadLine()
{
if (this.cancelOperation)
{
this.cancelOperation = false;
}
if (this.sb == null)
{
this.sb = new StringBuilder(1024);
this.stream.BeginRead(this.byteBuffer, 0, this.byteBuffer.Length, new AsyncCallback(this.ReadBuffer), null);
return;
}
this.FlushMessageQueue();
}
internal void CancelOperation()
{
this.cancelOperation = true;
}
private void ReadBuffer(IAsyncResult ar)
{
int num;
try
{
num = this.stream.EndRead(ar);
}
catch (IOException)
{
num = 0;
}
catch (OperationCanceledException)
{
num = 0;
}
if (num == 0)
{
lock (this.messageQueue)
{
if (this.sb.Length != 0)
{
this.messageQueue.Enqueue(this.sb.ToString());
this.sb.Length = 0;
}
this.messageQueue.Enqueue(null);
}
try
{
this.FlushMessageQueue();
return;
}
finally
{
this.eofEvent.Set();
}
}
int chars = this.decoder.GetChars(this.byteBuffer, 0, num, this.charBuffer, 0);
this.sb.Append(this.charBuffer, 0, chars);
this.GetLinesFromStringBuilder();
this.stream.BeginRead(this.byteBuffer, 0, this.byteBuffer.Length, new AsyncCallback(this.ReadBuffer), null);
}
private void GetLinesFromStringBuilder()
{
int i = 0;
int num = 0;
int length = this.sb.Length;
if (this.bLastCarriageReturn && length > 0 && this.sb[0] == '\n')
{
i = 1;
num = 1;
this.bLastCarriageReturn = false;
}
while (i < length)
{
char c = this.sb[i];
if (c == '\r' || c == '\n')
{
if (c == '\r' && i + 1 < length && this.sb[i + 1] == '\n')
{
i++;
}
string obj = this.sb.ToString(num, i + 1 - num);
num = i + 1;
lock (this.messageQueue)
{
this.messageQueue.Enqueue(obj);
}
}
i++;
}
// Flush Fix: Send Whatever is left in the buffer
string endOfBuffer = this.sb.ToString(num, length - num);
lock (this.messageQueue)
{
this.messageQueue.Enqueue(endOfBuffer);
num = length;
}
// End Flush Fix
if (this.sb[length - 1] == '\r')
{
this.bLastCarriageReturn = true;
}
if (num < length)
{
this.sb.Remove(0, num);
}
else
{
this.sb.Length = 0;
}
this.FlushMessageQueue();
}
private void FlushMessageQueue()
{
while (this.messageQueue.Count > 0)
{
lock (this.messageQueue)
{
if (this.messageQueue.Count > 0)
{
string data = (string)this.messageQueue.Dequeue();
if (!this.cancelOperation)
{
this.userCallBack(data);
}
}
continue;
}
break;
}
}
internal void WaitUtilEOF()
{
if (this.eofEvent != null)
{
this.eofEvent.WaitOne();
this.eofEvent.Close();
this.eofEvent = null;
}
}
}
public class DataReceivedEventArgs : EventArgs
{
internal string _data;
/// <summary>Gets the line of characters that was written to a redirected <see cref="T:System.Diagnostics.Process" /> output stream.</summary>
/// <returns>The line that was written by an associated <see cref="T:System.Diagnostics.Process" /> to its redirected <see cref="P:System.Diagnostics.Process.StandardOutput" /> or <see cref="P:System.Diagnostics.Process.StandardError" /> stream.</returns>
/// <filterpriority>2</filterpriority>
public string Data
{
get
{
return this._data;
}
}
internal DataReceivedEventArgs(string data)
{
this._data = data;
}
}
}
```
My Converted Code looks like this:
```
Imports System
Imports System.Collections
Imports System.IO
Imports System.Text
Imports System.Threading
Namespace System.Diagnostics
Friend Delegate Sub UserCallBack(data As String)
Public Delegate Sub DataReceivedEventHandler(sender As Object, e As DataReceivedEventArgs)
Public Class FixedProcess
Inherits Process
Friend output As AsyncStreamReader
Friend [error] As AsyncStreamReader
Public Event OutputDataReceived As DataReceivedEventHandler '<----------Error 1
Public Event ErrorDataReceived As DataReceivedEventHandler '<------------Error 2
Public Shadows Sub BeginOutputReadLine()
Dim baseStream As Stream = StandardOutput.BaseStream
Me.output = New AsyncStreamReader(Me, baseStream, New UserCallBack(AddressOf Me.FixedOutputReadNotifyUser), StandardOutput.CurrentEncoding)
Me.output.BeginReadLine()
End Sub
Public Sub BeginErrorReadLine() '<-------------Error 3
Dim baseStream As Stream = StandardError.BaseStream
Me.[error] = New AsyncStreamReader(Me, baseStream, New UserCallBack(AddressOf Me.FixedErrorReadNotifyUser), StandardError.CurrentEncoding)
Me.[error].BeginReadLine()
End Sub
Friend Sub FixedOutputReadNotifyUser(data As String)
Dim outputDataReceived As DataReceivedEventHandler = Me.OutputDataReceived '<------------Error 4
If outputDataReceived IsNot Nothing Then
Dim dataReceivedEventArgs As New DataReceivedEventArgs(data)
If Me.SynchronizingObject IsNot Nothing AndAlso Me.SynchronizingObject.InvokeRequired Then
Me.SynchronizingObject.Invoke(outputDataReceived, New Object() {Me, dataReceivedEventArgs})
Return
End If
outputDataReceived(Me, dataReceivedEventArgs)
End If
End Sub
Friend Sub FixedErrorReadNotifyUser(data As String)
Dim errorDataReceived As DataReceivedEventHandler = Me.ErrorDataReceived '<-------------Error 5
If errorDataReceived IsNot Nothing Then
Dim dataReceivedEventArgs As New DataReceivedEventArgs(data)
If Me.SynchronizingObject IsNot Nothing AndAlso Me.SynchronizingObject.InvokeRequired Then
Me.SynchronizingObject.Invoke(errorDataReceived, New Object() {Me, dataReceivedEventArgs})
Return
End If
errorDataReceived(Me, dataReceivedEventArgs)
End If
End Sub
End Class
Friend Class AsyncStreamReader
Implements IDisposable
Friend Const DefaultBufferSize As Integer = 1024
Private Const MinBufferSize As Integer = 128
Private stream As Stream
Private encoding As Encoding
Private decoder As Decoder
Private byteBuffer As Byte()
Private charBuffer As Char()
Private _maxCharsPerBuffer As Integer
Private process As Process
Private userCallBack As UserCallBack
Private cancelOperation As Boolean
Private eofEvent As ManualResetEvent
Private messageQueue As Queue
Private sb As StringBuilder
Private bLastCarriageReturn As Boolean
Public Overridable ReadOnly Property CurrentEncoding() As Encoding
Get
Return Me.encoding
End Get
End Property
Public Overridable ReadOnly Property BaseStream() As Stream
Get
Return Me.stream
End Get
End Property
Friend Sub New(process As Process, stream As Stream, callback As UserCallBack, encoding As Encoding)
Me.New(process, stream, callback, encoding, 1024)
End Sub
Friend Sub New(process As Process, stream As Stream, callback As UserCallBack, encoding As Encoding, bufferSize As Integer)
Me.Init(process, stream, callback, encoding, bufferSize)
Me.messageQueue = New Queue()
End Sub
Private Sub Init(process As Process, stream As Stream, callback As UserCallBack, encoding As Encoding, bufferSize As Integer)
Me.process = process
Me.stream = stream
Me.encoding = encoding
Me.userCallBack = callback
Me.decoder = encoding.GetDecoder()
If bufferSize < 128 Then
bufferSize = 128
End If
Me.byteBuffer = New Byte(bufferSize - 1) {}
Me._maxCharsPerBuffer = encoding.GetMaxCharCount(bufferSize)
Me.charBuffer = New Char(Me._maxCharsPerBuffer - 1) {}
Me.cancelOperation = False
Me.eofEvent = New ManualResetEvent(False)
Me.sb = Nothing
Me.bLastCarriageReturn = False
End Sub
Public Overridable Sub Close()
Me.Dispose(True)
End Sub
Private Sub IDisposable_Dispose() Implements IDisposable.Dispose
Me.Dispose(True)
GC.SuppressFinalize(Me)
End Sub
Protected Overridable Sub Dispose(disposing As Boolean)
If disposing AndAlso Me.stream IsNot Nothing Then
Me.stream.Close()
End If
If Me.stream IsNot Nothing Then
Me.stream = Nothing
Me.encoding = Nothing
Me.decoder = Nothing
Me.byteBuffer = Nothing
Me.charBuffer = Nothing
End If
If Me.eofEvent IsNot Nothing Then
Me.eofEvent.Close()
Me.eofEvent = Nothing
End If
End Sub
Friend Sub BeginReadLine()
If Me.cancelOperation Then
Me.cancelOperation = False
End If
If Me.sb Is Nothing Then
Me.sb = New StringBuilder(1024)
Me.stream.BeginRead(Me.byteBuffer, 0, Me.byteBuffer.Length, New AsyncCallback(AddressOf Me.ReadBuffer), Nothing)
Return
End If
Me.FlushMessageQueue()
End Sub
Friend Sub CancelOperation() '<------- Error 6
Me.cancelOperation = True
End Sub
Private Sub ReadBuffer(ar As IAsyncResult)
Dim num As Integer
Try
num = Me.stream.EndRead(ar)
Catch generatedExceptionName As IOException
num = 0
Catch generatedExceptionName As OperationCanceledException
num = 0
End Try
If num = 0 Then
SyncLock Me.messageQueue
If Me.sb.Length <> 0 Then
Me.messageQueue.Enqueue(Me.sb.ToString())
Me.sb.Length = 0
End If
Me.messageQueue.Enqueue(Nothing)
End SyncLock
Try
Me.FlushMessageQueue()
Return
Finally
Me.eofEvent.[Set]()
End Try
End If
Dim chars As Integer = Me.decoder.GetChars(Me.byteBuffer, 0, num, Me.charBuffer, 0)
Me.sb.Append(Me.charBuffer, 0, chars)
Me.GetLinesFromStringBuilder()
Me.stream.BeginRead(Me.byteBuffer, 0, Me.byteBuffer.Length, New AsyncCallback(AddressOf Me.ReadBuffer), Nothing)
End Sub
Private Sub GetLinesFromStringBuilder()
Dim i As Integer = 0
Dim num As Integer = 0
Dim length As Integer = Me.sb.Length
If Me.bLastCarriageReturn AndAlso length > 0 AndAlso Me.sb(0) = ControlChars.Lf Then
i = 1
num = 1
Me.bLastCarriageReturn = False
End If
While i < length
Dim c As Char = Me.sb(i)
If c = ControlChars.Cr OrElse c = ControlChars.Lf Then
If c = ControlChars.Cr AndAlso i + 1 < length AndAlso Me.sb(i + 1) = ControlChars.Lf Then
i += 1
End If
Dim obj As String = Me.sb.ToString(num, i + 1 - num)
num = i + 1
SyncLock Me.messageQueue
Me.messageQueue.Enqueue(obj)
End SyncLock
End If
i += 1
End While
' Flush Fix: Send Whatever is left in the buffer
Dim endOfBuffer As String = Me.sb.ToString(num, length - num)
SyncLock Me.messageQueue
Me.messageQueue.Enqueue(endOfBuffer)
num = length
End SyncLock
' End Flush Fix
If Me.sb(length - 1) = ControlChars.Cr Then
Me.bLastCarriageReturn = True
End If
If num < length Then
Me.sb.Remove(0, num)
Else
Me.sb.Length = 0
End If
Me.FlushMessageQueue()
End Sub
Private Sub FlushMessageQueue()
While Me.messageQueue.Count > 0
SyncLock Me.messageQueue
If Me.messageQueue.Count > 0 Then
Dim data As String = DirectCast(Me.messageQueue.Dequeue(), String)
If Not Me.cancelOperation Then
Me.userCallBack(data)
End If
End If
Continue While
End SyncLock
Exit While
End While
End Sub
Friend Sub WaitUtilEOF()
If Me.eofEvent IsNot Nothing Then
Me.eofEvent.WaitOne()
Me.eofEvent.Close()
Me.eofEvent = Nothing
End If
End Sub
End Class
Public Class DataReceivedEventArgs
Inherits EventArgs
Friend _data As String
''' <summary>Gets the line of characters that was written to a redirected <see cref="T:System.Diagnostics.Process" /> output stream.</summary>
''' <returns>The line that was written by an associated <see cref="T:System.Diagnostics.Process" /> to its redirected <see cref="P:System.Diagnostics.Process.StandardOutput" /> or <see cref="P:System.Diagnostics.Process.StandardError" /> stream.</returns>
''' <filterpriority>2</filterpriority>
Public ReadOnly Property Data() As String
Get
Return Me._data
End Get
End Property
Friend Sub New(data As String)
Me._data = data
End Sub
End Class
End Namespace
```
Error 1-3 seem to be warnings and might actually work
Especially Error 4 and 5 give me a headache "Public Event OutputDataRecieved(sender As Object, e As DataRecievedEventArgs) is an event, and cannot be called directly. Use the RaiseEvent statement to raise an event."
Eventhandlers dont seem to work with any of the code converters I have tried and I am lacking the VB skills to convert it manually.
Is there a friendly soul out there who can properly convert this class so that it actually works?
Thanks a lot!
Roman | 2012/09/12 | [
"https://Stackoverflow.com/questions/12389346",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1665789/"
] | You need to add the Overloads keyword to the BeginErrorReadLine method signature.
```
Public Overloads Sub BeginErrorReadLine() '<-------------Error 3
```
The event declarations need to be declared as Shadows because they otherwise conflict with the base class event declarations.
```
Public Shadows Event OutputDataReceived As DataReceivedEventHandler '<----------Error 1
```
Then in your FixedOutputReadNotifyUser method, you don't need to check the event handler as you do in C# to see if it is nothing. VB will do that for you. Instead, simply raise it as follows:
```
Friend Sub FixedOutputReadNotifyUser(data As String)
Dim dataReceivedEventArgs As New DataReceivedEventArgs(data)
RaiseEvent OutputDataReceived(Me, dataReceivedEventArgs)
End Sub
```
The last issue is the original class uses case sensitivity to differentiate between the "cancelOperation" field and "CancelOperation" method. Best option is to prefix the field with an underscore as follows: `Private _CancelOperation As Boolean` and then fix the corresponding references in the class. | For your "Error 4" & "Error 5", use this instead - note that you need to set the local variable to the hidden VB backing delegate field ending in "Event". Also note that your test for the local variable being nothing is still valid since we're not checking if an event is nothing, but a local variable of a delegate type - the approach for "Error 5" is exactly the same:
```
Friend Sub FixedOutputReadNotifyUser(ByVal data As String)
Dim outputDataReceived As DataReceivedEventHandler = Me.OutputDataReceivedEvent
If outputDataReceived IsNot Nothing Then
Dim dataReceivedEventArgs As New DataReceivedEventArgs(data)
If Me.SynchronizingObject IsNot Nothing AndAlso Me.SynchronizingObject.InvokeRequired Then
Me.SynchronizingObject.Invoke(outputDataReceived, New Object() { Me, dataReceivedEventArgs })
Return
End If
outputDataReceived(Me, dataReceivedEventArgs)
End If
End Sub
``` |
12,389,346 | Hello I have found a great class written in c# which I would like to use in a VB.NET project.
I found it in this thread:
[C# : Redirect console application output : How to flush the output?](https://stackoverflow.com/questions/1033648/c-sharp-redirect-console-application-output-how-to-flush-the-output)
The C# Class
looks like this:
```
using System;
using System.Collections;
using System.IO;
using System.Text;
using System.Threading;
namespace System.Diagnostics
{
internal delegate void UserCallBack(string data);
public delegate void DataReceivedEventHandler(object sender, DataReceivedEventArgs e);
public class FixedProcess : Process
{
internal AsyncStreamReader output;
internal AsyncStreamReader error;
public event DataReceivedEventHandler OutputDataReceived;
public event DataReceivedEventHandler ErrorDataReceived;
public new void BeginOutputReadLine()
{
Stream baseStream = StandardOutput.BaseStream;
this.output = new AsyncStreamReader(this, baseStream, new UserCallBack(this.FixedOutputReadNotifyUser), StandardOutput.CurrentEncoding);
this.output.BeginReadLine();
}
public void BeginErrorReadLine()
{
Stream baseStream = StandardError.BaseStream;
this.error = new AsyncStreamReader(this, baseStream, new UserCallBack(this.FixedErrorReadNotifyUser), StandardError.CurrentEncoding);
this.error.BeginReadLine();
}
internal void FixedOutputReadNotifyUser(string data)
{
DataReceivedEventHandler outputDataReceived = this.OutputDataReceived;
if (outputDataReceived != null)
{
DataReceivedEventArgs dataReceivedEventArgs = new DataReceivedEventArgs(data);
if (this.SynchronizingObject != null && this.SynchronizingObject.InvokeRequired)
{
this.SynchronizingObject.Invoke(outputDataReceived, new object[]
{
this,
dataReceivedEventArgs
});
return;
}
outputDataReceived(this, dataReceivedEventArgs);
}
}
internal void FixedErrorReadNotifyUser(string data)
{
DataReceivedEventHandler errorDataReceived = this.ErrorDataReceived;
if (errorDataReceived != null)
{
DataReceivedEventArgs dataReceivedEventArgs = new DataReceivedEventArgs(data);
if (this.SynchronizingObject != null && this.SynchronizingObject.InvokeRequired)
{
this.SynchronizingObject.Invoke(errorDataReceived, new object[]
{
this,
dataReceivedEventArgs
});
return;
}
errorDataReceived(this, dataReceivedEventArgs);
}
}
}
internal class AsyncStreamReader : IDisposable
{
internal const int DefaultBufferSize = 1024;
private const int MinBufferSize = 128;
private Stream stream;
private Encoding encoding;
private Decoder decoder;
private byte[] byteBuffer;
private char[] charBuffer;
private int _maxCharsPerBuffer;
private Process process;
private UserCallBack userCallBack;
private bool cancelOperation;
private ManualResetEvent eofEvent;
private Queue messageQueue;
private StringBuilder sb;
private bool bLastCarriageReturn;
public virtual Encoding CurrentEncoding
{
get
{
return this.encoding;
}
}
public virtual Stream BaseStream
{
get
{
return this.stream;
}
}
internal AsyncStreamReader(Process process, Stream stream, UserCallBack callback, Encoding encoding)
: this(process, stream, callback, encoding, 1024)
{
}
internal AsyncStreamReader(Process process, Stream stream, UserCallBack callback, Encoding encoding, int bufferSize)
{
this.Init(process, stream, callback, encoding, bufferSize);
this.messageQueue = new Queue();
}
private void Init(Process process, Stream stream, UserCallBack callback, Encoding encoding, int bufferSize)
{
this.process = process;
this.stream = stream;
this.encoding = encoding;
this.userCallBack = callback;
this.decoder = encoding.GetDecoder();
if (bufferSize < 128)
{
bufferSize = 128;
}
this.byteBuffer = new byte[bufferSize];
this._maxCharsPerBuffer = encoding.GetMaxCharCount(bufferSize);
this.charBuffer = new char[this._maxCharsPerBuffer];
this.cancelOperation = false;
this.eofEvent = new ManualResetEvent(false);
this.sb = null;
this.bLastCarriageReturn = false;
}
public virtual void Close()
{
this.Dispose(true);
}
void IDisposable.Dispose()
{
this.Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (disposing && this.stream != null)
{
this.stream.Close();
}
if (this.stream != null)
{
this.stream = null;
this.encoding = null;
this.decoder = null;
this.byteBuffer = null;
this.charBuffer = null;
}
if (this.eofEvent != null)
{
this.eofEvent.Close();
this.eofEvent = null;
}
}
internal void BeginReadLine()
{
if (this.cancelOperation)
{
this.cancelOperation = false;
}
if (this.sb == null)
{
this.sb = new StringBuilder(1024);
this.stream.BeginRead(this.byteBuffer, 0, this.byteBuffer.Length, new AsyncCallback(this.ReadBuffer), null);
return;
}
this.FlushMessageQueue();
}
internal void CancelOperation()
{
this.cancelOperation = true;
}
private void ReadBuffer(IAsyncResult ar)
{
int num;
try
{
num = this.stream.EndRead(ar);
}
catch (IOException)
{
num = 0;
}
catch (OperationCanceledException)
{
num = 0;
}
if (num == 0)
{
lock (this.messageQueue)
{
if (this.sb.Length != 0)
{
this.messageQueue.Enqueue(this.sb.ToString());
this.sb.Length = 0;
}
this.messageQueue.Enqueue(null);
}
try
{
this.FlushMessageQueue();
return;
}
finally
{
this.eofEvent.Set();
}
}
int chars = this.decoder.GetChars(this.byteBuffer, 0, num, this.charBuffer, 0);
this.sb.Append(this.charBuffer, 0, chars);
this.GetLinesFromStringBuilder();
this.stream.BeginRead(this.byteBuffer, 0, this.byteBuffer.Length, new AsyncCallback(this.ReadBuffer), null);
}
private void GetLinesFromStringBuilder()
{
int i = 0;
int num = 0;
int length = this.sb.Length;
if (this.bLastCarriageReturn && length > 0 && this.sb[0] == '\n')
{
i = 1;
num = 1;
this.bLastCarriageReturn = false;
}
while (i < length)
{
char c = this.sb[i];
if (c == '\r' || c == '\n')
{
if (c == '\r' && i + 1 < length && this.sb[i + 1] == '\n')
{
i++;
}
string obj = this.sb.ToString(num, i + 1 - num);
num = i + 1;
lock (this.messageQueue)
{
this.messageQueue.Enqueue(obj);
}
}
i++;
}
// Flush Fix: Send Whatever is left in the buffer
string endOfBuffer = this.sb.ToString(num, length - num);
lock (this.messageQueue)
{
this.messageQueue.Enqueue(endOfBuffer);
num = length;
}
// End Flush Fix
if (this.sb[length - 1] == '\r')
{
this.bLastCarriageReturn = true;
}
if (num < length)
{
this.sb.Remove(0, num);
}
else
{
this.sb.Length = 0;
}
this.FlushMessageQueue();
}
private void FlushMessageQueue()
{
while (this.messageQueue.Count > 0)
{
lock (this.messageQueue)
{
if (this.messageQueue.Count > 0)
{
string data = (string)this.messageQueue.Dequeue();
if (!this.cancelOperation)
{
this.userCallBack(data);
}
}
continue;
}
break;
}
}
internal void WaitUtilEOF()
{
if (this.eofEvent != null)
{
this.eofEvent.WaitOne();
this.eofEvent.Close();
this.eofEvent = null;
}
}
}
public class DataReceivedEventArgs : EventArgs
{
internal string _data;
/// <summary>Gets the line of characters that was written to a redirected <see cref="T:System.Diagnostics.Process" /> output stream.</summary>
/// <returns>The line that was written by an associated <see cref="T:System.Diagnostics.Process" /> to its redirected <see cref="P:System.Diagnostics.Process.StandardOutput" /> or <see cref="P:System.Diagnostics.Process.StandardError" /> stream.</returns>
/// <filterpriority>2</filterpriority>
public string Data
{
get
{
return this._data;
}
}
internal DataReceivedEventArgs(string data)
{
this._data = data;
}
}
}
```
My Converted Code looks like this:
```
Imports System
Imports System.Collections
Imports System.IO
Imports System.Text
Imports System.Threading
Namespace System.Diagnostics
Friend Delegate Sub UserCallBack(data As String)
Public Delegate Sub DataReceivedEventHandler(sender As Object, e As DataReceivedEventArgs)
Public Class FixedProcess
Inherits Process
Friend output As AsyncStreamReader
Friend [error] As AsyncStreamReader
Public Event OutputDataReceived As DataReceivedEventHandler '<----------Error 1
Public Event ErrorDataReceived As DataReceivedEventHandler '<------------Error 2
Public Shadows Sub BeginOutputReadLine()
Dim baseStream As Stream = StandardOutput.BaseStream
Me.output = New AsyncStreamReader(Me, baseStream, New UserCallBack(AddressOf Me.FixedOutputReadNotifyUser), StandardOutput.CurrentEncoding)
Me.output.BeginReadLine()
End Sub
Public Sub BeginErrorReadLine() '<-------------Error 3
Dim baseStream As Stream = StandardError.BaseStream
Me.[error] = New AsyncStreamReader(Me, baseStream, New UserCallBack(AddressOf Me.FixedErrorReadNotifyUser), StandardError.CurrentEncoding)
Me.[error].BeginReadLine()
End Sub
Friend Sub FixedOutputReadNotifyUser(data As String)
Dim outputDataReceived As DataReceivedEventHandler = Me.OutputDataReceived '<------------Error 4
If outputDataReceived IsNot Nothing Then
Dim dataReceivedEventArgs As New DataReceivedEventArgs(data)
If Me.SynchronizingObject IsNot Nothing AndAlso Me.SynchronizingObject.InvokeRequired Then
Me.SynchronizingObject.Invoke(outputDataReceived, New Object() {Me, dataReceivedEventArgs})
Return
End If
outputDataReceived(Me, dataReceivedEventArgs)
End If
End Sub
Friend Sub FixedErrorReadNotifyUser(data As String)
Dim errorDataReceived As DataReceivedEventHandler = Me.ErrorDataReceived '<-------------Error 5
If errorDataReceived IsNot Nothing Then
Dim dataReceivedEventArgs As New DataReceivedEventArgs(data)
If Me.SynchronizingObject IsNot Nothing AndAlso Me.SynchronizingObject.InvokeRequired Then
Me.SynchronizingObject.Invoke(errorDataReceived, New Object() {Me, dataReceivedEventArgs})
Return
End If
errorDataReceived(Me, dataReceivedEventArgs)
End If
End Sub
End Class
Friend Class AsyncStreamReader
Implements IDisposable
Friend Const DefaultBufferSize As Integer = 1024
Private Const MinBufferSize As Integer = 128
Private stream As Stream
Private encoding As Encoding
Private decoder As Decoder
Private byteBuffer As Byte()
Private charBuffer As Char()
Private _maxCharsPerBuffer As Integer
Private process As Process
Private userCallBack As UserCallBack
Private cancelOperation As Boolean
Private eofEvent As ManualResetEvent
Private messageQueue As Queue
Private sb As StringBuilder
Private bLastCarriageReturn As Boolean
Public Overridable ReadOnly Property CurrentEncoding() As Encoding
Get
Return Me.encoding
End Get
End Property
Public Overridable ReadOnly Property BaseStream() As Stream
Get
Return Me.stream
End Get
End Property
Friend Sub New(process As Process, stream As Stream, callback As UserCallBack, encoding As Encoding)
Me.New(process, stream, callback, encoding, 1024)
End Sub
Friend Sub New(process As Process, stream As Stream, callback As UserCallBack, encoding As Encoding, bufferSize As Integer)
Me.Init(process, stream, callback, encoding, bufferSize)
Me.messageQueue = New Queue()
End Sub
Private Sub Init(process As Process, stream As Stream, callback As UserCallBack, encoding As Encoding, bufferSize As Integer)
Me.process = process
Me.stream = stream
Me.encoding = encoding
Me.userCallBack = callback
Me.decoder = encoding.GetDecoder()
If bufferSize < 128 Then
bufferSize = 128
End If
Me.byteBuffer = New Byte(bufferSize - 1) {}
Me._maxCharsPerBuffer = encoding.GetMaxCharCount(bufferSize)
Me.charBuffer = New Char(Me._maxCharsPerBuffer - 1) {}
Me.cancelOperation = False
Me.eofEvent = New ManualResetEvent(False)
Me.sb = Nothing
Me.bLastCarriageReturn = False
End Sub
Public Overridable Sub Close()
Me.Dispose(True)
End Sub
Private Sub IDisposable_Dispose() Implements IDisposable.Dispose
Me.Dispose(True)
GC.SuppressFinalize(Me)
End Sub
Protected Overridable Sub Dispose(disposing As Boolean)
If disposing AndAlso Me.stream IsNot Nothing Then
Me.stream.Close()
End If
If Me.stream IsNot Nothing Then
Me.stream = Nothing
Me.encoding = Nothing
Me.decoder = Nothing
Me.byteBuffer = Nothing
Me.charBuffer = Nothing
End If
If Me.eofEvent IsNot Nothing Then
Me.eofEvent.Close()
Me.eofEvent = Nothing
End If
End Sub
Friend Sub BeginReadLine()
If Me.cancelOperation Then
Me.cancelOperation = False
End If
If Me.sb Is Nothing Then
Me.sb = New StringBuilder(1024)
Me.stream.BeginRead(Me.byteBuffer, 0, Me.byteBuffer.Length, New AsyncCallback(AddressOf Me.ReadBuffer), Nothing)
Return
End If
Me.FlushMessageQueue()
End Sub
Friend Sub CancelOperation() '<------- Error 6
Me.cancelOperation = True
End Sub
Private Sub ReadBuffer(ar As IAsyncResult)
Dim num As Integer
Try
num = Me.stream.EndRead(ar)
Catch generatedExceptionName As IOException
num = 0
Catch generatedExceptionName As OperationCanceledException
num = 0
End Try
If num = 0 Then
SyncLock Me.messageQueue
If Me.sb.Length <> 0 Then
Me.messageQueue.Enqueue(Me.sb.ToString())
Me.sb.Length = 0
End If
Me.messageQueue.Enqueue(Nothing)
End SyncLock
Try
Me.FlushMessageQueue()
Return
Finally
Me.eofEvent.[Set]()
End Try
End If
Dim chars As Integer = Me.decoder.GetChars(Me.byteBuffer, 0, num, Me.charBuffer, 0)
Me.sb.Append(Me.charBuffer, 0, chars)
Me.GetLinesFromStringBuilder()
Me.stream.BeginRead(Me.byteBuffer, 0, Me.byteBuffer.Length, New AsyncCallback(AddressOf Me.ReadBuffer), Nothing)
End Sub
Private Sub GetLinesFromStringBuilder()
Dim i As Integer = 0
Dim num As Integer = 0
Dim length As Integer = Me.sb.Length
If Me.bLastCarriageReturn AndAlso length > 0 AndAlso Me.sb(0) = ControlChars.Lf Then
i = 1
num = 1
Me.bLastCarriageReturn = False
End If
While i < length
Dim c As Char = Me.sb(i)
If c = ControlChars.Cr OrElse c = ControlChars.Lf Then
If c = ControlChars.Cr AndAlso i + 1 < length AndAlso Me.sb(i + 1) = ControlChars.Lf Then
i += 1
End If
Dim obj As String = Me.sb.ToString(num, i + 1 - num)
num = i + 1
SyncLock Me.messageQueue
Me.messageQueue.Enqueue(obj)
End SyncLock
End If
i += 1
End While
' Flush Fix: Send Whatever is left in the buffer
Dim endOfBuffer As String = Me.sb.ToString(num, length - num)
SyncLock Me.messageQueue
Me.messageQueue.Enqueue(endOfBuffer)
num = length
End SyncLock
' End Flush Fix
If Me.sb(length - 1) = ControlChars.Cr Then
Me.bLastCarriageReturn = True
End If
If num < length Then
Me.sb.Remove(0, num)
Else
Me.sb.Length = 0
End If
Me.FlushMessageQueue()
End Sub
Private Sub FlushMessageQueue()
While Me.messageQueue.Count > 0
SyncLock Me.messageQueue
If Me.messageQueue.Count > 0 Then
Dim data As String = DirectCast(Me.messageQueue.Dequeue(), String)
If Not Me.cancelOperation Then
Me.userCallBack(data)
End If
End If
Continue While
End SyncLock
Exit While
End While
End Sub
Friend Sub WaitUtilEOF()
If Me.eofEvent IsNot Nothing Then
Me.eofEvent.WaitOne()
Me.eofEvent.Close()
Me.eofEvent = Nothing
End If
End Sub
End Class
Public Class DataReceivedEventArgs
Inherits EventArgs
Friend _data As String
''' <summary>Gets the line of characters that was written to a redirected <see cref="T:System.Diagnostics.Process" /> output stream.</summary>
''' <returns>The line that was written by an associated <see cref="T:System.Diagnostics.Process" /> to its redirected <see cref="P:System.Diagnostics.Process.StandardOutput" /> or <see cref="P:System.Diagnostics.Process.StandardError" /> stream.</returns>
''' <filterpriority>2</filterpriority>
Public ReadOnly Property Data() As String
Get
Return Me._data
End Get
End Property
Friend Sub New(data As String)
Me._data = data
End Sub
End Class
End Namespace
```
Error 1-3 seem to be warnings and might actually work
Especially Error 4 and 5 give me a headache "Public Event OutputDataRecieved(sender As Object, e As DataRecievedEventArgs) is an event, and cannot be called directly. Use the RaiseEvent statement to raise an event."
Eventhandlers dont seem to work with any of the code converters I have tried and I am lacking the VB skills to convert it manually.
Is there a friendly soul out there who can properly convert this class so that it actually works?
Thanks a lot!
Roman | 2012/09/12 | [
"https://Stackoverflow.com/questions/12389346",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1665789/"
] | You need to add the Overloads keyword to the BeginErrorReadLine method signature.
```
Public Overloads Sub BeginErrorReadLine() '<-------------Error 3
```
The event declarations need to be declared as Shadows because they otherwise conflict with the base class event declarations.
```
Public Shadows Event OutputDataReceived As DataReceivedEventHandler '<----------Error 1
```
Then in your FixedOutputReadNotifyUser method, you don't need to check the event handler as you do in C# to see if it is nothing. VB will do that for you. Instead, simply raise it as follows:
```
Friend Sub FixedOutputReadNotifyUser(data As String)
Dim dataReceivedEventArgs As New DataReceivedEventArgs(data)
RaiseEvent OutputDataReceived(Me, dataReceivedEventArgs)
End Sub
```
The last issue is the original class uses case sensitivity to differentiate between the "cancelOperation" field and "CancelOperation" method. Best option is to prefix the field with an underscore as follows: `Private _CancelOperation As Boolean` and then fix the corresponding references in the class. | Below is the code I am using now. I removed the namespace as I did not know how to inlcude a second namespace in my project and pasted the code into a new Module. Then as suggested in the original c# solution i just changed my "p as new process" to "p as new FixedProcess".
Thanks again for all the suggestions!
You guys rock!
To give you a complete picture of what I am trying to do I am also including the Form Code. I am not considering myself a programmer so please bear with me if it is not as sophisticated as most of you could possible do it. The intention of this is to remote control a SSH session with plink and to automatically execute commands on Cisco Routers.
The code works quite will now with one (hopefully) little flaw left: If I close the underlying plink.exe I would like to also close the input and output streams. So far I could not find out in my "borrowed" class how to do that.
I would like to do it on the close event of the form. It kills the plink.exe process, but if I open the form again for another session, it DOUBLES the output, if i close and reopen once more it Tripples the output...
Any suggestions how to properly close the streams?
```
Imports System
Imports System.Text
Imports System.IO
Imports System.Diagnostics
Imports System.Threading
Imports System.ComponentModel
Imports Microsoft.VisualBasic
Imports System.Collections.Generic
Imports System.Linq
Imports System.Collections
Module Module2
Friend Delegate Sub UserCallBack(ByVal data As String)
Public Delegate Sub DataReceivedEventHandler(ByVal sender As Object, ByVal e As DataReceivedEventArgs)
Public Class FixedProcess
Inherits Process
Friend output As AsyncStreamReader
Friend [error] As AsyncStreamReader
Public Shadows Event OutputDataReceived As DataReceivedEventHandler
Public Shadows Event ErrorDataReceived As DataReceivedEventHandler
Public CancelAll As Boolean = False
Public Overloads Sub BeginOutputReadLine()
Dim baseStream As Stream = StandardOutput.BaseStream
Me.output = New AsyncStreamReader(Me, baseStream, New UserCallBack(AddressOf Me.FixedOutputReadNotifyUser), StandardOutput.CurrentEncoding)
Me.output.BeginReadLine()
End Sub
Public Overloads Sub BeginErrorReadLine()
Dim baseStream As Stream = StandardError.BaseStream
Me.[error] = New AsyncStreamReader(Me, baseStream, New UserCallBack(AddressOf Me.FixedErrorReadNotifyUser), StandardError.CurrentEncoding)
Me.[error].BeginReadLine()
End Sub
Friend Sub FixedOutputReadNotifyUser(ByVal data As String)
Dim dataReceivedEventArgs As New DataReceivedEventArgs(data)
RaiseEvent OutputDataReceived(Me, dataReceivedEventArgs)
End Sub
Friend Sub FixedErrorReadNotifyUser(ByVal data As String)
Dim errorDataReceivedEventArgs As New DataReceivedEventArgs(data)
RaiseEvent ErrorDataReceived(Me, errorDataReceivedEventArgs)
End Sub
End Class
Friend Class AsyncStreamReader
Implements IDisposable
Friend Const DefaultBufferSize As Integer = 1024
Private Const MinBufferSize As Integer = 128
Private stream As Stream
Private encoding As Encoding
Private decoder As Decoder
Private byteBuffer As Byte()
Private charBuffer As Char()
Private _maxCharsPerBuffer As Integer
Private process As Process
Private userCallBack As UserCallBack
Public cancelOperation As Boolean
Private eofEvent As ManualResetEvent
Private messageQueue As Queue
Private sb As StringBuilder
Private bLastCarriageReturn As Boolean
Public Overridable ReadOnly Property CurrentEncoding() As Encoding
Get
Return Me.encoding
End Get
End Property
Public Overridable ReadOnly Property BaseStream() As Stream
Get
Return Me.stream
End Get
End Property
Friend Sub New(ByVal process As Process, ByVal stream As Stream, ByVal callback As UserCallBack, ByVal encoding As Encoding)
Me.New(process, stream, callback, encoding, 1024)
End Sub
Friend Sub New(ByVal process As Process, ByVal stream As Stream, ByVal callback As UserCallBack, ByVal encoding As Encoding, ByVal bufferSize As Integer)
Me.Init(process, stream, callback, encoding, bufferSize)
Me.messageQueue = New Queue()
End Sub
Private Sub Init(ByVal process As Process, ByVal stream As Stream, ByVal callback As UserCallBack, ByVal encoding As Encoding, ByVal bufferSize As Integer)
Me.process = process
Me.stream = stream
Me.encoding = encoding
Me.userCallBack = callback
Me.decoder = encoding.GetDecoder()
If bufferSize < 128 Then
bufferSize = 128
End If
Me.byteBuffer = New Byte(bufferSize - 1) {}
Me._maxCharsPerBuffer = encoding.GetMaxCharCount(bufferSize)
Me.charBuffer = New Char(Me._maxCharsPerBuffer - 1) {}
Me.cancelOperation = False
Me.eofEvent = New ManualResetEvent(False)
Me.sb = Nothing
Me.bLastCarriageReturn = False
End Sub
Public Overridable Sub Close()
Me.Dispose(True)
End Sub
Private Sub IDisposable_Dispose() Implements IDisposable.Dispose
Me.Dispose(True)
GC.SuppressFinalize(Me)
End Sub
Protected Overridable Sub Dispose(ByVal disposing As Boolean)
If disposing AndAlso Me.stream IsNot Nothing Then
Me.stream.Close()
End If
If Me.stream IsNot Nothing Then
Me.stream = Nothing
Me.encoding = Nothing
Me.decoder = Nothing
Me.byteBuffer = Nothing
Me.charBuffer = Nothing
End If
If Me.eofEvent IsNot Nothing Then
Me.eofEvent.Close()
Me.eofEvent = Nothing
End If
End Sub
Friend Sub BeginReadLine()
If Me.cancelOperation Then
Me.cancelOperation = False
End If
If Me.sb Is Nothing Then
Me.sb = New StringBuilder(1024)
Me.stream.BeginRead(Me.byteBuffer, 0, Me.byteBuffer.Length, New AsyncCallback(AddressOf Me.ReadBuffer), Nothing)
Return
End If
Me.FlushMessageQueue()
End Sub
Friend Sub _CancelOperation()
Me.cancelOperation = True
End Sub
Private Sub ReadBuffer(ByVal ar As IAsyncResult)
Dim num As Integer
Try
num = Me.stream.EndRead(ar)
Catch generatedExceptionName As IOException
num = 0
Catch generatedExceptionName As OperationCanceledException
num = 0
End Try
If num = 0 Then
SyncLock Me.messageQueue
If Me.sb.Length <> 0 Then
Me.messageQueue.Enqueue(Me.sb.ToString())
Me.sb.Length = 0
End If
Me.messageQueue.Enqueue(Nothing)
End SyncLock
Try
Me.FlushMessageQueue()
Return
Finally
Me.eofEvent.[Set]()
End Try
End If
Dim chars As Integer = Me.decoder.GetChars(Me.byteBuffer, 0, num, Me.charBuffer, 0)
Me.sb.Append(Me.charBuffer, 0, chars)
Me.GetLinesFromStringBuilder()
Me.stream.BeginRead(Me.byteBuffer, 0, Me.byteBuffer.Length, New AsyncCallback(AddressOf Me.ReadBuffer), Nothing)
End Sub
Private Sub GetLinesFromStringBuilder()
Dim i As Integer = 0
Dim num As Integer = 0
Dim length As Integer = Me.sb.Length
If Me.bLastCarriageReturn AndAlso length > 0 AndAlso Me.sb(0) = ControlChars.Lf Then
i = 1
num = 1
Me.bLastCarriageReturn = False
End If
While i < length
Dim c As Char = Me.sb(i)
If c = ControlChars.Cr OrElse c = ControlChars.Lf Then
If c = ControlChars.Cr AndAlso i + 1 < length AndAlso Me.sb(i + 1) = ControlChars.Lf Then
i += 1
End If
Dim obj As String = Me.sb.ToString(num, i + 1 - num)
num = i + 1
SyncLock Me.messageQueue
Me.messageQueue.Enqueue(obj)
End SyncLock
End If
i += 1
End While
' Flush Fix: Send Whatever is left in the buffer
Dim endOfBuffer As String = Me.sb.ToString(num, length - num)
SyncLock Me.messageQueue
Me.messageQueue.Enqueue(endOfBuffer)
num = length
End SyncLock
' End Flush Fix
If Me.sb(length - 1) = ControlChars.Cr Then
Me.bLastCarriageReturn = True
End If
If num < length Then
Me.sb.Remove(0, num)
Else
Me.sb.Length = 0
End If
Me.FlushMessageQueue()
End Sub
Private Sub FlushMessageQueue()
While Me.messageQueue.Count > 0
SyncLock Me.messageQueue
If Me.messageQueue.Count > 0 Then
Dim data As String = DirectCast(Me.messageQueue.Dequeue(), String)
If Not Me.cancelOperation Then
Me.userCallBack(data)
End If
End If
Continue While
End SyncLock
Exit While
End While
End Sub
Friend Sub WaitUtilEOF()
If Me.eofEvent IsNot Nothing Then
Me.eofEvent.WaitOne()
Me.eofEvent.Close()
Me.eofEvent = Nothing
End If
End Sub
End Class
Public Class DataReceivedEventArgs
Inherits EventArgs
Friend _data As String
''' <summary>Gets the line of characters that was written to a redirected <see cref="T:System.Diagnostics.Process" /> output stream.</summary>
''' <returns>The line that was written by an associated <see cref="T:System.Diagnostics.Process" /> to its redirected <see cref="P:System.Diagnostics.Process.StandardOutput" /> or <see cref="P:System.Diagnostics.Process.StandardError" /> stream.</returns>
''' <filterpriority>2</filterpriority>
Public ReadOnly Property Data() As String
Get
Return Me._data
End Get
End Property
Friend Sub New(ByVal data As String)
Me._data = data
End Sub
End Class
End Module
```
and my Form Code...
```
Imports System
Imports System.Text
Imports System.IO
Imports System.Diagnostics
Imports System.Threading
Imports System.ComponentModel
Imports Microsoft.VisualBasic
Imports System.Collections.Generic
Imports System.Linq
Imports System.Collections
Public Class Form3
' Define static variables shared by class methods.
Private Shared shellOutput As StringBuilder = Nothing
Private Shared numOutputLines As Integer = 0
Private Shared stdIN As StreamWriter
Private Shared p As New FixedProcess 'as new
Private Shared oldOutlineData As String = ""
Private Shared PasswordInput As Boolean = False
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
ShowISDNStatus()
End Sub
Public Sub ShowISDNStatus()
Dim p_info As New ProcessStartInfo 'as new
p_info.FileName = Form1.PlinkPath
p_info.Arguments = Form1.KommandoArguments
p_info.UseShellExecute = False
p_info.CreateNoWindow = True
p_info.RedirectStandardOutput = True
p_info.RedirectStandardInput = True
p_info.RedirectStandardError = True
' Set our event handler to asynchronously read the shell output.
AddHandler p.OutputDataReceived, AddressOf dirOutputHandler
AddHandler p.ErrorDataReceived, AddressOf dirOutputHandler
shellOutput = New StringBuilder
p.StartInfo = p_info
p.Start()
p.BeginOutputReadLine()
p.BeginErrorReadLine()
stdIN = p.StandardInput
'stdIN.WriteLine("enable" & vbCr & "K#limdor1" & vbCrLf)
'Timer1.Enabled = True
'System.Threading.Thread.Sleep(500)
'stdIN.WriteLine("term len 0")
'stdIN.WriteLine("show isdn status")
stdIN.WriteLine("enable" & vbCr & Form1.TextPassword.Text & vbCrLf)
Timer1.Enabled = True
System.Threading.Thread.Sleep(500)
Me.TextBox2.Text = ""
stdIN.WriteLine("term len 0")
stdIN.WriteLine("show isdn status")
Me.TextBox1.Select(TextBox1.Text.Length, 0)
Me.TextBox1.ScrollToCaret()
End Sub
Private Shared Sub dirOutputHandler(ByVal sendingProcess As Object, ByVal outLine As DataReceivedEventArgs)
''If Not String.IsNullOrEmpty(outLine.Data) Then
shellOutput.Append(outLine.Data)
'For i = 1 To Len(outLine.Data)
' FormDebug.TextBox1.Text = "Len von OutlineData: " & Len(outLine.Data) & " " & Asc(Mid(outLine.Data, i, 1)) & "---" & Mid(outLine.Data, i, 1)
'Next
If outLine.Data = "Store key in cache? (y/n) " Then
stdIN.WriteLine("y")
End If
Form3.TextBox1.Text = outLine.Data
''End If
End Sub
Private Sub Form3_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
End Sub
Private Sub Form3_Closing(ByVal sender As Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles MyBase.Closing
p.Kill()
End Sub
Private Sub TextBox2_PreviewKeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.PreviewKeyDownEventArgs) Handles TextBox2.PreviewKeyDown
If e.KeyCode = Keys.Return Then
If PasswordInput = False Then
If Me.TextBox2.Text = "en" Then
Me.TextBox2.UseSystemPasswordChar = True
Me.TextBox2.Text = ""
PasswordInput = True
Timer1.Enabled = False
Me.TextBox1.AppendText("Password:")
ElseIf Me.TextBox2.Text = "ena" Then
Me.TextBox2.UseSystemPasswordChar = True
Me.TextBox2.Text = ""
PasswordInput = True
Timer1.Enabled = False
Me.TextBox1.AppendText("Password:")
ElseIf Me.TextBox2.Text = "enab" Then
Me.TextBox2.UseSystemPasswordChar = True
Me.TextBox2.Text = ""
PasswordInput = True
Timer1.Enabled = False
Me.TextBox1.AppendText("Password:")
ElseIf Me.TextBox2.Text = "enabl" Then
Me.TextBox2.UseSystemPasswordChar = True
Me.TextBox2.Text = ""
PasswordInput = True
Timer1.Enabled = False
Me.TextBox1.AppendText("Password:")
ElseIf Me.TextBox2.Text = "enable" Then
Me.TextBox2.UseSystemPasswordChar = True
Me.TextBox2.Text = ""
PasswordInput = True
Timer1.Enabled = False
Me.TextBox1.AppendText("Password:")
ElseIf Me.TextBox2.Text = "" Then
stdIN.WriteLine()
System.Threading.Thread.Sleep(500)
Me.TextBox1.Select(TextBox1.Text.Length, 0)
Me.TextBox1.ScrollToCaret()
Else
stdIN.WriteLine(Me.TextBox2.Text)
System.Threading.Thread.Sleep(500)
Me.TextBox2.Text = ""
Me.TextBox1.Text = shellOutput.ToString
Me.TextBox1.Select(TextBox1.Text.Length, 0)
Me.TextBox1.ScrollToCaret()
End If
Else
stdIN.WriteLine("enable" & vbCr & Me.TextBox2.Text & vbCrLf)
System.Threading.Thread.Sleep(500)
Me.TextBox2.Text = ""
Timer1.Enabled = True
Me.TextBox2.UseSystemPasswordChar = False
stdIN.WriteLine("term len 0")
Me.TextBox1.Select(TextBox1.Text.Length, 0)
Me.TextBox1.ScrollToCaret()
PasswordInput = False
End If
End If
End Sub
Private Sub TextBox2_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox2.TextChanged
End Sub
Private Sub TextBox1_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox1.TextChanged
Me.TextBox1.SelectAll()
Me.TextBox1.ScrollToCaret()
End Sub
Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
' If Me.TextBox1.Text <> shellOutput.ToString Then Me.TextBox1.Text = shellOutput.ToString
Me.TextBox1.Text = shellOutput.ToString
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
FormDebug.Show()
'Dim frm As New Form3
'Static Num As Integer
'Num = Num + 1
'frm.Text = "Copy of Form3 - " & Num
'frm.Show()
End Sub
End Class
``` |
9,153,102 | Ok this has really got me confused.
This query returns the expected results albeit with duplicate car\_id numbers
```
SELECT car_id FROM `Updates` ORDER BY `updates`.`created` DESC
```
These 2 queries return the same set of results:
```
SELECT distinct `Updates`.`car_id` FROM `Updates` ORDER BY `updates`.`created` DESC
SELECT car_id FROM `Updates` GROUP BY car_id ORDER BY `updates`.`created` DESC
```
See below though as to how they differ:
 | 2012/02/05 | [
"https://Stackoverflow.com/questions/9153102",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/222285/"
] | You're ordering by `updates.created`. Presumably this means that each distinct `carid` will come up, just not exactly where you expect it to. Try ordering by `carid` to perform the comparison. | Would Something Like This Work:
SELECT \* FROM Updates GROUP BY car\_id ORDER BY created DESC |
9,153,102 | Ok this has really got me confused.
This query returns the expected results albeit with duplicate car\_id numbers
```
SELECT car_id FROM `Updates` ORDER BY `updates`.`created` DESC
```
These 2 queries return the same set of results:
```
SELECT distinct `Updates`.`car_id` FROM `Updates` ORDER BY `updates`.`created` DESC
SELECT car_id FROM `Updates` GROUP BY car_id ORDER BY `updates`.`created` DESC
```
See below though as to how they differ:
 | 2012/02/05 | [
"https://Stackoverflow.com/questions/9153102",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/222285/"
] | I don't think that this is strictly relevant with your problem but:
```
SELECT DISTINCT car_id
FROM Updates
ORDER BY created DESC
```
is not valid standard SQL syntax. There may be many rows with same `car_id` and different `created` values. Which one should be used for the ordering?
Perhaps you want to rewrite the query so it returns meaningful results:
```
SELECT car_id
FROM Updates
GROUP BY car_id
ORDER BY MAX(created) DESC --- or MIN(created)
-- whatever suits you
``` | You're ordering by `updates.created`. Presumably this means that each distinct `carid` will come up, just not exactly where you expect it to. Try ordering by `carid` to perform the comparison. |
9,153,102 | Ok this has really got me confused.
This query returns the expected results albeit with duplicate car\_id numbers
```
SELECT car_id FROM `Updates` ORDER BY `updates`.`created` DESC
```
These 2 queries return the same set of results:
```
SELECT distinct `Updates`.`car_id` FROM `Updates` ORDER BY `updates`.`created` DESC
SELECT car_id FROM `Updates` GROUP BY car_id ORDER BY `updates`.`created` DESC
```
See below though as to how they differ:
 | 2012/02/05 | [
"https://Stackoverflow.com/questions/9153102",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/222285/"
] | I don't think that this is strictly relevant with your problem but:
```
SELECT DISTINCT car_id
FROM Updates
ORDER BY created DESC
```
is not valid standard SQL syntax. There may be many rows with same `car_id` and different `created` values. Which one should be used for the ordering?
Perhaps you want to rewrite the query so it returns meaningful results:
```
SELECT car_id
FROM Updates
GROUP BY car_id
ORDER BY MAX(created) DESC --- or MIN(created)
-- whatever suits you
``` | Would Something Like This Work:
SELECT \* FROM Updates GROUP BY car\_id ORDER BY created DESC |
22,847,865 | Please consider the following statement:
```
var matches = person.Contacts.Where(c => c.ContactType == searchContact.ContactType).ToList();
```
This will filter all the records with matching ContactType of searchContact object and returns only the filtered Contacts of person.
But without ToList() method call at the end of the Where clause, it will return all the Contacts of person.
Now, consider the following code segment.
```
Dictionary<int, string> colors = new Dictionary<int, string>(){ {1, "red"}, {2, "blue"}, {3, "green"}, {4, "yellow"}, {5, "red"}, {6, "blue"}, {7, "red"} };
var colorSet = colors.Where(c => c.Value == "red");
```
This query will filter only the elements with value "red", even without calling ToList() method.
My question is why this two statements (one that compares values and one that compares properties) behave in a different way without ToList() method call?
Why this problem does not occur with FirstOrDefault instead of Where clause?
I really appreciate, if anyone can explain the scenario or post some references that I can follow.
Thanks!! | 2014/04/03 | [
"https://Stackoverflow.com/questions/22847865",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1710097/"
] | >
> But without ToList() method call at the end of the Where clause, it will return all the Contacts of person.
>
>
>
No, without `ToList` it will return a query which, when iterated, will yield all of the contacts matching the value you specified to filter on. Calling `ToList` only materializes that query into the results of that query. Waiting a while and iterating it later, possibly using some other method of iteration such as `foreach`, will only change the results if the underlying data source (in this case, a database, by the look of thigns) changes its data.
As to your dictionary filter, the same thing applies. Without calling `ToList` the variable represents *a query to get the data when asked*, not *the results of that query*, which is what you would get by calling `ToList`.
The use of a property versus a field is irrelevant here. Having said *that*, both queries are using properties, not fields. Even if one did use a field though, it wouldn't change a thing. | >
> But without ToList() method call at the end of the Where clause, it will return all the Contacts of person.
>
>
>
You are wrong.`ToList` is just forces the iteration and gives you your *filtered elements* as a `List`.`LINQ` uses deferred execution which means until you use `foreach` loop to iterate over items or use `ToList` or `ToArray` methods, it's not executed.So `ToList` doesn't change your items. `Value` is also a property (see `KeyValuePair<T,K>` class), so you are performing a comparison based on property values in both query.There is no difference at all. |
22,847,865 | Please consider the following statement:
```
var matches = person.Contacts.Where(c => c.ContactType == searchContact.ContactType).ToList();
```
This will filter all the records with matching ContactType of searchContact object and returns only the filtered Contacts of person.
But without ToList() method call at the end of the Where clause, it will return all the Contacts of person.
Now, consider the following code segment.
```
Dictionary<int, string> colors = new Dictionary<int, string>(){ {1, "red"}, {2, "blue"}, {3, "green"}, {4, "yellow"}, {5, "red"}, {6, "blue"}, {7, "red"} };
var colorSet = colors.Where(c => c.Value == "red");
```
This query will filter only the elements with value "red", even without calling ToList() method.
My question is why this two statements (one that compares values and one that compares properties) behave in a different way without ToList() method call?
Why this problem does not occur with FirstOrDefault instead of Where clause?
I really appreciate, if anyone can explain the scenario or post some references that I can follow.
Thanks!! | 2014/04/03 | [
"https://Stackoverflow.com/questions/22847865",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1710097/"
] | You are mistaken. Without calling `ToList()` or another method to force immediate execution, both statements will return an `IQueryable<T>`. Until you iterate over your query variable by using a `foreach` the query variable remains just that.
This article on MSDN should explain things well: [Query Execution](http://msdn.microsoft.com/en-us/library/bb738633%28v=vs.110%29.aspx).
What you are experiencing is called **Deferred Query Execution**.
>
> In a query that returns a sequence of values, the query variable
> itself never holds the query results and only stores the query
> commands. Execution of the query is deferred until the query variable
> is iterated over in a foreach or For Each loop. This is known as
> deferred execution.
>
>
>
When you use `ToList()` what occurs is known as **Immediate Query Execution**.
>
> In contrast to the deferred execution of queries that produce a
> sequence of values, queries that return a singleton value are executed
> immediately. Some examples of singleton queries are Average, Count,
> First, and Max. These execute immediately because the query must
> produce a sequence to calculate the singleton result. You can also
> force immediate execution. This is useful when you want to cache the
> results of a query. To force immediate execution of a query that does
> not produce a singleton value, you can call the ToList method, the
> ToDictionary method, or the ToArray method on a query or query
> variable.
>
>
>
These are core behaviors of LINQ. | >
> But without ToList() method call at the end of the Where clause, it will return all the Contacts of person.
>
>
>
You are wrong.`ToList` is just forces the iteration and gives you your *filtered elements* as a `List`.`LINQ` uses deferred execution which means until you use `foreach` loop to iterate over items or use `ToList` or `ToArray` methods, it's not executed.So `ToList` doesn't change your items. `Value` is also a property (see `KeyValuePair<T,K>` class), so you are performing a comparison based on property values in both query.There is no difference at all. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.