text:
Q: What does "critical but stable" mean? I sometimes see the term "critical but stable" in the news. It is often used to describe someone who has been very seriously injured.
For example (15 December 2019): "[A police officer] said the man who had been shot was in a "critical but stable " condition in hospital."
I understand that "critically ill" means that life is in danger. Similarly "stable" is the opposite.
Quotes from www.lexico.com
critically

To an extreme degree with a risk of death.
  'two critically wounded people died in hospital'.
     'critically ill patients who were awaiting surgery'

stable

(of a patient or their medical condition) not deteriorating in health after an injury or operation.

'he is now in a stable condition in hospital'
What does "critical but stable" really mean?

A: It seems contradictory on the surface, but it really does just combine the definitions you listed. So,the patient's condition is very serious or an extreme degree of injury, but not currently deteriorating or worsening.

A: It will probably not be possible to get an authoritative answer to this question. The trouble is, although the phrase "critical but stable" is commonly used, authoritative sources suggest that a) it's illogical and b) it should not be used.
Here's what the American Hospital Association said in 2003 about patient conditions:

Condition
For the one-word condition, use the terms "undetermined," "good," "fair," "serious" or "critical." Definitions of patient conditions are listed below:
Undetermined - Patient is awaiting physician and/or assessment.
Good - Vital signs are stable and within normal limits. Patient is conscious and comfortable. Indicators are excellent.
Fair - Vital signs are stable and within normal limits. Patient is conscious, but may be uncomfortable. Indicators are favorable.
Serious - Vital signs may be unstable and not within normal limits. Patient is acutely ill. Indicators are questionable.
Critical - Vital signs are unstable and not within normal limits. Patient may be unconscious. Indicators are unfavorable.

AHA: Advisory: HIPAA Updated Guidelines for Releasing Information on the Condition of Patients. American Hospital Association.
By these standards, critical means "unstable," so "critical but stable" wouldn't seem to make sense.
The AHA guidelines continue:

Clinicians find the "critical but stable" term useful when discussing cases amongst themselves because it helps them differentiate patients who are expected to recover from those whose prognosis is worse.  But a critical condition means that at least some vital signs are unstable, so this is inherently contradictory.  The term "stable" should not be used as a condition. Furthermore, this term should not be used in combination with other conditions, which by definition, often indicate a patient is unstable.

So, the AHA acknowledges that "critical but stable" is often used to mean something like very bad, but may recover. Like you, the AHA finds this term misleading and suggests it not be used. But these are only guidelines, after all.

A: You specify British English but the only other answer with a quote is from a US source. I was curious if it was materially different in the UK.
The UK newspaper article critical and serious condition: what hospitals mean when they report a patient's state indicates it means much the same here. (the bolded part is the direct answer to your question)

Sometimes, people will include a suggestion of whether someone's
  condition is stable, improving or getting worse. A "Critical but
  stable" condition, for instance, indicates that someone is in a bad
  state but not likely to get worse in the short-term.
Others recommend against using that phrasing, however, since being in
  a critical condition implies that a patient vital signs are not
  stable.

A: You have a volume control in your radio. You can set it to a very high volume (this may bother you). This is the critical part.
If you leave the volume at this level, this is the stable part.

A: Stable and Unstable means the projected health status of an individual. It is talking about the future.
The first part (Undetermined, Good, Fair, Serious, Critical) is talking about their current status.

A: It's a common form of words.  Perhaps not to be analysed TOO closely.   I think we can agree on it meaning 'pretty bad, but unlikely to die tonight.'
Here's a couple more fun prognoses.
George Cooper was pronounced dead at the scene of the crime.  His widow described his condition as 'satisfactory'.
I asked my doctor if I was at risk of Early Onset Alzheimer's.  He replied "What do you mean, 'early'?"

A:
I understand that "critically ill" means that life is in danger.

Yes.

Similarly "stable" is the opposite.

No.
"Stable" does not mean "non-critical". It means "stable"!
A stable condition is not fluctuating/changing unpredictably. The physician believes that the patient's condition will not change unexpectedly, and therefore they can make useful predictions about what will happen next.
That stable condition can still be described as "critical"; there is no contradiction here.

A: Trying to find a meaning in these words by following a definition is the wrong approach, as critical but stable is a kind of euphemism.
Much in the same way as the wording "according to circumstances" is, depending on how it's being said, either a polite way of saying: "I have no idea!", or "I'm not going to tell you!".
Most certainly, every patient's condition is "according to circumstances" (whatever the circumstances may be!), so basically saying that is nothing but saying: "Bugger off!", only more polite, and less troubling for people who are emotinally involved. Because after all, if the situation is good according to circumstances, that's quite positive, is it not!
Similarly, when you say "critical", then that means as much as "that doesn't look good, I expect the person may die". You do not say that to either relatives or in public. You do not say that to, or nearby, the patient (awake or unconcious) either. Never, not ever. The consequences of saying such a thing may be terrible.
Thus, when you are saying such a thing, you add "but stable" which in reality means nothing more but "we're currently not desperately trying to stop this bleeding, and we're currently not reanimating".
But still, although the word "stable" has absolutely no meaning in terms of "condition will not change" (or even "condition will not change to the worse"), and usually people know very well that it is a kind of "lie", it is still very much appeasing the perceived situation for people directly involved.


text:
Q: BasicConfigurator doesn't log stack traces by default in JUnit Tests In running some JUnit tests I start with the following to set up Log4J:
BasicConfigurator.configure()
I'm then calling the following via Commons Logging:
LogFactory.getLogger(this.getClass()).fatal(exception)
This doesn't print stack traces though (only the exception message).
I need to know what steps are necessary to print stack traces via the simplified logging setup used in JUnit tests? I would prefer not to have to fully configure Log4J just for JUnit tests, but if I must, let me know.

A: This is nothing to do with the logger configurations.
Read the javadoc for the fatal(Object) method.  It says:

"WARNING Note that passing a Throwable to this method will print the name of the Throwable but no stack trace. To print a stack trace use the fatal(Object, Throwable) form instead."

If you want the logs to include a stacktrace, you must use the 2 argument version of the method.  This applies to the corresponding methods for other log levels as well.

redpajama_set_name: RedPajamaStackExchange


text:
Q: MySQL 3 insert with on duplicate key update query multiple tables not working If i execute the query below in PhpMyAdmin there is nog problem at all, but if i execute from PHP it gives errors, why?
Execute from PhP like this:
mysql_query($query_antwoorden.$query_huurtermijnen.$query_gesloten) or die (....
INSERT INTO data_prijzen_antwoorden (`ID_advertentie`,`antw_wisseldagen`,`antw_gesloten`,`antw_borg`)
VALUES (19,1,1,2)
ON DUPLICATE KEY UPDATE antw_wisseldagen = VALUES(antw_wisseldagen), antw_gesloten = VALUES(antw_gesloten), antw_borg = VALUES(antw_borg);

INSERT INTO data_huurtermijnen_wisseldagen (`ID_advertentie`,`ID_htbl_huurtermijn`,`huurtermijn_beschikbaar`,`startdag`,`starttijd`,`einddag`,`eindtijd`)
VALUES (19,1,1,'Maandag','9.00','Vrijdag','17.00'),(19,2,1,'Vrijdag','12.00','Vrijdag','10.00'),(19,3,1,'Maandag','3.00','Vrijdag','4.00'),(19,4,1,'Vrijdag','10.00','Maandag','1.00'),(19,5,1,'Vrijdag','12.00','Zondag','10.00'),(19,6,1,'dag','0.00','dag','17.00'),(19,7,1,'dag','0.00','dag','12.00'),(19,8,1,'dag','0.00','dag','17.30')
ON DUPLICATE KEY UPDATE huurtermijn_beschikbaar = VALUES(huurtermijn_beschikbaar), startdag = VALUES(startdag), starttijd = VALUES(starttijd), einddag = VALUES(einddag), eindtijd = VALUES(eindtijd);

INSERT INTO data_periodes_gesloten (`ID_advertentie`,`from_11`,`to_11`,`from_12`,`to_12`,`from_13`,`to_13`,`array_gesloten_data`)
VALUES (19,'19-12-2012','21-12-2012',NULL,NULL,NULL,NULL,'1355875200,1355961600,1356048000')
ON DUPLICATE KEY UPDATE from_11 = VALUES(from_11), to_11 = VALUES(to_11), from_12 = VALUES(from_12), to_12 = VALUES(to_12), from_13 = VALUES(from_13), to_13 = VALUES(to_13), array_gesloten_data = VALUES(array_gesloten_data);

A: you can't execute multiple queries in a single query call in PHP. It's an anti-sql injection defense mechanism.
You'll have to do 3 separate ->query() calls.


text:
Q: Create raster surface from points with barrier I have a point layer, that represents an elevation in that given point. This I need to create a raster/surface/DEM from, preferably by interpolating by Nearest Neighbour method or some way Liniar between the points. However I only need it inside my barrier which I have as a polygon and polyline layer. I'm trying to use Nearest/Natural Neighbour method with the polygon/polyline layer as processing extent, but this doesn't give the "cut" raster result I'm looking for.
I've tried converting my buffer into a raster and add that under Processing Extent Snap Raster, without getting the desired results.
I have ArcGIS Advanced 10.5.1 with Spatial and 3d Analyst.

A: I have been simulating your problem here and unfortunately I have no advanced license, but a normal one. Anyways, I got to the following workflow, which I believe will give you what you want.

*

*Create and empty raster covering your study area with the tool Create Raster Dataset. Choose your cell size wisely (I would go for the minimum distance between the points)

*Use the Point to Raster tool to extract the point values and stick them to the raster

*Create your DEM based on the algorithm you want

*Clip the raster that is in the barrier polygon

Let me know if that works!


text:
Q: Vagrant + Puppets modules is anywhere good resource for puppet modules? I need something for nginx, varnish and zend-server ce, i'm sure that would be somewhere just I cannot find it.
Thanks in advance,
Jaro.

A: Check out the puppet labs repository of modules!
http://forge.puppetlabs.com/
Hope that's what you're looking for!
Cheers,
Jake


text:
Q: Taking the last four characters of an charachter array I have
TCHAR szPIDKEY[255];//for product id
 DWORD dwLen = sizeof(szPIDKEY)/sizeof(szPIDKEY[0]); //calculating the size of the key
UINT res = MsiGetProperty(hInstall, _T("PIDKEY"), szPIDKEY, &dwLen);
if(res != ERROR_SUCCESS)
{
    //fail the installation
    return 1;
}

the key string looks like xxxx-xxxx-xxxx-xxxx, i want to take only the last four xxxx in TCHAR , how to do this?
Thanks

A:  #ifndef UNICODE
 typedef std::string String
 #else
 typedef std::wstring String
 #endif

String szKey = szPIDKEY;
size_t found = szKey.find_last_of("-");
String szFind = szKey.substr (found,4);

A: Is this really so hard?
TCHAR lastFour[5] /* 4 + 1 for null terminator */
_tcscpy(lastFour, szPIDKEY + dwLen - 4); /* copy the last four characters and
                                        null terminator */

If you want to do strings the C way, then you are going to have to learn how to do pointer manipulations like the above. szPIDKEY is an array, but it also functions as a pointer to the first element of the array, szPIDKEY + dwLen is then a pointer to the last character of the key (the null terminator). So szPIDKEY + dwLen - 4 is a pointer to four characters before that.
Untested code.

A: TCHAR is nothing else but a char if UNICODE is not defined and wchar if it is defined. So if you want to take the last 4 symbols you may treat is as you would have treated these types.
So maybe you should do something like:
#ifdef UNICODE
#include <wchar.h>
int get_len(TCHAR[] val) {
  return wcslen(val);
}
#else
#include <cstring>
int get_len(TCHAR[] val) {
  return strlen(val);
}
#endif

EDIT: In fact there is a function already defined in windows that does what I described above and it is _tcslen (thanks to jajjaj for this one). However I decided to leave the code above so that you get the idea what it does.
And then using the function above you have the last 4 characters stored in

szPIDKEY[_tcslen(szPIDKEY-4)], ...szPIDKEY[_tcslen(szPIDKEY-1)]

Hope this helps.


text:
Q: Is it possible to install Node.js and NPM on Ubuntu Core? I would like to know if Node.js is available in Ubuntu Core and if yes, how I can install it.
I see this issue Node on Snappy Ubuntu, but it says nothing.
Thank you very much.

A: This worked for me.
I used the info here: Install applications in Ubuntu core

sudo snap install classic --devmode --edge

then

sudo classic

To enable aptitude, then your normal:

sudo apt-get install nodejs nodejs-legacy npm
sudo npm i -g npm

To get NPM to version: 3.5.2 and Node to: 4.2.6
Then NPM can't be updated further this way, as it complains about the version of Node that breaks NPM. Normally to update NPM I'd use 'n':

sudo npm i -g n
sudo n stable

But as NPM doesn't work with this version of Node that's not happening.
I found this How can I update my nodeJS to the latest version? and used:

sudo apt-get install curl
curl -sL https://deb.nodesource.com/setup_8.x | sudo -E bash -
sudo apt-get install -y nodejs

Now Node version is: 8.9.4, and NPM can once again be updated as usual; and you can also use NPM to install 'n' and update Node however you want if you need a specific version.
Then you can install git to clone your app or do whatever.
You've probably already solved your problem, but offering a possible solution in case anyone else is after one.

A: If you need Nodejs for your application, convert your application to snap (with snapcraft) and install it snap install <your application> . Nodejs is then packaged in the snap and you do not need to extra install it. Otherwise may be Ubuntu Server is better suited for you.


text:
Q: Javafx Apply CSS to element of Custom-Menu-Item I have a context menu with a single custom-menu-item. The custom-menu-item consists of a pane which in turns holds a vbox.
My goal is to get rid of the blue highlighting. I have successfully got rid of blue highlighting with the context-menu. But cannot access the layer below it (the pane or vbox). The context menu has been assigned .context as a class name.
FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("/resources/fxml/ThePane.fxml"));
Pane pane = (Pane) fxmlLoader.load();
customMenuItem = new CustomMenuItem(pane);

.context .custom-menu-item:focused{
    -fx-background-color:white;
}

.context .custom-menu-item{
    -fx-background-color:white;
}


text:
Q: how to send response immediately from rest api when it triggers a job in the backend? I need to trigger a job using the api, I dont want the api give response only after the completion of job, would like to respond back with "your job has been created" and let the job run in the backend and complete after couple of minutes.
As am newbie to jaxrs, I couldn't able to find solution to this problem. All i can see is send a 201 response. yes but how?
Below is the code am using :
@Path("{triggerjob}")
public Response ClassA {
ClassB objB = new ClassB();
objB.methodOne(jsonObject);
//what to do for response message as soon as job submitted?
return Response.status(201).build();
}

public void Class B {
ClassC objC = new ClassC();
objC.methodOne(jsonObject); //This triggers the job and job runs for 1/2 hour
}

So the classB will be return to Class A only after the job is completed, I would like to the user to know that the job is triggered and will be completed after half hour.
How to achieve this? How to jump to return statement and provide the update to the user who triggered this job?

A: You should run your job in async way.
For example via EJB @Asynchronous
@Stateless
public class B  {
    @Asynchronous
    public void doAsynchronousWork() {

    }
}

By the way for the http response the best response code here would be  202 accepted


text:
Q: I need help showing the following integral evaluates to $0$. The integral is: $$\int_0^{2\pi}\sum_{n=1}^{N}a_n \sin (nt)\cos(n\xi) \sum_{n=1}^{N} a_n\sin(n\xi)\cos(n\tau) \, d\xi$$

A: Hint: Exchange the order of summation and use the product-to-sum formula:
$$ \sin \alpha \cos \beta = \frac{1}{2} (\sin (\alpha + \beta) + \sin(\alpha - \beta))
$$

A: It suffices to remark that
$$\int_0^{2\pi}\cos(n\xi)\sin(m\xi)\>d\xi=\int_{-\pi}^\pi\cos(n\xi)\sin(m\xi)\>d\xi=0\ ,$$
since the  integrand is an odd function of $\xi$.

A: Starting form your expression
$$\int_0^{2\pi}\sum_{n=1}^{N}a_n \sin (nt)\cos(n\xi) \sum_{m=1}^{N} a_m\sin(m\xi)\cos(m\tau) \, d\xi$$
You can exchange integration with the sums
$$\sum_{n=1}^{N}a_n \sin (nt)\sum_{m=1}^{N}a_m \cos(m\tau)\int_0^{2\pi}\cos(n\xi) \sin(m\xi) \, d\xi$$
Now, you can demonstrate that the integral is $0$, for any value of $n$ and $m$ (I suppose they are integer, Am I right?). For demonstrating this fact, you can use the symmetric properties of the sine and cosine (one is odd and the other is even).
For computing the last integral, you can use the expresions for the sine of the sum of angles, finding
$$\cos(nx)\sin(mx)=\left[\sin\left((n-m)x\right)+\sin\left((n+m)x\right)\right]$$
Now, you can easily prove that
$$\int_{0}^{2\pi}dx \sin(kx)=0,\quad\forall n\in\mathbb{Z}$$
And, hence, your original expresion is zero

A: $$
\int_0^{2\pi}\sum_{i=1}^{N}a_i \sin (it)\cos(i\xi) \sum_{j=1}^{N} a_j\sin(j\xi)\cos(j\tau) \, d\xi
$$
$$
\sum_{i=1}^{N}a_i \sin (it) \sum_{j=1}^{N} a_j\int_0^{2\pi}\sin(j\xi)\cos(i\xi)\cos(j\tau) \, d\xi
$$
$$
\sum_{i=1}^{N}a_i \sin (it) \sum_{j=1}^{N} a_j\cos(j\tau)\int_0^{2\pi}\frac{1}{2}(\sin((i+j)\xi) + \sin((j-i)\xi))\, d\xi
$$
$$
\int_0^{2\pi}(\sin((i+j)\xi) + \sin((j-i)\xi))\, d\xi = -\frac{1}{i+j}[\cos((i+j)2\pi) - \cos(0)] - \frac{1}{j-i}[\cos((j-i)2\pi) - \cos(0)] = 0
$$
(since $i,j \in \mathbb{Z}$ )
when $i = j$:
one has:
$$
\frac{1}{2}\int_0^{2\pi}2\sin(i\xi)\cos(i\xi) \, d\xi  = \frac{1}{2}\int_0^{2\pi }\sin(2 i\xi) \, d\xi  = -\frac{1}{4i} [\cos(4\pi i) - cos(0)] = 0
$$
$$
\sum_{i=1}^{N}a_i \sin (it) \sum_{j=1}^{N} a_j\cos(j\tau)\int_0^{2\pi}\frac{1}{2}(\sin((i+j)\xi) + \sin((j-i)\xi))\, d\xi = \\
\sum_{i=1}^{N}a_i \sin (it) \sum_{j=1}^{N} a_j\cos(j\tau) \times 0 = 0
$$


text:
Q: Jest simulate not showing text on textbox Here is my test script to test 'SearchBox' component using Jest/Enzyme -
   test('searchbox input!',()=>{
const wrapper=global.mount(<SearchBox  onTextChangedFunc={dummyFunction}></SearchBox>)
const textBox=wrapper.find('#inputText')
textBox.simulate('change',{target:{value:'p12346997'}})
wrapper.update();
console.log(wrapper.debug());
})

Here is the dummyFunction -
function dummyFunction(e)
{
}

I can not figure out why the console.log at the last line does not show the updated text. This is what I am getting on the console -
 <SearchBox onTextChangedFunc={[Function: dummyFunction]}>
<div className="textBoxContainer" style={{...}}>
  <input id="inputText" className="customTextbox" required={true} onChange={[Function: dummyFunction]} onBlur={[undefined]} />
  <label className="lbl" name="placeholder_label" onClick={[Function: bound labelClicked]} />
  <label id="inputError" className="err" />
</div>

I was expecting to see the text 'p12346997' on the console log as a value for the input (with id "inputText").
Please let me know if I can give more details.

A: You are binding it to an empty function, what you can do here is that you can simply
expect(dummyFunction).toHaveBeenCalled();

The reason for that is, that I guess you have attribute value={this.state.customTextBox}, that updates the value in state and then binds it to input. So in order to see that I would suggest to ways. You either expect that dummyFunction to have been called with that object
const dummyFunction = jest.fn();

expect(dummyFunction).toHaveBeenCalledWith({target:{value:'p12346997'}});

or if you are binding the value with the state, simply check if the object in state has that value:
 expect(wrapper.state().myInput).toBe('p12346997');


text:
Q: Beginner C# programming, fill array with user input but not using for loop Fill array with user input but not using for loop, because the user need to select when to enter the data.
for loop will not be useful here because I'm not trying to let the user enter all the input at once, but when the user chooses to via switch statement.
I don't know if this makes any sense, new here, excuse my unprofessional language.
static void AddChemical(string[] ChemicalName, string[] Supplier, int[] YearPurchased, int[] Toxicty, int[] Flammability, int[] Corrosiveness, int[] Explosive, int[] Harmful, int[] Overall, float[] Quantity, float[] Cost)
{
    int Count = 0;
    Count = Count + 1;

    Console.Write("Enter the name of the Chemical: ");
    ChemicalName[Count] = Console.ReadLine();

    Console.Write("Enter the year it was Purchased: ");
    int.TryParse(Console.ReadLine(), out YearPurchased[Count]);

    Console.Write("Enter the Supplier of the Chemical: ");
    Supplier[Count] = Console.ReadLine();

    Console.Write("Enter the Quantity of the Chemical in (L/Kg): ");
    float.TryParse(Console.ReadLine(), out Quantity[Count]);

    Console.Write("Enter the cost of the Chemical: ");
    float.TryParse(Console.ReadLine(), out Cost[Count]);

    Console.Write("Enter the Toxicty of the Chemical: ");
    int.TryParse(Console.ReadLine(), out Toxicty[Count]);

    Console.Write("Enter the Flammability of the Chemical: ");
    int.TryParse(Console.ReadLine(), out Flammability[Count]);

    Console.Write("Enter the Corrosiveness of the chemical: ");
    int.TryParse(Console.ReadLine(), out Corrosiveness[Count]);

    Console.Write("Enter the Explosive of the Chemical: ");
    int.TryParse(Console.ReadLine(), out Explosive[Count]);

    Console.Write("Enter the Harmful of the Chemical: ");
    int.TryParse(Console.ReadLine(), out Harmful[Count]);
}

This method is inside a switch statement.

A: I Really Have no idea what you are trying to do, but if you are talking about entering all the inputs into a array but not in the same time you can use collections.
first you need to use the nampspace
using System.Collections
Then Create a new Collection that holds on your results
ArrayList dataHolder = new ArrayList();

Then Whenever you need to add Something to it just type this code
dataHolder.Add("We are adding a string");
dataHolder.Add(21) // Adding a Number

and you can get them letter by index
Console.WriteLine(dataHolder[1]); // Outputs 21

BTW this is really non-efficient way of writing the code but i am just helping you out ;)


text:
Q: How to get back to the application which escapes control? Scenario :
"My application may escape control during UI automation to another application like the browser etc"
Solution :
"I want to get back to my application which I am automating after it loses control and moves to another app so that I can proceed with my automation"
Tried :
I can figure out if an application escapes control by checking the bundle id's after each action so that if the actual and current bundle id's differ I get to know that my application lost control.
I am blocked on how to proceed further in getting back to my application in case it moves out of control
Thank you for your time and effort in going through till the end  :)

A: This is a limitation of the "sandbox" in iOS -- once your app loses focus, UIAutomation must terminate as well.  You will need to launch another instruments session to automate the browser (or whatever application you're switching to).
See this question for some information on launching an automation session against those apps.


text:
Q: Multiline label in asp.net I want to use a multiline label but as the control is browser dependent, even on setting the height, width and wrap properties of the label control I am unable to display multiline text It doesn't support every browser in the same way.

A: Labels are single line by default.
But if you want to display multiple lines in a text box, then there is one option that might work.
I could not get autowrap to work, but if you want specific line breaks to occur, then
label.text = string1 + "
" + string2 + "
" + string3;

It may seem simple, but the C# Environment.Newline did not work in aspx.
Only rendering the
 worked for me.

A: If you mean asp:Label then it resolves to a span element in HTML output. It is neither single-line or multiline.
Define some fixed width for this element and the text will wrap into several lines when it's long enough.
<asp:Label runat="server" style="width:300px;">

A: You can concatenate the string in asp:label with "
" because it will result in html.
For Example:
label1.Text = strSample1 & "
" & strSample2

If you don't specific the width of label, it will auto expand the width to fit your string.

A: width ="...px"  style="word-wrap:normal; "

If you want to break last word if it exceeds width then style="word-wrap:break-word; "
You can use  max-width:...px; on style tag for being sure word wrapping if you change width programmaticaly.

A: You can solve it with "maximunsize" and "autosize" label properties and your problem is solved:
<asp:Label runat="server" style="width:300px;" maximunsize="300px" autosize="true">


text:
Q: Convert ByteBuffer to byte array java Does anyone know how to convert ByteBuffer to byte[] array? I need to get byte array from my ByteBuffer. When I run bytebuffer.hasArray() it returns no. Every question I looked so far is converting byte array to byteBuffer, but I need it other way around.
Thank you.

A: If hasArray() reports false then, calling array() will throw an exception.
In that case, the only way to get the data in a byte[] is to allocate a byte[] and copy the bytes to the byte[] using get(byte[]) or similar.

A: ByteBuffer exposes the bulk get(byte[]) method which transfers bytes from the buffer into the array. You'll need to instantiate an array of length equal to the number of remaining bytes in the buffer.
ByteBuffer buf = ...
byte[] arr = new byte[buf.remaining()];
buf.get(arr);


text:
Q: Applying a show/hide class div to every div with different content This is probably a simple question but after trying a few methods i need some advice.
I have some divs that when you hover over them, will show another div (acting like a tooltip) with different content for each div. The jsFiddle i have provided shows an example of it on the red div. What i am trying to achieve through jQuery is when you hover over any other div show that divs content.
At the moment, i have 2 divs (blue and red) and can only get it to work with the red with the jQuery provided. How would this work for multiple divs?
I would have easily used a tooltip plugin however i am using this example in anther plugin and they conflict very bad with tooltips inside the slider.
http://jsfiddle.net/DeRx8/1/
 $('.red').hover(function () {
        $(".tooltip").fadeIn(250);
    }, function () {
        $(".tooltip").fadeOut(250);
    });

If anyone can guide me where to start that would be great.
Thanks
PS * I am going to have over 10 divs red, bluc, pink, green ect..

A: With multiple selector
$(document).ready(function () {
    $('.red, .blue').hover(function () {
        $(".tooltip").fadeIn(250);
    }, function () {
        $(".tooltip").fadeOut(250);
    });
});

Demo Fiddle

A: you can do
$(document).ready(function () {
$('.red,.blue').hover(function () {
    $(this).next(".tooltip").fadeIn(250);
}, function () {
    $(this).next(".tooltip").fadeOut(250);
});
});

http://jsfiddle.net/DeRx8/3/
UPDATE
$(document).ready(function () {
$('.red,.blue').hover(function () {
    var left=$(this).offset().left+$(this).width()-40;
    $(this).next(".tooltip").css("left",left).fadeIn(250);
}, function () {
    $(this).next(".tooltip").fadeOut(250);
});
});

position .tooltip
http://jsfiddle.net/DeRx8/5/

A: You can do this
$(document).ready(function () {
    $('.red,.blue').hover(function () {
        $(this).next(".tooltip").fadeToggle(250);
    });
});

http://jsfiddle.net/Sq5nP/
If you want to position the tooltip via css you can use the + adjacent selector if your tooltip will always be the next sibling
.red+.tooltip {
    display:none;
    background-color:#993;
    width:50px;
    height:50px;
    position:absolute;
    right:60px;
    top:40px;
}
.blue+.tooltip {
    display:none;
    background-color:blue;
    width:50px;
    height:50px;
    position:absolute;
    right:170px;
    top:10px;
}

http://jsfiddle.net/yyrp7/


text:
Q: Minified React error #31 with sharepoint online using React + redux I'm facing an error that has been searching by myself for 2 days. But currently It's still not resolved, so I came here to ask If anyone ever faced this?
I'm using Redux toolkit in a sharepoint online project for passing data to each other components.
The first component worked perfectly, but when I use useSelector function for the 2nd one, this error appears
Although when I tried using console.log for each component, both are still receiving the data but
using data for the 2nd component will happen this error.
So has anyone ever faced this please help me out~, here is my codes
slice:
import { createSlice } from '@reduxjs/toolkit';

export interface titleState {
  title: string;
}

const initialState: titleState = {
  title : 'Your title'
};

export const titleSlice = createSlice({
  name: 'title',
  initialState,
  reducers: {
    SET_TITLE: (state, action) => {
      state.title = action.payload;
    }
  }
});

export const { SET_TITLE } = titleSlice.actions;

export default titleSlice.reducer;

store
import { configureStore } from '@reduxjs/toolkit';
import titleReducer from "../features/titleSlice/titleSlice";
export const store: any = configureStore({
  reducer: {
    title: titleReducer
  },
});

export type RootState = ReturnType<typeof store.getState>;
export type AppDispatch = typeof store.dispatch;

first component:
import { useSelector, useDispatch } from "react-redux";
import { AppDispatch, RootState } from "../../../../redux/store/store";

const FirstComponent: FunctionComponent<FirstComponent> = (
  props
) => {
  const STATE_TITLE = useSelector((state: RootState) => state.title);
  console.log(STATE_TITLE);
  const dispatch = useDispatch<AppDispatch>();
const handleTitle = (e) => {
    dispatch(SET_TITLE(e.target.value));
    setTitle(e.target.value);
  }
return (

   <textarea
     onChange={handleTitle} //works fine
   />

}

second component:
import { useSelector, useDispatch } from "react-redux";
import { AppDispatch, RootState } from "../../../../redux/store/store";
const SecondComponent: FunctionComponent<ISecondComponentProps> = (props) => {
  const TITLE_STATE = useSelector((state: RootState) => state.title)
  console.log(TITLE_STATE)
return (

   {YOUR_TITLE} //this line happens error

)

and here is the error from development tab :

A: The error happens because your TITLE_STATE is an object and not a string. Try changing the return statement of the second component to

   {TITLE_STATE?.title}

If this works, the error was because you were trying to render objects directly. And investigate why your textarea component returns an object instead of string as value, since that is the root cause here


text:
Q: Как определить кнопку какого пункта ListView мы нажали? Как определить кнопку какого пункта ListView мы нажали?
В каждом пункте списка есть TextView и 2 кнопки. Вторая из них Удалить. по её нажатию нужно удалить пункт списка...
protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        data = new ArrayList<Map<String, Object>>(
                names.length);
        Map<String, Object> m;
        for (int i = 0; i < names.length; i++) {
            m = new HashMap<String, Object>();
            m.put(ATTRIBUTE_NAME_TEXT, names[i]);
            m.put(ATTRIBUTE_NAME_BUTTON, button[i]);
            m.put(ATTRIBUTE_NAME_BUTTON2, button2[0]);
            data.add(m);
        }
        String[] from = { ATTRIBUTE_NAME_TEXT, ATTRIBUTE_NAME_BUTTON,
                ATTRIBUTE_NAME_BUTTON2 };
        // массив ID View-компонентов, в которые будут вставлять данные
        int[] to = { R.id.text1, R.id.btn1, R.id.btn2 };
        SimpleAdapter sAdapter = new SimpleAdapter(this, data, R.layout.my_list_item,
                from, to);
        lvMain = (ListView) findViewById(R.id.lvMain);
        lvMain.setAdapter(sAdapter);

    }

То есть надо написать метод :
 public void onButtonClick(View v){
       ????  a = ???
        data.remove(a.position);
    }

A: Разобрался уже:
public void onButtonClick(View v) {
    final int postion = lvMain.getPositionForView(v);
    data.remove(postion);
    sAdapter.notifyDataSetChanged();
}


text:
Q: Creating operating system (OS) user in Oracle LINUX I am a user with sudo access. To install MySQL, I have to create an operating system (OS) user  called MySQL. Can I create a user which also has sudo access on this machine?

A: The documented way to create the mysql account is:
groupadd mysql
useradd -r -g mysql mysql

Add the -m option if you want that account to be used as a login account, which looks to be the case.
If you have full sudo access, you can grant sudo rights to that use with using
sudo visudo

and adding a line similar the one starting with your username and replacing your username with mysql.


text:
Q: update query is updating every new value and removing previously updated values from DB I am trying to update some table row values in PHP. While updating query works fine but it is updating only new values when I am hitting submit. But the old already stored same column values are removing. What can I do now?
This is my code:
 if((isset($row['rdocket'])) && ($row['rdocket'] != NULL)){
echo "<td> <input pattern='.{9}' class='c-font-sm' value='$row[rdocket]' readonly></input> </td>";
}
else
{
echo "<td> <input pattern='.{9}' id='test' class='c-font-sm' value='$row[rdocket]' name='p_$row[id]'></input> </td>";
}

Update-file.php
$Quantity1=$_POST['p_'.$row['id']. ''];

     $id=$row['id'];
     $store=$row['rstore'];
     echo $store;

            foreach ($_POST as $key => $value)
            {

            echo $key;

            echo $value;

            }

     $query="update product_details SET rdocket='$Quantity1' WHERE id='$id'";
     if(mysqli_query($link, $query))
      {

      }
     else
       {
    echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
        }
     }

A: Solved:
if(!empty($quantity1)){ $query="update product_details SET rdocket='$Quantity1' WHERE id='$id'"; if(mysqli_query($link, $query)) { } else { echo "ERROR: Could not able to execute $sql. " . mysqli_error($link); } } }


text:
Q: Buck with input feedback? I made a ZCS buck converter for the following specifications:
12 V to 5 V, 50W, 200 kHz switching frequency.
But in reality, the source might not be 12 V always, and may have fluctuations. Is there any way to address this problem? Something like sensing the input voltage and adding associated control (I know it is the output that is "fed back" to get the required output)? Initially I thought this could be addressed by current-mode control, but I am not sure it pertains to the fluctuating source issue.

A: The closed control loop for the output voltage handles that. Adding another control loop which works on the same target will not improve anything but create a very near pole and the system may hop from one stability region to the other at random and thus, become meta-instable.
You need enough inductivity headroom to handle the largest voltage spread. That's all.


text:
Q: Remove an event listener from a draggable component I am working with ES6 components in React and making a simple slider component.  On my mousedown event, I am adding a listener for mousemove as a handler for onDrag isn't quite responsive enough. I am trying to remove the mousemove listener on mouseup as that means the user is done dragging on the slider. However, I can't get my event listener off, and it keeps firing the onDrag function (will log "I still execute"). Am I missing something obvious? I tried passing a named function like other answers suggested, but it still fires.
ES6 code:
import React from 'react';

class PriceSlider extends React.Component {
  constructor(props, context) {
    super(props, context);
    this.state = {positionX: 0, offset: null, dragging: null}
  }
  _onDrag(e) {
    console.log("i still execute")
    if(e.clientX > 0) {
      this.setState({positionX: e.clientX});
    }
  }
  _removeDragHandlers() {
    let node = React.findDOMNode(this.refs.circle1);
    node.removeEventListener("mousemove", this._onDrag.bind(this), false);
    return;
  }
  _addDragHandlers() {
    let node = React.findDOMNode(this.refs.circle1);
    node.addEventListener("mousemove", this._onDrag.bind(this), false);
    return;
  }
  componentDidMount() {
    this.setState({offset: this.refs.circle1.getDOMNode().getBoundingClientRect().left })
  }
  _onMouseDown(e) {
    this._addDragHandlers();
  }
  _onMouseUp(e){
    this._removeDragHandlers();
  }
  render() {
    let circle1Style = {left: this.state.positionX - this.state.offset}

    if(this.state.positionX === 0) {
      circle1Style = {left: this.state.positionX}
    }

    return(

        Low

        High

    )
  }
}

With a named function, I tried doing something like:
node.addEventListener("mousemove", function onDrag() {
  if(!this.state.dragging)  {
    node.removeEventListener("mousemove", onDrag, false)
  }
})

To no avail.  Any help or suggestions on improving this are much appreciated. I do not have jQuery or other Javascript libraries included, and need to solve this without the help of a plugin or library.

A: this._onDrag.bind(this) returns a new function every time - so you add and then try to remove different functions. You need to do it once and then refer to the same function every time:
constructor(props, context) {
    …
    this._onDrag = this._onDrag.bind(this);
}
_removeDragHandlers() {
    …
    node.removeEventListener("mousemove", this._onDrag);
}
_addDragHandlers() {
    …
    node.addEventListener("mousemove", this._onDrag, false);
}


text:
Q: conditional calculation based on values from another column I have 2 tables
Table 1

Table 2

They are connected by pkg and Item. This results in the following

As you can see from the image "Item" has a mix of "BULK" & "PKG" values.
I want to create a new column that uses the cross reference to bring in new values.
The new table I want would look like this
 **ITEM**  **Value**   **BULK**  **PKG**   **NEW COLUMN**
  135          2                                 1
  136          4                                 3
  35           1          135       35           1
  36           3          136       36           3

The top 2 items on the left are the associated "BULK" values.  I want to bring in the PKG value that appears.

A: You can use the same ISBLANK conditional expression as in your other question, but use a lookup instead of just Value.
New Column =
IF(
    ISBLANK( Table1[Bulk] ),
    LOOKUPVALUE( Table1[Value], Table1[BULK], Table1[ITEM] )
    Table1[Value]
)

Note that this will throw an error if you have multiple BULK values corresponding to a single ITEM.


text:
Q: Parsing file name from String I am trying to find a simple regex that starts with url and ends with jpg) to extract the string url(file:///C:\\Testing\\external\\thex-2_rtfimage_1.jpg).
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class ExtractFile
{
     public static final String EXAMPLE_TEST =
     "this is url(file:///C:\\Testing\\external\\thex-2_rtfimage_1.jpg) which is attached";

     public static void main(String[] args) {
        Pattern pattern = Pattern.compile("url");
        Matcher matcher = pattern.matcher(EXAMPLE_TEST);
        // check all occurance
        while (matcher.find()) {
           System.out.print("Start index: " + matcher.start());
           System.out.print(" End index: " + matcher.end() + " ");
           System.out.println(matcher.group());
        }
     }
}

A: You can just use word boundaries and .*? to match text between url and jpg:
Pattern pattern = Pattern.compile("\\burl.*?jpg\\b");

A: The following pattern should work to detect anything that starts with a url and finishes with jpg
((url)[\w\W\d\D]+(.jpg)+(\W){1}) // matches `url(` to start, anything in the middle that you will use for url names, followed by `.jpg`, and a bracket `)`

var text = "url(file:///C:\\Testing\\external\\thex-2_rtfimage_1.jpg)";
var x = text.match(/((url)[\w\W\d\D]+(.jpg)+(\W){1})/g);
alert(x);

The demonstration uses JavaScript as I went to JSFiddle to work the solution out. But the pattern is usable in Java too.
Another solution for your pattern can be:
\burl([\w\W])+(.jpg\))

This matches using a word boundary (\b)where it starts with urlfollowed by a match for one or more word, non-word,digit, or non-digit characters, and then .jpg ending with a right parentheses ). It would've been better if you provided your a sample of your expected input and answer. But given your statement, this is what I came up with. But there could very well be other working solutions!


text:
Q: Restricting access to the remote on the client side. Is it possible? Does anyone know if there is any way to restrict access to the remote on the client?
I have 2 repositories, I shoud commit to one of those (let's call it A), not the other (B), but I technically have rw access to both of them. I would like to set option in repository config file to prevent me from accidental push to B.
Is it possible?
Cheers,
Michal

A: yes. Hooks are one way to add that safe guard. I would recommend using gitolite as it is designed for this type of repository management.

A: How about removing the push URL?
git remote set-url --push origin ''


text:
Q: Expose host services (Postgres, Redis) to Docker container (Apache Superset) I'm trying to setup Apache Superset.
I want to access Postgres and Redis services running on host from a Superset instance running in Docker.
(I don't want to run dockers for db and redis as I have already installed these services in my application).
I see following in superset documentation:
Note: Users often want to connect to other databases from Superset. Currently, the easiest way to do this is to modify the docker-compose-non-dev.yml file and add your database as a service that the other services depend on (via x-superset-depends-on).
Here I'm clueless on how to configure yaml file for this. I'm pretty much new to docker. Could any one please guide me? Here is the yaml file service section from docker-compose-non-dev.yml.
  redis:
    image: redis:7
    container_name: superset_cache
    restart: unless-stopped
    volumes:
      - redis:/data

  db:
    env_file: docker/.env-non-dev
    image: postgres:14
    container_name: superset_db
    restart: unless-stopped
    volumes:
      - db_home:/var/lib/postgresql/data```

A: If I understand correctly you want to do two things:

*

*Use existing services for those components

Just make sure they're accessible from your Superset docker container and then specify the paths to those resources in superset_config.py or superset_config_docker.py, which is presumably where you're setting other config options.  E.g., to point to your Postgres service as the backend database, specify:
SQLALCHEMY_DATABASE_URI='postgresql://username:password@path/dbname'

Where path is the URL or IP address of your Postgres instance.  For Redis, it's not as clear but I think you'd set that location with REDIS_HOST= in your config.  And you can use a .env file to store these strings instead of putting them directly in your config file.

*Not run the unnecessary containers

You should be able to just delete the container specs you have in your post and remove both of them from the x-superset-depends-on: &superset-depends-on list at the top of the docker-compose file.


text:
Q: Wrap divs from div parent I have this code

I want to wrap all .superdiv children divs into a div called

How can I make that ?
Thanks

A: You could use the .wrapInner() method:
$('.superdiv').wrapInner('

');

You could also use the .wrapAll() method on the children elements:
$('.superdiv').children().wrapAll('

');

A: Try following
$(".superdiv > div").wrapAll("
");


text:
Q: How to parse raw POST data into array? I have a raw form-data that look like this:
------------V2ymHFg03ehbqgZCaKO6jy
Content-Disposition: form-data; name="intro"

O
------------V2ymHFg03ehbqgZCaKO6jy
Content-Disposition: form-data; name="title"

T
------------V2ymHFg03ehbqgZCaKO6jy
Content-Disposition: form-data; name="apiKey"

98d32fdsa
------------V2ymHFg03ehbqgZCaKO6jy
Content-Disposition: form-data; name="method"

/media/add
------------V2ymHFg03ehbqgZCaKO6jy
Content-Disposition: form-data; name="upload_field"; filename="original_filename.png"
Content-Type: image/png

------------V2ymHFg03ehbqgZCaKO6jy--

(In place of second line of upload_field there are data of this file (invisible here). So my question is:
How to parse above data to have a table:
$result['intro']

and so on with data inside?

A: $boundary = "------------V2ymHFg03ehbqgZCaKO6jy"; // take this from content-type
$rawfields = explode($boundary,$data);
array_pop($rawfields); // drop the last -- piece
foreach ( $rawfields as $id=>$block )
{
    list($mime,$content) = explode("\r\n\r\n",$block,2); // I think it's <cr><lf> by standards, maybe check!
    if ( preg_match('/name="([^"]*)"/i',$mime,$match) )
    {
        $result[$match[1]] = $content;
        // todo: do funky stuff with other fields
    } else {
        $result[] = $content; // just in case...
    }
}

presto.
edit: you should also trim off the newline from each content block, but rtrim will chop more than one newline, so you have to get a little more creative.

A: The content-type of the overall document is multipart, with the parts being separated by the given boundary.
Each part, or message, within the multipart document is in a standard message format: header lines, followed by a blank line, followed by a sequence of bytes representing the content of that part. Both HTTP and SMTP work like this.
With header lines like Content-Disposition: form-data; name="title", you have to be careful with the name because it could be encoded (think about how to represent an arbitrary value, such as one containing a double quote mark or a newline).

A: I was dealing with a similar problem myself and wrote my own version of mvds's code to also work with binary files. Here's the thread for future reference.


text:
Q: Format Python Floating Point Numbers like Java does My program consists of a Java and a Python component and I want Python to format floating point numbers exactly in the same way as Java does by default.
Java:
    float number1 = (float) Math.PI;
    float number2 = (float) Math.PI / 1000f;
    float number3 = (float) Math.PI / 10000f;
    float number4 = (float) Math.PI / 100000f;
    float number5 = (float) (int)(Math.PI * 1000000f) / 1000000f / 100000f;

    System.out.println(number1); // prints 3.1415927
    System.out.println(number2); // prints 0.0031415927
    System.out.println(number3); // prints 3.1415926E-4
    System.out.println(number4); // prints 3.1415926E-5
    System.out.println(number5); // prints 3.141592E-5

How to get the same output in Python?
First attempts in Python:
import math

number1 = float(math.pi)
number2 = float(math.pi / 1000)
number3 = float(math.pi / 10000)
number4 = float(math.pi / 100000)
number5 = float(int(math.pi * 1000000) / 1000000 / 100000)

print(number1) # prints 3.141592653589793
print(number2) # prints 0.0031415926535897933
print(number3) # prints 0.0003141592653589793
print(number4) # prints 3.141592653589793e-05
print(number5) # prints 3.141592e-05

print("{:8e}".format(number1)) # prints 3.141593e+00
print("{:8e}".format(number2)) # prints 3.141593e-03
print("{:8e}".format(number3)) # prints 3.141593e-04
print("{:8e}".format(number4)) # prints 3.141593e-05
print("{:8e}".format(number5)) # prints 3.141592e-05

A: Your formatting syntax is incorrect. Do this instead
print("{:.15f}".format(math.pi))

or the old fashioned way
print("%.15f" % (math.pi))


text:
Q: Google Cloud Platform Boot Disk Pricing I'm quite confused by how GCP prices disks. We're currently using GCP's free plan, with an always free f1-micro instance. I understand that additional disks have a price per GB month, but I'm really confused on how the boot disk is priced. It comes with 10 GB by default, and since the f1-micro instance is free, I'm guessing the default 10GB is also free. However, 10GB could possibly be not enough for future usage and I'm confused on how resizing is priced. I had trouble finding any documentation on this, as there's nothing about boot disk pricing. How is space on the boot disk/default disk priced?

A: You can estimate possible spendings with Google Cloud Pricing Calculator. Also, you can see the estimated costs of your instances and Compute Engine resources when you create them in the Google Cloud Console.
To find more details have have a look at the documentation Disks and images pricing section Disk pricing:

Each VM instance has at least one disk attached to it. Each disk
incurs a cost, described in this section. In addition, if you use
snapshots, there are separate snapshot charges.
All disk-related charges in this section are prorated based on a
granularity of seconds. This includes all persistent disk types,
snapshot storage, and local SSD pricing.

For example:

Persistent disks are priced by the amount of provisioned space per
disk. Persistent disk I/O operations are included in the charges for
provisioned space and persistent disk performance grows linearly by
the size of the persistent disk volume, so you might want to create a
larger or smaller persistent disk to account for your I/O needs. For
more information, see the persistent disk specifications.

The price will be different if you decided to use Local SSD.
In addition, have a look at the VM instances pricing, Networking pricing, Sustained use discounts and Committed use discounts.
If you still have some questions you can reach Google Cloud Sales.


text:
Q: Where to Get Software design feedback I know this site is for very specific programming questions. Does anyone have any recommendations for sites that allow longer discussions on technology choices and perhaps even discussion of specific software designs for new projects?  Sometimes getting a few good people to look through a proposal can help you avoid major headaches by pointing out better design alternatives.

A: If the question is about modeling your future product, come here to SO with UML or modeling tags.
Technology choices are for Programmers site.
Questions on Software design are for SO if you have a question as:

I have tried ... and don't like the results because of... What can I do?
How to realize ... in ... technology? That ... and this ... won't help.
How this operation ... can be done in ... technology.
How this thought ... could be expressed in UML?
Have I my UML diagram correct?
I organized my classes/project so... and obviously, got lost. Is it workable? Can it be workable this way? What I have to change?

Questions of type:

How to do ..., I don't know how to start?
How such project ... can be organized?
What technology to use for...

are rather for Programmers, too.
I.e., you are coming here to SO with a piece of done work. To Programmers it is allowed to come in search for the starting step or for the deeper philosophy of the problem.


text:
Q: how to delete fk children in nhibernate I would like to delete the ICollection PriceBreaks from Product.
I'm using the following method. However they dont seem to delete. What am i missing.
 When i step thru. i notice that "product.PriceBreaks.Clear();" doesn't actually clear the items. Do i need to flush or something?
public void RemovePriceBreak(int productId)
{
using (ISession session = EStore.Domain.Helpers.NHibernateHelper.OpenSession())
using (ITransaction transaction = session.BeginTransaction())
{
    var product = session.Get<Product>(productId);
   // i can see 20 PriceBreak records, tho nh prof saids PriceBreak table hasn't been hit
    product.PriceBreaks.Clear();
    session.SaveOrUpdate(product);
    transaction.Commit(); // PriceBreak table is hit here with select statement, no delete?
}

}
Here are my hbm files
  <class name="Product" table="Products">
    <id name="Id" type="Int32" column="Id" unsaved-value="0">
      <generator class="identity"/>
    </id>
    <property name="CompanyId" column="CompanyId" type="Int32" not-null="true" />
    <property name="Name" column="Name"/>
    <set name="PriceBreaks" table="PriceBreaks" generic="true" cascade="all-delete-orphan" inverse="true" >
      <key column="ProductId" />
      <one-to-many class="EStore.Domain.Model.PriceBreak, EStore.Domain" />
    </set>
  </class>

<class name="PriceBreak" table="PriceBreaks">
    <id name="Id" type="Int32" column="Id" unsaved-value="0">
      <generator class="identity"/>
    </id>
    <many-to-one name="Product" column="ProductId"  not-null="true"  class="EStore.Domain.Model.Product, EStore.Domain" />
  </class>

My Entities
 public class Product
    {

        public virtual int Id { get; set; }
    public virtual ICollection<PriceBreak> PriceBreaks { get; set; }
        public virtual void AddPriceBreak(PriceBreak priceBreak)
        {
            priceBreak.Product = this;
            PriceBreaks.Add(priceBreak);
        }
    }

 public class PriceBreak
    {
        public virtual int Id { get; set; }
        public virtual Product Product { get; set; }
    }

Here is the sql from nhprof
//
SELECT product0_.Id               as Id0_0_
FROM   Products product0_
WHERE  product0_.Id = 23 /* @p0 */
and then
SELECT pricebreak0_.ProductId        as ProductId1_,
       pricebreak0_.Id               as Id1_,
       pricebreak0_.Id               as Id1_0_,
       pricebreak0_.ProductId        as ProductId1_0_,
FROM   PriceBreaks pricebreak0_
WHERE  pricebreak0_.ProductId = 23 /* @p0 */
there is no update or select

A: Product probably needs to be associated with that session. It looks like you are trying to save a detached object. Which means there is no session to track that call to clear the PriceBreaks. Change it to this...
public void RemovePriceBreak(int productId)
{

    using (ISession session = EStore.Domain.Helpers.NHibernateHelper.OpenSession())
    using (ITransaction transaction = session.BeginTransaction())
    {
        var product = session.Get<Product>(productId);
        product.PriceBreaks.Clear();
        session.SaveOrUpdate(product);
        transaction.Commit();
    }
}

or move the session and transaction management further up. Which would basically eliminate the need for this method.

A: Have you tried deleting the cascade="all" on the PriceBreak side ?
Have you tried using session.Save() instead of SaveOrUpdate() ?


text:
Q: My code tries to configure the CAN device, but it never leaves configuration mode. Why? I'm using a PIC32MX534F064L, and I just started working with the CAN module. The first thing I tried was using the examples from Microchip. None of them worked. The basic problem is these lines:
CANSetOperatingMode(CAN1, CAN_NORMAL_OPERATION);
while(CANGetOperatingMode(CAN1) != CAN_NORMAL_OPERATION);

The while on the second line never completes.
I'll explain. The PIC32's CAN module has to be configured in the following order:

*

*Enable the CAN module.

*Switch the CAN module to "configuration" operation mode.

*Configure the CAN module.

*Switch CAN module to "normal" operation mode.

Step 2 and 4 are a little more complicated. Instead of just setting a register which would change the mode, there's a two-step process. You set a register (C1CON.REQOP) to request that the operation mode (C1CON.OPMOD) will change, and when the CAN module is ready to change, it does.
Anyway, here is the code. I'm sure I just forgot something, but scouring the Internet and trying various examples has been without result.
#include <plib.h>

#pragma config FPLLMUL = MUL_20, FPLLIDIV = DIV_2, FPLLODIV = DIV_1, FWDTEN = OFF
#pragma config POSCMOD = HS, FNOSC = PRIPLL, FPBDIV = DIV_1

#define SYS_FREQ (80000000L)
#define CAN_BUS_SPEED 250000

BYTE CAN1MessageFifoArea[2 * 8 * 16];

int main(void)
{
    CAN_BIT_CONFIG canBitConfig;
    CAN_OP_MODE mode;
    int i;

    SYSTEMConfig(SYS_FREQ, SYS_CFG_WAIT_STATES | SYS_CFG_PCACHE);

    CANEnableModule(CAN1,TRUE);
    while(C1CONbits.ON == 0);
    CANSetOperatingMode(CAN1, CAN_CONFIGURATION);
    while(CANGetOperatingMode(CAN1) != CAN_CONFIGURATION);

    canBitConfig.phaseSeg2Tq            = CAN_BIT_3TQ;
    canBitConfig.phaseSeg1Tq            = CAN_BIT_3TQ;
    canBitConfig.propagationSegTq       = CAN_BIT_3TQ;
    canBitConfig.phaseSeg2TimeSelect    = TRUE;
    canBitConfig.sample3Time            = TRUE;
    canBitConfig.syncJumpWidth          = CAN_BIT_2TQ;
    CANSetSpeed(CAN1,&canBitConfig,SYS_FREQ,CAN_BUS_SPEED);

    CANAssignMemoryBuffer(CAN1,CAN1MessageFifoArea,(2 * 8 * 16));

    CANConfigureChannelForTx(CAN1, CAN_CHANNEL0, 8,
                             CAN_TX_RTR_DISABLED, CAN_LOW_MEDIUM_PRIORITY);
    CANConfigureChannelForRx(CAN1, CAN_CHANNEL1, 8,
                             CAN_RX_FULL_RECEIVE);

    CANConfigureFilter      (CAN1, CAN_FILTER0, 0x8004001, CAN_EID);
    CANConfigureFilterMask  (CAN1, CAN_FILTER_MASK0, 0x3FFFFFFF,
                             CAN_EID, CAN_FILTER_MASK_IDE_TYPE);
    CANLinkFilterToChannel  (CAN1, CAN_FILTER0, CAN_FILTER_MASK0, CAN_CHANNEL1);
    CANEnableFilter         (CAN1, CAN_FILTER0, TRUE);

    CANEnableChannelEvent(CAN1, CAN_CHANNEL1, CAN_RX_CHANNEL_NOT_EMPTY, TRUE);
    CANEnableModuleEvent(CAN1, CAN_RX_EVENT, TRUE);

    // The code gets stuck in the while and never finishes.
    C1CONbits.CANBUSY = 1;
    CANSetOperatingMode(CAN1, CAN_NORMAL_OPERATION);
    while(CANGetOperatingMode(CAN1) != CAN_NORMAL_OPERATION);

    // This code is never reached
    i=0;
    while(1)
        ++i;
}

A: Well, it turned out that if you connect a CAN transceiver to the CAN pins on the PIC, but fail to supply it with power, then the PIC never leaves configuration mode. Connecting the transceiver to a reliable power source solved the problem.

A: Here's an interesting one on a PIC18F-Q chip (PIC18F26Q84 to be exact).  Code kept hanging when trying to exit CAN BUS Configuration with CANTX on RB2, CANRX on RB3.  Code would NOT hang when changing the CAN Bus RX input from RB3 to some other input pin.  Just trying to read RB3 as a digital input always came back as 0 even when set as a regular digital input pin and feeding 3.3V into it.  The solution?  TURN OFF JTAG Boundary Scan in CONFIG2.
Update: At this point in time, the documentation and MCC for the PIC18F26Q84 incorrectly configures C1FIFOBA = 0x3800.  That's great for the PIC18F27Q84 but the PIC18F26Q84 works a lot better with C1FIFOBA = 0x2600;


text:
Q: Python Selenium Chrome Not Running Headless I'm currently writing a program in which I'm connecting to chrome. I would like to make this process without a new chrome window popping up every time. I know that --headless makes chrome run silently, but my current code is not working; it is still opening up chrome tabs.
Current Code:
chrome_options = Options()
chrome_options.add_argument("--headless")
driver = webdriver.Chrome(chrome_options = chrome_options)

What am I doing wrong or what do I need to add?

A: If you are using linux one alternate solution to run the browser in headless mode is to use pyvirtual display.
First install xvfb and pyvirtual display:
sudo apt-get install xvfb xserver-xephyr

sudo pip install pyvirtualdisplay

The code will be:
from pyvirtualdisplay import Display
import webdriver
display = Display(visible=0, size=(800, 600))
display.start()
browser = webdriver.Chrome()


text:
Q: Postgresql не возвращает результат, но нет ошибок В базу postgresql стучатся много скриптов, все обращаются через pgbouncer и делают выборки задач через select for update skip locked. В условный 1 из 30 запросов база отдает пустой результат селекта, хотя записи для выборки есть. В логе pgsql, pgbouncer и pdo::errorInfo ошибок нет.
Почему база может не отдавать результат запроса?


text:
Q: Find all elements with specific data attribute if their val() is not undifined I need to initialize an  array of elements, that have specific data attribute. But only the elements that have value should be in array (the elements can be select, input and etc.)
UPDATE: for example: if the element is text input and has not value, or, if the element is select but no option is selected by user, it shouldn't be added to array.
how should I modify the array below?
var myArr = element.find('[data-filter-field]')

A: You can use $.filter to filter elements with value

$("#btn").on('click', function(){
  var inputs = $("[data-filter-field]").filter(function(){
  return !!this.value
  });

  $.each(inputs, function(i,el){
    console.log(el.id)
  })
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<input id="txt1" data-filter-field="true">
<input id="txt2" data-filter-field="true">
<input id="txt3" data-filter-field="true">
<input id="txt4" data-filter-field="true">
<input id="txt5" data-filter-field="true">

<button id="btn"> Get element Lists </button>


text:
Q: Creating std::set copies only one element, how to fix this? v_map has the correct amount of information stored, however when i try to use std::set it only copies one element ,I assume the first one. This is my first time  using std::set , maybe I miss something here...Thanks for your help !
typedef std::map<std::string,std::pair<int,int>> points_map;
void list_average(points_map &v_map)
{
    Comparator compFunctor = [](std::pair<std::string,std::pair<int,int>> elem1,std::pair<std::string,std::pair<int,int>> elem2)
            {
                std::pair<int,int> it = elem1.second;
                std::pair<int,int> jt = elem2.second;
                return it.first < jt.first;
            };
    std::set<std::pair<std::string,std::pair<int,int>>,Comparator> v_set(v_map.begin(),v_map.end(),compFunctor);
    for (std::pair<std::string,std::pair<int,int>> it : v_set)
    {
        std::pair<int,int> jt = it.second;
        std::cout << it.first << " " << (jt.second - jt.first) / jt.first<< std::endl;

    }
}

Note the following is the full program, I apologize in advance for the ugly code , and length of the code ,also I rewrote the name in the upper part of my code, in the full code , this particular function is called list_atlag
#include <iostream>
#include <string>
#include <map>
#include <set>
#include <vector>
#include <codecvt>
#include <iterator>
#include <numeric>
#include <functional>

#include <boost/filesystem.hpp>
#include <boost/foreach.hpp>
#include <boost/program_options.hpp>
#include <boost/tokenizer.hpp>

class Adatok
{
  public:
    Adatok(std::string name, std::string path, std::string date, int points) : _name(name), _path(path), _date(date), _points(points) {}
    Adatok(const Adatok &other) = default;
    Adatok &operator=(const Adatok &other) = default;

    std::string get_name() { return _name; }
    std::string get_path() { return _path; }
    std::string get_date() { return _date; }
    int get_points() { return _points; }

  private:
    std::string _name;
    std::string _path;
    std::string _date;
    int _points;
};
class Ranglista
{
  public:
    Ranglista(std::string name, int points) : _name(name), _points(points) {}
    Ranglista(const Ranglista &other) = default;
    Ranglista &operator=(const Ranglista &other) = default;

    std::string get_name() { return _name; }
    int get_points() { return _points; }
    bool operator<(const Ranglista &other)
    {
        return _points > other._points;
    }

  private:
    std::string _name;
    int _points;
};
class Vedes
{
  public:
    Vedes(std::string name, int point) : _name(name), _point(point) { _count++; }
    Vedes(const Vedes &other) = default;
    Vedes &operator=(const Vedes &other) = default;
    std::string get_name() { return _name; }
    int get_point() { return _point; }
    int get_count() { return _count; }
    void set_stuff(int &points)
    {
        _point += points;
        _count++;
    }
    bool operator<(const Vedes &other)
    {
        return _count > other._count;
    }

  private:
    std::string _name;
    int _point;
    int _count = 0;
};

typedef std::map<std::string, int> path_value; //minden path + az erteke
typedef std::vector<Adatok> name_path_date;    //bejegyzesek
typedef std::vector<Ranglista> ranglista;      //ranglista
typedef std::map<std::string,std::pair<int,int>> vedes_vec;          //vedesek
typedef std::function<bool(std::pair<std::string,std::pair<int,int>>,std::pair<std::string,std::pair<int,int>>)> Comparator;

void create_pv(path_value &, boost::filesystem::path);                                   //feltolti a path+ertek map-ot
void create_npd(name_path_date &, path_value &, std::string input);                      //feltolti a bejegyzesek vektorat + mindenki pontszama map
void create_np(name_path_date &, path_value &);                                          // name + path map
void list_np(path_value &name_point);                                                    // nam + path kiiratas
void list_bejegyzesek(name_path_date &bejegyzesek);                                      // bejegyzesek vektora kiiratas
bool check_bejegyzesek(name_path_date &bejegyzesek, std::string name, std::string path); //van-e mar ilyen bejegyzes
void create_rl(ranglista &rl_vec, path_value &name_point);                               //ranglista feltoltes
void list_rl(ranglista &rl_vec);                                                         //ranglista kiiratas
void vedes_atlag(name_path_date &bejegyzesek, vedes_vec &v_vec);                         //vedes atlag map
void list_atlag(vedes_vec &v_vec);                                                       //vedes atlag kiiratas
bool check_vedes(vedes_vec &v_vec, std::string name);
void vedes_elem(vedes_vec &v_vec, std::string name, int &&points); //
//void accumulate_pv(path_value&);

int main(int argc, char **argv)
{
    std::vector<std::string> roots = {"City/Debrecen/Oktatás/Informatika/Programozás/DEIK/Prog1/", "City/Debrecen/Oktatás/Informatika/Programozás/DEIK/"};
    std::string input_file_name = "db-2018-05-06.csv";

    /* OPTIONS */
    boost::program_options::options_description desc("ALLOWED OPTIONS");
    desc.add_options()("help", "help msg")("root,r", boost::program_options::value<std::vector<std::string>>())("csv", boost::program_options::value<std::string>(), "comma separated values")("rank", "rang lista")("vedes", "labor vedesek");
    boost::program_options::positional_options_description pdesc;
    pdesc.add("root", -1);
    boost::program_options::variables_map vm;
    boost::program_options::store(boost::program_options::command_line_parser(argc, argv).options(desc).positional(pdesc).run(), vm);
    boost::program_options::notify(vm);

    int sum = 0;
    path_value pv_map;
    if (vm.count("help") || argc == 1)
    {
        std::cout << desc << std::endl;
        return 1;
    }
    if (vm.count("root"))
    {
        roots = vm["root"].as<std::vector<std::string>>();
        for (auto &i : roots)
        {
            boost::filesystem::path path(i);
            create_pv(pv_map, path);
        }
        for (path_value::iterator it{pv_map.begin()}; it != pv_map.end(); it++)
            sum += it->second;
        //std::cout << sum << std::endl;create_npd
        std::cout << std::accumulate(pv_map.begin(), pv_map.end(), 0, [](int value, const std::map<std::string, int>::value_type &p) { return value + p.second; });
        std::cout << std::endl;
    }

    if (vm.count("csv"))
    {
        //input_file_name = vm["csv"].as<std::string>();
        std::ifstream input_file{vm["csv"].as<std::string>()};
        name_path_date bejegyzesek;
        std::string temp;
        path_value name_point;

        while (getline(input_file, temp))
            create_npd(bejegyzesek, pv_map, temp);
        create_np(bejegyzesek, name_point);
        //list_bejegyzesek(bejegyzesek);
        //list_np(name_point);
        if (vm.count("rank"))
        {
            ranglista rl_vec;
            create_rl(rl_vec, name_point);
            list_rl(rl_vec);
        }
        if (vm.count("vedes"))
        {

            vedes_vec v_vec;
            vedes_atlag(bejegyzesek, v_vec);
            list_atlag(v_vec);
        }
        return 0;
    }
    return 0;
}

void create_pv(path_value &pv_map, boost::filesystem::path path)
{
    boost::filesystem::directory_iterator it{path}, eod;
    BOOST_FOREACH (boost::filesystem::path const &p, std::make_pair(it, eod))
    {
        if (boost::filesystem::is_regular_file(p))
        {
            boost::filesystem::ifstream regular_file{p};
            std::string temp;
            int sum = 0; //aktualis .props erteke
            while (getline(regular_file, temp))
            {
                temp.erase(0, temp.find_last_of('/'));
                temp.erase(0, temp.find_first_of(' '));
                sum += std::atoi((temp.substr(temp.find_first_of("0123456789"), temp.find_last_of("0123456789"))).c_str());
            }
            std::string result = p.string();
            std::string result_path = result.substr(0, result.find_last_of('/'));
            //std::cout << result_path << std::endl;
            //pv_map.insert(std::make_pair(result, sum));
            pv_map[result_path] = sum;
        }
        else
            create_pv(pv_map, p);
    }
}
//void accumulate_pv(path_value& pv_map)
//{
//   std::cout<<std::accumulate(pv_map.begin(),pv_map.end(),0,[](int value,const path_value::int& p){return value+p.second;});
//}
void create_npd(name_path_date &bejegyzesek, path_value &pv_map, std::string input)
{
    boost::tokenizer<boost::escaped_list_separator<char>> tokenizer{input};
    boost::tokenizer<boost::escaped_list_separator<char>>::iterator it{tokenizer.begin()};
    std::string name = *it;
    std::string path = *(++it);
    std::string date = *(++it);
    path = path.substr(2);
    if (!check_bejegyzesek(bejegyzesek, name, path))
        bejegyzesek.push_back(Adatok(name, path, date, pv_map["/home/erik/Documents/Programs/"+path]));
}
bool check_bejegyzesek(name_path_date &bejegyzesek, std::string name, std::string path)
{
    bool ok = false;
    for (name_path_date::iterator it{bejegyzesek.begin()}; it != bejegyzesek.end(); it++)
    {
        if ((it->get_name() == name) && (it->get_path() == path))
            ok = true;
    }
    return ok;
}
bool check_vedes(vedes_vec &v_vec, std::string name)
{
    vedes_vec::iterator it = v_vec.find(name);
    if (it != v_vec.end()) return true;
    else return false;
}
void vedes_elem(vedes_vec &v_vec, std::string name, int &&points)
{
    /*for (auto &it : v_vec)
        if (it.get_name() == name)
            it.set_stuff(points);
            */
    vedes_vec::iterator i  = v_vec.find(name);
    std::pair<int,int> it = i->second;
    //auto& jt = it->second;
    it.first++;
    it.second += points;
}
void create_np(name_path_date &bejegyzesek, path_value &name_point)
{
    for (name_path_date::iterator it{bejegyzesek.begin()}; it != bejegyzesek.end(); it++)
        if (name_point.count(it->get_name()) == 0)
            name_point.insert(std::make_pair(it->get_name(), it->get_points()));
        else
            name_point[it->get_name()] += it->get_points();
}
void list_np(path_value &name_point)
{
    for (path_value::iterator it{name_point.begin()}; it != name_point.end(); it++)
    {
        if (it->second)
            std::cout << it->first << " " << it->second << std::endl;
    }
}
void list_bejegyzesek(name_path_date &bejegyzesek)
{
    for (name_path_date::iterator it{bejegyzesek.begin()}; it != bejegyzesek.end(); it++)
        if (it->get_name() == "Varga Erik")
            std::cout << it->get_name() << " " << it->get_path() << " " << it->get_points() << std::endl;
}
void create_rl(ranglista &rl_vec, path_value &name_point)
{
    for (auto &it : name_point)
    {
        if (it.second > 0)
            rl_vec.push_back(Ranglista(it.first, it.second));
    }
    std::sort(rl_vec.begin(), rl_vec.end());
}
void list_rl(ranglista &rl_vec)
{
    for (auto &it : rl_vec)
        std::cout << it.get_name() << " " << it.get_points() << std::endl;
}
void vedes_atlag(name_path_date &bejegyzesek, vedes_vec &v_vec)
{
    std::string key = "City/Debrecen/Oktatás/Informatika/Programozás/DEIK/Prog1/Labor/Védés/";
    for (auto &it : bejegyzesek)
    {
        if ((it.get_path().find("City/Debrecen/Oktatás/Informatika/Programozás/DEIK/Prog1/Labor/Védés/") != std::string::npos) && (it.get_points()) && (!check_vedes(v_vec, it.get_name())))
            v_vec.insert(std::make_pair(it.get_name(),std::make_pair(1,it.get_points())));
        else if ((check_vedes(v_vec, it.get_name())) && (it.get_path().find("City/Debrecen/Oktatás/Informatika/Programozás/DEIK/Prog1/Labor/Védés/") != std::string::npos) && (it.get_points()))
            vedes_elem(v_vec, it.get_name(), it.get_points());
    }
}
void list_atlag(vedes_vec &v_vec)
{
    //std::sort(v_vec.begin(), v_vec.end());
    Comparator compFunctor = [](std::pair<std::string,std::pair<int,int>> elem1,std::pair<std::string,std::pair<int,int>> elem2)
            {
                std::pair<int,int> it = elem1.second;
                std::pair<int,int> jt = elem2.second;
                return it.first < jt.first;
            };
    std::set<std::pair<std::string,std::pair<int,int>>,Comparator> v_set(v_vec.begin(),v_vec.end(),compFunctor);
    //int sum = 0;
    //int csum = 0;
    for (std::pair<std::string,std::pair<int,int>> it : v_set)
    {
        std::pair<int,int> jt = it.second;
        std::cout << it.first << " " << (jt.second - jt.first) / jt.first<< std::endl;
        //sum += it.get_point();
        //csum += it.get_count();

        //sum = std::accumulate(v_vec.begin(), v_vec.end(), 0, [](int i, Vedes &o) { return i + o.get_point(); });
        //csum = std::accumulate(v_vec.begin(), v_vec.end(), 0, [](int i, Vedes &o) { return i + o.get_count(); });
    }
    //std::cout << (sum - csum) / csum << std::endl;
}

A: so, as described here
template<
    class Key,
    class Compare = std::less<Key>,
    class Allocator = std::allocator<Key>
> class set;

std::set is an associative container that contains a sorted set of unique objects of type Key.

I cleaned up your code, and made a Minimal, Complete, and Verifiable example,
#include <iostream>
#include <map>
#include <set>

using point_pair = std::pair<int,int>;
using points_map = std::map<std::string, point_pair>;
using points_set_pair = std::pair<std::string, point_pair>;
auto compFunctor = [](const points_set_pair &elem1, const points_set_pair &elem2)
{
    return elem1.second.first < elem2.second.first;
};
using points_set = std::set<points_set_pair, decltype(compFunctor)>;

void list_average(const points_map &v_map)
{
    points_set v_set(v_map.begin(),v_map.end(),compFunctor);
    for (auto &elem : v_set)
    {
        const point_pair &jt = elem.second;
        std::cout << elem.first << " " << (jt.second - jt.first) / jt.first<< "\n";

    }
}

Now consider the first version of main
int main()
{
    points_map v_map = { {"foo", { 1, 2}}, {"bar", { 3, 4}}};

    list_average(v_map);
}

output:
foo 1
bar 0

Now consider the second version of main:
int main()
{
    points_map v_map = { {"foo", { 1, 2}}, {"bar", { 1, 4}}};

    list_average(v_map);
}

output:
bar 3

See the problem? As .second.first of the elements are both 1, the latter replaces the first. It is not unique. That's the downside of std::set.

So, what then?
Don't use std::set, but use std::vector and std::sort. Example:
#include <iostream>
#include <map>
#include <vector>
#include <algorithm>

using point_pair = std::pair<int,int>;
using points_map = std::map<std::string, point_pair>;
using string_point_pair = std::pair<std::string, point_pair>;
auto compFunctor = [](string_point_pair const &elem1, string_point_pair const &elem2)
{
    return
        elem1.second.first != elem2.second.first?
        elem1.second.first < elem2.second.first:
        elem1.second.second < elem2.second.second;
};

void list_average(points_map const &v_map)
{
    std::vector<string_point_pair> v_vec(v_map.begin(),v_map.end());
    std::sort(v_vec.begin(), v_vec.end(), compFunctor);
    for (auto &elem : v_vec)
    {
        const point_pair &jt = elem.second;
        std::cout << elem.first << " " << (jt.second - jt.first) / jt.first<< "\n";

    }
}

int main()
{
    points_map v_map = { {"foo", { 1, 2}}, {"bar", { 1, 4}}, {"baz", { 2, 4}}};

    list_average(v_map);
}

Output:
foo 1
bar 3
baz 1

live demo


text:
Q: 'pip install --user' gives errors CONTEXT:
I am having trouble installing a module (namely 'plotly').  I have seen a lot of information, which is overwhelming, and so I hope to take the problem step-by-step.
SETUP:

*

*MacOS High Sierra version 10.13.3

*python version 2.7.10

*possibly relevant: I also installed python 3.6, but when I type python version 2.7 gets started (this is another issue that I need to sort out)

WHAT I HAVE TRIED (OR REFRAINED FROM DOING) AND WHAT I UNDERSTAND:

*

*Simply typing pip install plotly throws an error (and I think I understand why it should): OSError: [Errno 13] Permission denied: '/Library/Python/2.7/site-packages/ipython_genutils'

*In the past I have used sudo pip install, but since then have learned it is a bad thing, so now I am trying to do things "neatly".

*Disappointingly, doing pip install --user plotly also throws an permission error, but not the same as 1.:
OSError: [Errno 13] Permission denied: '/Users/erc/Library/Python/2.7'
which I guess is logical since it is trying to install the module in a different location.

At this point I am not sure what to do.

A: Using Pip is not the best idea, try using virtualenv:
pip install virtualenv

The installation of virtualenv shouldn't throw an error.
Look up the usage, or use this reference:
http://sourabhbajaj.com/mac-setup/Python/virtualenv.html
Also, try python3 to execute 3.6.


text:
Q: xml xml.etree.ElementTree as ET Quiero imprimir solo un dato de un xml, pero me imprime más datos de los que necesito, no puedo ver un ejemplo que me funciona, funciona para otros pero no sé por qué no imprime lo que necesito.
Este es mi código:
import xml.etree.ElementTree as ET
tree=ET.parse('C:/Users/Dell/OneDrive/07.Codigo/01.py/A.xml').getroot()
for Emisor in tree:
  print(Emisor.text,Emisor.text)

quiero que me imprima:"50630122200050322056700100001010000000010140301584"
pero imprime lo siguiente:
50630122200050322056700100001010000000010140301584
454001
00100001010000000010
2022-12-30T15:19:52.170

01
01
04

the xml is this, (part of the xml)
<FacturaElectronica xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:xsd="http://www.w3.org/2001/XMLSchema"
    xmlns="https://cdn.comprobanteselectronicos.go.cr/xml-schemas/v4.3/facturaElectronica"
    xsi:schemaLocation="https://cdn.comprobanteselectronicos.go.cr/xml-schemas/v4.3/facturaElectronica https://cdn.comprobanteselectronicos.go.cr/xml-schemas/v4.3/facturaElectronica.xsd">
    <Clave>50630122200050322056700100001010000000010140301584</Clave>
    <CodigoActividad>454001</CodigoActividad>
    <NumeroConsecutivo>00100001010000000010</NumeroConsecutivo>
    <FechaEmision>2022-12-30T15:19:52.170</FechaEmision>
    <Emisor>
        <Nombre>HxxxR xxxx xxxZ xxxxxLO</Nombre>
        <Identificacion>
            <Tipo>01</Tipo>
            <Numero>xxxxx567</Numero>
        </Identificacion>
        <Ubicacion>
            <Provincia>3</Provincia>
            <Canton>01</Canton>
            <Distrito>09</Distrito>


text:
Q: pyProcedure method which adds a new mission class Rocket:

    def __init__(self, name, mission):
        self.__name = name
        self.__mission = mission

    def getMission(self):
        return self.__mission
    def addMission(self, mission):
        # procedure method which adds a new mission. There can be one (str) or multiple (list) existing missions

I can't understand how to implement this addMission func within a class correctly.
Output should be something like this: Missions: ['Dragon 2 pad abort test', 'Dragon 2 in-flight abort test']. What I've "come up with" simply produces the right answer if that default input is placed, albeit it has the wrong inner mechanics. Thus, with different input it won't produce a thing:
self.__mission = [self.__mission, mission]

How do I... make it work?

A: Try this:
class Rocket:
    def __init__(self, name, mission):
        if not type(mission) in [list, tuple]:
            raise TypeError("constructor argument mission must be of type list or tuple")
        self.__name = name
        self.__mission = mission

    def getMission(self):
        return self.__mission
    def addMission(self, mission):
        # procedure method which adds a new mission. There can be one (str) or multiple (list) existing missions
        if type(mission) == str:
            self.__mission.append(str)
        elif type(mission) in [list, tuple]:
                self.__mission.extend(miss)
        else:
            raise TypeError("addMission argument mission must have types str, list or tuple")

A: Unfortunately, this code doesn't work =(
def addMission(self, mission):
    if isinstance(mission, str) is True:
        [self.__mission].append(mission)
    elif isinstance(mission, list) is True:
        [self.__mission].extend(mission)

As result I have only 1 value from getMission(). Second value doesn't add to list.


text:
Q: Вывод на консоль элементов из xml Объясните, пожалуйста, как вывести на консоль данные из xml файла из корневой ветки. Почему-то выводится только название корневой ветки, а сами элементы не выводятся.
namespace Bank
{
    class DataLayer //выборка данных в xml файле
    {

        static string pathXml = ConfigurationSettings.AppSettings["pathXmlData"].ToString();
        static string pathTxt = ConfigurationSettings.AppSettings["pathTxtData"].ToString();

        public static Man GetManDetails(string name, string surName)
        {
            Man man = new Man(); //потому что возвращаем тип Man

            XmlDataDocument xmlDoc = new XmlDataDocument();
            xmlDoc.Load(pathXml);
            XmlNode root = xmlDoc.DocumentElement;
            XmlNode node = root.SelectSingleNode(string.Format("Man[name='{0}' and surName='{1}']", name, surName));

            XmlNodeList list = node.ChildNodes;

            for (int i = 0; i < list.Count; i++)
                man.ManInfo[list.Item(i).Name] = list.Item(i).InnerText;

            return man;
        }
    }
}
namespace Bank
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine(DataLayer.GetManDetails("Иван", "Иванов"));
            Console.ReadLine();
        }
    }
}

При вызове метода GetManDetails на консоль выводится Bank.Man., т.е. название корня, где хранятся элементы корня Man, а сами элементы не выводятся. Знаю, что необходимо использовать цикл, но все равно не получается.
A: Если я правильно понял ваш вопрос, нужно что-то вроде
foreach (ManInfo info in DataLayer.GetManDetails("Иван", "Иванов").ManInfo) {
    Console.WriteLine(info);
    Console.ReadLine();
}


text:
Q: AngularJS ng-options not populating from Promise values I have a select box which bind the data from the database.

   <select id="country" ng-model="selectedCountry"
           ng-options="country.CountryName for country in countries">
      <option value="" selected>Select your option</option>
   </select>

Below is the loadCountries function
$scope.loadCountries = function () {
    var resultList = mainService.loadCountries();
    resultList.then(function (response) {
        $scope.countries = response.data;
        $scope.selectedCountry = $scope.countries[0];
    });
}

Also here is the loadcountires code in service
function mainService($http) {
    this.loadCountries = function () {
        var result = $http({
            method: 'GET',
            url: '/API/Country/Countries'
        });
        return result;
    }
}

When I checked countries list, it is populating succesfully, but not binding to ng-options in the select box.
Can anyone help me with this please !!

A: Change ng-options like this and try.

   <select id="country" ng-model="selectedCountry"
           ng-options="country as country.CountryName for country in countries">
      <option value="" selected>Select your option</option>
   </select>


text:
Q: java language. it says my file doesn't exist but it does private void traverse(String dir, int ctr) throws IOException

{
    // get current file and name

    File myFile = new File(dir);
    System.out.println("dir path: " + myFile.getAbsolutePath()); // correct path
    System.out.println("exists? : " + myFile.exists()); // returns false
    String name = myFile.getName();
    System.out.println(dir + " is dir? " + myFile.isDirectory());
    if (name.equals("tree.txt"))
        return;

    // print tabs and name
    for (int i = 0; i < ctr; ++i)
        bw2.write("\t");
    bw2.write(name);
    bw2.newLine();

    if (myFile.isFile() && name.charAt(0) != '.')

    {
        File f = new File(dir + "." + name);
        int version = 1; // if doesn't exist then version is 1

        if (f.exists())
        {
            FileInputStream fis = new FileInputStream(f);
            InputStreamReader isr = new InputStreamReader(fis);
            BufferedReader br = new BufferedReader(isr);

            version = Integer.parseInt(br.readLine()); // get version

            br.close();
        }

        fos1 = new FileOutputStream(f);

        osw1 = new OutputStreamWriter(fos1);

        bw1 = new BufferedWriter(osw1);

        bw1.write(version); // write version

        bw1.close();

    }

    else if (myFile.isDirectory())

    {
        String dirContents[] = myFile.list();

        for (String content : dirContents)

        {
            traverse(dir + content + '/', ctr + 1);
        }

    }
} // end traverse

output:
kedy@Laptop:~/Desktop/connection$ java Server
dir path: /home/kedy/Desktop/connection/test.txt
exists? : false
test.txt/ is dir? false
dir path: /home/kedy/Desktop/connection/tree.txt
exists? : false
tree.txt/ is dir? false
dir path: /home/kedy/Desktop/connection/folder 2
exists? : false
folder 2/ is dir? false
dir path: /home/kedy/Desktop/connection/test2.txt
exists? : false
test2.txt/ is dir? false
dir path: /home/kedy/Desktop/connection/folder
exists? : false
folder/ is dir? false

A: Looking at the output, I would venture a guess that there is indeed no file "test.txt/". However, there probably is a file "text.txt".

A: Change
traverse(dir + content + '/', ctr + 1);

to
traverse(dir + '/' + content, ctr + 1);

A: I will probably end up adding to this answer, but, first, you may want to check permissions, to see if the application has read access.
Which version of Java, which OS?
If you move the file to a common directory, common to all users, can the file be found?
You may want to have the path be an argument, so you can easily change it without recompiling your application, which testing this.


text:
Q: How can I prioritize messages on different queues? A resource allocation/prioritizing problem.
I'm working on a Java EE application which has a number of Message Driven Beans (MDB) which receive messages from different JMS queues, let's say queue A/MDB A and queue B/MDB B for simplicity.
When there is high load the system needs to prioritize messages coming in on queue A over messages on queue B. Why? Messages on queue A need to be processed as quickly as possible and thus MDB A needs "all" db, cpu resources etc.
Do you have any advice on how to solve this in a clean way? Not so clean could work as well...
My production server is WebSphere Application Server 7, using SIBus for message delivery. WebSphere MQ could be an option.
Thanks for any suggestions!

A: After investigating this issue with people that are experts in the area I got some bad news:
This probably can't be done.
100% can't be done using SIB, You can only prioritize messages within a single destination.
About WebSphere MQ, also seems that it can't be done, they only properties for queue priority is when dealing with a single queue in a cluster, which I guess doesn't help you.
So, sadly, this probably can't be done, if you need to prioritize messages you might need to change your architecture a bit.
 Perhaps a single queue with a selector. Then you can prioritize messages of some type.


text:
Q: Как отобразить экран приветствия (splash screen) с именами разработчиков и логотипом компании? Такая задача: нужно чтобы при запуске программы отображалась картина(обложка). Как пример привожу netbeans:

Но в моем случае, нужно чтоб просто отображалась обложка с именами разработчиков и логотипом компании.
Есть одна идея: программа при запуске просто открывает эту картину, но думаю это слишком просто(не надежно). Хотелось бы узнать есть ли способ получше?
Среда разработки: Qt C++.

A: Есть для этого готовый класс QSplashScreen.
Читайте хэлп в Qt.
Пример оттуда:
  int main(int argc, char *argv[])
  {
      QApplication app(argc, argv);
      QPixmap pixmap(":/splash.png");
      QSplashScreen splash(pixmap);
      splash.show();
      app.processEvents();
      ...
      QMainWindow window;
      window.show();
      splash.finish(&window);
      return app.exec();
  }


text:
Q: Пытаюсь поставить Windows 10 и Unix-систему вместе на одном компьютере Захотел испытать опыт работы с Unix-системами поставив Windows 10 и Ubuntu на одном ноуте, но не тут то было...
Отсек на жестком диске ноутбука 60Гб памяти, скачал на флешку Ubuntu последнюю версию с помощью ПО Unetbootin, отключил в BIOS secure boot и fast boot, запустился с флешки.
Во время установки Ubuntu попросили выбрать раскладку, что интересно - она не менялась, только английская. Забил на это и поехал дальше, в итоге увидел то что Ubuntu не видит никаких жесткого диска на моём ноуте, пустота в списке выбора (окошко "Тип установки"), снизу написано /dev/sda. Запустил Gparted, он видел только флешку с которой я запустился. Подумал на ПО Unetbootin.
Сделал флешку с помощью ПО Rufus, та же беда.
Попробовал менять флешки, результата ноль.
Подумал что установщик багованный, поставил версию Ubuntu 16-го года на флешку, то же самое, дисков не видит хоть убейся. Попробовал поставить Linux Mint, теперь раскладка менялась во время установки, но диск тоже не видит. При любых действиях с окошком "типа установки" следует вылет установщика, кроме нажатия кнопки выхода из установщика. Ноутбук Lenovo, стоит SSDшник один.

A: *

*Проверить в bios какой режим SATA установлен. Должен быть AHCI

*Разметить жесткий в винде предваратительно. Т.к. в линуксе этот процесс делается несколько иначе

*Сразу изучить информацию на тему установки линукс и виндовс на один жесткий диск. Загрузчики двух систем будут конфликтовать. И после успешной установки по-умолчанию будет грузиться только одна система. У меня это была винда, т.к. я её ставил после линукса

A: Если для начала Вы хотите только попробовать и испытать - совершенно не обязательно ставить отдельно. Если у Вас Windows 10 - используйте WSL (Windows Subsystem for Linux). Например - https://habr.com/ru/post/412633/ ссылок полно в сети.