qid
int64
1
74.7M
question
stringlengths
15
58.3k
date
stringlengths
10
10
metadata
list
response_j
stringlengths
4
30.2k
response_k
stringlengths
11
36.5k
3,283,460
I want to parse some emails from a user 's inbox but when I do: ``` typ, msg_data = imap_conn.fetch(uid, '(RFC822)') ``` It marks the email as SEEN or read. This is not the desired functionality. Do you know how can I keep the email at its previous stare either SEEN or NOT SEEN?
2010/07/19
[ "https://Stackoverflow.com/questions/3283460", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1438479/" ]
You might also set `read_only` to true when selecting the folder: ``` imap_conn.select('Inbox', readonly=True) ```
You may use imap\_tools package: <https://pypi.org/project/imap-tools/> ``` from imap_tools import MailBox, Q # get list of email subjects from INBOX folder with MailBox('imap.mail.com').login('test@mail.com', 'password') as mailbox: # mark_seen=False - not mark emails as seen on fetch subjects = [msg.subject for msg in mailbox.fetch(mark_seen=False)] ```
3,311,399
How would you check for the object type when looping std::list? ``` class A { int x; int y; public: A() {x = 1; y = 2;} }; class B { double x; double y; public: B() {x = 1; y = 2;} }; class C { float x; float y; public: C() {x = 1; y = 2;} }; int main() { A a; B b; C c; list <boost::variant<A, B, C>> l; l.push_back(a); l.push_back(b); l.push_back(c); list <boost::variant<A, B, C>>::iterator iter; for (iter = l.begin(); iter != l.end(); iter++) { //check for the object type, output data to stream } } ```
2010/07/22
[ "https://Stackoverflow.com/questions/3311399", "https://Stackoverflow.com", "https://Stackoverflow.com/users/187543/" ]
About the only time I can think of using Assembly language for optimizing code is when you need something very specific, like you need a GPIO on a microcontroller to toggle between high and low ***exactly*** every 9 clock cycles. that's too short a time to manage with an interrupt, and higher level language compilers don't normally offer this kind of control over the instruction stream.
Read [the Graphics Programming Black Book by Michael Abrash](http://www.gamedev.net/reference/articles/article1698.asp)
3,311,399
How would you check for the object type when looping std::list? ``` class A { int x; int y; public: A() {x = 1; y = 2;} }; class B { double x; double y; public: B() {x = 1; y = 2;} }; class C { float x; float y; public: C() {x = 1; y = 2;} }; int main() { A a; B b; C c; list <boost::variant<A, B, C>> l; l.push_back(a); l.push_back(b); l.push_back(c); list <boost::variant<A, B, C>>::iterator iter; for (iter = l.begin(); iter != l.end(); iter++) { //check for the object type, output data to stream } } ```
2010/07/22
[ "https://Stackoverflow.com/questions/3311399", "https://Stackoverflow.com", "https://Stackoverflow.com/users/187543/" ]
These days, you have to be very good at assembly to beat the compiler. I can do it any day of the week, but only by viewing the compiler's output first. And then, if it gains more than a couple of percentage points I'd be surprised. These days, I only program in assembly when I'm doing something the compiler *can't* do.
When writing assembly, or even just straight raw bytes the assembler outputs, you can write programs that use computer hardware specific features or makes something otherwise very carefully specified. There might be really high benefits if your program does the optimized part far more often than it does anything else. *Always set up benchmarks before attempting optimizations.* The downcome is that your hand-written assembly works on fewer different hardware. It may even end up getting limited into the hardware model and revision! It's rare you ever can or need to write assembly routines because commonly written software must work on almost every hardware you find and your kitten. There's one interesting application if you know assembly. You can then write programs that produce assembly routines. Though it's mostly only fun unless you keep it really small so you can port it easily.
3,311,399
How would you check for the object type when looping std::list? ``` class A { int x; int y; public: A() {x = 1; y = 2;} }; class B { double x; double y; public: B() {x = 1; y = 2;} }; class C { float x; float y; public: C() {x = 1; y = 2;} }; int main() { A a; B b; C c; list <boost::variant<A, B, C>> l; l.push_back(a); l.push_back(b); l.push_back(c); list <boost::variant<A, B, C>>::iterator iter; for (iter = l.begin(); iter != l.end(); iter++) { //check for the object type, output data to stream } } ```
2010/07/22
[ "https://Stackoverflow.com/questions/3311399", "https://Stackoverflow.com", "https://Stackoverflow.com/users/187543/" ]
Typically you wouldn't program in assembly. You would program in C, and then look at the generated assembly to see what optimzations (or not) the C compiler made automatically. Adjusting your C code (to allow for better vectorization for example) will allow the compiler to re-arrange code better, which will give you optimized assembly
Compilers do a good job of generating assembler. However, there's a *bad* reason why hand-written assembler is faster. Since it's harder to write, you write less of it. It would be nice if programmers could discipline themselves to get the same job done in minimal code, regardless of language.
3,311,399
How would you check for the object type when looping std::list? ``` class A { int x; int y; public: A() {x = 1; y = 2;} }; class B { double x; double y; public: B() {x = 1; y = 2;} }; class C { float x; float y; public: C() {x = 1; y = 2;} }; int main() { A a; B b; C c; list <boost::variant<A, B, C>> l; l.push_back(a); l.push_back(b); l.push_back(c); list <boost::variant<A, B, C>>::iterator iter; for (iter = l.begin(); iter != l.end(); iter++) { //check for the object type, output data to stream } } ```
2010/07/22
[ "https://Stackoverflow.com/questions/3311399", "https://Stackoverflow.com", "https://Stackoverflow.com/users/187543/" ]
The most likely way programming in assembly can improve your code is by improving *you*: teaching you more about what is happening at a low level and getting the discipline of optimization can help you make good decisions in higher-level languages. As far as actually helping one program: as others have noted it's rarely worth it. It's just possible you can use it as a kind of advanced profile-driven optimization: try many variations until you find one that's best on your particular problem. To start with this: write a program in C or C++ or whatever compiled language you normally use, fire up your debugger, and disassemble a small but nontrivial function, and have a think about why the compiler did what it did. Then try writing a small bit of inline assembler yourself. On modern systems assembly is mostly easily embedded within C rather than done from scratch. Or alternatively, get a teeny machine like a PIC and make it flash a LED...
Compilers do a good job of generating assembler. However, there's a *bad* reason why hand-written assembler is faster. Since it's harder to write, you write less of it. It would be nice if programmers could discipline themselves to get the same job done in minimal code, regardless of language.
3,311,399
How would you check for the object type when looping std::list? ``` class A { int x; int y; public: A() {x = 1; y = 2;} }; class B { double x; double y; public: B() {x = 1; y = 2;} }; class C { float x; float y; public: C() {x = 1; y = 2;} }; int main() { A a; B b; C c; list <boost::variant<A, B, C>> l; l.push_back(a); l.push_back(b); l.push_back(c); list <boost::variant<A, B, C>>::iterator iter; for (iter = l.begin(); iter != l.end(); iter++) { //check for the object type, output data to stream } } ```
2010/07/22
[ "https://Stackoverflow.com/questions/3311399", "https://Stackoverflow.com", "https://Stackoverflow.com/users/187543/" ]
In principle, you can write highly-optimized code in assembly because the compiler is limited to specific, general-purpose optimizations that should apply to many programs, while you can be creative and use your knowledge of this particular program. To take a simple example, back when I was new to this business compilers were very limited in their ability to optimize register usage. You know that to perform any sort of arithmetic or logical operation, the CPU must generally load one of the values into a register, then perform the operation on the other, then save the result? Like to add two numbers together -- and I'll use a pseudo-assembler here because I don't know what assembly languages you know and I've forgotten most of the details myself -- you'd write something like this: ``` LOAD A,value1 ADD A,value2 STORE a,destination ``` Compilers used to generate the loads for every operation. So if your C program said: ``` x=x+y; z=z+x; ``` The compiler would generate something like: ``` LOAD A,x ADD A,y STORE A,x LOAD A,z ADD A,x STORE A,z ``` But a human could observe that by the time we get to the second statement, register A already contains x, and addition is commutative, so we could optimize this to: ``` LOAD A,x ADD A,y STORE A,x ADD A,z STORE A,z ``` Et cetera. One could go through all sorts of tiny micro-optimizations like this. I used to do that all the time back when I was young and the world was green. But over the years compilers have gotten much smarter, and CPUs have gotten more powerful so the micro-optimizations don't matter as much. Thus, I haven't written any assembly language code in, wow, probably 15 years. I used to read the assembly generated by the compiler when debugging, sometimes it would give a clue to a subtle problem, but I haven't done that in years now either. I don't think compilers are even written in assembly any more. Instead, you write the first draft of the compiler in a high level language on some other computer, i.e. you write a cross-compiler to get yourself off the ground. I suspect the only real use of assembly today is for extremely constrained environments, embedded systems and that sort of thing; and for programs that have to deal intimately with the hardware, like device drivers. I'd be interested to hear if there are any assembly programmers on this forum who care to tell us why they assembly programmers.
So, you think you are smarter than `gcc` optimizing compiler? If not, then fughed aboud it (learning assembly for the sake of getting better at optimization). That would be akin to learning `Scheme` language for the sake of getting better at recursion :)
3,311,399
How would you check for the object type when looping std::list? ``` class A { int x; int y; public: A() {x = 1; y = 2;} }; class B { double x; double y; public: B() {x = 1; y = 2;} }; class C { float x; float y; public: C() {x = 1; y = 2;} }; int main() { A a; B b; C c; list <boost::variant<A, B, C>> l; l.push_back(a); l.push_back(b); l.push_back(c); list <boost::variant<A, B, C>>::iterator iter; for (iter = l.begin(); iter != l.end(); iter++) { //check for the object type, output data to stream } } ```
2010/07/22
[ "https://Stackoverflow.com/questions/3311399", "https://Stackoverflow.com", "https://Stackoverflow.com/users/187543/" ]
Programming in assembly won't, in and of itself, optimize your code. The main thing about assembly is that it allows you to have very low-level access and to choose exactly what instructions the processor executes. Since you won't have some compiler generating the assembly for you, you can perform code optimizations when you write the program yourself, if you know how.
Read [the Graphics Programming Black Book by Michael Abrash](http://www.gamedev.net/reference/articles/article1698.asp)
3,311,399
How would you check for the object type when looping std::list? ``` class A { int x; int y; public: A() {x = 1; y = 2;} }; class B { double x; double y; public: B() {x = 1; y = 2;} }; class C { float x; float y; public: C() {x = 1; y = 2;} }; int main() { A a; B b; C c; list <boost::variant<A, B, C>> l; l.push_back(a); l.push_back(b); l.push_back(c); list <boost::variant<A, B, C>>::iterator iter; for (iter = l.begin(); iter != l.end(); iter++) { //check for the object type, output data to stream } } ```
2010/07/22
[ "https://Stackoverflow.com/questions/3311399", "https://Stackoverflow.com", "https://Stackoverflow.com/users/187543/" ]
About the only time I can think of using Assembly language for optimizing code is when you need something very specific, like you need a GPIO on a microcontroller to toggle between high and low ***exactly*** every 9 clock cycles. that's too short a time to manage with an interrupt, and higher level language compilers don't normally offer this kind of control over the instruction stream.
Compilers do a good job of generating assembler. However, there's a *bad* reason why hand-written assembler is faster. Since it's harder to write, you write less of it. It would be nice if programmers could discipline themselves to get the same job done in minimal code, regardless of language.
3,311,399
How would you check for the object type when looping std::list? ``` class A { int x; int y; public: A() {x = 1; y = 2;} }; class B { double x; double y; public: B() {x = 1; y = 2;} }; class C { float x; float y; public: C() {x = 1; y = 2;} }; int main() { A a; B b; C c; list <boost::variant<A, B, C>> l; l.push_back(a); l.push_back(b); l.push_back(c); list <boost::variant<A, B, C>>::iterator iter; for (iter = l.begin(); iter != l.end(); iter++) { //check for the object type, output data to stream } } ```
2010/07/22
[ "https://Stackoverflow.com/questions/3311399", "https://Stackoverflow.com", "https://Stackoverflow.com/users/187543/" ]
These days, you have to be very good at assembly to beat the compiler. I can do it any day of the week, but only by viewing the compiler's output first. And then, if it gains more than a couple of percentage points I'd be surprised. These days, I only program in assembly when I'm doing something the compiler *can't* do.
About the only time I can think of using Assembly language for optimizing code is when you need something very specific, like you need a GPIO on a microcontroller to toggle between high and low ***exactly*** every 9 clock cycles. that's too short a time to manage with an interrupt, and higher level language compilers don't normally offer this kind of control over the instruction stream.
3,311,399
How would you check for the object type when looping std::list? ``` class A { int x; int y; public: A() {x = 1; y = 2;} }; class B { double x; double y; public: B() {x = 1; y = 2;} }; class C { float x; float y; public: C() {x = 1; y = 2;} }; int main() { A a; B b; C c; list <boost::variant<A, B, C>> l; l.push_back(a); l.push_back(b); l.push_back(c); list <boost::variant<A, B, C>>::iterator iter; for (iter = l.begin(); iter != l.end(); iter++) { //check for the object type, output data to stream } } ```
2010/07/22
[ "https://Stackoverflow.com/questions/3311399", "https://Stackoverflow.com", "https://Stackoverflow.com/users/187543/" ]
The most likely way programming in assembly can improve your code is by improving *you*: teaching you more about what is happening at a low level and getting the discipline of optimization can help you make good decisions in higher-level languages. As far as actually helping one program: as others have noted it's rarely worth it. It's just possible you can use it as a kind of advanced profile-driven optimization: try many variations until you find one that's best on your particular problem. To start with this: write a program in C or C++ or whatever compiled language you normally use, fire up your debugger, and disassemble a small but nontrivial function, and have a think about why the compiler did what it did. Then try writing a small bit of inline assembler yourself. On modern systems assembly is mostly easily embedded within C rather than done from scratch. Or alternatively, get a teeny machine like a PIC and make it flash a LED...
About the only time I can think of using Assembly language for optimizing code is when you need something very specific, like you need a GPIO on a microcontroller to toggle between high and low ***exactly*** every 9 clock cycles. that's too short a time to manage with an interrupt, and higher level language compilers don't normally offer this kind of control over the instruction stream.
3,311,399
How would you check for the object type when looping std::list? ``` class A { int x; int y; public: A() {x = 1; y = 2;} }; class B { double x; double y; public: B() {x = 1; y = 2;} }; class C { float x; float y; public: C() {x = 1; y = 2;} }; int main() { A a; B b; C c; list <boost::variant<A, B, C>> l; l.push_back(a); l.push_back(b); l.push_back(c); list <boost::variant<A, B, C>>::iterator iter; for (iter = l.begin(); iter != l.end(); iter++) { //check for the object type, output data to stream } } ```
2010/07/22
[ "https://Stackoverflow.com/questions/3311399", "https://Stackoverflow.com", "https://Stackoverflow.com/users/187543/" ]
These days, you have to be very good at assembly to beat the compiler. I can do it any day of the week, but only by viewing the compiler's output first. And then, if it gains more than a couple of percentage points I'd be surprised. These days, I only program in assembly when I'm doing something the compiler *can't* do.
Typically you wouldn't program in assembly. You would program in C, and then look at the generated assembly to see what optimzations (or not) the C compiler made automatically. Adjusting your C code (to allow for better vectorization for example) will allow the compiler to re-arrange code better, which will give you optimized assembly
26,467,445
``` $xml = '<?xml version="1.0" encoding="UTF-8"?> <stw:ThumbnailResponse xmlns:stw="http://www.shrinktheweb.com/doc/stwresponse.xsd"> <stw:Response> <stw:ThumbnailResult> <stw:Thumbnail Exists="true">http://imagelink.com</stw:Thumbnail> <stw:Thumbnail Verified="false">delivered</stw:Thumbnail> </stw:ThumbnailResult> <stw:ResponseStatus> <stw:StatusCode>refresh</stw:StatusCode> </stw:ResponseStatus> <stw:ResponseTimestamp> <stw:StatusCode>1413812009</stw:StatusCode> </stw:ResponseTimestamp> <stw:ResponseCode> <stw:StatusCode>HTTP:200</stw:StatusCode> </stw:ResponseCode> <stw:CategoryCode> <stw:StatusCode></stw:StatusCode> </stw:CategoryCode> <stw:Quota_Remaining> <stw:StatusCode>132</stw:StatusCode> </stw:Quota_Remaining> <stw:Bandwidth_Remaining> <stw:StatusCode>999791</stw:StatusCode> </stw:Bandwidth_Remaining> </stw:Response> </stw:ThumbnailResponse>'; $dom = new DOMDocument; $dom->loadXML($xml); $result = $dom->getElementsByTagName('stw:Thumbnail')->item(0)->nodeValue; $status = $dom->getElementsByTagName('stw:Thumbnail')->item(0)->nodeValue; echo $result; ``` Having the above code should output <http://imagelink.com> and $status should hold "delivered" - but none of these work instead I am left with the error notice that: ``` Trying to get property of non-object ``` I have tried different xml parsing alternatives like simplexml (but that did not work when the tag names have : in it ) and i tried looping through the each scope in the xml (ThumbNailresponse, response and then thumbnailresult) without luck. How can i get the values inside stw:Thumbnail?
2014/10/20
[ "https://Stackoverflow.com/questions/26467445", "https://Stackoverflow.com", "https://Stackoverflow.com/users/267304/" ]
Using simple xml you could use `->children()` method on this one: ``` $xml = simplexml_load_string($xml_string); $stw = $xml->children('stw', 'http://www.shrinktheweb.com/doc/stwresponse.xsd'); echo '<pre>'; foreach($stw as $e) { print_r($e); // do what you have to do here } ```
This code actually runs just fine for me --- Typically, that sort of error means you may've made a typo on your `$dom` object - double check it and try again. Also, it is notable that you'll want to change the `item(0)` to `item(1)` when you're setting your `$status` variable. ``` $result = $dom->getElementsByTagName('stw:Thumbnail')->item(0)->nodeValue; $status = $dom->getElementsByTagName('stw:Thumbnail')->item(0)->nodeValue; ```
26,467,445
``` $xml = '<?xml version="1.0" encoding="UTF-8"?> <stw:ThumbnailResponse xmlns:stw="http://www.shrinktheweb.com/doc/stwresponse.xsd"> <stw:Response> <stw:ThumbnailResult> <stw:Thumbnail Exists="true">http://imagelink.com</stw:Thumbnail> <stw:Thumbnail Verified="false">delivered</stw:Thumbnail> </stw:ThumbnailResult> <stw:ResponseStatus> <stw:StatusCode>refresh</stw:StatusCode> </stw:ResponseStatus> <stw:ResponseTimestamp> <stw:StatusCode>1413812009</stw:StatusCode> </stw:ResponseTimestamp> <stw:ResponseCode> <stw:StatusCode>HTTP:200</stw:StatusCode> </stw:ResponseCode> <stw:CategoryCode> <stw:StatusCode></stw:StatusCode> </stw:CategoryCode> <stw:Quota_Remaining> <stw:StatusCode>132</stw:StatusCode> </stw:Quota_Remaining> <stw:Bandwidth_Remaining> <stw:StatusCode>999791</stw:StatusCode> </stw:Bandwidth_Remaining> </stw:Response> </stw:ThumbnailResponse>'; $dom = new DOMDocument; $dom->loadXML($xml); $result = $dom->getElementsByTagName('stw:Thumbnail')->item(0)->nodeValue; $status = $dom->getElementsByTagName('stw:Thumbnail')->item(0)->nodeValue; echo $result; ``` Having the above code should output <http://imagelink.com> and $status should hold "delivered" - but none of these work instead I am left with the error notice that: ``` Trying to get property of non-object ``` I have tried different xml parsing alternatives like simplexml (but that did not work when the tag names have : in it ) and i tried looping through the each scope in the xml (ThumbNailresponse, response and then thumbnailresult) without luck. How can i get the values inside stw:Thumbnail?
2014/10/20
[ "https://Stackoverflow.com/questions/26467445", "https://Stackoverflow.com", "https://Stackoverflow.com/users/267304/" ]
You need to specify a namespace and the method DOMDocument::getElementsByTagName can't handle it. In the [manual](http://php.net/manual/en/domdocument.getelementsbytagname.php): > > The local name (**without namespace**) of the tag to match on. > > > You can use [DOMDocument::getElementsByTagNameNS](http://php.net/manual/en/domdocument.getelementsbytagnamens.php) instead: ``` $dom = new DOMDocument; $dom->loadXML($xml); $namespaceURI = 'http://www.shrinktheweb.com/doc/stwresponse.xsd'; $result = $dom->getElementsByTagNameNS($namespaceURI, 'Thumbnail')->item(0)->nodeValue; ```
This code actually runs just fine for me --- Typically, that sort of error means you may've made a typo on your `$dom` object - double check it and try again. Also, it is notable that you'll want to change the `item(0)` to `item(1)` when you're setting your `$status` variable. ``` $result = $dom->getElementsByTagName('stw:Thumbnail')->item(0)->nodeValue; $status = $dom->getElementsByTagName('stw:Thumbnail')->item(0)->nodeValue; ```
35,535,374
I'm trying to show custom layout as an item in options menu. And this is what I have done so far ``` <item android:id="@+id/action_profile" android:orderInCategory="100" android:title="Profile" android:actionLayout="@layout/layout_menu_profile" app:showAsAction="never" /> ``` I tried ``` app:actionLayout="@layout/layout_menu_profile" ``` as well as per [this](https://stackoverflow.com/questions/28891582/custom-layout-in-toolbar-not-showing) SO link but still it shows only title - Profile I have created new project through Android Studio 1.5 with Blank Activity. with minSDK = 15 and targetSDK = 23 Following is the code in Blank Activity. ``` @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.menu_home, menu); MenuItem item = menu.findItem(R.id.action_profile); return true; } ``` where am I going wrong ?
2016/02/21
[ "https://Stackoverflow.com/questions/35535374", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1000864/" ]
use `app:actionLayout` instead of `android:actionLayout`. ``` <item ... app:actionLayout="@layout/layout_menu_profile" app:showAsAction="always" /> ```
Try this code ``` <item android:id="@+id/action_profile" android:orderInCategory="100" android:title="Profile" android:actionLayout="@layout/layout_menu_profile" app:showAsAction="always" /> ``` Just set the **showAsAction** elements to **always**
35,535,374
I'm trying to show custom layout as an item in options menu. And this is what I have done so far ``` <item android:id="@+id/action_profile" android:orderInCategory="100" android:title="Profile" android:actionLayout="@layout/layout_menu_profile" app:showAsAction="never" /> ``` I tried ``` app:actionLayout="@layout/layout_menu_profile" ``` as well as per [this](https://stackoverflow.com/questions/28891582/custom-layout-in-toolbar-not-showing) SO link but still it shows only title - Profile I have created new project through Android Studio 1.5 with Blank Activity. with minSDK = 15 and targetSDK = 23 Following is the code in Blank Activity. ``` @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.menu_home, menu); MenuItem item = menu.findItem(R.id.action_profile); return true; } ``` where am I going wrong ?
2016/02/21
[ "https://Stackoverflow.com/questions/35535374", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1000864/" ]
use `app:actionLayout` instead of `android:actionLayout`. ``` <item ... app:actionLayout="@layout/layout_menu_profile" app:showAsAction="always" /> ```
Use "app:" instead of "android:" ``` app:actionLayout="@layout/layout_menu_profile" ```
33,125,802
I have xml with a repeating node structure within single node. How do I parse all the values by level? ``` <Totallevel>3</Totallevel> <A> <B>text</B> <level>1</level> <A> <B>text</B> <level>2</level> <A> <B>text</B> <level>3</level> </A> </A> </A> ```
2015/10/14
[ "https://Stackoverflow.com/questions/33125802", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1929007/" ]
The pattern is that **utility services** are prefixed with AWS, while **standalone services** are prefixed by "Amazon". Services prefixed with AWS *typically use other services*, for example: * **AWS Elastic Beanstalk**, **AWS OpsWorks** and **AWS CloudFormation** launch other services * **AWS Lambda** is triggered by other services * **AWS Data Pipeline** moves data between other services * **AWS CloudFormation** launches other services Mind you, this doesn't apply to everything. For example, **Amazon EBS** can only be used with Amazon EC2, yet it has an "Amazon" prefix. The [AWS documentation page](https://aws.amazon.com/documentation/) is a great reference for determining the official name of a service.
*I originally answered on [AWS products and services naming nomenclature starting with 'Amazon' vs 'AWS'](https://stackoverflow.com/a/65221189/1381529). I consider this answer needs to be mentioned here as well*. Context: [Web Service](https://en.wikipedia.org/wiki/Web_service), initially designed as a replacement for [Remote Procedure Call (RPC)](https://en.wikipedia.org/wiki/Remote_procedure_call) was a revolutionary idea during the [Internet Boom](https://en.wikipedia.org/wiki/Dot-com_bubble) based mainly on XML. Amazon's philosophy was to manage all the [ERP](https://en.wikipedia.org/wiki/Enterprise_resource_planning) and Customer request using IT instead of traditional paper based processes. The same approach was then applied from **books** to **compute** resources (that's how S3 and EC2 products came to be). Any service designed to be used by the customer mainly through an API (or Web Service - today it will be [called **API first product**](https://swagger.io/resources/articles/adopting-an-api-first-approach/) ) it is part AWS collection of services, and when the service is seen as a **traditional product** (like replacement of a service that you would install on your desktop or use it from Cloud, mainly through an UI) is part of Amazon collection of services. Today we can see exceptions to this rule. Initially this was the thought of Jeff Bezos. To understand more about his philosophy, read: [The Secret of Amazon success internal APIs](https://apievangelist.com/2012/01/12/the-secret-to-amazons-success-internal-apis/): > > Think about what Bezos was asking! Every team within Amazon had to interact using **Web Services**. > > > **Anyone who doesn’t do this will be fired. Thank you; have a nice day!** > > > *Update*: In a nutshell, if the service is meant to be used (consumed) through an API it will be an *Amazon **Web Service*** (short: **AWS**), otherwise it will be an Amazon product.
22,900,119
I have a set of base steps in SpecFlow that do simple things like enter text and validate fields. I want so that these base steps can be used by non technical testers in creating higher level steps made out of these base steps. They should not need to know how to code or how to implement step definitions or how to use selenium at all. All they need to do is define a step in English that calls other base steps. Then they can repeat the process and make more steps out of the ones they just defined. This how I want automation to occur where I am so that non technical testers can create tests in English only, while coding can be done by someone else. Does SpecFlow support this? From what I can see you can define a step to use other steps in code (in the step definition bindings), but I cant see where you do something like this in the feature file itself, so no code is involved? Tools like Fitnesse are very good when offering this kind of functionality. Many Thanks.
2014/04/06
[ "https://Stackoverflow.com/questions/22900119", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1709356/" ]
If `tab` is uninitialized then you cannot access it by index as you are in `tab[0][column].push_back(colour);`.
Check also if you use C++1X : ``` vector<vector<Colour>> tab; ``` The no espace syntax ">>" doesn't work otherwise.
22,900,119
I have a set of base steps in SpecFlow that do simple things like enter text and validate fields. I want so that these base steps can be used by non technical testers in creating higher level steps made out of these base steps. They should not need to know how to code or how to implement step definitions or how to use selenium at all. All they need to do is define a step in English that calls other base steps. Then they can repeat the process and make more steps out of the ones they just defined. This how I want automation to occur where I am so that non technical testers can create tests in English only, while coding can be done by someone else. Does SpecFlow support this? From what I can see you can define a step to use other steps in code (in the step definition bindings), but I cant see where you do something like this in the feature file itself, so no code is involved? Tools like Fitnesse are very good when offering this kind of functionality. Many Thanks.
2014/04/06
[ "https://Stackoverflow.com/questions/22900119", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1709356/" ]
Your member variable is a vector of `vector<Colour>`. If you want to add a `Colour` to a particular `vector<Colour>` at a particular index, then you need to first identify if that vector at that index is present. If so then you can add the `Colour`. If not you are assigning to an address that is not present. You need something like ``` void Game:: add(size_t column, Colour const& colour) { if (column < tab.size()) { // only push a new colour onto this vector if one is present. tab[column].push_back(colour); } } ``` You should never access the element using the operator `[]` unless you are certain that an item is actually present at that location. You cannot simply assign things to vector elements if the vector size has not been allocated.
Check also if you use C++1X : ``` vector<vector<Colour>> tab; ``` The no espace syntax ">>" doesn't work otherwise.
57,868,096
I'm running a node project + reactjs on it. the process.env works inside the server.js but undefined in other js file. I tried to build the project using webpack and then run the nodejs project like here are the steps I did. yarn build CALLBACK\_URL=<https://localhost:9999/> BASE\_URL=<https://localhost:9443/> node server.js I'm getting the log in server.js process.env.BASE\_URL <https://localhost:9443/> process.env.CALLBACK\_URL <https://localhost:9999/> but I'm getting process.env.BASE\_URL : undefined in other js file.
2019/09/10
[ "https://Stackoverflow.com/questions/57868096", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3073958/" ]
Server.js is in the back end and is in scope of your "process" object. React runs in the client browser engine. You need to get the environment variables From the "process" object available in your back-end's webpack build context into the webpack React Built files! > > See > > > * [dotenv-webpack plugin](https://www.npmjs.com/package/dotenv-webpack) > * [webpack-define plugin](https://webpack.js.org/plugins/define-plugin/) > > > for a possible elegant solution > > >
in webpack.config you can add these lines in plugins section: ``` new webpack.DefinePlugin({ 'process.env.CALLBACK_URL': 'https://localhost:9999/', 'process.env.BASE_URL': 'https://localhost:9443/' }) ```
23,553
I am writing a semi-fantasy novel, which is set in medieval India and today's New York. I have never been to New York, and will not be there, for far period. How can I do research to embed the cultural and political references of New York into my novel
2016/06/25
[ "https://writers.stackexchange.com/questions/23553", "https://writers.stackexchange.com", "https://writers.stackexchange.com/users/19480/" ]
Google Maps and Street View is your friend. Take a virtual walk, learn the area, click on local stores, read reviews for these stores, check bus & metro schedules, find out about the parks, etc. If you're interested in more in-depth elements, you'll need to provide more details about the particular elements. But basically, the answer is the same: Researching nowadays is easy with Google. If you're after something really niche (say, how inhabitants of a certain district of New York think about another district), find a NY discussion group or something like that
Google Maps is fine for *geography*, but your question mentions "cultural and political references." If you cannot travel there, you have to find some way to be exposed to and/or interact with the people there. Cities have their own personalities. They have neighborhoods, cliques, sections, classes, ethnicities. With New York in particular, you have boroughs, and the personalities and cliques of those geographical distinctions are important. Manhattan is focused on wealth, art, culture, shopping. Brooklyn is more family-oriented. Some neighborhoods used to be grungy and are now full of hipsters. How do people feel about the hipsters? What have they done to the neighborhoods? Is it good or bad? There are neighborhoods which used to be so Italian that they developed their own dialect of the language (a mix of Sicilian and Neapolitan) and now they're full of Chinese and Russians. The Chinese make great neighbors because they're clean and polite; the Russians don't because they aren't. And so on. There are sports teams and rivalries. Baseball has the American and National Leagues, so you have Mets fans vs. Yankees fans. What borough are the fans in and what are the interactions? The Knicks now play basketball in Brooklyn. How did the locals feel about the stadium being built? What's the food like? What was invented in that city? What's made a particular way there? New York pizza and Chicago pizza are different things and have different fans. New York bagels are not Philadelphia bagels. How do people get around? The New York subway system is legendary, but it's also breaking down, and delays are rampant. There's an extensive bus system, plus Uber and Zipcar. The city is heavily Democratic, but they've elected Republicans before. Relations with the police range from good to murderous, sometimes literally. 9/11 left an enormous, unfathomable, indelible mark on the city which you cannot comprehend if you weren't there. It left scars on the pysches of millions. This is all not to say that you *can't* write about New York without being there, but to give you an idea of things you need to research if you want to represent the culture and politics with any accuracy. Start with newspapers. There's the [New York Daily News](http://www.nydailynews.com/) (a tabloid, but still a real paper), the [New York Times](http://www.nytimes.com/) (the Gray Lady, the country's paper of record, occasionally stuffy and too far left, solid reporting), the New York Post (trashy Murdoch-owned tabloid, makes stuff up, the U.S. version of the Daily Fail), [Newsday](http://www.newsday.com/) covers Long Island and Queens (worlds away from Manhattan). There are magazines as well, but newspapers are dailies, and following a story from day to day gives you the feel of how people are reacting. Try the local TV news as well and watch entire broadcasts from different networks.
42,183,485
I feel like an idiot for asking such a basic question but here goes... I'm trying out AWS Lambda in C# for the first time and according to the docs: > > Anything written to standard out or standard error - using > Console.Write or a similar method - will be logged in CloudWatch Logs. > > > OK well upon execution I get the following runtime exception: ``` Unable to load DLL 'api-ms-win-core-processenvironment-l1-1-0.dll': The specified module could not be found. (Exception from HRESULT: 0x8007007E): DllNotFoundException at Interop.mincore.GetStdHandle(Int32 nStdHandle) at System.ConsolePal.GetStandardFile(Int32 handleType, FileAccess access) at System.Console.<>c.<get_Out>b__25_0() at System.Console.EnsureInitialized[T](T& field, Func`1 initializer) at System.Console.WriteLine(String value) ``` My question is, how / where am I supposed to add the reference it's asking for? The answer seems non obvious.
2017/02/12
[ "https://Stackoverflow.com/questions/42183485", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7552065/" ]
As an alternative to `Console.Write` or `Console.WriteLine`, you can use the `Log` method on the static `Amazon.Lambda.Core.LambdaLogger` class. ``` private void DoSomething() { LambdaLogger.Log("Log message"); } ``` Some more info can be found here: <http://docs.aws.amazon.com/lambda/latest/dg/dotnet-logging.html>
Well turns out in the project.json file under the dependencies node, the wizard's serverless template made a reference to Microsoft.NETCore.App without specifying a "type" of "platform". I spotted other samples online where the type line was present and once I added it, everything started working! ``` "Microsoft.NETCore.App": { "type": "platform", "version": "1.1.0" }, ```
29,414,814
I have developed an rest service using spring-boot and Spring-boot-starter hateoas. And I am facing an issue with customizing ObjectMapper. The code goes below for the same: Application.java ``` @Configuration @Import(BillServiceConfig.class) @EnableAutoConfiguration @EnableEurekaClient @ComponentScan({"com.bill"}) @EnableWebMvc @EnableHypermediaSupport(type = EnableHypermediaSupport.HypermediaType.HAL) public class Application extends WebMvcConfigurerAdapter{ @Bean public Jackson2ObjectMapperBuilder jacksonBuilder() { Jackson2ObjectMapperBuilder builder = new Jackson2ObjectMapperBuilder(); builder.indentOutput(true).dateFormat(new SimpleDateFormat("MM-yyyy-dd")); ObjectMapper objectMapper = new ObjectMapper(); objectMapper.configure(SerializationFeature.WRAP_ROOT_VALUE, true); objectMapper.configure(DeserializationFeature.UNWRAP_ROOT_VALUE, true); builder.configure(objectMapper); return builder; } ``` Dependencies: ``` dependencies { compile "org.springframework.boot:spring-boot-starter-hateoas" compile "org.springframework.boot:spring-boot-starter-ws" compile "org.springframework.boot:spring-boot-starter-actuator" ``` Bill.java: ``` @JsonIgnoreProperties(ignoreUnknown = true) @JsonRootName("bills") public class Bill{ ``` BillController.java: ``` public ResponseEntity<Resources<Resource<Bill>>> getBills(){ ``` The output I am getting is: ``` { _embedded: { billList: ``` But I require "bills" in place of "billList". It is because of ObjectMapper is not getting customized. Am I missing any configuration, Kindly help me out in this issue. Thanks in advance.
2015/04/02
[ "https://Stackoverflow.com/questions/29414814", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1957631/" ]
I'm using spring-boot 1.5 RC1. If you remove the @EnableHypermediaSupport annotation spring-boot should configure spring-hateoas with ISO 8601 dates for you so long as you have java time module on the classpath. ``` <dependency> <groupId>com.fasterxml.jackson.datatype</groupId> <artifactId>jackson-datatype-jsr310</artifactId> </dependency> ``` This worked for me anyway. If you want further custom configuration see the solutions at <http://github.com/spring-projects/spring-hateoas/issues/333>
Root of this problem - default ObjectMapper from Spring MVC is used instead of one configured by author. This happens because of @EnableWebMvc. Quote from [Spring Boot guide](https://spring.io/guides/gs/spring-boot/) > > Normally you would add @EnableWebMvc for a Spring MVC app, but Spring > Boot adds it automatically when it sees spring-webmvc on the > classpath. > > > However if you one puts it, Spring MVC will create its own set of MessageConverters and won't use yours ObjectMapper. PS even though I post this answer so late, may be it will help others.
90,840
> > **Possible Duplicate:** > > [How the heck is http://to./ a valid domain name?](https://serverfault.com/questions/90737/how-the-heck-is-http-to-a-valid-domain-name) > > > <http://to./> must be the shortest domain name I have ever seen. How can did they register a domain without an extension?
2009/12/03
[ "https://serverfault.com/questions/90840", "https://serverfault.com", "https://serverfault.com/users/-1/" ]
They didn't, they have a top level domain (.to) - <http://www.to/> is them (when entering <http://to./your> browser automatically inserted the www. part and the trailing . prevented your browser from adding .com
Perhaps you are mistaken? `$ whois to.` `No whois server is known for this kind of object.`
90,840
> > **Possible Duplicate:** > > [How the heck is http://to./ a valid domain name?](https://serverfault.com/questions/90737/how-the-heck-is-http-to-a-valid-domain-name) > > > <http://to./> must be the shortest domain name I have ever seen. How can did they register a domain without an extension?
2009/12/03
[ "https://serverfault.com/questions/90840", "https://serverfault.com", "https://serverfault.com/users/-1/" ]
<http://www.iana.org/domains/root/db/to.html>
Perhaps you are mistaken? `$ whois to.` `No whois server is known for this kind of object.`
51,897
I'm trying to translate an English sentence into Japanese , but i got some problems and confuse which should i use between が or は . So please tell me which is the correct one . 1. ジョンさんは休日にいつも東京にいる。 2. ジョンさんが休日にいつも東京にいる。 Also 1. 彼は傷口にそっと触れる。 2. 彼が傷口にそっと触れる。
2017/07/31
[ "https://japanese.stackexchange.com/questions/51897", "https://japanese.stackexchange.com", "https://japanese.stackexchange.com/users/25205/" ]
I think one way to see the difference would be... 1. ジョンさん**は**休日にいつも東京にいる。 *lit.* As for John / Speaking of John, he is usually in Tokyo on holidays. (and someone else among the people we're talking about may also be in Tokyo.) 2. ジョンさん**が**休日にいつも東京にいる。 (Of all the people we are talking about) It is John (not someone else) who is usually in Tokyo on holidays. / John is the one who is usually in Tokyo on holidays. The は is the **topical/[thematic は](https://en.wikipedia.org/wiki/Japanese_grammar#Thematic_wa)**. Sentence 1 is usually said when ジョンさん is the topic of the conversation, i.e. ジョンさん has already been mentioned before this sentence is uttered, or the interlocuter(s) is/are expecting ジョンさん to be probably mentioned. The が is the **[exhaustive が](https://en.wikipedia.org/wiki/Japanese_grammar#Exhaustive_ga)**. Unlike wa, the subject particle ga nominates its referent as the sole satisfier of the predicate ([quoted from here](https://en.wikipedia.org/wiki/Japanese_grammar#Exhaustive_ga)). So you'd usually say like ジョンさん**が**(東京に)いる (It is John who is in Tokyo) as a reply to a question 誰が東京にいますか? --- 1. 彼**は**傷口にそっと触れる。 2. 彼**が**傷口にそっと触れる。 If this line is from a story/novel, then the present form 触れる is the **historical present** (史的現在). Both sentences are grammatically correct, and one would be preferred over the other depending on the context. You'd tend to use 彼は when 彼 has just done some other things or has just been mentioned, whereas you'd tend to use 彼が when you want to specifically say that it's 彼, not someone else, who does that action. (Thanks to @Sjiveru) が also tends to be used in relative clauses and subordinate clauses, e.g. 「彼**が**傷口にそっと触れると、彼女は~~」「彼**が**傷口に触れた瞬間」 The は can also be the **[contrastive は](https://en.wikipedia.org/wiki/Japanese_grammar#Exhaustive_ga)**. You can use the は to contrast 彼 (or 彼's action) with someone else (or their action). E.g. 「**彼女は**治療を拒んだが、**彼は**(not 彼が)傷口にそっと触れて…」
That should be #1, > > ジョンさんは休日にいつも東京にいる。 > > > unless you have more special context. **は** is for **general ideas** like when you say *the store at the corner opens at 8 every morning.* **が** is good for telling a ***happening***, or this is basically to be used in a ***modifying clauses.*** > > ジョンさんが休日にいつも東京にいる。 > > > This needs our imagination, needing context. It could be comparing with other people, but sounds more like talking about a change in John's life style to our native sense. > > Also 1. 彼は傷口にそっと触れる。 2. 彼が傷口にそっと触れる。 > > > We need the context. Why is it in the non-past form? It's sounding poetic. #1 sounds generic. #2 sounds like a happening.
136,678
I have a collection that contains linked assets. I would like to override their materials and give them a unique material. Is it possible to assign a material to a whole collection, and how ? Thanks !
2019/04/09
[ "https://blender.stackexchange.com/questions/136678", "https://blender.stackexchange.com", "https://blender.stackexchange.com/users/14306/" ]
If your model consists of only one object you can link the mesh/object data rather than the whole object, then create a new object in the scene and set the mesh/object data to the linked one. You can then add any material you want (as only the mesh is linked) and any changes done to the original mesh will still be made to the linked one. Note however that modifiers will not be linked this way and you will have to re-add them yourself. Edit : Here is a clear answer with pictures : 1 - Create your model [![1 - Create your model](https://i.stack.imgur.com/u6R6u.jpg)](https://i.stack.imgur.com/u6R6u.jpg) 2- Notice the name of the object data : [![enter image description here](https://i.stack.imgur.com/WZ5zm.jpg)](https://i.stack.imgur.com/WZ5zm.jpg) 3- Duplicate the object using Alt-D to maintain the same object data (as shown) : [![enter image description here](https://i.stack.imgur.com/BXx6K.jpg)](https://i.stack.imgur.com/BXx6K.jpg) 4- Go to material settings for each object and change material link to object instead of data (data is the default option). You can also do this step before duplicating if the number of objects is big : [![enter image description here](https://i.stack.imgur.com/00fgJ.jpg)](https://i.stack.imgur.com/00fgJ.jpg) Now you can assign different material to each object : [![enter image description here](https://i.stack.imgur.com/DzNee.jpg)](https://i.stack.imgur.com/DzNee.jpg) Any changes applied to the mesh will affect all objects but each will have its own material : [![enter image description here](https://i.stack.imgur.com/aVV7H.jpg)](https://i.stack.imgur.com/aVV7H.jpg) Notice that modifiers are object specific and if you change the modifier settings of one object it won't reflect on the duplicates (only mesh changes are shared) : [![enter image description here](https://i.stack.imgur.com/F6J45.jpg)](https://i.stack.imgur.com/F6J45.jpg)
The only way to do this is to change the materials in the original file(s). The whole purpose of linking is to have one source in eventually multiple projects. Change the source and all the projects get updated, that have links to that source. In your case, the collection should be the source and other projects should create links to this collection. If you do it the opposite direction, the collection doesn't make much sense.
136,678
I have a collection that contains linked assets. I would like to override their materials and give them a unique material. Is it possible to assign a material to a whole collection, and how ? Thanks !
2019/04/09
[ "https://blender.stackexchange.com/questions/136678", "https://blender.stackexchange.com", "https://blender.stackexchange.com/users/14306/" ]
You can override the materials from linked sources that are part of the same collection, just the same way you can override not linked ones. In the scene context section you can find the options for override, you can select a single material and that will be used for all objects. [![enter image description here](https://i.stack.imgur.com/F4QaN.png)](https://i.stack.imgur.com/F4QaN.png) From the blender manual: > > **Material Override** > > > Overrides all material settings to use the Material chosen here. > > > Examples of where this might be used: > > > To check lighting by using a plain diffuse material on all objects. > Render a wireframe of the scene. > Create a custom render pass such as an anti-aliased matte or global coordinates. > > >
The only way to do this is to change the materials in the original file(s). The whole purpose of linking is to have one source in eventually multiple projects. Change the source and all the projects get updated, that have links to that source. In your case, the collection should be the source and other projects should create links to this collection. If you do it the opposite direction, the collection doesn't make much sense.
136,678
I have a collection that contains linked assets. I would like to override their materials and give them a unique material. Is it possible to assign a material to a whole collection, and how ? Thanks !
2019/04/09
[ "https://blender.stackexchange.com/questions/136678", "https://blender.stackexchange.com", "https://blender.stackexchange.com/users/14306/" ]
What i found is: Mark the whole Collection, press `CTRL`+`L`, select *Material* and select the material you want. That will Link the selected material to the whole selection. [source](https://chiaroscorner.wordpress.com/2019/08/19/how-to-assign-one-material-to-multiple-objects-in-blender-2-8/)
The only way to do this is to change the materials in the original file(s). The whole purpose of linking is to have one source in eventually multiple projects. Change the source and all the projects get updated, that have links to that source. In your case, the collection should be the source and other projects should create links to this collection. If you do it the opposite direction, the collection doesn't make much sense.
136,678
I have a collection that contains linked assets. I would like to override their materials and give them a unique material. Is it possible to assign a material to a whole collection, and how ? Thanks !
2019/04/09
[ "https://blender.stackexchange.com/questions/136678", "https://blender.stackexchange.com", "https://blender.stackexchange.com/users/14306/" ]
You can override the materials from linked sources that are part of the same collection, just the same way you can override not linked ones. In the scene context section you can find the options for override, you can select a single material and that will be used for all objects. [![enter image description here](https://i.stack.imgur.com/F4QaN.png)](https://i.stack.imgur.com/F4QaN.png) From the blender manual: > > **Material Override** > > > Overrides all material settings to use the Material chosen here. > > > Examples of where this might be used: > > > To check lighting by using a plain diffuse material on all objects. > Render a wireframe of the scene. > Create a custom render pass such as an anti-aliased matte or global coordinates. > > >
If your model consists of only one object you can link the mesh/object data rather than the whole object, then create a new object in the scene and set the mesh/object data to the linked one. You can then add any material you want (as only the mesh is linked) and any changes done to the original mesh will still be made to the linked one. Note however that modifiers will not be linked this way and you will have to re-add them yourself. Edit : Here is a clear answer with pictures : 1 - Create your model [![1 - Create your model](https://i.stack.imgur.com/u6R6u.jpg)](https://i.stack.imgur.com/u6R6u.jpg) 2- Notice the name of the object data : [![enter image description here](https://i.stack.imgur.com/WZ5zm.jpg)](https://i.stack.imgur.com/WZ5zm.jpg) 3- Duplicate the object using Alt-D to maintain the same object data (as shown) : [![enter image description here](https://i.stack.imgur.com/BXx6K.jpg)](https://i.stack.imgur.com/BXx6K.jpg) 4- Go to material settings for each object and change material link to object instead of data (data is the default option). You can also do this step before duplicating if the number of objects is big : [![enter image description here](https://i.stack.imgur.com/00fgJ.jpg)](https://i.stack.imgur.com/00fgJ.jpg) Now you can assign different material to each object : [![enter image description here](https://i.stack.imgur.com/DzNee.jpg)](https://i.stack.imgur.com/DzNee.jpg) Any changes applied to the mesh will affect all objects but each will have its own material : [![enter image description here](https://i.stack.imgur.com/aVV7H.jpg)](https://i.stack.imgur.com/aVV7H.jpg) Notice that modifiers are object specific and if you change the modifier settings of one object it won't reflect on the duplicates (only mesh changes are shared) : [![enter image description here](https://i.stack.imgur.com/F6J45.jpg)](https://i.stack.imgur.com/F6J45.jpg)
136,678
I have a collection that contains linked assets. I would like to override their materials and give them a unique material. Is it possible to assign a material to a whole collection, and how ? Thanks !
2019/04/09
[ "https://blender.stackexchange.com/questions/136678", "https://blender.stackexchange.com", "https://blender.stackexchange.com/users/14306/" ]
If your model consists of only one object you can link the mesh/object data rather than the whole object, then create a new object in the scene and set the mesh/object data to the linked one. You can then add any material you want (as only the mesh is linked) and any changes done to the original mesh will still be made to the linked one. Note however that modifiers will not be linked this way and you will have to re-add them yourself. Edit : Here is a clear answer with pictures : 1 - Create your model [![1 - Create your model](https://i.stack.imgur.com/u6R6u.jpg)](https://i.stack.imgur.com/u6R6u.jpg) 2- Notice the name of the object data : [![enter image description here](https://i.stack.imgur.com/WZ5zm.jpg)](https://i.stack.imgur.com/WZ5zm.jpg) 3- Duplicate the object using Alt-D to maintain the same object data (as shown) : [![enter image description here](https://i.stack.imgur.com/BXx6K.jpg)](https://i.stack.imgur.com/BXx6K.jpg) 4- Go to material settings for each object and change material link to object instead of data (data is the default option). You can also do this step before duplicating if the number of objects is big : [![enter image description here](https://i.stack.imgur.com/00fgJ.jpg)](https://i.stack.imgur.com/00fgJ.jpg) Now you can assign different material to each object : [![enter image description here](https://i.stack.imgur.com/DzNee.jpg)](https://i.stack.imgur.com/DzNee.jpg) Any changes applied to the mesh will affect all objects but each will have its own material : [![enter image description here](https://i.stack.imgur.com/aVV7H.jpg)](https://i.stack.imgur.com/aVV7H.jpg) Notice that modifiers are object specific and if you change the modifier settings of one object it won't reflect on the duplicates (only mesh changes are shared) : [![enter image description here](https://i.stack.imgur.com/F6J45.jpg)](https://i.stack.imgur.com/F6J45.jpg)
What i found is: Mark the whole Collection, press `CTRL`+`L`, select *Material* and select the material you want. That will Link the selected material to the whole selection. [source](https://chiaroscorner.wordpress.com/2019/08/19/how-to-assign-one-material-to-multiple-objects-in-blender-2-8/)
136,678
I have a collection that contains linked assets. I would like to override their materials and give them a unique material. Is it possible to assign a material to a whole collection, and how ? Thanks !
2019/04/09
[ "https://blender.stackexchange.com/questions/136678", "https://blender.stackexchange.com", "https://blender.stackexchange.com/users/14306/" ]
You can override the materials from linked sources that are part of the same collection, just the same way you can override not linked ones. In the scene context section you can find the options for override, you can select a single material and that will be used for all objects. [![enter image description here](https://i.stack.imgur.com/F4QaN.png)](https://i.stack.imgur.com/F4QaN.png) From the blender manual: > > **Material Override** > > > Overrides all material settings to use the Material chosen here. > > > Examples of where this might be used: > > > To check lighting by using a plain diffuse material on all objects. > Render a wireframe of the scene. > Create a custom render pass such as an anti-aliased matte or global coordinates. > > >
What i found is: Mark the whole Collection, press `CTRL`+`L`, select *Material* and select the material you want. That will Link the selected material to the whole selection. [source](https://chiaroscorner.wordpress.com/2019/08/19/how-to-assign-one-material-to-multiple-objects-in-blender-2-8/)
2,295,495
I have an AllocatedStock table holding a case number (knows as a TPND) and a quantity. I need to select a list of product stock but present this with the product number (known as TPNB) rather than the case number. I also have a ProductLookup table which holds all TPNBs and TPNDs. **AllocatedStock** AllocatedStockID identity TPND int Quantity int **ProductLookup** ProductLookupID identity TPND int TPNB int There are a number of product types (TPNB) that can be provided in more that one case type (TPND). This the required result is total number of each product type held, I used a sum() function as follows: ``` select TPNB, sum(AllocatedQty) as 'QTY' from integration.ProductLookup as PL inner join dbo.AllocatedStock as AStock on PL.TPND = AStock.TPND group by TPNB ``` Unfortunately, the ProductLookup table contains some duplicate rows (historic bad data that can't be cleaned up) where a row contains the same TPND and TPNB as another row. The only thing I need to join to the ProductLookup table for is to get the TPNB for the TPND that I have in the AllocatedStock table. Is there any way to get the join to select only the 1st match? The problem I have at present is that for TPNDs that have a duplicate row in the ProductLookup table I get back double the quantity value. Would be grateful for any help, Thanks Rob.
2010/02/19
[ "https://Stackoverflow.com/questions/2295495", "https://Stackoverflow.com", "https://Stackoverflow.com/users/41169/" ]
`SELECT DISTINCT` should do it: ``` select TPNB, sum(AllocatedQty) as 'QTY' from (SELECT DISTINCT TPND, TPNB FROM integration.ProductLookup) as PL inner join dbo.AllocatedStock as AStock on PL.TPND = AStock.TPND group by TPNB ```
``` select distinct tpnb, qty from ( select TPNB, sum(AllocatedQty) as 'QTY' from integration.ProductLookup as PL inner join dbo.AllocatedStock as AStock on PL.TPND = AStock.TPND group by ProductLookupID ) a ```
2,295,495
I have an AllocatedStock table holding a case number (knows as a TPND) and a quantity. I need to select a list of product stock but present this with the product number (known as TPNB) rather than the case number. I also have a ProductLookup table which holds all TPNBs and TPNDs. **AllocatedStock** AllocatedStockID identity TPND int Quantity int **ProductLookup** ProductLookupID identity TPND int TPNB int There are a number of product types (TPNB) that can be provided in more that one case type (TPND). This the required result is total number of each product type held, I used a sum() function as follows: ``` select TPNB, sum(AllocatedQty) as 'QTY' from integration.ProductLookup as PL inner join dbo.AllocatedStock as AStock on PL.TPND = AStock.TPND group by TPNB ``` Unfortunately, the ProductLookup table contains some duplicate rows (historic bad data that can't be cleaned up) where a row contains the same TPND and TPNB as another row. The only thing I need to join to the ProductLookup table for is to get the TPNB for the TPND that I have in the AllocatedStock table. Is there any way to get the join to select only the 1st match? The problem I have at present is that for TPNDs that have a duplicate row in the ProductLookup table I get back double the quantity value. Would be grateful for any help, Thanks Rob.
2010/02/19
[ "https://Stackoverflow.com/questions/2295495", "https://Stackoverflow.com", "https://Stackoverflow.com/users/41169/" ]
`SELECT DISTINCT` should do it: ``` select TPNB, sum(AllocatedQty) as 'QTY' from (SELECT DISTINCT TPND, TPNB FROM integration.ProductLookup) as PL inner join dbo.AllocatedStock as AStock on PL.TPND = AStock.TPND group by TPNB ```
``` select TPNB, sum(AllocatedQty) as 'QTY' from ( SELECT TPND, TPNB FROM ProductLookup GROUP BY TPND, TPNB ) as PL inner join dbo.AllocatedStock as AStock on PL.TPND = AStock.TPND group by TPNB ```
2,295,495
I have an AllocatedStock table holding a case number (knows as a TPND) and a quantity. I need to select a list of product stock but present this with the product number (known as TPNB) rather than the case number. I also have a ProductLookup table which holds all TPNBs and TPNDs. **AllocatedStock** AllocatedStockID identity TPND int Quantity int **ProductLookup** ProductLookupID identity TPND int TPNB int There are a number of product types (TPNB) that can be provided in more that one case type (TPND). This the required result is total number of each product type held, I used a sum() function as follows: ``` select TPNB, sum(AllocatedQty) as 'QTY' from integration.ProductLookup as PL inner join dbo.AllocatedStock as AStock on PL.TPND = AStock.TPND group by TPNB ``` Unfortunately, the ProductLookup table contains some duplicate rows (historic bad data that can't be cleaned up) where a row contains the same TPND and TPNB as another row. The only thing I need to join to the ProductLookup table for is to get the TPNB for the TPND that I have in the AllocatedStock table. Is there any way to get the join to select only the 1st match? The problem I have at present is that for TPNDs that have a duplicate row in the ProductLookup table I get back double the quantity value. Would be grateful for any help, Thanks Rob.
2010/02/19
[ "https://Stackoverflow.com/questions/2295495", "https://Stackoverflow.com", "https://Stackoverflow.com/users/41169/" ]
Give this a whirl. I am using a derived query to 'clean' your productlookup table. ``` select TPNB, sum(AllocatedQty) as 'QTY' from (select distinct TPND, TPNB from integration.ProductLookup) as PL inner join dbo.AllocatedStock as AStock on PL.TPND = AStock.TPND group by TPNB ```
`SELECT DISTINCT` should do it: ``` select TPNB, sum(AllocatedQty) as 'QTY' from (SELECT DISTINCT TPND, TPNB FROM integration.ProductLookup) as PL inner join dbo.AllocatedStock as AStock on PL.TPND = AStock.TPND group by TPNB ```
2,295,495
I have an AllocatedStock table holding a case number (knows as a TPND) and a quantity. I need to select a list of product stock but present this with the product number (known as TPNB) rather than the case number. I also have a ProductLookup table which holds all TPNBs and TPNDs. **AllocatedStock** AllocatedStockID identity TPND int Quantity int **ProductLookup** ProductLookupID identity TPND int TPNB int There are a number of product types (TPNB) that can be provided in more that one case type (TPND). This the required result is total number of each product type held, I used a sum() function as follows: ``` select TPNB, sum(AllocatedQty) as 'QTY' from integration.ProductLookup as PL inner join dbo.AllocatedStock as AStock on PL.TPND = AStock.TPND group by TPNB ``` Unfortunately, the ProductLookup table contains some duplicate rows (historic bad data that can't be cleaned up) where a row contains the same TPND and TPNB as another row. The only thing I need to join to the ProductLookup table for is to get the TPNB for the TPND that I have in the AllocatedStock table. Is there any way to get the join to select only the 1st match? The problem I have at present is that for TPNDs that have a duplicate row in the ProductLookup table I get back double the quantity value. Would be grateful for any help, Thanks Rob.
2010/02/19
[ "https://Stackoverflow.com/questions/2295495", "https://Stackoverflow.com", "https://Stackoverflow.com/users/41169/" ]
Give this a whirl. I am using a derived query to 'clean' your productlookup table. ``` select TPNB, sum(AllocatedQty) as 'QTY' from (select distinct TPND, TPNB from integration.ProductLookup) as PL inner join dbo.AllocatedStock as AStock on PL.TPND = AStock.TPND group by TPNB ```
``` select distinct tpnb, qty from ( select TPNB, sum(AllocatedQty) as 'QTY' from integration.ProductLookup as PL inner join dbo.AllocatedStock as AStock on PL.TPND = AStock.TPND group by ProductLookupID ) a ```
2,295,495
I have an AllocatedStock table holding a case number (knows as a TPND) and a quantity. I need to select a list of product stock but present this with the product number (known as TPNB) rather than the case number. I also have a ProductLookup table which holds all TPNBs and TPNDs. **AllocatedStock** AllocatedStockID identity TPND int Quantity int **ProductLookup** ProductLookupID identity TPND int TPNB int There are a number of product types (TPNB) that can be provided in more that one case type (TPND). This the required result is total number of each product type held, I used a sum() function as follows: ``` select TPNB, sum(AllocatedQty) as 'QTY' from integration.ProductLookup as PL inner join dbo.AllocatedStock as AStock on PL.TPND = AStock.TPND group by TPNB ``` Unfortunately, the ProductLookup table contains some duplicate rows (historic bad data that can't be cleaned up) where a row contains the same TPND and TPNB as another row. The only thing I need to join to the ProductLookup table for is to get the TPNB for the TPND that I have in the AllocatedStock table. Is there any way to get the join to select only the 1st match? The problem I have at present is that for TPNDs that have a duplicate row in the ProductLookup table I get back double the quantity value. Would be grateful for any help, Thanks Rob.
2010/02/19
[ "https://Stackoverflow.com/questions/2295495", "https://Stackoverflow.com", "https://Stackoverflow.com/users/41169/" ]
Give this a whirl. I am using a derived query to 'clean' your productlookup table. ``` select TPNB, sum(AllocatedQty) as 'QTY' from (select distinct TPND, TPNB from integration.ProductLookup) as PL inner join dbo.AllocatedStock as AStock on PL.TPND = AStock.TPND group by TPNB ```
``` select TPNB, sum(AllocatedQty) as 'QTY' from ( SELECT TPND, TPNB FROM ProductLookup GROUP BY TPND, TPNB ) as PL inner join dbo.AllocatedStock as AStock on PL.TPND = AStock.TPND group by TPNB ```
154,679
I am trying to make a php script on a webserver write into a folder /data on a fileserver. Apache 2.2, PhP 5.x. It's just a test configuration but I'd like to understand the thing somehow as I am not very experienced regarding permissions when it comes to webservers. I am sharing the folder /data on the fileserver by adding ``` /data 192.168.20.6(rw,sync,no_subtree_check) ``` Mount the folder by ``` sudo mount 192.168.20.5:/data /mnt/data ``` Create a link to the webroot(does that makes sense at all?) ``` sudo ln -s /mnt/data /webroot/site1/share ``` Then I get this: ``` Warning: fopen(/webroot/site1/share/data/uploads/Fotoraum/Original/Bluehend/test.txt): failed to open stream: Permission denied ``` Where and how do I have to adjust permissions in a sane manner to allow the script to write into /data and its subfolders? Thanks a lot!
2014/09/09
[ "https://unix.stackexchange.com/questions/154679", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/83599/" ]
The problem is that the optional parameter assignments are recognized *before* parameter expansion occurs, so the line ``` $X ``` is recognized as a command with no preceding assignments. The first word of the result of expanding it is assumed to be the command name, so the shell tries to run `Y=10`. As is usually the case, you should not try to store code in a variable, but rather in a function. ``` X () { Y=10 echo foo } ```
The way to get a command to be parsed again after parameter expansion occurs is ```none X="Y=10 echo foo" eval "$X" ``` I'm assuming that you have a realistic reason for wanting to do this.
154,679
I am trying to make a php script on a webserver write into a folder /data on a fileserver. Apache 2.2, PhP 5.x. It's just a test configuration but I'd like to understand the thing somehow as I am not very experienced regarding permissions when it comes to webservers. I am sharing the folder /data on the fileserver by adding ``` /data 192.168.20.6(rw,sync,no_subtree_check) ``` Mount the folder by ``` sudo mount 192.168.20.5:/data /mnt/data ``` Create a link to the webroot(does that makes sense at all?) ``` sudo ln -s /mnt/data /webroot/site1/share ``` Then I get this: ``` Warning: fopen(/webroot/site1/share/data/uploads/Fotoraum/Original/Bluehend/test.txt): failed to open stream: Permission denied ``` Where and how do I have to adjust permissions in a sane manner to allow the script to write into /data and its subfolders? Thanks a lot!
2014/09/09
[ "https://unix.stackexchange.com/questions/154679", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/83599/" ]
The problem is that the optional parameter assignments are recognized *before* parameter expansion occurs, so the line ``` $X ``` is recognized as a command with no preceding assignments. The first word of the result of expanding it is assumed to be the command name, so the shell tries to run `Y=10`. As is usually the case, you should not try to store code in a variable, but rather in a function. ``` X () { Y=10 echo foo } ```
*It turned out that what I describe below is just an artifact of the minimal example, which leaves out the part where `Y` is used.* There is a variable assignment before the command in the line: ``` Y=10 echo foo ``` The assignment will set the variable `Y` to `10` during the execution of `echo foo`. Because `echo foo` makes no use of `Y`, the assignment does not have an effect. In all variants of this command in the question and the answers, that's the same - the `Y=10` has no effect there.
154,679
I am trying to make a php script on a webserver write into a folder /data on a fileserver. Apache 2.2, PhP 5.x. It's just a test configuration but I'd like to understand the thing somehow as I am not very experienced regarding permissions when it comes to webservers. I am sharing the folder /data on the fileserver by adding ``` /data 192.168.20.6(rw,sync,no_subtree_check) ``` Mount the folder by ``` sudo mount 192.168.20.5:/data /mnt/data ``` Create a link to the webroot(does that makes sense at all?) ``` sudo ln -s /mnt/data /webroot/site1/share ``` Then I get this: ``` Warning: fopen(/webroot/site1/share/data/uploads/Fotoraum/Original/Bluehend/test.txt): failed to open stream: Permission denied ``` Where and how do I have to adjust permissions in a sane manner to allow the script to write into /data and its subfolders? Thanks a lot!
2014/09/09
[ "https://unix.stackexchange.com/questions/154679", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/83599/" ]
The problem is that the optional parameter assignments are recognized *before* parameter expansion occurs, so the line ``` $X ``` is recognized as a command with no preceding assignments. The first word of the result of expanding it is assumed to be the command name, so the shell tries to run `Y=10`. As is usually the case, you should not try to store code in a variable, but rather in a function. ``` X () { Y=10 echo foo } ```
If you must do this, use `env`: ``` $ X='env Y=10 echo foo' foo ``` ...and to demonstrate `$Y`... ``` $ X='env Y=10 env' $ $X | grep \^Y Y=10 ``` ...but a function is better.
154,679
I am trying to make a php script on a webserver write into a folder /data on a fileserver. Apache 2.2, PhP 5.x. It's just a test configuration but I'd like to understand the thing somehow as I am not very experienced regarding permissions when it comes to webservers. I am sharing the folder /data on the fileserver by adding ``` /data 192.168.20.6(rw,sync,no_subtree_check) ``` Mount the folder by ``` sudo mount 192.168.20.5:/data /mnt/data ``` Create a link to the webroot(does that makes sense at all?) ``` sudo ln -s /mnt/data /webroot/site1/share ``` Then I get this: ``` Warning: fopen(/webroot/site1/share/data/uploads/Fotoraum/Original/Bluehend/test.txt): failed to open stream: Permission denied ``` Where and how do I have to adjust permissions in a sane manner to allow the script to write into /data and its subfolders? Thanks a lot!
2014/09/09
[ "https://unix.stackexchange.com/questions/154679", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/83599/" ]
*It turned out that what I describe below is just an artifact of the minimal example, which leaves out the part where `Y` is used.* There is a variable assignment before the command in the line: ``` Y=10 echo foo ``` The assignment will set the variable `Y` to `10` during the execution of `echo foo`. Because `echo foo` makes no use of `Y`, the assignment does not have an effect. In all variants of this command in the question and the answers, that's the same - the `Y=10` has no effect there.
The way to get a command to be parsed again after parameter expansion occurs is ```none X="Y=10 echo foo" eval "$X" ``` I'm assuming that you have a realistic reason for wanting to do this.
154,679
I am trying to make a php script on a webserver write into a folder /data on a fileserver. Apache 2.2, PhP 5.x. It's just a test configuration but I'd like to understand the thing somehow as I am not very experienced regarding permissions when it comes to webservers. I am sharing the folder /data on the fileserver by adding ``` /data 192.168.20.6(rw,sync,no_subtree_check) ``` Mount the folder by ``` sudo mount 192.168.20.5:/data /mnt/data ``` Create a link to the webroot(does that makes sense at all?) ``` sudo ln -s /mnt/data /webroot/site1/share ``` Then I get this: ``` Warning: fopen(/webroot/site1/share/data/uploads/Fotoraum/Original/Bluehend/test.txt): failed to open stream: Permission denied ``` Where and how do I have to adjust permissions in a sane manner to allow the script to write into /data and its subfolders? Thanks a lot!
2014/09/09
[ "https://unix.stackexchange.com/questions/154679", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/83599/" ]
If you must do this, use `env`: ``` $ X='env Y=10 echo foo' foo ``` ...and to demonstrate `$Y`... ``` $ X='env Y=10 env' $ $X | grep \^Y Y=10 ``` ...but a function is better.
The way to get a command to be parsed again after parameter expansion occurs is ```none X="Y=10 echo foo" eval "$X" ``` I'm assuming that you have a realistic reason for wanting to do this.
481,267
I have imported a .EPF Eclipse preferences file [from here](http://eclipsecolorthemes.org/?view=theme&id=8125) via `File > Import > General > Preferences`. The preferences file changes the colorization for the TeXlipse editor. How do I remove/reverse the changes that this .EPF import has made?
2012/09/29
[ "https://superuser.com/questions/481267", "https://superuser.com", "https://superuser.com/users/144591/" ]
You can reverse these theme color changes in one of two ways: **GUI Method** * *Short Instructions*: Navigate to `Window -> Preferences`. In the popup that is displayed, expand the menu for the language you're interested in (in this example, it will be Java). Navigate to `Java -> Editor -> Syntax Coloring`. Click the `Restore Defaults` button. Click the `Apply` button. * *Step-by-step*: 1. Click on the **Window** button on the toolbar. 2. Select the **Preferences** option from the subsequent drop-down menu. 3. In the window that is displayed next, click on the arrow to the left of **Java** (or whatever language you are interested in changing the settings for). 4. Click on the arrow to the left of the subsequent **Editor** option. 5. Click on the subsequent **Syntax Coloring** option. 6. At the bottom right of the window, click the **Restore Defaults** button. 7. Next to it, click the **Apply** button. 8. The default coloration for this language should now be restored. If it's not, you can try the second method. **Screenshots** ![window->preferences](https://i.imgur.com/lcjwXSe.png) ![restore defaults](https://i.imgur.com/qwSZkuy.png) **Direct Method** Your preferences are stored in a directory in the workspace. Its relative path is `.metadata/.plugins/org.eclipse.core.runtime/.settings`. If you delete everything in this directory and restart Eclipse, all settings will be reverted to their default values. (Note: ***all*** settings, not just necessarily the ones you're interested in.) Alternatively, you can try deleting specific `.prefs` files in an attempt to isolate the specific preferences to reset (for example, `org.eclipse.ui.prefs` and `org.eclipse.ui.ide.prefs` seem promising, but I haven't tested this). Also, since these preferences are workspace-specific, you can simply create a new workspace and move your existing projects to it.
I didn't manage to directly reverse the effects of the import but to change the colorization I downloaded the [Eclipse Colorer plugin](http://colorer.sourceforge.net/eclipsecolorer/index.html) which worked a treat.
2,149,636
The question I have is from a past exam paper: Identity if it is an integral domain, whether it admits a finite basis over a coefficient ring, or whether it is isomorphic to another ring. The first one is $$R = \mathbb{Z}[x]/(6x^2 -1, 2x-4)$$ My first angle of attack is to find if we can simplify the ideal $I=(6x^2-1,2x-4)$ in hopes of finding a monic irreducible polynomial by taking combinations of elements of the ideal to end up with $I = (f)$ to apply a substitution isomorphism, maybe this is too hopeful. We start out by making a few computation on elements of the ring \begin{align\*} 6x^2-1 &= 0\\ 2x\*3x-1&=12x-1 = 0\\ \end{align\*} So we can use $12x-1=0$ and $2x-4$ to perhaps find if this ring is isomorphic to some modular ring. $$6(2x-4) = 12x - 24 = 1-24 = 0 = 23 \in I$$ and $$R = \mathbb{Z}[x]/(23,6x^2-1,2x-4) \cong \mathbb{Z}\_{23}[x]/(6x^2-1,2x-4)$$ Next we can use this modulo $23$ in the following way to perform further computations: $$4(6x^2-1) = 24x^2-4=x^2-4=0$$ We then can reduce the ideal to $$I = (x^2-4,2x-4)$$ If $x^2 = 4$ and $2x=4$ we must have that $x = 2$ and $I = (x-2)$ We then write $$R \cong \mathbb{Z}\_{23}[x] /(x-2) \cong \mathbb{Z}\_{23}[2] = \mathbb{Z}\_{23}$$ Also, I know that this ring isn't an integral domain because we can take $23,1 \in R$ and get $23\*1 = 0$, so therefore $23$ is a zero divisor. Let me know if my working is correct, I feel a little bit iffy about reducing the ideal, thanks. EDIT: A finite basis for $R$ would just be $\{a|a \in \mathbb{Z}\}$
2017/02/18
[ "https://math.stackexchange.com/questions/2149636", "https://math.stackexchange.com", "https://math.stackexchange.com/users/311475/" ]
Here's an intuitive overview: What is a matrix? A matrix is a *representation* of a linear transformation between two vector spaces. The way we get this representation is by considering the linear transformation of *basis vectors*. If we know the linear transformation of all the basis vectors, we know the transformation of any vector by expressing it as a combination of basis vectors. So we define a matrix is a list of transformations of basis vectors (the columns of the matrix), and we define matrix multiplication as finding the appropriate combination of transformed basis vectors (tell me if this needs clarification). Consider an eigenspace $E\_\lambda$ of a linear transformation $T$. We know that there is a basis for $E\_\lambda$ which has $\dim E\_\lambda$ vectors. A basis is linearly independent, so there's an idea that if we have a set of linearly independent vectors, we can add in some more vectors to get a basis for the entire vector space. Now, we use our basis for $E\_\lambda$ and the other vectors we added in to create a matrix representation of $T$. What we're going to do this time though is probably get a different, but equally valid representation of $T$ than the one we originally had. When we transform the basis vectors of $E\_\lambda$, we know we get a scalar multiple of the original vector. This is why the first few columns (list of transformations of basis vectors) of the matrix they give are columns with all 0s except for the one eigenvalue. From this matrix representation we created, we start to calculate the determinant, and we know that $(x-\lambda)$ shows up at least $\dim E\_\lambda$ times. But it might show up more times. Therefore the algebraic multiplicity (the number of times $(x-\lambda)$ appears) is greater than or equal to the dimension of the eigenspace ($\dim E\_\lambda$). Did that help?
Note that from theorem we know that two distinct eigenvectors must correspond to two linearly independent vectors. NOT THE OTHER WAY AROUND. That is, two vectors can be linearly independent having the same eigenvalue. So, suppose the multiplicity of an eigenvalue is 2. Then, this either means that there are two linearly independent eigenvector or two linearly dependent eigenvector. If they are linearly dependent, then their dimension is obviously one. If not, then their dimension is at most two. And this generalizes to more than two vectors. Hence, it cannot exceed the multiplicity. Was a little late, but hope it helps future readers.
2,149,636
The question I have is from a past exam paper: Identity if it is an integral domain, whether it admits a finite basis over a coefficient ring, or whether it is isomorphic to another ring. The first one is $$R = \mathbb{Z}[x]/(6x^2 -1, 2x-4)$$ My first angle of attack is to find if we can simplify the ideal $I=(6x^2-1,2x-4)$ in hopes of finding a monic irreducible polynomial by taking combinations of elements of the ideal to end up with $I = (f)$ to apply a substitution isomorphism, maybe this is too hopeful. We start out by making a few computation on elements of the ring \begin{align\*} 6x^2-1 &= 0\\ 2x\*3x-1&=12x-1 = 0\\ \end{align\*} So we can use $12x-1=0$ and $2x-4$ to perhaps find if this ring is isomorphic to some modular ring. $$6(2x-4) = 12x - 24 = 1-24 = 0 = 23 \in I$$ and $$R = \mathbb{Z}[x]/(23,6x^2-1,2x-4) \cong \mathbb{Z}\_{23}[x]/(6x^2-1,2x-4)$$ Next we can use this modulo $23$ in the following way to perform further computations: $$4(6x^2-1) = 24x^2-4=x^2-4=0$$ We then can reduce the ideal to $$I = (x^2-4,2x-4)$$ If $x^2 = 4$ and $2x=4$ we must have that $x = 2$ and $I = (x-2)$ We then write $$R \cong \mathbb{Z}\_{23}[x] /(x-2) \cong \mathbb{Z}\_{23}[2] = \mathbb{Z}\_{23}$$ Also, I know that this ring isn't an integral domain because we can take $23,1 \in R$ and get $23\*1 = 0$, so therefore $23$ is a zero divisor. Let me know if my working is correct, I feel a little bit iffy about reducing the ideal, thanks. EDIT: A finite basis for $R$ would just be $\{a|a \in \mathbb{Z}\}$
2017/02/18
[ "https://math.stackexchange.com/questions/2149636", "https://math.stackexchange.com", "https://math.stackexchange.com/users/311475/" ]
Here's an intuitive overview: What is a matrix? A matrix is a *representation* of a linear transformation between two vector spaces. The way we get this representation is by considering the linear transformation of *basis vectors*. If we know the linear transformation of all the basis vectors, we know the transformation of any vector by expressing it as a combination of basis vectors. So we define a matrix is a list of transformations of basis vectors (the columns of the matrix), and we define matrix multiplication as finding the appropriate combination of transformed basis vectors (tell me if this needs clarification). Consider an eigenspace $E\_\lambda$ of a linear transformation $T$. We know that there is a basis for $E\_\lambda$ which has $\dim E\_\lambda$ vectors. A basis is linearly independent, so there's an idea that if we have a set of linearly independent vectors, we can add in some more vectors to get a basis for the entire vector space. Now, we use our basis for $E\_\lambda$ and the other vectors we added in to create a matrix representation of $T$. What we're going to do this time though is probably get a different, but equally valid representation of $T$ than the one we originally had. When we transform the basis vectors of $E\_\lambda$, we know we get a scalar multiple of the original vector. This is why the first few columns (list of transformations of basis vectors) of the matrix they give are columns with all 0s except for the one eigenvalue. From this matrix representation we created, we start to calculate the determinant, and we know that $(x-\lambda)$ shows up at least $\dim E\_\lambda$ times. But it might show up more times. Therefore the algebraic multiplicity (the number of times $(x-\lambda)$ appears) is greater than or equal to the dimension of the eigenspace ($\dim E\_\lambda$). Did that help?
I can't provide any additional intuition for this, but hopefully, some clarity will help you feel more deeply why this is true. This answer is a concrete companion to the intuitive answer by @user156213. Essentially, this proof boils down to the construction of a particular basis such that the matrix of the linear transformation $T : \mathbb{R}^n \rightarrow \mathbb{R}^n$ under this basis allows us to clearly see the multiplicity of a given eigenvalue $\lambda\_i$. Recall that the matrix of a linear transformation $T$ is uniquely determined by the action of $T$ on a chosen set of basis vectors. In particular, if $A$ is the standard matrix of $T$, $A$ is given by the action of $T$ on the standard basis vectors in $\mathbb{R}^n$, $\mathbf{e}\_1,\dotsc,\mathbf{e}\_n$. That is, $$A = \begin{bmatrix} T(\mathbf{e}\_1) & T(\mathbf{e}\_2) & \dotsb & T(\mathbf{e}\_n) \end{bmatrix}\\ \text{where $\mathbf{e}\_j$ is the $j$th column of the identity matrix in $\mathbb{R}^n$}$$ If another basis $\mathcal{B}$ is used, where $\mathcal{B} = \{\mathbf{b}\_1,\mathbf{b}\_2,\dotsc,\mathbf{b}\_n\}$, then the matrix of $T$ relative to $\mathcal{B}$, $[A]\_{\mathcal{B}}$, is given by $$[A]\_{\mathcal{B}} = \begin{bmatrix} T([\mathbf{b}\_1]\_{\mathcal{B}}) & T([\mathbf{b}\_2]\_{\mathcal{B}}) & \dotsb & T([\mathbf{b}\_n]\_{\mathcal{B}}) \end{bmatrix} $$ Note that because the $\mathbf{b}\_j$'s are the basis vectors in $\mathcal{B}$, $[\mathbf{b}\_j]\_{\mathcal{B}} = \mathbf{e}\_j$, so we have $$[A]\_{\mathcal{B}} = \begin{bmatrix} T(\mathbf{e}\_1) & T(\mathbf{e}\_2) & \dotsb & T(\mathbf{e}\_n) \end{bmatrix} $$ Now, if the basis $\mathcal{B}$ is built such that $\{\mathbf{b}\_1,\dotsc,\mathbf{b}\_k\}$ forms a basis for $E\_\lambda$, the eigenspace corresponding to the eigenvalue $\lambda\_i$, then we have $$[A]\_{\mathcal{B}} = \begin{bmatrix} \lambda\_i \mathbf{e}\_1 & \lambda\_i \mathbf{e}\_2 & \dotsb & \lambda\_i \mathbf{e}\_k & T(\mathbf{e}\_{k+1}) & \dotsb & T(\mathbf{e}\_{n}) \end{bmatrix} $$ Note that $[A]\_{\mathcal{B}}$ coincides with the matrix $A'$ from the study guide you linked. From here, can you see why $(\lambda - \lambda\_i)^k$ is a factor of $\det\, (\lambda I\_n - A')$ and thus why the multiplicity of $\lambda\_i$ is at least $k$?
2,149,636
The question I have is from a past exam paper: Identity if it is an integral domain, whether it admits a finite basis over a coefficient ring, or whether it is isomorphic to another ring. The first one is $$R = \mathbb{Z}[x]/(6x^2 -1, 2x-4)$$ My first angle of attack is to find if we can simplify the ideal $I=(6x^2-1,2x-4)$ in hopes of finding a monic irreducible polynomial by taking combinations of elements of the ideal to end up with $I = (f)$ to apply a substitution isomorphism, maybe this is too hopeful. We start out by making a few computation on elements of the ring \begin{align\*} 6x^2-1 &= 0\\ 2x\*3x-1&=12x-1 = 0\\ \end{align\*} So we can use $12x-1=0$ and $2x-4$ to perhaps find if this ring is isomorphic to some modular ring. $$6(2x-4) = 12x - 24 = 1-24 = 0 = 23 \in I$$ and $$R = \mathbb{Z}[x]/(23,6x^2-1,2x-4) \cong \mathbb{Z}\_{23}[x]/(6x^2-1,2x-4)$$ Next we can use this modulo $23$ in the following way to perform further computations: $$4(6x^2-1) = 24x^2-4=x^2-4=0$$ We then can reduce the ideal to $$I = (x^2-4,2x-4)$$ If $x^2 = 4$ and $2x=4$ we must have that $x = 2$ and $I = (x-2)$ We then write $$R \cong \mathbb{Z}\_{23}[x] /(x-2) \cong \mathbb{Z}\_{23}[2] = \mathbb{Z}\_{23}$$ Also, I know that this ring isn't an integral domain because we can take $23,1 \in R$ and get $23\*1 = 0$, so therefore $23$ is a zero divisor. Let me know if my working is correct, I feel a little bit iffy about reducing the ideal, thanks. EDIT: A finite basis for $R$ would just be $\{a|a \in \mathbb{Z}\}$
2017/02/18
[ "https://math.stackexchange.com/questions/2149636", "https://math.stackexchange.com", "https://math.stackexchange.com/users/311475/" ]
Note that from theorem we know that two distinct eigenvectors must correspond to two linearly independent vectors. NOT THE OTHER WAY AROUND. That is, two vectors can be linearly independent having the same eigenvalue. So, suppose the multiplicity of an eigenvalue is 2. Then, this either means that there are two linearly independent eigenvector or two linearly dependent eigenvector. If they are linearly dependent, then their dimension is obviously one. If not, then their dimension is at most two. And this generalizes to more than two vectors. Hence, it cannot exceed the multiplicity. Was a little late, but hope it helps future readers.
I can't provide any additional intuition for this, but hopefully, some clarity will help you feel more deeply why this is true. This answer is a concrete companion to the intuitive answer by @user156213. Essentially, this proof boils down to the construction of a particular basis such that the matrix of the linear transformation $T : \mathbb{R}^n \rightarrow \mathbb{R}^n$ under this basis allows us to clearly see the multiplicity of a given eigenvalue $\lambda\_i$. Recall that the matrix of a linear transformation $T$ is uniquely determined by the action of $T$ on a chosen set of basis vectors. In particular, if $A$ is the standard matrix of $T$, $A$ is given by the action of $T$ on the standard basis vectors in $\mathbb{R}^n$, $\mathbf{e}\_1,\dotsc,\mathbf{e}\_n$. That is, $$A = \begin{bmatrix} T(\mathbf{e}\_1) & T(\mathbf{e}\_2) & \dotsb & T(\mathbf{e}\_n) \end{bmatrix}\\ \text{where $\mathbf{e}\_j$ is the $j$th column of the identity matrix in $\mathbb{R}^n$}$$ If another basis $\mathcal{B}$ is used, where $\mathcal{B} = \{\mathbf{b}\_1,\mathbf{b}\_2,\dotsc,\mathbf{b}\_n\}$, then the matrix of $T$ relative to $\mathcal{B}$, $[A]\_{\mathcal{B}}$, is given by $$[A]\_{\mathcal{B}} = \begin{bmatrix} T([\mathbf{b}\_1]\_{\mathcal{B}}) & T([\mathbf{b}\_2]\_{\mathcal{B}}) & \dotsb & T([\mathbf{b}\_n]\_{\mathcal{B}}) \end{bmatrix} $$ Note that because the $\mathbf{b}\_j$'s are the basis vectors in $\mathcal{B}$, $[\mathbf{b}\_j]\_{\mathcal{B}} = \mathbf{e}\_j$, so we have $$[A]\_{\mathcal{B}} = \begin{bmatrix} T(\mathbf{e}\_1) & T(\mathbf{e}\_2) & \dotsb & T(\mathbf{e}\_n) \end{bmatrix} $$ Now, if the basis $\mathcal{B}$ is built such that $\{\mathbf{b}\_1,\dotsc,\mathbf{b}\_k\}$ forms a basis for $E\_\lambda$, the eigenspace corresponding to the eigenvalue $\lambda\_i$, then we have $$[A]\_{\mathcal{B}} = \begin{bmatrix} \lambda\_i \mathbf{e}\_1 & \lambda\_i \mathbf{e}\_2 & \dotsb & \lambda\_i \mathbf{e}\_k & T(\mathbf{e}\_{k+1}) & \dotsb & T(\mathbf{e}\_{n}) \end{bmatrix} $$ Note that $[A]\_{\mathcal{B}}$ coincides with the matrix $A'$ from the study guide you linked. From here, can you see why $(\lambda - \lambda\_i)^k$ is a factor of $\det\, (\lambda I\_n - A')$ and thus why the multiplicity of $\lambda\_i$ is at least $k$?
50,314,709
I managed to scrape some data from a dynamic website and my output is in json format with only value, How do I modify this code to get both key and value json format and write into a file using python ``` import requests import json URL='http://tfda.go.tz/portal/en/trader_module/trader_module/getRegisteredDrugs_products' payload = "draw=1&columns%5B0%5D%5Bdata%5D=no&columns%5B0%5D%5Bname%5D=&columns%5B0%5D%5Bsearchable%5D=True&columns%5B0%5D%5Borderable%5D=True&columns%5B0%5D%5Bsearch%5D%5Bvalue%5D=&columns%5B0%5D%5Bsearch%5D%5Bregex%5D=False&columns%5B1%5D%5Bdata%5D=certificate_no&columns%5B1%5D%5Bname%5D=&columns%5B1%5D%5Bsearchable%5D=True&columns%5B1%5D%5Borderable%5D=True&columns%5B1%5D%5Bsearch%5D%5Bvalue%5D=&columns%5B1%5D%5Bsearch%5D%5Bregex%5D=False&columns%5B2%5D%5Bdata%5D=brand_name&columns%5B2%5D%5Bname%5D=&columns%5B2%5D%5Bsearchable%5D=True&columns%5B2%5D%5Borderable%5D=True&columns%5B2%5D%5Bsearch%5D%5Bvalue%5D=&columns%5B2%5D%5Bsearch%5D%5Bregex%5D=False&columns%5B3%5D%5Bdata%5D=classification_name&columns%5B3%5D%5Bname%5D=&columns%5B3%5D%5Bsearchable%5D=True&columns%5B3%5D%5Borderable%5D=True&columns%5B3%5D%5Bsearch%5D%5Bvalue%5D=&columns%5B3%5D%5Bsearch%5D%5Bregex%5D=False&columns%5B4%5D%5Bdata%5D=common_name&columns%5B4%5D%5Bname%5D=&columns%5B4%5D%5Bsearchable%5D=True&columns%5B4%5D%5Borderable%5D=True&columns%5B4%5D%5Bsearch%5D%5Bvalue%5D=&columns%5B4%5D%5Bsearch%5D%5Bregex%5D=False&columns%5B5%5D%5Bdata%5D=dosage_form&columns%5B5%5D%5Bname%5D=&columns%5B5%5D%5Bsearchable%5D=True&columns%5B5%5D%5Borderable%5D=True&columns%5B5%5D%5Bsearch%5D%5Bvalue%5D=&columns%5B5%5D%5Bsearch%5D%5Bregex%5D=False&columns%5B6%5D%5Bdata%5D=product_strength&columns%5B6%5D%5Bname%5D=&columns%5B6%5D%5Bsearchable%5D=True&columns%5B6%5D%5Borderable%5D=True&columns%5B6%5D%5Bsearch%5D%5Bvalue%5D=&columns%5B6%5D%5Bsearch%5D%5Bregex%5D=False&columns%5B7%5D%5Bdata%5D=registrant&columns%5B7%5D%5Bname%5D=&columns%5B7%5D%5Bsearchable%5D=True&columns%5B7%5D%5Borderable%5D=True&columns%5B7%5D%5Bsearch%5D%5Bvalue%5D=&columns%5B7%5D%5Bsearch%5D%5Bregex%5D=False&columns%5B8%5D%5Bdata%5D=registrant_country&columns%5B8%5D%5Bname%5D=&columns%5B8%5D%5Bsearchable%5D=True&columns%5B8%5D%5Borderable%5D=True&columns%5B8%5D%5Bsearch%5D%5Bvalue%5D=&columns%5B8%5D%5Bsearch%5D%5Bregex%5D=False&columns%5B9%5D%5Bdata%5D=manufacturer&columns%5B9%5D%5Bname%5D=&columns%5B9%5D%5Bsearchable%5D=True&columns%5B9%5D%5Borderable%5D=True&columns%5B9%5D%5Bsearch%5D%5Bvalue%5D=&columns%5B9%5D%5Bsearch%5D%5Bregex%5D=False&columns%5B10%5D%5Bdata%5D=manufacturer_country&columns%5B10%5D%5Bname%5D=&columns%5B10%5D%5Bsearchable%5D=True&columns%5B10%5D%5Borderable%5D=True&columns%5B10%5D%5Bsearch%5D%5Bvalue%5D=&columns%5B10%5D%5Bsearch%5D%5Bregex%5D=False&columns%5B11%5D%5Bdata%5D=expiry_date&columns%5B11%5D%5Bname%5D=&columns%5B11%5D%5Bsearchable%5D=True&columns%5B11%5D%5Borderable%5D=True&columns%5B11%5D%5Bsearch%5D%5Bvalue%5D=&columns%5B11%5D%5Bsearch%5D%5Bregex%5D=False&columns%5B12%5D%5Bdata%5D=id&columns%5B12%5D%5Bname%5D=&columns%5B12%5D%5Bsearchable%5D=True&columns%5B12%5D%5Borderable%5D=True&columns%5B12%5D%5Bsearch%5D%5Bvalue%5D=&columns%5B12%5D%5Bsearch%5D%5Bregex%5D=False&order%5B0%5D%5Bcolumn%5D=0&order%5B0%5D%5Bdir%5D=asc&start=0&length=3911&search%5Bvalue%5D=&search%5Bregex%5D=False" with requests.Session() as s: s.headers={"User-Agent":"Mozilla/5.0"} s.headers.update({'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'}) res = s.post(URL, data = payload) for data in res.json()['data']: serial = data['no'] certno = data['certificate_no'] brndname = data['brand_name'] clssification = data['classification_name'] common_name = data['common_name'] dosage_form = data['dosage_form'] expiry_date = data['expiry_date'] manufacturer = data['manufacturer'] manufacturer_country = data['manufacturer_country'] product_strength = data['product_strength'] registrant = data['registrant'] registrant_country = data['registrant_country'] output = (dataserial,certno,brndname,clssification, common_name,dosage_form,expiry_date,m anufacturer, manufacturer_country, product_strength,registrant,registrant_country) data = {'brandname':brndname, 'cerficate_number':certno,'expiry_date':expiry_date,'product_strength':product_strength} output = json.dumps(data, ensure_ascii=True, sort_keys=True) with open('drugs.json', 'w') as file: json.dump(output, file) file.write('file') file.close() ``` Here is the output I managed to get [screenshot](https://i.stack.imgur.com/pPH9W.png) but an example of what I require is in this format ``` { "brand_name":"Supirocin" "certificate_no":"TAN 00,1820 D01A GLE" "classification_name":"Human Medicinal Products" "common_name":"Mupirocin" "dosage_form":"Ointment" "expiry_date":"22-06-2018" "id":"18345" "manufacturer":"Glenmark Pharmaceuticals Limited" "manufacturer_country":"INDIA" "no":"6" "product_strength":"2 %w/w" "registrant":"Glenmark Pharmaceuticals Limited" "registrant_country":"INDIA" } ```
2018/05/13
[ "https://Stackoverflow.com/questions/50314709", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5897603/" ]
Try this to get the exact output you have mentioned in your post: ``` import requests import json URL='http://tfda.go.tz/portal/en/trader_module/trader_module/getRegisteredDrugs_products' payload = "draw=1&columns%5B0%5D%5Bdata%5D=no&columns%5B0%5D%5Bname%5D=&columns%5B0%5D%5Bsearchable%5D=True&columns%5B0%5D%5Borderable%5D=True&columns%5B0%5D%5Bsearch%5D%5Bvalue%5D=&columns%5B0%5D%5Bsearch%5D%5Bregex%5D=False&columns%5B1%5D%5Bdata%5D=certificate_no&columns%5B1%5D%5Bname%5D=&columns%5B1%5D%5Bsearchable%5D=True&columns%5B1%5D%5Borderable%5D=True&columns%5B1%5D%5Bsearch%5D%5Bvalue%5D=&columns%5B1%5D%5Bsearch%5D%5Bregex%5D=False&columns%5B2%5D%5Bdata%5D=brand_name&columns%5B2%5D%5Bname%5D=&columns%5B2%5D%5Bsearchable%5D=True&columns%5B2%5D%5Borderable%5D=True&columns%5B2%5D%5Bsearch%5D%5Bvalue%5D=&columns%5B2%5D%5Bsearch%5D%5Bregex%5D=False&columns%5B3%5D%5Bdata%5D=classification_name&columns%5B3%5D%5Bname%5D=&columns%5B3%5D%5Bsearchable%5D=True&columns%5B3%5D%5Borderable%5D=True&columns%5B3%5D%5Bsearch%5D%5Bvalue%5D=&columns%5B3%5D%5Bsearch%5D%5Bregex%5D=False&columns%5B4%5D%5Bdata%5D=common_name&columns%5B4%5D%5Bname%5D=&columns%5B4%5D%5Bsearchable%5D=True&columns%5B4%5D%5Borderable%5D=True&columns%5B4%5D%5Bsearch%5D%5Bvalue%5D=&columns%5B4%5D%5Bsearch%5D%5Bregex%5D=False&columns%5B5%5D%5Bdata%5D=dosage_form&columns%5B5%5D%5Bname%5D=&columns%5B5%5D%5Bsearchable%5D=True&columns%5B5%5D%5Borderable%5D=True&columns%5B5%5D%5Bsearch%5D%5Bvalue%5D=&columns%5B5%5D%5Bsearch%5D%5Bregex%5D=False&columns%5B6%5D%5Bdata%5D=product_strength&columns%5B6%5D%5Bname%5D=&columns%5B6%5D%5Bsearchable%5D=True&columns%5B6%5D%5Borderable%5D=True&columns%5B6%5D%5Bsearch%5D%5Bvalue%5D=&columns%5B6%5D%5Bsearch%5D%5Bregex%5D=False&columns%5B7%5D%5Bdata%5D=registrant&columns%5B7%5D%5Bname%5D=&columns%5B7%5D%5Bsearchable%5D=True&columns%5B7%5D%5Borderable%5D=True&columns%5B7%5D%5Bsearch%5D%5Bvalue%5D=&columns%5B7%5D%5Bsearch%5D%5Bregex%5D=False&columns%5B8%5D%5Bdata%5D=registrant_country&columns%5B8%5D%5Bname%5D=&columns%5B8%5D%5Bsearchable%5D=True&columns%5B8%5D%5Borderable%5D=True&columns%5B8%5D%5Bsearch%5D%5Bvalue%5D=&columns%5B8%5D%5Bsearch%5D%5Bregex%5D=False&columns%5B9%5D%5Bdata%5D=manufacturer&columns%5B9%5D%5Bname%5D=&columns%5B9%5D%5Bsearchable%5D=True&columns%5B9%5D%5Borderable%5D=True&columns%5B9%5D%5Bsearch%5D%5Bvalue%5D=&columns%5B9%5D%5Bsearch%5D%5Bregex%5D=False&columns%5B10%5D%5Bdata%5D=manufacturer_country&columns%5B10%5D%5Bname%5D=&columns%5B10%5D%5Bsearchable%5D=True&columns%5B10%5D%5Borderable%5D=True&columns%5B10%5D%5Bsearch%5D%5Bvalue%5D=&columns%5B10%5D%5Bsearch%5D%5Bregex%5D=False&columns%5B11%5D%5Bdata%5D=expiry_date&columns%5B11%5D%5Bname%5D=&columns%5B11%5D%5Bsearchable%5D=True&columns%5B11%5D%5Borderable%5D=True&columns%5B11%5D%5Bsearch%5D%5Bvalue%5D=&columns%5B11%5D%5Bsearch%5D%5Bregex%5D=False&columns%5B12%5D%5Bdata%5D=id&columns%5B12%5D%5Bname%5D=&columns%5B12%5D%5Bsearchable%5D=True&columns%5B12%5D%5Borderable%5D=True&columns%5B12%5D%5Bsearch%5D%5Bvalue%5D=&columns%5B12%5D%5Bsearch%5D%5Bregex%5D=False&order%5B0%5D%5Bcolumn%5D=0&order%5B0%5D%5Bdir%5D=asc&start=0&length=3911&search%5Bvalue%5D=&search%5Bregex%5D=False" with requests.Session() as s: s.headers={"User-Agent":"Mozilla/5.0"} s.headers.update({'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'}) res = s.post(URL, data = payload) itemlist = [] for data in res.json()['data']: item = {} item['serial'] = data['no'] item['certno'] = data['certificate_no'] item['brndname'] = data['brand_name'] item['clssification'] = data['classification_name'] item['common_name'] = data['common_name'] item['dosage_form'] = data['dosage_form'] item['expiry_date'] = data['expiry_date'] item['manufacturer'] = data['manufacturer'] item['manufacturer_country'] = data['manufacturer_country'] item['product_strength'] = data['product_strength'] item['registrant'] = data['registrant'] item['registrant_country'] = data['registrant_country'] itemlist.append(item) print(itemlist) ```
You first create a dictionary and then convert it to JSON .for example : ``` name ='ali' family='shahabi' output={'name' :name ,'family': family} json.dumps(output) ``` print : ``` '{"name": "ali", "family": "shahabi"}' ``` I suggest convert : ``` output = (dataserial,certno,brndname,clssification, common_name,dosage_form,expiry_date,m anufacturer, manufacturer_country, product_strength,registrant,registrant_country) ``` to ``` output = {'dataserial':dataserial,'certno':certno,'brndname':brndname , ....} ```
23,692,656
Haskell appears to be extremely picky about whitespace in my main function. The following compiles nicely ``` module Main where import System.Environment main :: IO() main = do args <- getArgs putStrLn ("Hello, " ++ args !! 0) ``` But the following two programs give me a parse error ``` module Main where import System.Environment main :: IO() main = do args <- getArgs putStrLn ("Hello, " ++ args !! 0) ``` and ``` module Main where import System.Environment main :: IO() main = do args <- getArgs putStrLn ("Hello, " ++ args !! 0) ``` It would seem that `printStrLn` *must* line up with `args` or haskell throws a fit. This seems unnecessary. Why is haskell doing this?
2014/05/16
[ "https://Stackoverflow.com/questions/23692656", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1020076/" ]
To add to [Mephy’s answer](https://stackoverflow.com/a/23692683), while Haskell, written in usual Haskell style, *does* care about indentation (called ‘layout’ in the specification), you can write your code in a style such that indentation is ignored: ``` module Main where { import System.Environment; main :: IO (); main = do { args <- getArgs; putStrLn ("Hello, " ++ args !! 0) } } ``` You don’t usually see this style being used for a whole module. Occasionally you’ll see it being used for a single short `do` or `let` block or something (you can mix both styles), but most people rely on layout.
Haskell does indeed cares about indentation, just like Python. When using the `do` construct, you must have all your actions in the same column. Note you also need to use spaces, not tabs, as '\t' will usually get ignored.
255,957
Someone who has been worn down by a harsh working-life?
2015/06/30
[ "https://english.stackexchange.com/questions/255957", "https://english.stackexchange.com", "https://english.stackexchange.com/users/127228/" ]
Such a person would become ***[careworn](http://dictionary.reference.com/browse/careworn)***. > > adjective > > > 1. showing signs of care or worry; fatigued by trouble or anxiety; haggard: > > > "a careworn old woman." > > > Reference <http://dictionary.reference.com/browse/careworn>
**workhorse** (*noun*): * a person or machine that dependably performs hard work over a long period of time [ODO](http://www.oxforddictionaries.com/definition/english/workhorse) * someone who does a lot of hard or boring work [Macmillan](http://www.macmillandictionary.com/dictionary/british/workhorse)
255,957
Someone who has been worn down by a harsh working-life?
2015/06/30
[ "https://english.stackexchange.com/questions/255957", "https://english.stackexchange.com", "https://english.stackexchange.com/users/127228/" ]
I think ***[toiler](http://www.vocabulary.com/dictionary/toiler)*** may suggest the idea of a hard worker: > > * Toilers are people who work long and hard. Any employer would be grateful to have toilers as employees. > * If you know that to toil is to work hard, then the meaning of toiler won't be a surprise. A toiler works strenuously; you won't see a toiler hanging out by the water cooler. **People with physical jobs such as construction workers and miners are often referred to as toilers.** > > > (www.vocabulary.com)
> > slogger > > > someone who works diligently for long hours. (TFD) > > >
255,957
Someone who has been worn down by a harsh working-life?
2015/06/30
[ "https://english.stackexchange.com/questions/255957", "https://english.stackexchange.com", "https://english.stackexchange.com/users/127228/" ]
Such a person would become ***[careworn](http://dictionary.reference.com/browse/careworn)***. > > adjective > > > 1. showing signs of care or worry; fatigued by trouble or anxiety; haggard: > > > "a careworn old woman." > > > Reference <http://dictionary.reference.com/browse/careworn>
Well, yes, exactly: [***downtrodden***](http://www.vocabulary.com/dictionary/downtrodden) > > abused or oppressed by people in power > > > ... but you'd be using it in a more literal and less figurative sense. Worn down by work with little reward.
255,957
Someone who has been worn down by a harsh working-life?
2015/06/30
[ "https://english.stackexchange.com/questions/255957", "https://english.stackexchange.com", "https://english.stackexchange.com/users/127228/" ]
Such a person would become ***[careworn](http://dictionary.reference.com/browse/careworn)***. > > adjective > > > 1. showing signs of care or worry; fatigued by trouble or anxiety; haggard: > > > "a careworn old woman." > > > Reference <http://dictionary.reference.com/browse/careworn>
I think ***[toiler](http://www.vocabulary.com/dictionary/toiler)*** may suggest the idea of a hard worker: > > * Toilers are people who work long and hard. Any employer would be grateful to have toilers as employees. > * If you know that to toil is to work hard, then the meaning of toiler won't be a surprise. A toiler works strenuously; you won't see a toiler hanging out by the water cooler. **People with physical jobs such as construction workers and miners are often referred to as toilers.** > > > (www.vocabulary.com)
255,957
Someone who has been worn down by a harsh working-life?
2015/06/30
[ "https://english.stackexchange.com/questions/255957", "https://english.stackexchange.com", "https://english.stackexchange.com/users/127228/" ]
I think **haggard** fits the bill here. HAGGARD having a gaunt, wasted, or exhausted appearance, as from prolonged suffering, exertion, or anxiety; worn
> > slogger > > > someone who works diligently for long hours. (TFD) > > >
255,957
Someone who has been worn down by a harsh working-life?
2015/06/30
[ "https://english.stackexchange.com/questions/255957", "https://english.stackexchange.com", "https://english.stackexchange.com/users/127228/" ]
I think **haggard** fits the bill here. HAGGARD having a gaunt, wasted, or exhausted appearance, as from prolonged suffering, exertion, or anxiety; worn
Such a person would become ***[careworn](http://dictionary.reference.com/browse/careworn)***. > > adjective > > > 1. showing signs of care or worry; fatigued by trouble or anxiety; haggard: > > > "a careworn old woman." > > > Reference <http://dictionary.reference.com/browse/careworn>
255,957
Someone who has been worn down by a harsh working-life?
2015/06/30
[ "https://english.stackexchange.com/questions/255957", "https://english.stackexchange.com", "https://english.stackexchange.com/users/127228/" ]
I think **haggard** fits the bill here. HAGGARD having a gaunt, wasted, or exhausted appearance, as from prolonged suffering, exertion, or anxiety; worn
**workhorse** (*noun*): * a person or machine that dependably performs hard work over a long period of time [ODO](http://www.oxforddictionaries.com/definition/english/workhorse) * someone who does a lot of hard or boring work [Macmillan](http://www.macmillandictionary.com/dictionary/british/workhorse)
255,957
Someone who has been worn down by a harsh working-life?
2015/06/30
[ "https://english.stackexchange.com/questions/255957", "https://english.stackexchange.com", "https://english.stackexchange.com/users/127228/" ]
I think ***[toiler](http://www.vocabulary.com/dictionary/toiler)*** may suggest the idea of a hard worker: > > * Toilers are people who work long and hard. Any employer would be grateful to have toilers as employees. > * If you know that to toil is to work hard, then the meaning of toiler won't be a surprise. A toiler works strenuously; you won't see a toiler hanging out by the water cooler. **People with physical jobs such as construction workers and miners are often referred to as toilers.** > > > (www.vocabulary.com)
Well, yes, exactly: [***downtrodden***](http://www.vocabulary.com/dictionary/downtrodden) > > abused or oppressed by people in power > > > ... but you'd be using it in a more literal and less figurative sense. Worn down by work with little reward.
255,957
Someone who has been worn down by a harsh working-life?
2015/06/30
[ "https://english.stackexchange.com/questions/255957", "https://english.stackexchange.com", "https://english.stackexchange.com/users/127228/" ]
I think **haggard** fits the bill here. HAGGARD having a gaunt, wasted, or exhausted appearance, as from prolonged suffering, exertion, or anxiety; worn
I think ***[toiler](http://www.vocabulary.com/dictionary/toiler)*** may suggest the idea of a hard worker: > > * Toilers are people who work long and hard. Any employer would be grateful to have toilers as employees. > * If you know that to toil is to work hard, then the meaning of toiler won't be a surprise. A toiler works strenuously; you won't see a toiler hanging out by the water cooler. **People with physical jobs such as construction workers and miners are often referred to as toilers.** > > > (www.vocabulary.com)
255,957
Someone who has been worn down by a harsh working-life?
2015/06/30
[ "https://english.stackexchange.com/questions/255957", "https://english.stackexchange.com", "https://english.stackexchange.com/users/127228/" ]
I think **haggard** fits the bill here. HAGGARD having a gaunt, wasted, or exhausted appearance, as from prolonged suffering, exertion, or anxiety; worn
Well, yes, exactly: [***downtrodden***](http://www.vocabulary.com/dictionary/downtrodden) > > abused or oppressed by people in power > > > ... but you'd be using it in a more literal and less figurative sense. Worn down by work with little reward.
26,890,888
I'm using google tag manager: ```js <script> (function(w, d, s, l, i) { w[l] = w[l] || []; w[l].push({ 'gtm.start': new Date().getTime(), event: 'gtm.js' }); var f = d.getElementsByTagName(s)[0], j = d.createElement(s), dl = l != 'dataLayer' ? '&l=' + l : ''; j.async = true; j.src = '//www.googletagmanager.com/gtm.js?id=' + i + dl; f.parentNode.insertBefore(j, f); })(window, document, 'script', 'dataLayer', 'GTM-XXXX'); </script> ``` But when I used `https://` to call the page, it gave me mixed content error: 1) .... was loaded over HTTPS, but ran insecure content from '<http://www.youtube.com/iframe_api>': this content should also be loaded over HTTPS. 2) .... was loaded over HTTPS, but ran insecure content from '<http://s.ytimg.com/yts/jsbin/www-widgetapi-vflFaZyew/www-widgetapi.js>': this content should also be loaded over HTTPS. I can't figure out why or how to fix this, could you please help? Thanks.
2014/11/12
[ "https://Stackoverflow.com/questions/26890888", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4199129/" ]
You may want to make sure that your tags (especially custom tags) are not specifying the http protocol. You can make URLs work on both http and https by not using the protocol portion of the URL. For example: ``` //www.google.com/ ```
If your are using scully, this issue is discussed [here](https://github.com/scullyio/scully/issues/291). Scully generates renders using http. So, the google tag manager script in your header will contain http request in all pages. Solution 1 ========== As SanderElias pointed out in the [issue](https://github.com/scullyio/scully/issues/291), ``` A quick solution would be a plugin that scans your results, and replaces http with https, However, we are already looking into supporting https during development, which will solve your issue too. ``` So I used this [plugin](https://github.com/gammastream/scully-plugins/tree/master/projects/scully-plugin-regex) with this setup. ``` const RegexPlugin = getRegexPlugin(); setPluginConfig(RegexPlugin, { replacements: [{ from: 'http:', to: 'https:' }] }); ``` This will indeed replace all http by https. **Warning**: If you have links that only work with http, that will broke them all. So, I had to manually change it back to http after the scully post render. Solution 2 ========== Run scully in SSL mode.
5,647,270
I have a small issue with integrating uploadify with zendframework. I have found a lot of posts about this issue but none of them able to help me. in uploadify script when I use this ``` 'script': '/uploadtest.php', ``` It works perfectly alright. but when I use this and call a action in controller like this. ``` 'script': 'http://zendbase.local/asset/asset/addedit', ``` OR `'script': '/asset/asset/addedit'`, It does not work. while above url is accessible directly. but somehow swf uploadify is not calling this url successfully while it shows me bar with 100% success. Any idea? edit: I have tried this solution mentioned at <http://www.uploadify.com/forums/discussion/1848/zend-framework-integration-help/p1> ``` 'script': '<?php echo $this->url(array('module' => 'asset', 'controller' => 'asset', 'action' => 'addedit')) ?>', ``` but gives me a error "Message: Cannot assemble. Reversed route is not specified."
2011/04/13
[ "https://Stackoverflow.com/questions/5647270", "https://Stackoverflow.com", "https://Stackoverflow.com/users/376702/" ]
I figure out the solution. It was stupid mistake. my controller was not accessible for every one and it was returning the login page as response. so I change the rights in my ACL and it works fine. I recommend Charles Proxy (http://www.charlesproxy.com) for debugging which helped me a lot to read the response from swf call. Thanks.
I had problem with the same error > > cannot assemble. reversed route is not specified > > > The solution, like they wrote in zend manual "Since regex patterns are not easily reversed, you will need to prepare a reverse URL if you wish to use a URL helper or even an assemble method of this class. This reversed path is represented by a string parsable by sprintf() and is defined as a fourth construct parameter:" ``` $route = new Zend_Controller_Router_Route_Regex( 'archive/(\d+)', array( ... ), array('year' => 1), 'archive/%s' ); ``` I found the solution in this thread [Zend community thread](http://zend-framework-community.634137.n4.nabble.com/Using-url-view-helper-with-regex-route-td660695.html)
13,655,916
I am trying to use RestyGWT's JsonEncoderDecoder to encode/decode JSON objects. From their documentation I was able to do: ``` public interface PersonCodec extends JsonEncoderDecoder<PersonCodec>> {} ``` and use the encode/decode functions. However, when I do: ``` public interface PersonListCodec extends JsonEncoderDecoder<List<PersonCodec>> {} ``` it gives me compilation errors: ``` java.lang.NullPointerException at org.fusesource.restygwt.rebind.BaseSourceCreator.<init>(BaseSourceCreator.java:76) at org.fusesource.restygwt.rebind.JsonEncoderDecoderClassCreator.<init>(JsonEncoderDecoderClassCreator.java:79) at org.fusesource.restygwt.rebind.ExtendedJsonEncoderDecoderClassCreator.createComposerFactory(ExtendedJsonEncoderDecoderClassCreator.java:46) at org.fusesource.restygwt.rebind.BaseSourceCreator.create(BaseSourceCreator.java:210) at org.fusesource.restygwt.rebind.JsonEncoderDecoderGenerator.generate(JsonEncoderDecoderGenerator.java:38) at com.google.gwt.core.ext.IncrementalGenerator.generateNonIncrementally(IncrementalGenerator.java:40) at com.google.gwt.dev.javac.StandardGeneratorContext.runGeneratorIncrementally(StandardGeneratorContext.java:657) at com.google.gwt.dev.cfg.RuleGenerateWith.realize(RuleGenerateWith.java:41) at com.google.gwt.dev.shell.StandardRebindOracle$Rebinder.rebind(StandardRebindOracle.java:79) at com.google.gwt.dev.shell.StandardRebindOracle.rebind(StandardRebindOracle.java:276) at com.google.gwt.dev.shell.StandardRebindOracle.rebind(StandardRebindOracle.java:265) at com.google.gwt.dev.DistillerRebindPermutationOracle.getAllPossibleRebindAnswers(DistillerRebindPermutationOracle.java:91) at com.google.gwt.dev.jjs.impl.UnifyAst$UnifyVisitor.handleGwtCreate(UnifyAst.java:355) at com.google.gwt.dev.jjs.impl.UnifyAst$UnifyVisitor.handleMagicMethodCall(UnifyAst.java:433) at com.google.gwt.dev.jjs.impl.UnifyAst$UnifyVisitor.endVisit(UnifyAst.java:237) at com.google.gwt.dev.jjs.ast.JMethodCall.traverse(JMethodCall.java:243) at com.google.gwt.dev.jjs.ast.JModVisitor.traverse(JModVisitor.java:361) ... ``` Any ideas on how to make this work? Or other suggestion for encoding/decoding json to java objects? Thanks!
2012/12/01
[ "https://Stackoverflow.com/questions/13655916", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1186955/" ]
I was able to encode my list using the following piece of code: ``` JSONArray batch = new JSONArray(); int idx=0; for (Pojo i : buffer) { batch.set(idx++, CODEC.encode(i)); } ```
I wrap my List in an Object since I am in control of the output. ``` @XmlRootElement public class WrapperResult { protected List<Person> result; } ``` Then I can encode and decode lists with no problem.
12,355,231
I work on an authentication component for my application. I'm using the Apache Shiro API with salted password. I create a new user with the salt like in this example : ``` ByteSource salt = randomNumberGenerator.nextBytes(32); byte[] byteTabSalt = salt.getBytes(); String strSalt = byteArrayToHexString(byteTabSalt); String hashedPasswordBase64 = new Sha256Hash(inPassword, salt, 512).toBase64(); ``` But I'dont understand how I am suppose to use the salt to auhtenticate a user in the doGetAuthenticationInfo method. My method must return a SaltedAuthenticatedInfo but I don't understand how I'm suppose to create it. I don't understand the link between the Credential Matcher and the SaltedAuthenticateInfo. Do I have to inform a credential matcher when I create password salts ? Thanks for your help.
2012/09/10
[ "https://Stackoverflow.com/questions/12355231", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1269325/" ]
SaltedAuthenticationInfo ------------------------ `SaltedAuthenticationInfo` is an interface. The Shiro API provides a number of default implementations for convenience. As much as possible try to use one of the default implementations; avoid creating your own. I suggest `SimpleAuthenticationInfo` which implements more than just `SaltedAuthenticationInfo` but will probably suffice for your purposes. See [org.apache.shiro.authc.SimpleAuthenticationInfo](http://shiro.apache.org/static/current/apidocs/org/apache/shiro/authc/SimpleAuthenticationInfo.html "Shiro JavaDoc") for more information. If you absolutely need to implement your own `SaltedAuthenticationInfo`, you should follow the documentation carefully. See [org.apache.shiro.authc.AuthenticationInfo](http://shiro.apache.org/static/current/apidocs/org/apache/shiro/authc/AuthenticationInfo.html "Shiro JavaDoc") and [org.apache.shiro.authc.SaltedAuthenticationInfo](http://shiro.apache.org/static/current/apidocs/org/apache/shiro/authc/SaltedAuthenticationInfo.html "Shiro JavaDoc") for more information. HashedCredentialMatcher ----------------------- `boolean doCredentialsMatch(AuthenticationToken, AuthenticationInfo)` actually takes care of the authentication logic. This method takes the user-submitted credentials in the form of an `AuthenticationToken` and compares them to the previously stored credentials in the form of `AuthenticationInfo`. You have to make sure that you pass all the necessary information to `HashCredentialMatcher` first though (iterations, algorithm, and a salt in the `SaltedAuthenticationInfo`). pseudo-example use, ``` final int iterations = 50000; AuthenticationToken authToken = ...; SaltedAuthenticationInfo saltedAuthInfo = ...; HashedCredentialsMatcher authenticator = new HashedCredentialsMatcher(Sha256Hash.ALGORITHM_NAME); authenticator.setHashIterations(iterations); final boolean successfulAuthentication = authenticator.doCredentialsMatch(authToken, saltedAuthInfo); ``` See [org.apache.shiro.authc.credential.HashedCredentialsMatcher](http://shiro.apache.org/static/current/apidocs/org/apache/shiro/authc/credential/HashedCredentialsMatcher.html "Shiro JavaDoc") for more information. Other security notes -------------------- * **Salt length** 256-bit salt looks good. With a salt that large you minimize the risk of any two users sharing the same salt. Keep in mind when picking a salt length that the [Birthday Paradox](http://en.wikipedia.org/wiki/Birthday_problem) comes into play. * **Number of iterations** As a rule of thumb you should *never* use less than 10,000. You currently use 512, ``` String hashedPasswordBase64 = new Sha256Hash(inPassword, salt, 512).toBase64(); ``` Most hashing algorithms are extremely fast (sha256 included), you don't want to do any would-be hackers any favors. The more iterations you use the slower authentication will be, but it directly slows down cracking attempts as well. You will want to set the number of iterations as high as possible while still maintaining an acceptable responsiveness for your application. You may be surprised how high you can go. Personally I tend to use millions; but I am paranoid and don't mind a slight delay See [Key Stretching](http://en.wikipedia.org/wiki/Key_stretching) for more information. * **Personally I would avoid hard coding any of the hashing parameters (hashing algorithm, salt size, iteration count, ect)** By hard coding these values you limit your immediate ability to adapt and respond. Storing these values with the hashed credentials allows you to make a more dynamic authentication where you can configure and roll out stronger algorithms in the future with relatively little effort. For example your default hashing algorithm may be sha256 using 50,000 iterations and a 256-bit salt. In the future though 50,000 iterations may not be enough. Without much fuss you would be able to change the preferred algorithm configuration to iterate 100,000 times for all new passwords. You don't have to worry about breaking old passwords because you are not changing the algorithm parameters that you stored with existing credentials. You can also use this to change the salt-size or even the algorithm altogether. If desired you can then make everyone to change their password; forcing users pick up the new (hopefully stronger) preferred algorithm setup. The Unix operating system has done this for years with [/etc/shadow](http://en.wikipedia.org/wiki/Shadow_password). It takes a bit more effort up front, but it's worth the investment. Strong authentication controls are critical.
My error was to not create correctly the AuthenticationInfo which was compare the AuthenticationToken. So in the doGetAuthenticationInfo method of my own realm I do this : ``` Object principal = arg0.getPrincipal(); Object credentials = arg0.getCredentials(); String realmName = this.getName(); // to get the realm name SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(principal, credentials, realmName); CredentialsMatcher credentialsMatcher = this.getCredentialsMatcher(); boolean successfulAuthentication = credentialsMatcher.doCredentialsMatch(arg0, simpleAuthenticationInfo); ``` And so the boolean successfulAuthentication is true. But I don't understand what's the difference between CredentialsMatcher and HashedCredentialsMatcher because that one was to false. I have to read Javadoc.
27,556,104
In my program an array `fClasses` of fixed length [7] of objects is created, each object is a class `FClass` that contains 3 `Strings`, an `int`, and an `int[]`. These values are read from a .txt file and added to a specific index of the array based on the value of the `int`. There are less entries in the .txt file then there are indices in the array so the array ends up looking something like this: ``` fClasses[0] { str1, str2, str3, int1, int [] {1,2,3,4,5}} fClasses[1] { str1, str2, str3, int1, int [] {1,2,3,4,5}} fClasses[2] { str1, str2, str3, int1, int [] {1,2,3,4,5}} fClasses[3] null fClasses[4] null fClasses[5] { str1, str2, str3, int1, int [] {1,2,3,4,5}} fClasses[6] { str1, str2, str3, int1, int [] {1,2,3,4,5}} ``` Later in the program I need to sort the array based on the average of the `ints` in the `int[]`. I have a working method to return this but when I try to sort the array using `compareTo` and `Arrays.sort` I get a long list of errors starting with these: ``` Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException at java.util.ComparableTimSort.countRunAndMakeAscending(Unknown Source) at java.util.ComparableTimSort.sort(Unknown Source) at java.util.Arrays.sort(Unknown Source) at FProg.sortClasses(FProg.java:228) ``` My `compareTo` method looks like this and it's located in a class that implements `Comparable`: ``` public int compareTo(FClass other) { if (other == null || this.avg == other.avg) { return 0; } else if (this.avg < other.avg) { return -1; } else { return 1; } } ``` And I'm trying to call this method to do the sorting: ``` public void sortClasses() { Arrays.sort(fClasses, 0, MAX_CLASSES); } ``` I have tested it with a .txt file that contains enough entries to fill the array and the sort works correctly in that case, so I believe the problem I'm having is that my sort method can't sort an array with null elements in it. Is there any way this can be achieved?
2014/12/18
[ "https://Stackoverflow.com/questions/27556104", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4375799/" ]
You need your own `Comparator` implementation and check for nulls and return 0 ``` Arrays.sort(fClasses, new Comparator<FClass>() { @Override public int compare(FClass o1, FClass o2) { if (o1 == null && o2 == null) { return 0; } if (o1 == null) { return 1; } if (o2 == null) { return -1; } return o1.compareTo(o2); }}); ```
You have to create a `Comparator<FClass>`, rather than use a `Comparable<FClass>`. ``` public class FClassComparator implements Comparator<FClass> { public int compare(FClass left, FClass right) { // Swap -1 and 1 here if you want nulls to move to the front. if (left == null) return right == null ? 0 : 1; if (right == null) return -1; // you are now guaranteed that neither left nor right are null. // I'm assuming avg is int. There is also Double.compare if they aren't. return Integer.compare(left.avg, right.avg); } } ``` Then call sort via: ``` Arrays.sort(fClassArray, new FClassComparator()); ```
27,556,104
In my program an array `fClasses` of fixed length [7] of objects is created, each object is a class `FClass` that contains 3 `Strings`, an `int`, and an `int[]`. These values are read from a .txt file and added to a specific index of the array based on the value of the `int`. There are less entries in the .txt file then there are indices in the array so the array ends up looking something like this: ``` fClasses[0] { str1, str2, str3, int1, int [] {1,2,3,4,5}} fClasses[1] { str1, str2, str3, int1, int [] {1,2,3,4,5}} fClasses[2] { str1, str2, str3, int1, int [] {1,2,3,4,5}} fClasses[3] null fClasses[4] null fClasses[5] { str1, str2, str3, int1, int [] {1,2,3,4,5}} fClasses[6] { str1, str2, str3, int1, int [] {1,2,3,4,5}} ``` Later in the program I need to sort the array based on the average of the `ints` in the `int[]`. I have a working method to return this but when I try to sort the array using `compareTo` and `Arrays.sort` I get a long list of errors starting with these: ``` Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException at java.util.ComparableTimSort.countRunAndMakeAscending(Unknown Source) at java.util.ComparableTimSort.sort(Unknown Source) at java.util.Arrays.sort(Unknown Source) at FProg.sortClasses(FProg.java:228) ``` My `compareTo` method looks like this and it's located in a class that implements `Comparable`: ``` public int compareTo(FClass other) { if (other == null || this.avg == other.avg) { return 0; } else if (this.avg < other.avg) { return -1; } else { return 1; } } ``` And I'm trying to call this method to do the sorting: ``` public void sortClasses() { Arrays.sort(fClasses, 0, MAX_CLASSES); } ``` I have tested it with a .txt file that contains enough entries to fill the array and the sort works correctly in that case, so I believe the problem I'm having is that my sort method can't sort an array with null elements in it. Is there any way this can be achieved?
2014/12/18
[ "https://Stackoverflow.com/questions/27556104", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4375799/" ]
You need your own `Comparator` implementation and check for nulls and return 0 ``` Arrays.sort(fClasses, new Comparator<FClass>() { @Override public int compare(FClass o1, FClass o2) { if (o1 == null && o2 == null) { return 0; } if (o1 == null) { return 1; } if (o2 == null) { return -1; } return o1.compareTo(o2); }}); ```
Using Java 8, you can easily build the comparator you need: ``` Arrays.sort(fClasses, Comparator.nullsFirst(Comparator.naturalOrder())); ``` Use `nullsLast` instead if that's what you want, of course.
27,556,104
In my program an array `fClasses` of fixed length [7] of objects is created, each object is a class `FClass` that contains 3 `Strings`, an `int`, and an `int[]`. These values are read from a .txt file and added to a specific index of the array based on the value of the `int`. There are less entries in the .txt file then there are indices in the array so the array ends up looking something like this: ``` fClasses[0] { str1, str2, str3, int1, int [] {1,2,3,4,5}} fClasses[1] { str1, str2, str3, int1, int [] {1,2,3,4,5}} fClasses[2] { str1, str2, str3, int1, int [] {1,2,3,4,5}} fClasses[3] null fClasses[4] null fClasses[5] { str1, str2, str3, int1, int [] {1,2,3,4,5}} fClasses[6] { str1, str2, str3, int1, int [] {1,2,3,4,5}} ``` Later in the program I need to sort the array based on the average of the `ints` in the `int[]`. I have a working method to return this but when I try to sort the array using `compareTo` and `Arrays.sort` I get a long list of errors starting with these: ``` Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException at java.util.ComparableTimSort.countRunAndMakeAscending(Unknown Source) at java.util.ComparableTimSort.sort(Unknown Source) at java.util.Arrays.sort(Unknown Source) at FProg.sortClasses(FProg.java:228) ``` My `compareTo` method looks like this and it's located in a class that implements `Comparable`: ``` public int compareTo(FClass other) { if (other == null || this.avg == other.avg) { return 0; } else if (this.avg < other.avg) { return -1; } else { return 1; } } ``` And I'm trying to call this method to do the sorting: ``` public void sortClasses() { Arrays.sort(fClasses, 0, MAX_CLASSES); } ``` I have tested it with a .txt file that contains enough entries to fill the array and the sort works correctly in that case, so I believe the problem I'm having is that my sort method can't sort an array with null elements in it. Is there any way this can be achieved?
2014/12/18
[ "https://Stackoverflow.com/questions/27556104", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4375799/" ]
You need your own `Comparator` implementation and check for nulls and return 0 ``` Arrays.sort(fClasses, new Comparator<FClass>() { @Override public int compare(FClass o1, FClass o2) { if (o1 == null && o2 == null) { return 0; } if (o1 == null) { return 1; } if (o2 == null) { return -1; } return o1.compareTo(o2); }}); ```
With [Apache Commons Collections 4](https://commons.apache.org/proper/commons-collections/) you can use [ComparatorUtils](https://commons.apache.org/proper/commons-collections/apidocs/org/apache/commons/collections4/ComparatorUtils.html) to do that: ``` Collections.sort(arr, ComparatorUtils.nullLowComparator(ComparatorUtils.NATURAL_COMPARATOR)); ```
27,556,104
In my program an array `fClasses` of fixed length [7] of objects is created, each object is a class `FClass` that contains 3 `Strings`, an `int`, and an `int[]`. These values are read from a .txt file and added to a specific index of the array based on the value of the `int`. There are less entries in the .txt file then there are indices in the array so the array ends up looking something like this: ``` fClasses[0] { str1, str2, str3, int1, int [] {1,2,3,4,5}} fClasses[1] { str1, str2, str3, int1, int [] {1,2,3,4,5}} fClasses[2] { str1, str2, str3, int1, int [] {1,2,3,4,5}} fClasses[3] null fClasses[4] null fClasses[5] { str1, str2, str3, int1, int [] {1,2,3,4,5}} fClasses[6] { str1, str2, str3, int1, int [] {1,2,3,4,5}} ``` Later in the program I need to sort the array based on the average of the `ints` in the `int[]`. I have a working method to return this but when I try to sort the array using `compareTo` and `Arrays.sort` I get a long list of errors starting with these: ``` Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException at java.util.ComparableTimSort.countRunAndMakeAscending(Unknown Source) at java.util.ComparableTimSort.sort(Unknown Source) at java.util.Arrays.sort(Unknown Source) at FProg.sortClasses(FProg.java:228) ``` My `compareTo` method looks like this and it's located in a class that implements `Comparable`: ``` public int compareTo(FClass other) { if (other == null || this.avg == other.avg) { return 0; } else if (this.avg < other.avg) { return -1; } else { return 1; } } ``` And I'm trying to call this method to do the sorting: ``` public void sortClasses() { Arrays.sort(fClasses, 0, MAX_CLASSES); } ``` I have tested it with a .txt file that contains enough entries to fill the array and the sort works correctly in that case, so I believe the problem I'm having is that my sort method can't sort an array with null elements in it. Is there any way this can be achieved?
2014/12/18
[ "https://Stackoverflow.com/questions/27556104", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4375799/" ]
You need your own `Comparator` implementation and check for nulls and return 0 ``` Arrays.sort(fClasses, new Comparator<FClass>() { @Override public int compare(FClass o1, FClass o2) { if (o1 == null && o2 == null) { return 0; } if (o1 == null) { return 1; } if (o2 == null) { return -1; } return o1.compareTo(o2); }}); ```
By importing the [org.apache.commons.collections.comparators](https://commons.apache.org/proper/commons-collections/javadocs/api-2.1.1/org/apache/commons/collections/comparators/NullComparator.html) package of the [Apache 2.1.1 Release](https://commons.apache.org/proper/commons-collections/javadocs/api-2.1.1/overview-summary.html) library, I'm able to sort a list, such as an `ArrayList<String>`, using the `NullComparator` as the second argument of the `Collections.sort()` method, as follows: ``` ArrayList<String> list = new ArrayList<String>(); list.add("foo"); list.add("bar"); list.add("baz"); list.add(null); // Sort the list Collections.sort(list, new NullComparator(true)); System.out.println(list); // outputs: // [bar, baz, foo, null] ``` The thing I like about this approach is that the `NullComparator` has an overload constructor which allows you to specify whether you want `null` to be considered a high value or a low value, which seems pretty intuitive to me. ``` NullComparator(boolean nullsAreHigh) ``` Hope this helps someone!
27,556,104
In my program an array `fClasses` of fixed length [7] of objects is created, each object is a class `FClass` that contains 3 `Strings`, an `int`, and an `int[]`. These values are read from a .txt file and added to a specific index of the array based on the value of the `int`. There are less entries in the .txt file then there are indices in the array so the array ends up looking something like this: ``` fClasses[0] { str1, str2, str3, int1, int [] {1,2,3,4,5}} fClasses[1] { str1, str2, str3, int1, int [] {1,2,3,4,5}} fClasses[2] { str1, str2, str3, int1, int [] {1,2,3,4,5}} fClasses[3] null fClasses[4] null fClasses[5] { str1, str2, str3, int1, int [] {1,2,3,4,5}} fClasses[6] { str1, str2, str3, int1, int [] {1,2,3,4,5}} ``` Later in the program I need to sort the array based on the average of the `ints` in the `int[]`. I have a working method to return this but when I try to sort the array using `compareTo` and `Arrays.sort` I get a long list of errors starting with these: ``` Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException at java.util.ComparableTimSort.countRunAndMakeAscending(Unknown Source) at java.util.ComparableTimSort.sort(Unknown Source) at java.util.Arrays.sort(Unknown Source) at FProg.sortClasses(FProg.java:228) ``` My `compareTo` method looks like this and it's located in a class that implements `Comparable`: ``` public int compareTo(FClass other) { if (other == null || this.avg == other.avg) { return 0; } else if (this.avg < other.avg) { return -1; } else { return 1; } } ``` And I'm trying to call this method to do the sorting: ``` public void sortClasses() { Arrays.sort(fClasses, 0, MAX_CLASSES); } ``` I have tested it with a .txt file that contains enough entries to fill the array and the sort works correctly in that case, so I believe the problem I'm having is that my sort method can't sort an array with null elements in it. Is there any way this can be achieved?
2014/12/18
[ "https://Stackoverflow.com/questions/27556104", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4375799/" ]
Using Java 8, you can easily build the comparator you need: ``` Arrays.sort(fClasses, Comparator.nullsFirst(Comparator.naturalOrder())); ``` Use `nullsLast` instead if that's what you want, of course.
You have to create a `Comparator<FClass>`, rather than use a `Comparable<FClass>`. ``` public class FClassComparator implements Comparator<FClass> { public int compare(FClass left, FClass right) { // Swap -1 and 1 here if you want nulls to move to the front. if (left == null) return right == null ? 0 : 1; if (right == null) return -1; // you are now guaranteed that neither left nor right are null. // I'm assuming avg is int. There is also Double.compare if they aren't. return Integer.compare(left.avg, right.avg); } } ``` Then call sort via: ``` Arrays.sort(fClassArray, new FClassComparator()); ```
27,556,104
In my program an array `fClasses` of fixed length [7] of objects is created, each object is a class `FClass` that contains 3 `Strings`, an `int`, and an `int[]`. These values are read from a .txt file and added to a specific index of the array based on the value of the `int`. There are less entries in the .txt file then there are indices in the array so the array ends up looking something like this: ``` fClasses[0] { str1, str2, str3, int1, int [] {1,2,3,4,5}} fClasses[1] { str1, str2, str3, int1, int [] {1,2,3,4,5}} fClasses[2] { str1, str2, str3, int1, int [] {1,2,3,4,5}} fClasses[3] null fClasses[4] null fClasses[5] { str1, str2, str3, int1, int [] {1,2,3,4,5}} fClasses[6] { str1, str2, str3, int1, int [] {1,2,3,4,5}} ``` Later in the program I need to sort the array based on the average of the `ints` in the `int[]`. I have a working method to return this but when I try to sort the array using `compareTo` and `Arrays.sort` I get a long list of errors starting with these: ``` Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException at java.util.ComparableTimSort.countRunAndMakeAscending(Unknown Source) at java.util.ComparableTimSort.sort(Unknown Source) at java.util.Arrays.sort(Unknown Source) at FProg.sortClasses(FProg.java:228) ``` My `compareTo` method looks like this and it's located in a class that implements `Comparable`: ``` public int compareTo(FClass other) { if (other == null || this.avg == other.avg) { return 0; } else if (this.avg < other.avg) { return -1; } else { return 1; } } ``` And I'm trying to call this method to do the sorting: ``` public void sortClasses() { Arrays.sort(fClasses, 0, MAX_CLASSES); } ``` I have tested it with a .txt file that contains enough entries to fill the array and the sort works correctly in that case, so I believe the problem I'm having is that my sort method can't sort an array with null elements in it. Is there any way this can be achieved?
2014/12/18
[ "https://Stackoverflow.com/questions/27556104", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4375799/" ]
You have to create a `Comparator<FClass>`, rather than use a `Comparable<FClass>`. ``` public class FClassComparator implements Comparator<FClass> { public int compare(FClass left, FClass right) { // Swap -1 and 1 here if you want nulls to move to the front. if (left == null) return right == null ? 0 : 1; if (right == null) return -1; // you are now guaranteed that neither left nor right are null. // I'm assuming avg is int. There is also Double.compare if they aren't. return Integer.compare(left.avg, right.avg); } } ``` Then call sort via: ``` Arrays.sort(fClassArray, new FClassComparator()); ```
With [Apache Commons Collections 4](https://commons.apache.org/proper/commons-collections/) you can use [ComparatorUtils](https://commons.apache.org/proper/commons-collections/apidocs/org/apache/commons/collections4/ComparatorUtils.html) to do that: ``` Collections.sort(arr, ComparatorUtils.nullLowComparator(ComparatorUtils.NATURAL_COMPARATOR)); ```
27,556,104
In my program an array `fClasses` of fixed length [7] of objects is created, each object is a class `FClass` that contains 3 `Strings`, an `int`, and an `int[]`. These values are read from a .txt file and added to a specific index of the array based on the value of the `int`. There are less entries in the .txt file then there are indices in the array so the array ends up looking something like this: ``` fClasses[0] { str1, str2, str3, int1, int [] {1,2,3,4,5}} fClasses[1] { str1, str2, str3, int1, int [] {1,2,3,4,5}} fClasses[2] { str1, str2, str3, int1, int [] {1,2,3,4,5}} fClasses[3] null fClasses[4] null fClasses[5] { str1, str2, str3, int1, int [] {1,2,3,4,5}} fClasses[6] { str1, str2, str3, int1, int [] {1,2,3,4,5}} ``` Later in the program I need to sort the array based on the average of the `ints` in the `int[]`. I have a working method to return this but when I try to sort the array using `compareTo` and `Arrays.sort` I get a long list of errors starting with these: ``` Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException at java.util.ComparableTimSort.countRunAndMakeAscending(Unknown Source) at java.util.ComparableTimSort.sort(Unknown Source) at java.util.Arrays.sort(Unknown Source) at FProg.sortClasses(FProg.java:228) ``` My `compareTo` method looks like this and it's located in a class that implements `Comparable`: ``` public int compareTo(FClass other) { if (other == null || this.avg == other.avg) { return 0; } else if (this.avg < other.avg) { return -1; } else { return 1; } } ``` And I'm trying to call this method to do the sorting: ``` public void sortClasses() { Arrays.sort(fClasses, 0, MAX_CLASSES); } ``` I have tested it with a .txt file that contains enough entries to fill the array and the sort works correctly in that case, so I believe the problem I'm having is that my sort method can't sort an array with null elements in it. Is there any way this can be achieved?
2014/12/18
[ "https://Stackoverflow.com/questions/27556104", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4375799/" ]
You have to create a `Comparator<FClass>`, rather than use a `Comparable<FClass>`. ``` public class FClassComparator implements Comparator<FClass> { public int compare(FClass left, FClass right) { // Swap -1 and 1 here if you want nulls to move to the front. if (left == null) return right == null ? 0 : 1; if (right == null) return -1; // you are now guaranteed that neither left nor right are null. // I'm assuming avg is int. There is also Double.compare if they aren't. return Integer.compare(left.avg, right.avg); } } ``` Then call sort via: ``` Arrays.sort(fClassArray, new FClassComparator()); ```
By importing the [org.apache.commons.collections.comparators](https://commons.apache.org/proper/commons-collections/javadocs/api-2.1.1/org/apache/commons/collections/comparators/NullComparator.html) package of the [Apache 2.1.1 Release](https://commons.apache.org/proper/commons-collections/javadocs/api-2.1.1/overview-summary.html) library, I'm able to sort a list, such as an `ArrayList<String>`, using the `NullComparator` as the second argument of the `Collections.sort()` method, as follows: ``` ArrayList<String> list = new ArrayList<String>(); list.add("foo"); list.add("bar"); list.add("baz"); list.add(null); // Sort the list Collections.sort(list, new NullComparator(true)); System.out.println(list); // outputs: // [bar, baz, foo, null] ``` The thing I like about this approach is that the `NullComparator` has an overload constructor which allows you to specify whether you want `null` to be considered a high value or a low value, which seems pretty intuitive to me. ``` NullComparator(boolean nullsAreHigh) ``` Hope this helps someone!
27,556,104
In my program an array `fClasses` of fixed length [7] of objects is created, each object is a class `FClass` that contains 3 `Strings`, an `int`, and an `int[]`. These values are read from a .txt file and added to a specific index of the array based on the value of the `int`. There are less entries in the .txt file then there are indices in the array so the array ends up looking something like this: ``` fClasses[0] { str1, str2, str3, int1, int [] {1,2,3,4,5}} fClasses[1] { str1, str2, str3, int1, int [] {1,2,3,4,5}} fClasses[2] { str1, str2, str3, int1, int [] {1,2,3,4,5}} fClasses[3] null fClasses[4] null fClasses[5] { str1, str2, str3, int1, int [] {1,2,3,4,5}} fClasses[6] { str1, str2, str3, int1, int [] {1,2,3,4,5}} ``` Later in the program I need to sort the array based on the average of the `ints` in the `int[]`. I have a working method to return this but when I try to sort the array using `compareTo` and `Arrays.sort` I get a long list of errors starting with these: ``` Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException at java.util.ComparableTimSort.countRunAndMakeAscending(Unknown Source) at java.util.ComparableTimSort.sort(Unknown Source) at java.util.Arrays.sort(Unknown Source) at FProg.sortClasses(FProg.java:228) ``` My `compareTo` method looks like this and it's located in a class that implements `Comparable`: ``` public int compareTo(FClass other) { if (other == null || this.avg == other.avg) { return 0; } else if (this.avg < other.avg) { return -1; } else { return 1; } } ``` And I'm trying to call this method to do the sorting: ``` public void sortClasses() { Arrays.sort(fClasses, 0, MAX_CLASSES); } ``` I have tested it with a .txt file that contains enough entries to fill the array and the sort works correctly in that case, so I believe the problem I'm having is that my sort method can't sort an array with null elements in it. Is there any way this can be achieved?
2014/12/18
[ "https://Stackoverflow.com/questions/27556104", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4375799/" ]
Using Java 8, you can easily build the comparator you need: ``` Arrays.sort(fClasses, Comparator.nullsFirst(Comparator.naturalOrder())); ``` Use `nullsLast` instead if that's what you want, of course.
With [Apache Commons Collections 4](https://commons.apache.org/proper/commons-collections/) you can use [ComparatorUtils](https://commons.apache.org/proper/commons-collections/apidocs/org/apache/commons/collections4/ComparatorUtils.html) to do that: ``` Collections.sort(arr, ComparatorUtils.nullLowComparator(ComparatorUtils.NATURAL_COMPARATOR)); ```
27,556,104
In my program an array `fClasses` of fixed length [7] of objects is created, each object is a class `FClass` that contains 3 `Strings`, an `int`, and an `int[]`. These values are read from a .txt file and added to a specific index of the array based on the value of the `int`. There are less entries in the .txt file then there are indices in the array so the array ends up looking something like this: ``` fClasses[0] { str1, str2, str3, int1, int [] {1,2,3,4,5}} fClasses[1] { str1, str2, str3, int1, int [] {1,2,3,4,5}} fClasses[2] { str1, str2, str3, int1, int [] {1,2,3,4,5}} fClasses[3] null fClasses[4] null fClasses[5] { str1, str2, str3, int1, int [] {1,2,3,4,5}} fClasses[6] { str1, str2, str3, int1, int [] {1,2,3,4,5}} ``` Later in the program I need to sort the array based on the average of the `ints` in the `int[]`. I have a working method to return this but when I try to sort the array using `compareTo` and `Arrays.sort` I get a long list of errors starting with these: ``` Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException at java.util.ComparableTimSort.countRunAndMakeAscending(Unknown Source) at java.util.ComparableTimSort.sort(Unknown Source) at java.util.Arrays.sort(Unknown Source) at FProg.sortClasses(FProg.java:228) ``` My `compareTo` method looks like this and it's located in a class that implements `Comparable`: ``` public int compareTo(FClass other) { if (other == null || this.avg == other.avg) { return 0; } else if (this.avg < other.avg) { return -1; } else { return 1; } } ``` And I'm trying to call this method to do the sorting: ``` public void sortClasses() { Arrays.sort(fClasses, 0, MAX_CLASSES); } ``` I have tested it with a .txt file that contains enough entries to fill the array and the sort works correctly in that case, so I believe the problem I'm having is that my sort method can't sort an array with null elements in it. Is there any way this can be achieved?
2014/12/18
[ "https://Stackoverflow.com/questions/27556104", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4375799/" ]
Using Java 8, you can easily build the comparator you need: ``` Arrays.sort(fClasses, Comparator.nullsFirst(Comparator.naturalOrder())); ``` Use `nullsLast` instead if that's what you want, of course.
By importing the [org.apache.commons.collections.comparators](https://commons.apache.org/proper/commons-collections/javadocs/api-2.1.1/org/apache/commons/collections/comparators/NullComparator.html) package of the [Apache 2.1.1 Release](https://commons.apache.org/proper/commons-collections/javadocs/api-2.1.1/overview-summary.html) library, I'm able to sort a list, such as an `ArrayList<String>`, using the `NullComparator` as the second argument of the `Collections.sort()` method, as follows: ``` ArrayList<String> list = new ArrayList<String>(); list.add("foo"); list.add("bar"); list.add("baz"); list.add(null); // Sort the list Collections.sort(list, new NullComparator(true)); System.out.println(list); // outputs: // [bar, baz, foo, null] ``` The thing I like about this approach is that the `NullComparator` has an overload constructor which allows you to specify whether you want `null` to be considered a high value or a low value, which seems pretty intuitive to me. ``` NullComparator(boolean nullsAreHigh) ``` Hope this helps someone!
27,556,104
In my program an array `fClasses` of fixed length [7] of objects is created, each object is a class `FClass` that contains 3 `Strings`, an `int`, and an `int[]`. These values are read from a .txt file and added to a specific index of the array based on the value of the `int`. There are less entries in the .txt file then there are indices in the array so the array ends up looking something like this: ``` fClasses[0] { str1, str2, str3, int1, int [] {1,2,3,4,5}} fClasses[1] { str1, str2, str3, int1, int [] {1,2,3,4,5}} fClasses[2] { str1, str2, str3, int1, int [] {1,2,3,4,5}} fClasses[3] null fClasses[4] null fClasses[5] { str1, str2, str3, int1, int [] {1,2,3,4,5}} fClasses[6] { str1, str2, str3, int1, int [] {1,2,3,4,5}} ``` Later in the program I need to sort the array based on the average of the `ints` in the `int[]`. I have a working method to return this but when I try to sort the array using `compareTo` and `Arrays.sort` I get a long list of errors starting with these: ``` Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException at java.util.ComparableTimSort.countRunAndMakeAscending(Unknown Source) at java.util.ComparableTimSort.sort(Unknown Source) at java.util.Arrays.sort(Unknown Source) at FProg.sortClasses(FProg.java:228) ``` My `compareTo` method looks like this and it's located in a class that implements `Comparable`: ``` public int compareTo(FClass other) { if (other == null || this.avg == other.avg) { return 0; } else if (this.avg < other.avg) { return -1; } else { return 1; } } ``` And I'm trying to call this method to do the sorting: ``` public void sortClasses() { Arrays.sort(fClasses, 0, MAX_CLASSES); } ``` I have tested it with a .txt file that contains enough entries to fill the array and the sort works correctly in that case, so I believe the problem I'm having is that my sort method can't sort an array with null elements in it. Is there any way this can be achieved?
2014/12/18
[ "https://Stackoverflow.com/questions/27556104", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4375799/" ]
With [Apache Commons Collections 4](https://commons.apache.org/proper/commons-collections/) you can use [ComparatorUtils](https://commons.apache.org/proper/commons-collections/apidocs/org/apache/commons/collections4/ComparatorUtils.html) to do that: ``` Collections.sort(arr, ComparatorUtils.nullLowComparator(ComparatorUtils.NATURAL_COMPARATOR)); ```
By importing the [org.apache.commons.collections.comparators](https://commons.apache.org/proper/commons-collections/javadocs/api-2.1.1/org/apache/commons/collections/comparators/NullComparator.html) package of the [Apache 2.1.1 Release](https://commons.apache.org/proper/commons-collections/javadocs/api-2.1.1/overview-summary.html) library, I'm able to sort a list, such as an `ArrayList<String>`, using the `NullComparator` as the second argument of the `Collections.sort()` method, as follows: ``` ArrayList<String> list = new ArrayList<String>(); list.add("foo"); list.add("bar"); list.add("baz"); list.add(null); // Sort the list Collections.sort(list, new NullComparator(true)); System.out.println(list); // outputs: // [bar, baz, foo, null] ``` The thing I like about this approach is that the `NullComparator` has an overload constructor which allows you to specify whether you want `null` to be considered a high value or a low value, which seems pretty intuitive to me. ``` NullComparator(boolean nullsAreHigh) ``` Hope this helps someone!
3,550,337
Could someone give me some guidance on when I should use `WITH (NOLOCK)` as opposed to `SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED` What are the pros/cons of each? Are there any unintended consequences you've run into using one as opposed to the other?
2010/08/23
[ "https://Stackoverflow.com/questions/3550337", "https://Stackoverflow.com", "https://Stackoverflow.com/users/195583/" ]
They are the same thing. If you use the `set transaction isolation level` statement, it will apply to all the tables in the connection, so if you only want a `nolock` on one or two tables use that; otherwise use the other. Both will give you dirty reads. If you are okay with that, then use them. If you can't have dirty reads, then consider `snapshot` or `serializable` hints instead.
As you have to use WITH (NOLOCK) for each table it might be annoying to write it in every FROM or JOIN clause. However it has a reason why it is called a "dirty" read. So you really should know when you do one, and not set it as default for the session scope. Why? Forgetting a WITH (NOLOCK) might not affect your program in a very dramatic way, however doing a dirty read where you do **not** want one can make the difference in certain circumstances. So use WITH (NOLOCK) if the current data selected is allowed to be incorrect, as it might be rolled back later. This is mostly used when you want to increase performance, and the requirements on your application context allow it to take the risk that inconsistent data is being displayed. However you or someone in charge has to weigh up pros and cons of the decision of using WITH (NOLOCK).
3,550,337
Could someone give me some guidance on when I should use `WITH (NOLOCK)` as opposed to `SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED` What are the pros/cons of each? Are there any unintended consequences you've run into using one as opposed to the other?
2010/08/23
[ "https://Stackoverflow.com/questions/3550337", "https://Stackoverflow.com", "https://Stackoverflow.com/users/195583/" ]
They are the same thing. If you use the `set transaction isolation level` statement, it will apply to all the tables in the connection, so if you only want a `nolock` on one or two tables use that; otherwise use the other. Both will give you dirty reads. If you are okay with that, then use them. If you can't have dirty reads, then consider `snapshot` or `serializable` hints instead.
You cannot use Set Transaction Isolation Level Read Uncommitted in a View (you can only have one script in there in fact), so you would have to use (nolock) if dirty rows should be included.
3,550,337
Could someone give me some guidance on when I should use `WITH (NOLOCK)` as opposed to `SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED` What are the pros/cons of each? Are there any unintended consequences you've run into using one as opposed to the other?
2010/08/23
[ "https://Stackoverflow.com/questions/3550337", "https://Stackoverflow.com", "https://Stackoverflow.com/users/195583/" ]
WITH (NOLOCK) is a hint on a table level. Setting the transaction isolation level to READ\_UNCOMMITTED with affect the connection. The difference is in terms of scope. See READUNCOMMITTED and NOLOCK in the SQL Server documentation here: <http://technet.microsoft.com/en-us/library/ms187373.aspx> For TRANSACTION ISOLATION LEVEL: <http://technet.microsoft.com/en-us/library/ms173763.aspx>
You cannot use Set Transaction Isolation Level Read Uncommitted in a View (you can only have one script in there in fact), so you would have to use (nolock) if dirty rows should be included.
3,550,337
Could someone give me some guidance on when I should use `WITH (NOLOCK)` as opposed to `SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED` What are the pros/cons of each? Are there any unintended consequences you've run into using one as opposed to the other?
2010/08/23
[ "https://Stackoverflow.com/questions/3550337", "https://Stackoverflow.com", "https://Stackoverflow.com/users/195583/" ]
They are the same thing. If you use the `set transaction isolation level` statement, it will apply to all the tables in the connection, so if you only want a `nolock` on one or two tables use that; otherwise use the other. Both will give you dirty reads. If you are okay with that, then use them. If you can't have dirty reads, then consider `snapshot` or `serializable` hints instead.
WITH (NOLOCK) is a hint on a table level. Setting the transaction isolation level to READ\_UNCOMMITTED with affect the connection. The difference is in terms of scope. See READUNCOMMITTED and NOLOCK in the SQL Server documentation here: <http://technet.microsoft.com/en-us/library/ms187373.aspx> For TRANSACTION ISOLATION LEVEL: <http://technet.microsoft.com/en-us/library/ms173763.aspx>
3,550,337
Could someone give me some guidance on when I should use `WITH (NOLOCK)` as opposed to `SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED` What are the pros/cons of each? Are there any unintended consequences you've run into using one as opposed to the other?
2010/08/23
[ "https://Stackoverflow.com/questions/3550337", "https://Stackoverflow.com", "https://Stackoverflow.com/users/195583/" ]
WITH (NOLOCK) is a hint on a table level. Setting the transaction isolation level to READ\_UNCOMMITTED with affect the connection. The difference is in terms of scope. See READUNCOMMITTED and NOLOCK in the SQL Server documentation here: <http://technet.microsoft.com/en-us/library/ms187373.aspx> For TRANSACTION ISOLATION LEVEL: <http://technet.microsoft.com/en-us/library/ms173763.aspx>
* NOLOCK is local to the table (or views etc) * READ UNCOMMITTED is per session/connection As for guidelines... a random search from StackOverflow and the electric interweb... * [Is the NOLOCK (Sql Server hint) bad practice?](https://stackoverflow.com/questions/1452996/is-the-nolock-sql-server-hint-bad-practice) * [When is it appropriate to use NOLOCK?](https://stackoverflow.com/questions/816650/when-is-it-appropriate-to-use-nolock) * [Get rid of those NOLOCK hints…](http://www.networkworld.com/community/node/42271)
3,550,337
Could someone give me some guidance on when I should use `WITH (NOLOCK)` as opposed to `SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED` What are the pros/cons of each? Are there any unintended consequences you've run into using one as opposed to the other?
2010/08/23
[ "https://Stackoverflow.com/questions/3550337", "https://Stackoverflow.com", "https://Stackoverflow.com/users/195583/" ]
* NOLOCK is local to the table (or views etc) * READ UNCOMMITTED is per session/connection As for guidelines... a random search from StackOverflow and the electric interweb... * [Is the NOLOCK (Sql Server hint) bad practice?](https://stackoverflow.com/questions/1452996/is-the-nolock-sql-server-hint-bad-practice) * [When is it appropriate to use NOLOCK?](https://stackoverflow.com/questions/816650/when-is-it-appropriate-to-use-nolock) * [Get rid of those NOLOCK hints…](http://www.networkworld.com/community/node/42271)
As you have to use WITH (NOLOCK) for each table it might be annoying to write it in every FROM or JOIN clause. However it has a reason why it is called a "dirty" read. So you really should know when you do one, and not set it as default for the session scope. Why? Forgetting a WITH (NOLOCK) might not affect your program in a very dramatic way, however doing a dirty read where you do **not** want one can make the difference in certain circumstances. So use WITH (NOLOCK) if the current data selected is allowed to be incorrect, as it might be rolled back later. This is mostly used when you want to increase performance, and the requirements on your application context allow it to take the risk that inconsistent data is being displayed. However you or someone in charge has to weigh up pros and cons of the decision of using WITH (NOLOCK).
3,550,337
Could someone give me some guidance on when I should use `WITH (NOLOCK)` as opposed to `SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED` What are the pros/cons of each? Are there any unintended consequences you've run into using one as opposed to the other?
2010/08/23
[ "https://Stackoverflow.com/questions/3550337", "https://Stackoverflow.com", "https://Stackoverflow.com/users/195583/" ]
WITH (NOLOCK) is a hint on a table level. Setting the transaction isolation level to READ\_UNCOMMITTED with affect the connection. The difference is in terms of scope. See READUNCOMMITTED and NOLOCK in the SQL Server documentation here: <http://technet.microsoft.com/en-us/library/ms187373.aspx> For TRANSACTION ISOLATION LEVEL: <http://technet.microsoft.com/en-us/library/ms173763.aspx>
As you have to use WITH (NOLOCK) for each table it might be annoying to write it in every FROM or JOIN clause. However it has a reason why it is called a "dirty" read. So you really should know when you do one, and not set it as default for the session scope. Why? Forgetting a WITH (NOLOCK) might not affect your program in a very dramatic way, however doing a dirty read where you do **not** want one can make the difference in certain circumstances. So use WITH (NOLOCK) if the current data selected is allowed to be incorrect, as it might be rolled back later. This is mostly used when you want to increase performance, and the requirements on your application context allow it to take the risk that inconsistent data is being displayed. However you or someone in charge has to weigh up pros and cons of the decision of using WITH (NOLOCK).
3,550,337
Could someone give me some guidance on when I should use `WITH (NOLOCK)` as opposed to `SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED` What are the pros/cons of each? Are there any unintended consequences you've run into using one as opposed to the other?
2010/08/23
[ "https://Stackoverflow.com/questions/3550337", "https://Stackoverflow.com", "https://Stackoverflow.com/users/195583/" ]
To my knowledge the only difference is the scope of the effects as Strommy said. NOLOCK hint on a table and the READ UNCOMMITTED on the session. As to problems that can occur, it's all about consistency. If you care then be aware that you could get what is called dirty reads which could influence other data being manipulated on incorrect information. I personally don't think I have seen any problems from this but that may be more due to how I use nolock. You need to be aware that there are scenarios where it will be OK to use. Scenarios where you are mostly adding new data to a table but have another process that comes in behind to check for a data scenario. That will probably be OK since the major flow doesn't include going back and updating rows during a read. Also I believe that these days you should look into Multi-version Concurrency Control. I believe they added it in 2005 and it helps stop the writers from blocking readers by giving readers a snapshot of the database to use. I'll include a link and leave further research to the reader: [MVCC](http://en.wikipedia.org/wiki/Multiversion_concurrency_control) [Database Isolation Levels](http://en.wikipedia.org/wiki/Isolation_(database_systems))
As you have to use WITH (NOLOCK) for each table it might be annoying to write it in every FROM or JOIN clause. However it has a reason why it is called a "dirty" read. So you really should know when you do one, and not set it as default for the session scope. Why? Forgetting a WITH (NOLOCK) might not affect your program in a very dramatic way, however doing a dirty read where you do **not** want one can make the difference in certain circumstances. So use WITH (NOLOCK) if the current data selected is allowed to be incorrect, as it might be rolled back later. This is mostly used when you want to increase performance, and the requirements on your application context allow it to take the risk that inconsistent data is being displayed. However you or someone in charge has to weigh up pros and cons of the decision of using WITH (NOLOCK).
3,550,337
Could someone give me some guidance on when I should use `WITH (NOLOCK)` as opposed to `SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED` What are the pros/cons of each? Are there any unintended consequences you've run into using one as opposed to the other?
2010/08/23
[ "https://Stackoverflow.com/questions/3550337", "https://Stackoverflow.com", "https://Stackoverflow.com/users/195583/" ]
WITH (NOLOCK) is a hint on a table level. Setting the transaction isolation level to READ\_UNCOMMITTED with affect the connection. The difference is in terms of scope. See READUNCOMMITTED and NOLOCK in the SQL Server documentation here: <http://technet.microsoft.com/en-us/library/ms187373.aspx> For TRANSACTION ISOLATION LEVEL: <http://technet.microsoft.com/en-us/library/ms173763.aspx>
To my knowledge the only difference is the scope of the effects as Strommy said. NOLOCK hint on a table and the READ UNCOMMITTED on the session. As to problems that can occur, it's all about consistency. If you care then be aware that you could get what is called dirty reads which could influence other data being manipulated on incorrect information. I personally don't think I have seen any problems from this but that may be more due to how I use nolock. You need to be aware that there are scenarios where it will be OK to use. Scenarios where you are mostly adding new data to a table but have another process that comes in behind to check for a data scenario. That will probably be OK since the major flow doesn't include going back and updating rows during a read. Also I believe that these days you should look into Multi-version Concurrency Control. I believe they added it in 2005 and it helps stop the writers from blocking readers by giving readers a snapshot of the database to use. I'll include a link and leave further research to the reader: [MVCC](http://en.wikipedia.org/wiki/Multiversion_concurrency_control) [Database Isolation Levels](http://en.wikipedia.org/wiki/Isolation_(database_systems))
3,550,337
Could someone give me some guidance on when I should use `WITH (NOLOCK)` as opposed to `SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED` What are the pros/cons of each? Are there any unintended consequences you've run into using one as opposed to the other?
2010/08/23
[ "https://Stackoverflow.com/questions/3550337", "https://Stackoverflow.com", "https://Stackoverflow.com/users/195583/" ]
They are the same thing. If you use the `set transaction isolation level` statement, it will apply to all the tables in the connection, so if you only want a `nolock` on one or two tables use that; otherwise use the other. Both will give you dirty reads. If you are okay with that, then use them. If you can't have dirty reads, then consider `snapshot` or `serializable` hints instead.
* NOLOCK is local to the table (or views etc) * READ UNCOMMITTED is per session/connection As for guidelines... a random search from StackOverflow and the electric interweb... * [Is the NOLOCK (Sql Server hint) bad practice?](https://stackoverflow.com/questions/1452996/is-the-nolock-sql-server-hint-bad-practice) * [When is it appropriate to use NOLOCK?](https://stackoverflow.com/questions/816650/when-is-it-appropriate-to-use-nolock) * [Get rid of those NOLOCK hints…](http://www.networkworld.com/community/node/42271)
20,594,281
I have simple question from OCJP Given: ``` 1. public class TestSeven extends Thread { 2. private static int x; 3. public synchronized void doThings() { 4. int current = x; 5. current++; 6. x = current; 7. } 8. public void run() { 9. doThings(); 10. } 11. } ``` Which statement is true? A. Compilation fails. B. An exception is thrown at runtime. C. Synchronizing the run() method would make the class thread-safe. D. The data in variable "x" are protected from concurrent access problems. E. Declaring the doThings() method as static would make the class thread-safe. F. Wrapping the statements within doThings() in a synchronized(new Object()) { } block would make the class thread-safe. Answer is option E. My Question: as method doThings() is already synchornozed, doesn't it make thread safe? Please also give some good links for these topics.
2013/12/15
[ "https://Stackoverflow.com/questions/20594281", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3104319/" ]
The problem is that `x` is a static variable, that is thus shared by all the threads. And since all the threads are not synchronized on a single object (every thread uses `this` as the lock), nothing prevents two threads to execute the `doThings()` method in parallel. Two threads might thus read the value of x in parallel, and then increment it in parallel, missing increments. Making `doThings()` static would make all the threads synchonize on a single object: `TestSeven.class`
No, because it accesses the static field `x` non-atomically. You could also make it threadsafe by using an [java.util.concurrent.atomic.AtomicInteger](http://docs.oracle.com/javase/6/docs/api/java/util/concurrent/atomic/AtomicInteger.html#getAndIncrement%28%29) with `getAndIncrement()`. But the original form isn't, consider a second thread reaching line 1 while another thread is on line 3... one of the increments would be lost.
20,594,281
I have simple question from OCJP Given: ``` 1. public class TestSeven extends Thread { 2. private static int x; 3. public synchronized void doThings() { 4. int current = x; 5. current++; 6. x = current; 7. } 8. public void run() { 9. doThings(); 10. } 11. } ``` Which statement is true? A. Compilation fails. B. An exception is thrown at runtime. C. Synchronizing the run() method would make the class thread-safe. D. The data in variable "x" are protected from concurrent access problems. E. Declaring the doThings() method as static would make the class thread-safe. F. Wrapping the statements within doThings() in a synchronized(new Object()) { } block would make the class thread-safe. Answer is option E. My Question: as method doThings() is already synchornozed, doesn't it make thread safe? Please also give some good links for these topics.
2013/12/15
[ "https://Stackoverflow.com/questions/20594281", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3104319/" ]
A `synchronized` associated to an object's instance's method does not care of static variables, that are class's variables. Indeed, in your case, the mutated variable is a `static` one: `x` In order to synchronize a static variable, both easiest ways in this snippet code would be to declare `doThings()` as static (so that it would lock on the class itself, not the object), or to lock the `TestSeven.class` in the case of a `synchronized` block: ``` public synchronized static void doThings() ``` or ``` public void doThings(){ synchronized(TestSeven.class){ //... } } ```
No, because it accesses the static field `x` non-atomically. You could also make it threadsafe by using an [java.util.concurrent.atomic.AtomicInteger](http://docs.oracle.com/javase/6/docs/api/java/util/concurrent/atomic/AtomicInteger.html#getAndIncrement%28%29) with `getAndIncrement()`. But the original form isn't, consider a second thread reaching line 1 while another thread is on line 3... one of the increments would be lost.
20,594,281
I have simple question from OCJP Given: ``` 1. public class TestSeven extends Thread { 2. private static int x; 3. public synchronized void doThings() { 4. int current = x; 5. current++; 6. x = current; 7. } 8. public void run() { 9. doThings(); 10. } 11. } ``` Which statement is true? A. Compilation fails. B. An exception is thrown at runtime. C. Synchronizing the run() method would make the class thread-safe. D. The data in variable "x" are protected from concurrent access problems. E. Declaring the doThings() method as static would make the class thread-safe. F. Wrapping the statements within doThings() in a synchronized(new Object()) { } block would make the class thread-safe. Answer is option E. My Question: as method doThings() is already synchornozed, doesn't it make thread safe? Please also give some good links for these topics.
2013/12/15
[ "https://Stackoverflow.com/questions/20594281", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3104319/" ]
No, That method `doThings()` is not thread safe, because, it was synchronized on `this` instance means different object will use **them** as the lock to access it. So no synchronization is there. If that method `doThings()` uses a shared lock to access the method, then, this method is perfectly synchronized. Or, making it class level property will synchronize.
No, because it accesses the static field `x` non-atomically. You could also make it threadsafe by using an [java.util.concurrent.atomic.AtomicInteger](http://docs.oracle.com/javase/6/docs/api/java/util/concurrent/atomic/AtomicInteger.html#getAndIncrement%28%29) with `getAndIncrement()`. But the original form isn't, consider a second thread reaching line 1 while another thread is on line 3... one of the increments would be lost.
20,594,281
I have simple question from OCJP Given: ``` 1. public class TestSeven extends Thread { 2. private static int x; 3. public synchronized void doThings() { 4. int current = x; 5. current++; 6. x = current; 7. } 8. public void run() { 9. doThings(); 10. } 11. } ``` Which statement is true? A. Compilation fails. B. An exception is thrown at runtime. C. Synchronizing the run() method would make the class thread-safe. D. The data in variable "x" are protected from concurrent access problems. E. Declaring the doThings() method as static would make the class thread-safe. F. Wrapping the statements within doThings() in a synchronized(new Object()) { } block would make the class thread-safe. Answer is option E. My Question: as method doThings() is already synchornozed, doesn't it make thread safe? Please also give some good links for these topics.
2013/12/15
[ "https://Stackoverflow.com/questions/20594281", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3104319/" ]
No, because it accesses the static field `x` non-atomically. You could also make it threadsafe by using an [java.util.concurrent.atomic.AtomicInteger](http://docs.oracle.com/javase/6/docs/api/java/util/concurrent/atomic/AtomicInteger.html#getAndIncrement%28%29) with `getAndIncrement()`. But the original form isn't, consider a second thread reaching line 1 while another thread is on line 3... one of the increments would be lost.
Though the answers are more on synchronized method of doThings(), which is correct, but in particular the static member x, “may be” cached with the values in respective Thread objects. The x will not be truely shared among all threads until it is volatile.
20,594,281
I have simple question from OCJP Given: ``` 1. public class TestSeven extends Thread { 2. private static int x; 3. public synchronized void doThings() { 4. int current = x; 5. current++; 6. x = current; 7. } 8. public void run() { 9. doThings(); 10. } 11. } ``` Which statement is true? A. Compilation fails. B. An exception is thrown at runtime. C. Synchronizing the run() method would make the class thread-safe. D. The data in variable "x" are protected from concurrent access problems. E. Declaring the doThings() method as static would make the class thread-safe. F. Wrapping the statements within doThings() in a synchronized(new Object()) { } block would make the class thread-safe. Answer is option E. My Question: as method doThings() is already synchornozed, doesn't it make thread safe? Please also give some good links for these topics.
2013/12/15
[ "https://Stackoverflow.com/questions/20594281", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3104319/" ]
The problem is that `x` is a static variable, that is thus shared by all the threads. And since all the threads are not synchronized on a single object (every thread uses `this` as the lock), nothing prevents two threads to execute the `doThings()` method in parallel. Two threads might thus read the value of x in parallel, and then increment it in parallel, missing increments. Making `doThings()` static would make all the threads synchonize on a single object: `TestSeven.class`
A `synchronized` associated to an object's instance's method does not care of static variables, that are class's variables. Indeed, in your case, the mutated variable is a `static` one: `x` In order to synchronize a static variable, both easiest ways in this snippet code would be to declare `doThings()` as static (so that it would lock on the class itself, not the object), or to lock the `TestSeven.class` in the case of a `synchronized` block: ``` public synchronized static void doThings() ``` or ``` public void doThings(){ synchronized(TestSeven.class){ //... } } ```
20,594,281
I have simple question from OCJP Given: ``` 1. public class TestSeven extends Thread { 2. private static int x; 3. public synchronized void doThings() { 4. int current = x; 5. current++; 6. x = current; 7. } 8. public void run() { 9. doThings(); 10. } 11. } ``` Which statement is true? A. Compilation fails. B. An exception is thrown at runtime. C. Synchronizing the run() method would make the class thread-safe. D. The data in variable "x" are protected from concurrent access problems. E. Declaring the doThings() method as static would make the class thread-safe. F. Wrapping the statements within doThings() in a synchronized(new Object()) { } block would make the class thread-safe. Answer is option E. My Question: as method doThings() is already synchornozed, doesn't it make thread safe? Please also give some good links for these topics.
2013/12/15
[ "https://Stackoverflow.com/questions/20594281", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3104319/" ]
The problem is that `x` is a static variable, that is thus shared by all the threads. And since all the threads are not synchronized on a single object (every thread uses `this` as the lock), nothing prevents two threads to execute the `doThings()` method in parallel. Two threads might thus read the value of x in parallel, and then increment it in parallel, missing increments. Making `doThings()` static would make all the threads synchonize on a single object: `TestSeven.class`
No, That method `doThings()` is not thread safe, because, it was synchronized on `this` instance means different object will use **them** as the lock to access it. So no synchronization is there. If that method `doThings()` uses a shared lock to access the method, then, this method is perfectly synchronized. Or, making it class level property will synchronize.
20,594,281
I have simple question from OCJP Given: ``` 1. public class TestSeven extends Thread { 2. private static int x; 3. public synchronized void doThings() { 4. int current = x; 5. current++; 6. x = current; 7. } 8. public void run() { 9. doThings(); 10. } 11. } ``` Which statement is true? A. Compilation fails. B. An exception is thrown at runtime. C. Synchronizing the run() method would make the class thread-safe. D. The data in variable "x" are protected from concurrent access problems. E. Declaring the doThings() method as static would make the class thread-safe. F. Wrapping the statements within doThings() in a synchronized(new Object()) { } block would make the class thread-safe. Answer is option E. My Question: as method doThings() is already synchornozed, doesn't it make thread safe? Please also give some good links for these topics.
2013/12/15
[ "https://Stackoverflow.com/questions/20594281", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3104319/" ]
The problem is that `x` is a static variable, that is thus shared by all the threads. And since all the threads are not synchronized on a single object (every thread uses `this` as the lock), nothing prevents two threads to execute the `doThings()` method in parallel. Two threads might thus read the value of x in parallel, and then increment it in parallel, missing increments. Making `doThings()` static would make all the threads synchonize on a single object: `TestSeven.class`
Though the answers are more on synchronized method of doThings(), which is correct, but in particular the static member x, “may be” cached with the values in respective Thread objects. The x will not be truely shared among all threads until it is volatile.
20,594,281
I have simple question from OCJP Given: ``` 1. public class TestSeven extends Thread { 2. private static int x; 3. public synchronized void doThings() { 4. int current = x; 5. current++; 6. x = current; 7. } 8. public void run() { 9. doThings(); 10. } 11. } ``` Which statement is true? A. Compilation fails. B. An exception is thrown at runtime. C. Synchronizing the run() method would make the class thread-safe. D. The data in variable "x" are protected from concurrent access problems. E. Declaring the doThings() method as static would make the class thread-safe. F. Wrapping the statements within doThings() in a synchronized(new Object()) { } block would make the class thread-safe. Answer is option E. My Question: as method doThings() is already synchornozed, doesn't it make thread safe? Please also give some good links for these topics.
2013/12/15
[ "https://Stackoverflow.com/questions/20594281", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3104319/" ]
A `synchronized` associated to an object's instance's method does not care of static variables, that are class's variables. Indeed, in your case, the mutated variable is a `static` one: `x` In order to synchronize a static variable, both easiest ways in this snippet code would be to declare `doThings()` as static (so that it would lock on the class itself, not the object), or to lock the `TestSeven.class` in the case of a `synchronized` block: ``` public synchronized static void doThings() ``` or ``` public void doThings(){ synchronized(TestSeven.class){ //... } } ```
Though the answers are more on synchronized method of doThings(), which is correct, but in particular the static member x, “may be” cached with the values in respective Thread objects. The x will not be truely shared among all threads until it is volatile.
20,594,281
I have simple question from OCJP Given: ``` 1. public class TestSeven extends Thread { 2. private static int x; 3. public synchronized void doThings() { 4. int current = x; 5. current++; 6. x = current; 7. } 8. public void run() { 9. doThings(); 10. } 11. } ``` Which statement is true? A. Compilation fails. B. An exception is thrown at runtime. C. Synchronizing the run() method would make the class thread-safe. D. The data in variable "x" are protected from concurrent access problems. E. Declaring the doThings() method as static would make the class thread-safe. F. Wrapping the statements within doThings() in a synchronized(new Object()) { } block would make the class thread-safe. Answer is option E. My Question: as method doThings() is already synchornozed, doesn't it make thread safe? Please also give some good links for these topics.
2013/12/15
[ "https://Stackoverflow.com/questions/20594281", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3104319/" ]
No, That method `doThings()` is not thread safe, because, it was synchronized on `this` instance means different object will use **them** as the lock to access it. So no synchronization is there. If that method `doThings()` uses a shared lock to access the method, then, this method is perfectly synchronized. Or, making it class level property will synchronize.
Though the answers are more on synchronized method of doThings(), which is correct, but in particular the static member x, “may be” cached with the values in respective Thread objects. The x will not be truely shared among all threads until it is volatile.
1,382,553
Given an integer $n$ between 1 and 1000000, how do you directly prove that $n$ has at most 19 prime factors (with multiplicity)? I'm quite stuck on how to do this. I can understand the base case which is $n=2$. This obviously is correct, but I don't know how to continue with this proof from here on out. Any help is great.
2015/08/03
[ "https://math.stackexchange.com/questions/1382553", "https://math.stackexchange.com", "https://math.stackexchange.com/users/249468/" ]
Assume that there exists an integer $n\le 1000000$ with $20$ prime factors. Then each of these prime factors is at least $2$, so $n$ is at least the product of twenty $2$s, that is, $2^{20}=1048576>1000000$; this contradicts our hypothesis and therefore there is no such integer.
$2$ is the smallest prime number. So the smallest possible number with 20 prime factors is $2\cdot 2\cdot 2\cdot 2\cdot 2......\cdot 2\cdot 2$ which is $2^{20}$ which is more than your number
491,318
I have a laptop with 2 harddrive bays. One bay holds a smaller WD Scorpio. This is the boot drive that holds the operating system (Windows 7), and it no longer large enough. The other bay holds a newer (3 months old) Hitachi hd500gb that I was using for storage and backup of programs. This drive is not bootable. I want to set my computer to boot from the newer 500GB drive without losing any of the saved backed up info on it. Is there any way to do this? I want to be able to remove the old drive from the laptop when I'm done, in order to save weight and power. The laptop model is a gateway p-7805u.
2012/10/22
[ "https://superuser.com/questions/491318", "https://superuser.com", "https://superuser.com/users/167027/" ]
Perhaps your tab size is set to 2 spaces. Click on menu "settings" then "Preferences...", then switch to tab "Language menu/Tab settings", check the value of "Tab size" on the right bottom
Make sure you don't have the 'Replace by space' checkbox set next to the 'Tab Settings' in the Preferences->Language Menu/Tab settings.
54,539,478
When I have an interface with only one field (`val`) ``` interface ValObj { val: number } ``` creating an object with another field yields an error. ``` const someObj: ValObj = { val: 5, someStr:"hello" } ``` But this principle isn't consistent when we return a value from a function. Defining a function to return that same interface, and returning the same object works. ``` const func: () => ValObj = () => ({ val: 5, someStr: "sdf" }) ``` [Demo](https://stackblitz.com/edit/typescript-8sogr6) Why does Typescript's type checking allow this? Is there any way around it?
2019/02/05
[ "https://Stackoverflow.com/questions/54539478", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7224430/" ]
The error you are seeing in the first example is a product of excess property checks. Excess propeties are checked only when an object literal is directly assigned to something of a given type. In this case: ``` const func: () => ValObj = () => ({ val: 5, someStr: "sdf" }) ``` The way typing is done is to figure out the type of the arrow function first, which is `() => { val: number, someStr: string }` and then to check if this compatible with the given function signature `() => ValObj` which it is since `{ val: number, someStr: string }` is a subtype of `ValObj`. Nowhere was the object literal **directly** assigned to `ValObj`. You get an error if you are explicit about the return type of the arrow function: ``` const func: () => ValObj = () : ValObj => ({ val: 5, someStr: "sdf" }) ```
You are not defining the return type of the inner method call. It's default to `any` change it to ``` const func: () => ValObj = (): ValObj => ({ val: 5, someStr: "sdf" }) ```
50,661,663
I'm currently trying to figure out the way to produce equivalent assembly code from corresponding C source file. I've been using the C language for several years, but have little experience with assembly language. I was able to output the assembly code using the `-S` option in gcc. However, the resulting assembly code contained call instructions which in turn make a jump to another function like `_exp`. This is not what I wanted, I needed a fully functional assembly code in a single file, with no dependency to other code. Is it possible to achieve what I'm looking for? To better describe the problem, I'm showing you my code here: ``` #include <math.h> float sigmoid(float i){ return 1/(1+exp(-i)); } ``` The platform I am working on is Windows 10 64-bit, the compiler I'm using is cl.exe from MSbuild. My initial objective was to see, at a lowest level possible, how computers calculate mathematical functions. The level where I decided to observe the calculation process is assembly code, and the mathematical function I've chosen was sigmoid defined as above.
2018/06/02
[ "https://Stackoverflow.com/questions/50661663", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9886444/" ]
`_exp` is the standard math library function [`double exp(double)`](http://en.cppreference.com/w/c/numeric/math/exp); apparently you're on a platform that prepends a leading underscore to C symbol names. Given a `.s` that calls some library functions, build it the same way you would a `.c` file that calls library functions: ``` gcc foo.S -o foo -lm ``` You'll get a dynamic executable by default. --- **But if you really want *all* the code in one file with no external dependencies, you can link your `.c` into a static executable and disassemble that.** ``` gcc -O3 -march=native foo.c -o foo -static -lm objdump -drwC -Mintel foo > foo.s ``` There's no guarantee that the `_exp` implementation in `libm.a` (static library) is identical to the one you'd get in `libm.so` or `libm.dll` or whatever, because it's a different file. This is especially true for a function like `memcpy` where dynamic-linker tricks are often used to select an optimal version (for your CPU) at run-time.
It is not possible in general, there are exceptions sure, I could craft one so that means other folks can too, but it isnt an interesting program. Normally your C program, your main() entry point is only a percentage of the code. There is a bootstrap that contains the actual entry point for the operating system to launch your program, this does some things that prepare your virtual memory space so that your program can run. Zeros .bss and other such things. that is often and or should be written in assembly language (otherwise you get a chicken and egg problem) but not an assembly language file you will see unless you go find the sources for the C library, you will often get an object as part of the toolchain along with other compiler libraries, etc. Then if you make any C calls or create code that results in a compiler library call (perform a divide on a platform that doesnt support divide, perform floating point on a platform that doesnt have floating point, etc) that is another object that came from some other C or assembly that is part of the library or compiler sources and is not something you will see during the compile/assemble/link (the chain in toolchain) process. So except for specifically crafted trivial programs or specifically crafted tools for this purpose (for specific likely baremetal platforms), you will not see your whole program turn into one big assembly source file before it gets assembled then linked. If not baremetal then there is of course the operating system layer which you certainly would not get to see as part of your source code, ultimately the C library calls that need the system will have a place where they do that, all compiled to object/lib before you use them, and the assembly sources for the operating system side is part of some other source and build process somewhere else.
9,300,893
I'm trying to make a dropdown suggestion box using jQuery. I have a function that looks like this: ``` function onChoiceSelected(index){ var item = $("#suggestionBox li").get(index); alert("inner html: "+item.html()); currentSuggestionInput.val(item.html()); hideSuggestions(); } ``` For some reason, that get function is stopping execution. If I replace it with `.first()`, for example, it all works fine. What am I doing wrong? **Follow up question:** * Is there some way to see what errors are happening, rather than just having silent failure? * I'm running firebug, but I never see any errors or anything like that. Anyone know a good article about getting a proper development environment set up for this stuff?
2012/02/15
[ "https://Stackoverflow.com/questions/9300893", "https://Stackoverflow.com", "https://Stackoverflow.com/users/492848/" ]
The `get` method returns the DOM node at the index specified. Since you are then trying to call a jQuery method on that, it will fail. The `eq` method should do what you want. It will have the same effect as your `get` call, but it will return a jQuery object rather than the DOM node itself.
You want to use [`eq()`](http://api.jquery.com/eq/), not [`get()`](http://api.jquery.com/get/). ``` var item = $("#suggestionBox li").eq(index); ``` * [`get()`](http://api.jquery.com/get/) is DOM node * [`eq()`](http://api.jquery.com/eq/) is the jQuery object.
9,300,893
I'm trying to make a dropdown suggestion box using jQuery. I have a function that looks like this: ``` function onChoiceSelected(index){ var item = $("#suggestionBox li").get(index); alert("inner html: "+item.html()); currentSuggestionInput.val(item.html()); hideSuggestions(); } ``` For some reason, that get function is stopping execution. If I replace it with `.first()`, for example, it all works fine. What am I doing wrong? **Follow up question:** * Is there some way to see what errors are happening, rather than just having silent failure? * I'm running firebug, but I never see any errors or anything like that. Anyone know a good article about getting a proper development environment set up for this stuff?
2012/02/15
[ "https://Stackoverflow.com/questions/9300893", "https://Stackoverflow.com", "https://Stackoverflow.com/users/492848/" ]
You want to use [`eq()`](http://api.jquery.com/eq/), not [`get()`](http://api.jquery.com/get/). ``` var item = $("#suggestionBox li").eq(index); ``` * [`get()`](http://api.jquery.com/get/) is DOM node * [`eq()`](http://api.jquery.com/eq/) is the jQuery object.
You should be seeing errors in the console of firebug. You can also use tools like console.log(index) in firebug, as well as run the javascript directly from the console screen. What value are you getting for index?
9,300,893
I'm trying to make a dropdown suggestion box using jQuery. I have a function that looks like this: ``` function onChoiceSelected(index){ var item = $("#suggestionBox li").get(index); alert("inner html: "+item.html()); currentSuggestionInput.val(item.html()); hideSuggestions(); } ``` For some reason, that get function is stopping execution. If I replace it with `.first()`, for example, it all works fine. What am I doing wrong? **Follow up question:** * Is there some way to see what errors are happening, rather than just having silent failure? * I'm running firebug, but I never see any errors or anything like that. Anyone know a good article about getting a proper development environment set up for this stuff?
2012/02/15
[ "https://Stackoverflow.com/questions/9300893", "https://Stackoverflow.com", "https://Stackoverflow.com/users/492848/" ]
You want to use [`eq()`](http://api.jquery.com/eq/), not [`get()`](http://api.jquery.com/get/). ``` var item = $("#suggestionBox li").eq(index); ``` * [`get()`](http://api.jquery.com/get/) is DOM node * [`eq()`](http://api.jquery.com/eq/) is the jQuery object.
do it as ``` function onChoiceSelected(index){ var item = $($("#suggestionBox li").get(index)); alert("inner html: "+item.html()); currentSuggestionInput.val(item.html()); hideSuggestions(); } ```
9,300,893
I'm trying to make a dropdown suggestion box using jQuery. I have a function that looks like this: ``` function onChoiceSelected(index){ var item = $("#suggestionBox li").get(index); alert("inner html: "+item.html()); currentSuggestionInput.val(item.html()); hideSuggestions(); } ``` For some reason, that get function is stopping execution. If I replace it with `.first()`, for example, it all works fine. What am I doing wrong? **Follow up question:** * Is there some way to see what errors are happening, rather than just having silent failure? * I'm running firebug, but I never see any errors or anything like that. Anyone know a good article about getting a proper development environment set up for this stuff?
2012/02/15
[ "https://Stackoverflow.com/questions/9300893", "https://Stackoverflow.com", "https://Stackoverflow.com/users/492848/" ]
The `get` method returns the DOM node at the index specified. Since you are then trying to call a jQuery method on that, it will fail. The `eq` method should do what you want. It will have the same effect as your `get` call, but it will return a jQuery object rather than the DOM node itself.
You should be seeing errors in the console of firebug. You can also use tools like console.log(index) in firebug, as well as run the javascript directly from the console screen. What value are you getting for index?
9,300,893
I'm trying to make a dropdown suggestion box using jQuery. I have a function that looks like this: ``` function onChoiceSelected(index){ var item = $("#suggestionBox li").get(index); alert("inner html: "+item.html()); currentSuggestionInput.val(item.html()); hideSuggestions(); } ``` For some reason, that get function is stopping execution. If I replace it with `.first()`, for example, it all works fine. What am I doing wrong? **Follow up question:** * Is there some way to see what errors are happening, rather than just having silent failure? * I'm running firebug, but I never see any errors or anything like that. Anyone know a good article about getting a proper development environment set up for this stuff?
2012/02/15
[ "https://Stackoverflow.com/questions/9300893", "https://Stackoverflow.com", "https://Stackoverflow.com/users/492848/" ]
The `get` method returns the DOM node at the index specified. Since you are then trying to call a jQuery method on that, it will fail. The `eq` method should do what you want. It will have the same effect as your `get` call, but it will return a jQuery object rather than the DOM node itself.
do it as ``` function onChoiceSelected(index){ var item = $($("#suggestionBox li").get(index)); alert("inner html: "+item.html()); currentSuggestionInput.val(item.html()); hideSuggestions(); } ```
9,300,893
I'm trying to make a dropdown suggestion box using jQuery. I have a function that looks like this: ``` function onChoiceSelected(index){ var item = $("#suggestionBox li").get(index); alert("inner html: "+item.html()); currentSuggestionInput.val(item.html()); hideSuggestions(); } ``` For some reason, that get function is stopping execution. If I replace it with `.first()`, for example, it all works fine. What am I doing wrong? **Follow up question:** * Is there some way to see what errors are happening, rather than just having silent failure? * I'm running firebug, but I never see any errors or anything like that. Anyone know a good article about getting a proper development environment set up for this stuff?
2012/02/15
[ "https://Stackoverflow.com/questions/9300893", "https://Stackoverflow.com", "https://Stackoverflow.com/users/492848/" ]
You should be seeing errors in the console of firebug. You can also use tools like console.log(index) in firebug, as well as run the javascript directly from the console screen. What value are you getting for index?
do it as ``` function onChoiceSelected(index){ var item = $($("#suggestionBox li").get(index)); alert("inner html: "+item.html()); currentSuggestionInput.val(item.html()); hideSuggestions(); } ```