Q:

Electron Volts in Covalent Bonds of Nitrogen

(once again this question is not a duplicate of any other question to my knowledge, and this should actually help alot of people trying to ionize air)
for one you can easily figure out that nitrogen is 15.58eV and oxygen is 13.6eV, but the problem is in the air nitrogen bonds with another nitrogen (N2) and oxygen bonds with another oxygen (O2). My chemistry teacher said that the 2 atoms eV dont just add up he said it shouldnt be to much more then 15.58eV. What does it add up to and what is the equation of figuring that out. I suprisingly cant find this anywhere on the internet, so an equation of some sort would help a bunch. thanks!

A:

There isn't a simple way to get the ionisation energy of the molecule from the ionisation energies of the atoms that make it up. You have to either do a calculation of the molecular wavefunction or of course measure it experimentally.
When commenting on one of your previous questions I gave you the experimentally measured ionisation energies for $N_2$ and $O_2$ from the NIST web site. The ionisation energy of $N_2$ molecule is $15.58$eV as described here, and the ionisation energy of the $O_2$ molecule is $12.07$eV as described here. This compares to $14.54$eV and $13.62$eV for the nitrogen and oxygen atoms respectively.


Q:

I'm having an error in BaseAdapter

I having an error inside my simple app, and I don't know why. I got that app running once, but now it just crashes. It doesn't show any syntax errors, and everything compiles without problems. Here's the code:
Main.java
public class Main extends ListActivity {

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.list_example);

    final List<CustomListItem> items = new ArrayList<>(3);

    items.add(new CustomListItem (1, "Item 1", getResources().getDrawable(R.drawable.ic_launcher)));
    items.add(new CustomListItem (2, "Item 2", getResources().getDrawable(R.drawable.ic_launcher)));
    items.add(new CustomListItem (3, "Item 3", getResources().getDrawable(R.drawable.ic_launcher)));

    ListAdapter adapter = new MyListItemAdapter(items, this);
    ListView lv = getListView();
    lv.setAdapter(adapter);
    lv.setTextFilterEnabled(true);

    lv.setOnItemClickListener(new OnItemClickListener() {
        public void onItemClick(AdapterView<?> parent, View view,
                                int position, long id) {

            final CustomListItem item = items.get(position);
            final int menuIndex = item.getIndex();
            switch (menuIndex) {
                case 1:
                    break;
                case 2:
                    break;
                case 3:
                    break;
                default:
                    break;
            }
        }
    });
}

MyListItemAdapter.java
public class MyListItemAdapter extends BaseAdapter {
private List<CustomListItem> items;
private Context context;
private int numItems = 0;

public MyListItemAdapter(final List<CustomListItem> items, Context context) {
    this.items = items;
    this.context = context;
    this.numItems = items.size();
}

public int getCount() {
    return numItems;
}

public CustomListItem getItem(int position) {
    return items.get(position);
}

public long getItemId(int position) {
    return 0;
}

public View getView(int position, View convertView, ViewGroup parent) {

    final CustomListItem item = items.get(position);

    final RelativeLayout itemLayout = (RelativeLayout) LayoutInflater.from(context).inflate(R.layout.list_item, parent, false);

    ImageView imgIcon = (ImageView) itemLayout.findViewById(R.id.image);
    imgIcon.setImageDrawable(item.getPicture());

    TextView txtLabel = (TextView) itemLayout.findViewById(R.id.txtLabel);
    txtLabel.setText(item.getLabel());

    return itemLayout;
}

CustomListItem.java
public class CustomListItem {
private int mIndex;
private String mLabel;
private Drawable mPicture;
public CustomListItem(final int index, final String label, final Drawable pic) {
    mIndex = index;
    mLabel = label;
    mPicture = pic;
}

public int getIndex() {
    return mIndex;
}

public String getLabel() {
    return mLabel;
}

public Drawable getPicture() {
    return mPicture;
}

}
logcat
 14806-14806/com.robigroza.baseadaptertest E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.NullPointerException at com.robigroza.baseadaptertest.MyListItemAdapter.getView(MyListItemAdapter.java:46)
        at android.widget.AbsListView.obtainView(AbsListView.java:2465)
        at android.widget.ListView.measureHeightOfChildren(ListView.java:1250)
        at android.widget.ListView.onMeasure(ListView.java:1162)
        at android.view.View.measure(View.java:15371)
        at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4876)
        at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1396)
        at android.widget.LinearLayout.measureVertical(LinearLayout.java:681)
        at android.widget.LinearLayout.onMeasure(LinearLayout.java:574)
        at android.view.View.measure(View.java:15371)
        at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4876)
        at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
        at android.view.View.measure(View.java:15371)
        at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4876)
        at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1396)
        at android.widget.LinearLayout.measureVertical(LinearLayout.java:681)
        at android.widget.LinearLayout.onMeasure(LinearLayout.java:574)
        at android.view.View.measure(View.java:15371)
        at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4876)
        at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
        at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2423)
        at android.view.View.measure(View.java:15371)
        at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:2011)
        at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1250)
        at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1425)
        at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1143)
        at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:4674)
        at android.view.Choreographer$CallbackRecord.run(Choreographer.java:725)
        at android.view.Choreographer.doCallbacks(Choreographer.java:555)
        at android.view.Choreographer.doFrame(Choreographer.java:525)
        at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:711)
        at android.os.Handler.handleCallback(Handler.java:615)
        at android.os.Handler.dispatchMessage(Handler.java:92)
        at android.os.Looper.loop(Looper.java:137)
        at android.app.ActivityThread.main(ActivityThread.java:4960)
        at java.lang.reflect.Method.invokeNative(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:511)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1038)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:805)
        at dalvik.system.NativeStart.main(Native Method)

A:

Since getView needs to return a View try this:
public View getView(int position, View convertView, ViewGroup parent) {

    View rootView = convertView;
    if(rootView == null){

       LayoutInflater inflater = (LayoutInflater)LayoutInflater.from(context);
       rootView = inflater.inflate(R.layout.list_item, parent, false);

       final CustomListItem item = items.get(position);

    }

    if(item != null){
       ImageView imgIcon = (ImageView) rootView.findViewById(R.id.image);
       imgIcon.setImageDrawable(item.getPicture());

       TextView txtLabel = (TextView) rootView.findViewById(R.id.txtLabel);
       txtLabel.setText(item.getLabel());
    }

    return rootView;
}

Try this hope it helps!!!


Q:

Does clojure have identifier macros?

In other words, is there any way to trigger macro expansion on forms that don't look like (MACRO arg* ...).
To give a hypothetical example:
(defmacro my-var
  (do (printf "Using my-var!\n") 42))
(+ my-var 1) ;; Should print & return 43

What I really want to do is call macroexpand on a term with free variables. I want to these free variables should have special meaning during macro expansion, but should go back to "normal" afterward.

A:

This facility currently exists in Clojure as one of the features of the Clojure Contrib library tools.macro. The relevant tools.macro macros are defsymbolmacro, with-symbol-macros and symbol-macrolet – here's a symbol-macrolet example from the README (as found on the tip of the master branch right now):
(symbol-macrolet [def foo]
  (def def def))

expands to (def def foo)

symbol-macrolet is used to introduce lexically scoped symbol macros, while defsymbolmacro introduces symbol macros to be applied inside any with-symbol-macros blocks (doing away with with-symbol-macros would only be possible with support from the Clojure compiler itself).
AFAIK, some version of symbol-macrolet has been a planned feature for inclusion in Clojure's compiler itself for quite a while; it is expected that when and if it lands, it will likely be called letmacro. There's no concrete public timeline for that, though, and it is certainly not guaranteed to land at all.
The names that tools.macro uses are inspired by Common Lisp, where the relevant macros are known as define-symbol-macro and symbol-macrolet. Since this is a standard compiler feature in CL, symbol macros introduced with define-symbol-macro are actually applied globally without assistance from any helper macros.

A:

Sorry, no, Clojure does not have this feature.
With the exception of the reader macros such as quote ', syntax-quote `, dispatch #, etc. which do expand outside the function argument position, you cannot add macros that expand in this position.
Reader literals are slightly related in that you can define literal syntax that will be converted into a data structure at read time, though these cannot be used as variables like you are describing.
The auto-gensym feature of the syntax-quote reader macro has a little of this flavor though in a much more limited way.


Q:

Place element in LinearLayout with minimal space between them

I have a vertical LinearLayout with two TextView, the default space between them is to much big for me, I try to minimize it to almost 0 without success.
 <LinearLayout
         android:id="@+id/main"
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
         android:gravity="center"
         android:orientation="vertical"
          >

         <TextView
             android:id="@+id/text1"
             android:layout_width="wrap_content"
             android:layout_height="wrap_content"
             android:gravity="center"/>

         <TextView
             android:id="@+id/text2"
             android:layout_width="wrap_content"
             android:layout_height="wrap_content"
             android:gravity="center"/>

     </LinearLayout>

I tried to set android:padding,android:layout_margin on the LinearLayout but it doesnt work. I also tried to give to each TextEdit padding but it didnt halped aslo.
How can I place them near to each other?

A:

Set a negative layout_marginTop value to your text2 can minimize the space between the text showing, your layout goes like this:
 <LinearLayout
         android:id="@+id/main"
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
         android:gravity="center"
         android:orientation="vertical"
          >

         <TextView
             android:id="@+id/text1"
             android:layout_width="wrap_content"
             android:layout_height="wrap_content"
             android:gravity="center"/>

         <TextView
             android:id="@+id/text2"
             android:layout_width="wrap_content"
             android:layout_height="wrap_content"
             android:layout_marginTop="-7dp"
             android:gravity="center"/>

     </LinearLayout>


Q:

Isnt that true? Python x>y "", line 1 and syntax error

Why I cant run that? If I run with indent, It says unexpected indent.
 x = 20
 y = 17
 while x > y
 print(x)

or
 x = 20
 y = 17
 while x > y
   print(x)

A:

Here's a corrected version of your code. Of course, x > y will always be true, so the loop will run forever.
x = 20
y = 17
while x > y:
    print(x)


Q:

How to generate authorization request header?

How can I generate a authorization request header ?
I have read about authorization request header and I generated one using username and password in base 64, but when I pass it on request header it doesn't work ("error": "invalid_client).
Using Postman to make the request everything works :
POST /oauth/token
content-type: application/x-www-form-urlencoded
authorization: Basic M1g4Vlk2QllHOFFJTDA3amt1cWpsUnNKOmhoWkNlSEg0SzFuVVJ2VTZmNUs5MmFiTlNSN3h3ZlBCYVN6OXI1WG1pcDNZOGJCbA==
user-agent: PostmanRuntime/7.1.5
accept: */*
host: 127.0.0.1:5000
accept-encoding: gzip, deflate
content-length: 97

Obs ¹ : The api uses the password grant type and return a bearer token
Obs ² : When I generate a authorization request header using username and password (base64.b64encode(b'')) the lenght of the output is 20 characters

A:

In Flask Authlib, you can define three types of  Auth methods : client_secret_basic, client_secret_post and none, these types indicates witch parameters and how you need to pass them in headers. This is referente to RFC6749 spec.


Q:

Can I modify one spreadsheet document (google sheets) based on information from a separate spreadsheet

Not sure if this is the best place to ask about spreadsheets, but here goes:
I'm trying to help someone modify information on one spreadsheet document when information on a separate spreadsheet document is modified (without coding a solution from scratch using the sheetsAPI).
For example, my client has a product database stored in a spreadsheet document, products, when a customer places an order on the clients website, a separate spreadsheet document, openOrders, is updated using the sheetsAPI and some server code. When this document is updated, I'd like to subtract the quantity of items being ordered, from the quantity of the item (or items) available being listed in products. I'm wondering if letting these spreadsheet documents "speak" to each other is possible without coding a solution server-side using the API.
products looks kind of like this:
Product Name | Units | Unit Price
---------------------------------
Product 1    |     6 |       1600
Product 2    |     3 |       1200
Product 3    |    17 |        400
Product 4    |     2 |        600

openOrders looks kind of like this:
Product Ordered | Units | Unit Price | Total
--------------------------------------------
Product 3       |     1 |        400 |   400
Product 2       |     2 |       1200 |  2400
Product 3       |     5 |        400 |  2000
Product 1       |     1 |       1600 |  1600

When the openOrders sheet is updated with a new order, I'd like to subtract the number of Units ordered, from the number of Units available in products. Keep in mind these are two separate spreadsheet documents. I am new to spreadsheets so this is all very foreign to me, it could be possible that I'm using the spreadsheets in a fundamentally incorrect way, and I'm open to that possibility.

A:

you can do:
=ARRAYFORMULA(QUERY({A2:A, B2:B*-1;
 IMPORTRANGE("ID_of_spreadsheet", "Sheet1!A2:B")},
 "select sum(Col2) where Col1 <> '' group by Col1 label sum(Col2)''", 0)*-1)


Q:

Can evil beings be found in the Feywild, and good ones in the Shadowfell?

The Feywild and Shadowfell are planes parallel to the Prime material plane. Though they are usually depicted as good and evil planes respectively, is there evil that resides in the Feywild, or good that resides in the Shadowfell?

A:

Though the Feywild might generally be depicted as a wondrous place full of life and vibrant colours while the Shadowfell a dark, dismal place of shadow and death, this hardly means they are (meant to be) inherently good and evil.
The TL;DR version is simply that evil certainly resides in the Feywild and good certainly resides in the Shadowfell.
The Feywild
The Feywild is home to many malevolent and typically evil beings. Hags, goblins, orges, giants, werewolves, blights... You name it. The 4e Heroes of the Feywild (HotF) suppliment even states:

These villains can be as fundamentally evil as devils or demon lords, and they wield powers of comparable might.

While there may not be a lot of information about the Feywild in 5e there is:

Seelie and Unseelie Fey.
[...] Seelie and unseelie do not directly correlate with good and evil, though many mortals make that equation. Many seelie fey are good, and many unseelie are evil...

There's plenty of evidence that can be found in the 4e books Manual of the Planes and HotF and the 5e DMG to suggest that the Feywild is certainly not full of only good creatures.
The Shadowfell
There seems to be less direct evidence that there's good in the Shadowfell but one quote in 4e's The Shadowfell - Gloomwrought and Beyond, I think, strongly suggests that even the Shadowfell is not entirely full of evil beings.

The Shadowfell is not inherently evil, but evil creatures are strong and plentiful there.

Evil may be abundant but it is never stated that only evil beings ever reside in the Shadowfell.
The Manual of the Planes also states:

For all the Shadowfell’s dismal reputation, it does have bright spots where those who fight against the malaise and the chill live almost ordinary lives. In fact, for many visitors to the Shadowfell, the plane has more in common with the natural world than it has differences.

Much like the natural world there is both good and evil.

A:

I don't know about the Shadowfell, but yes, there is evil in the Feywild.
Page 10 of Heroes of the Feywild, referring to the Feydark (the Feywild's counterpart to the Underdark), states, "Food and water are plentiful for the underground inhabitants, but so are predators and malicious fey that inhabit the subterranean realm."
Also, page 12 of the same book states, "Though they have no true representative among the Court of Stars, there are fey creatures of evil, maliciousness, and corruption that are collectively known as the Unseelie fey. Many of these creatures draw power or are shaped by the power of shadow, drawn from the Feywild’s opposite counterpart, the Shadowfell."


Q:

Using SCOPE_IDENTITY result in another query

I'm having difficulties with this code
EXECUTE Environment.dbo.psu_some_psu

@instanceId = 1
,@serverId = 2
,@ip = '111.111.111.111'
,@clientName = 'dev-contact'
,@applicationId = 9
,@accountId = 35
,@userID = 22

DECLARE @restoreId INT
SET @restoreId = SCOPE_IDENTITY()

UPDATE Environment.dbo.restore_requests
SET Status = 1
WHERE Id = @restoreId

The stored procedure insert a row with indentity and with a status by default.
After the execution of the stored procedure i use scope_identity to get the ID of the inserted row.
But i cant get the update to work, i think there is a problem with the WHERE condition.
Thanks

A:

It's called SCOPE_IDENTITY() because it returns the last identity value inserted in the current scope - and since each procedure has it's own scope - you do not get the expected results.

Returns the last identity value inserted into an identity column in the same scope. A scope is a module: a stored procedure, trigger, function, or batch. Therefore, if two statements are in the same stored procedure, function, or batch, they are in the same scope.

Use an output parameter to return the scope_identity() from inside the procedure that actually executes the insert statement.
Also, please note that if you are inserting multiple records, the scope_identity() will return only the last value - in such cases you use the output clause on the insert statement to get a table containing all the newly inserted identity values.
DECLARE @MyTableVar table( NewScrapReasonID smallint,
                           Name varchar(50),
                           ModifiedDate datetime);
INSERT Production.ScrapReason
    OUTPUT INSERTED.ScrapReasonID, INSERTED.Name, INSERTED.ModifiedDate
        INTO @MyTableVar
VALUES (N'Operator error', GETDATE());


Q:

How to compare two stl lists filled with classes

I am writing a program for my c++ class and i am stuck on a problem. For the project i had to make two teams of supers and preform a simulation of a battle. In my main.cpp I created two list for each team and filled them with a 3 classes representing 3 characters per team. In the classes, I have attributes and one of the attributes is 'double speed'. I sorted the two teams to make the first character of the list to have the fastest speed of each team and is followed by the next fastest. Now comes the part I am stuck on. I have to do the simulation now and have the fastest overall character goes first followed by the next fastest. First, I do not know how to add the opposite team into a list inside my class, and second, I do not know how to compare the list to see who goes first. I created a list within my class called
list<super*>target

Which is list of pointers. I tried to add the opposite team to my target list when I created the teams like so:
for(int i = 0; i < 3; i++) {
    hptr = new super;
    vptr = new super;

    TeamA.push_back(*hptr);
    TeamB.push_back(*vptr);

    hptr -> addtarget(vptr);
    vptr -> addtarget(hptr);
}

But I get an error in my addtarget function which is:
void super::addtarget(super *tptr){

target.push_back(*tptr);

}

and the error message is:
error: no matching function for call to 'std::list<super*>::push_back(super&)'

I have been stuck with this problem for a couple of days and I just can not seem to get around it. I do not want exact code on how to do this, but just a head start so I can try to figure it out.

A:

1.add super to the list
TeamA.push_back(hptr);
TeamB.push_back(vptr);

We can see from the error message that the target list stores the pointer to a super object, so you should use target.push_back(tptr) instead of target.push_back(*tptr); tptr refers to a pointer of a super. *tptr is a super object.
2.compare the stl::list element
You can specify a custom sort predicate.
bool compareSuper(const super* a, const super* b) {
    return (a->speed) > (b->speed);
 }

 TeamA.sort(compareSuper); // TeamA is in decreasing order after sort
 TeamB.sort(compareSuper); // TeamB is in decreasing order after sort


Q:

How to use multiple producers and one consumer with activeMQ?

So i am trying to use ActiveMQ within my java project (I never used anything like this before but I've read about how it works).
The application runs on 5 different nodes and on each of them are created the messages that should be send into the same queue.
Here is how I think it should work : I have a class which creates these messages; these messages are created in any of those nodes; so this class works as a thread and should be "the producer", sending every message to the same queue.(therefore I have multiple producers)
The consumer class runs always on the same node.
Would this approach work for me? Would the queue be thread safe?

A:

Yes, your approach should work without any problem. All message brokers support multiple concurrent producers sending messages to the same queue. There should be no thread safety concerns.


Q:

Unable to apt-get update but connected to internet?

So I got a pi 3.0 and it has been running a apache webserver with php just fine. I have not logged into it in a while. Today, however, I was planning to install openvpn which failed to install. So I figured let me just update it with apt-get update but it returned errors:
root@raspberrypi:/home/pi# apt-get update
Err http://mirrordirector.raspbian.org jessie InRelease

Err http://archive.raspberrypi.org jessie InRelease

Err http://mirrordirector.raspbian.org jessie Release.gpg
Could not resolve 'mirrordirector.raspbian.org'
Err http://archive.raspberrypi.org jessie Release.gpg
Could not resolve 'archive.raspberrypi.org'
Reading package lists... Done
W: Failed to fetch http://mirrordirector.raspbian.org/raspbian/dists/jessie/InRelease

W: Failed to fetch http://archive.raspberrypi.org/debian/dists/jessie/InRelease

W: Failed to fetch http://mirrordirector.raspbian.org/raspbian/dists/jessie/Release.gpg  Could not resolve 'mirrordirector.raspbian.org'

W: Failed to fetch http://archive.raspberrypi.org/debian/dists/jessie/Release.gpg  Could not resolve 'archive.raspberrypi.org'

W: Some index files failed to download. They have been ignored, or old ones used instead.

I am connected via ssh from a remote location and the webserver is still running.
P.S. when I ping google.com or any website it cannot resolve host name.

A:

You could also try and ping 8.8.8.8 to see if you are actually able to get packets out to the internet. If you are then check your DNS settings as per
cat /etc/resolv.conf
You would expect to see something like
nameserver 8.8.8.8

Check that the DNS server in there is actually live and working. If not, edit it using something like nano, then see if it works.
If you cannot get packets out to the internet, check your internet settings.


Q:

When an answer is *only* a frame challenge, is it appropriate to point it out?

I left a comment on an answer which I believe is only a frame challenge to the question about imposing a "Limit Curse" on a player. This is what I said in that comment:

This answer is only a frame challenge, and therefore it does not answer the question asked. You are supposed to answer the Q first, and then challenge the frame later.

I link to the answer to the question, "How do we handle a desire to challenge the frame of a question?" because it gives the following guidelines, in my own words:

Still answer the question, even if you don't like it
Make sure the frame challenge is not most of your answer
Don't be upset if you are downvoted

For leaving the above comment, I have been told I was doing an inappropriate action. That is, I shouldn't let people know answers that are only frame challenges are not actually delivering what the querent wants.
My view of it is, even if I disagree with a particular Q, if I have the knowledge to challenge the frame of it, then I should also have the foresight to suggest ways on how to execute ideas which I believe can make the best out of a bad situation.
For example, in the linked question, if Ben truly wanted to go with executing his Limit Curse, then I have suggestions for what I believe to be the best way of executing that despite my opinion that it's best he should not do it at all. However, after giving my answer, I will still challenge his frame afterwards. I believe that is a proper frame challenge.
This is also why I think answers that are only frame challenges are not actually answers.
And so, to the thing I would like to hear the Stack's answers for: if an answer is only a frame challenge, is it appropriate or inappropriate to point it out in the comments? Should I leave it be?

A:

Guidelines
Our meta material on frame challenges are only guidelines. They're not rules, nor do we enforce them. (That way lies madness for the enforcers.)
These guidelines aren't soft rules either — they're very much guides toward best practices for those who want to give themselves a better chance at a successful, well-received frame challenge. They're help intended for authors to improve their content.
Since they're not rules, but suggestions and help, this is not the case:

This is also why I think answers that are only frame challenges are not actually answers.

Posts that attempt to answer the question are answers. Whether they're good answers or bad answers is to be determined by the quality of the content and the voters' reception of the same.
Most importantly though, guidelines can sometimes be incomplete, or even wrong for a specific case. There are corner cases and exceptions that will, despite violating the recognised guidelines for quality answer-writing, manage to buck the trends and be good answers anyway. We want those trend-defying answers to be able to be posted here so they can help us continue improving the Internet, and rules prohibiting them would be counter-productive.
Commenting
It's fine to comment pointing someone towards the frame-challenge guidelines.
Just as with any suggested change to a post though, the author may decline to take the suggestion. This should be received with equanimity and good grace, an appropriate vote, perhaps a parting comment (if it's not going to inflame the situation), and moving on.

A:

We do not need to point it out. You can always suggest improvements, but there's no need for frame challenges to also include an answer to the question, and the author is almost certainly aware they have done a pure frame challenge and so don't really need it pointed out to them.
I've updated the frame challenge guidelines to make this clearer. I'm sorry you went through that confusion and trouble, and I can see how you got there. Point 1 has been rephrased to this:

Provide your critique as part of an otherwise legitimate answer. (This isn't strictly required, but we very strongly recommend it. Sometimes declining to answer the question and instead going straight to a frame challenge — e.g. “don't do that at all” — is the right answer, but it's also risky and liable to backfire. This is a judgement call for the author and voters to handle.)

The intention is that 2 and 3 are firmly required, but not because of any special rules, but because we require them anyway:

We do require you to substantiate your frame challenge: if you don't, it's the kind of Bad Subjective opinionated answer that gets downvoted and deleted.
We do require that you don't cause trouble if people disagree: that's just site policy.

A:

Yes, it is appropriate to point out that pure frame challenges are often problematic in a comment on the answer.
The question and answer have gone through substantial revisions, but in the end, I expect users to respect the playstyle of the asker and help them in a way they will use.
In this case, you can certainly comment on the question, "Hey, you seem to be leaping to a single solution and should probably ask about your problem instead." It looks like SSD has actually edited the question at hand into that format, I would assume with the OP's consent.  Then, it's easier to answer with info on which of a variety of solutions are good or bad.
But if they don't want to ask about that, but ask about their specific solution - answer about their specific solution. If you just say "don't do that," expect people (including me) to downvote it and comment "You should give more help than just a frame challenge."
Because here's the deal.  Everyone's got their opinions. And in the past, on this site, before we derived the frame challenge guidelines, here's what happened.  There were always fights.
"I am doing survival horror in D&D and want good gun rules. Where are some good gun rules for D&D?"
"Don't use survival horror for D&D, use another game! D&D sucks for any genre other than heroic fantasy."
"I want a RAW answer to how to do X."
"RAW is bad and is for fools!  Just swag it."
Et cetera. I realize everyone always thinks they know better than the OP in cases like these.  And maybe you do. But maybe you just know different, and so it's not your place. Sometimes the mob loves the frame challenge and gives it a lot of votes.  It doesn't mean it's helpful, it just means it's turned a Q&A into a playstyle war.
If the question stays scoped to the proposed solution, if you just simply a priori disagree with the solution - move on to another question.
In this case - if you actually have experience with a "limit curse," or other similar kind of workaround, well then it's a legit answer to say "well we used something like that and here's how it worked out, and it worked out poorly."  GS/BS to the rescue. But "in my opinion that's bad, just, you know, because I'm a gamer and have opinions" - you are allowed to have that opinion, but it's not helpful.  So "someone's wrong on the internet," get over it.


Q:

Converting between ASCII, Binary, Octal, and Hexadecimal

Are there any libraries and/or built-in utilities that can facilitate the conversion of data between ASCII, Binary, Octal, and Hexadecimal?
Currently, I primarily need to convert ASCII to Binary, Octal, or Hexadecimal. At a later point, the starting and ending notations will be any of the aforementioned notations.

A:

Integer.toString(int,int) and Integer.parseInt(String,int) do this...


Q:

Java Battleship game

I have been given a problem statement to create a Battleship game in java.
My working code (Spring Boot+Web) is placed here along with the problem statement.
https://github.com/ankidaemon/BattleShip
This question is majorly focused on design, please help me figure out, how can I make it decoupled and apply suitable design patterns.
StartGame.java - getting called from controller
@Component
public class StartGame {

    private static final Logger logger = LoggerFactory.getLogger(StartGame.class);

    public String init(File inputFile) throws FileNotFoundException, InputException {
        // TODO Auto-generated method stub
        ArrayList<BattleShips> p1s = new ArrayList<BattleShips>();
        ArrayList<BattleShips> p2s = new ArrayList<BattleShips>();
        int areaWidth = 0;
        int areahight = 0;
        ArrayList<Coordinate> player1missiles = null;
        ArrayList<Coordinate> player2missiles = null;
        try{
            Scanner sc = new Scanner(inputFile);

            areaWidth = sc.nextInt();
            if(areaWidth>9 || areaWidth<1){
                raiseException("Supplied area width is invalid.",sc);
            }
            areahight = sc.next().toUpperCase().charAt(0) - 64;
            if(areahight>25 || areahight<0){
                raiseException("Supplied area height is invalid.",sc);
            }
            sc.nextLine();
            int noOfships = sc.nextInt();
            if(noOfships>areahight*areaWidth || noOfships<1){
                raiseException("Supplied no of ships is invalid.",sc);
            }
            sc.nextLine();
            for (int j = 0; j < noOfships; j++) {
                char typeOfShip = sc.next().toUpperCase().charAt(0);
                if(typeOfShip!='P' && typeOfShip!='Q'){
                    raiseException("Supplied type of ship is invalid.",sc);
                }
                int shipWidth = sc.nextInt();
                if(shipWidth>areaWidth || shipWidth<0){
                    raiseException("Supplied ship width is invalid.",sc);
                }
                int shiphight = sc.nextInt();
                if(shiphight>areahight || shiphight<0){
                    raiseException("Supplied ship height is invalid.",sc);
                }
                BattleShips ship;
                for (int i = 0; i <= 1; i++) {
                    char[] locCharArr = sc.next().toUpperCase().toCharArray();
                    int[] loc = new int[2];
                    loc[0] = locCharArr[0] - 65;
                    loc[1] = locCharArr[1] - 49;
                    if(loc[0]>areahight || loc[0]<0 || loc[1]>areaWidth || loc[1]<0){
                        raiseException("Supplied ship location is invalid.",sc);
                    }
                    ship = new BattleShips(shipWidth, shiphight, typeOfShip, loc);
                    if (i % 2 == 0)
                        p1s.add(ship);
                    else
                        p2s.add(ship);
                }
                sc.nextLine();
            }

            player1missiles = returnMissileCoordinates(sc.nextLine());
            player2missiles = returnMissileCoordinates(sc.nextLine());
            sc.close();
        }catch(InputMismatchException e){
            throw new InputException("Invalid Input supplied.",ErrorCode.INVALIDINPUT);
        }
        BattleArea player1 = new BattleArea("player1", areaWidth, areahight, p1s);
        BattleArea player2 = new BattleArea("player2", areaWidth, areahight, p2s);

        player1.placeShips();
        player2.placeShips();

        while (!player1.isLost() && !player2.isLost()) {
            for (int i = 0; i < player1missiles.size();) {
                Coordinate c = player1missiles.get(i);
                while (player1.fireMissile(c, player2)) {
                    player1missiles.remove(i);
                    if (i < player1missiles.size()) {
                        c = player1missiles.get(i);
                    } else
                        break;
                }
                if (player1missiles.size() > 0) {
                    player1missiles.remove(i);
                }
                break;
            }
            for (int j = 0; j < player2missiles.size();) {
                Coordinate c = player2missiles.get(j);
                while (player2.fireMissile(c, player1)) {
                    player2missiles.remove(j);
                    if (j < player2missiles.size()) {
                        c = player2missiles.get(j);
                    } else
                        break;
                }
                if (player2missiles.size() > 0) {
                    player2missiles.remove(j);
                }
                break;
            }
        }

        if (player1.isLost()) {
            logger.info("-------------------------");
            logger.info("Player 2 has Won the Game");
            logger.info("-------------------------");
            return "Player 2 has Won the Game";
        } else {
            logger.info("-------------------------");
            logger.info("Player 1 has Won the Game");
            logger.info("-------------------------");
            return "Player 1 has Won the Game";
        }
    }

    private static ArrayList<Coordinate> returnMissileCoordinates(String nextLine) {
        // TODO Auto-generated method stub
        ArrayList<Coordinate> tmp = new ArrayList<Coordinate>();
        String[] arr = nextLine.split("\\ ");
        Coordinate tmpC;
        for (String s : arr) {
            char[] charArr = s.toCharArray();
            tmpC = new Coordinate(charArr[1] - 49, charArr[0] - 65);
            tmp.add(tmpC);
        }
        return tmp;
    }

    private void raiseException(String message, Scanner sc) throws InputException {
        sc.close();
        throw new InputException(message, ErrorCode.INVALIDINPUT);
    }
}

BattleArea.java
public class BattleArea {

private static final Logger logger = LoggerFactory.getLogger(BattleArea.class);

private String belongsTo;
private int width,height;
private ArrayList<BattleShips> battleShips;
private Set<Coordinate> occupied=new TreeSet<Coordinate>();
private int[][] board=null;
private boolean lost=false;

public BattleArea(String belongsTo, int width, int height, ArrayList<BattleShips> battleShips) {
    super();
    this.belongsTo = belongsTo;
    this.width = width;
    this.height = height;
    this.battleShips = battleShips;
    this.board=new int[this.width][this.height];
}

public void placeShips(){
    for(BattleShips ship:this.battleShips){
        int x=ship.getLocation()[1];
        int y=ship.getLocation()[0];
        if(ship.getWidth()+x>this.width || ship.getHeight()+y>this.height){
            logger.error("Coordinate x-"+x+" y-"+y+" for "+this.belongsTo+" is not avilable.");
            throw new ProhibitedException("Ship cannot be placed in this location.",ErrorCode.OUTOFBATTLEAREA);
        }else{
            Coordinate c=new Coordinate(x, y);
            if(occupied.contains(c)){
                logger.error("Coordinate x-"+c.getX()+" y-"+c.getY()+" for "+this.belongsTo+" is already occupied.");
                throw new ProhibitedException("Ship cann't be placed in this location.",ErrorCode.ALREADYOCCUPIED);
            }else{
                Coordinate tempC;
                for(int i=x;i<ship.getWidth()+x;i++){
                    for(int j=y;j<ship.getHeight()+y;j++){
                        logger.debug("Placing at x-"+i+" y-"+j+" for "+this.belongsTo);
                        tempC=new Coordinate(i, j);
                        occupied.add(tempC);
                        if(ship.getTypeOfShip()=='P'){
                            board[i][j]=1;
                        }else if(ship.getTypeOfShip()=='Q'){
                            board[i][j]=2;
                        }
                    }
                }
            }
        }
    }
}

public boolean fireMissile(Coordinate c, BattleArea enemyBattleArea){
    int x=c.getX();
    int y=c.getY();
    logger.info("Firing at "+enemyBattleArea.belongsTo+" x-"+x+" y-"+y+" :");
    if(enemyBattleArea.board[x][y]!=0){
        if(enemyBattleArea.board[x][y]==-1){
            logger.debug("Already blasted!");
            return false;
        }
        else if(enemyBattleArea.board[x][y]==1){
            Coordinate temp=new Coordinate(x,y);
            enemyBattleArea.occupied.remove(temp);
            enemyBattleArea.board[x][y]=-1;
            if(enemyBattleArea.occupied.size()==0){
                enemyBattleArea.setLost(true);
            }
            logger.debug("Suucessfully blasted!!");
            return true;
        }else{
            enemyBattleArea.board[x][y]=enemyBattleArea.board[x][y]-1;
            logger.debug("Half life left!!");
            return true;
        }
    }else{
        logger.debug("Missed");
        return false;
    }
}

public boolean isLost() {
    return lost;
}

public void setLost(boolean lost) {
    this.lost = lost;
}
}

BattleShips.java
public class BattleShips {

private int width,height;
private char typeOfShip;
private int[] location;

public BattleShips(int width, int height, char typeOfShip, int[] loc) {
    super();
    this.width = width;
    this.height = height;
    this.typeOfShip = typeOfShip;
    this.location = loc;
}

public int getWidth() {
    return width;
}

public int getHeight() {
    return height;
}

public char getTypeOfShip() {
    return typeOfShip;
}

public int[] getLocation() {
    return location;
}

}

Coordinate.java
public class Coordinate implements Comparable<Coordinate> {

private int x,y;

public Coordinate(int x, int y) {
    super();
    this.x = x;
    this.y = y;
}

@Override
public String toString() {
    return "Coordinate [x=" + x + ", y=" + y + "]";
}

@Override
public int compareTo(Coordinate o) {
    // TODO Auto-generated method stub
    if(this.x==o.x && this.y==o.y)
        return 0;
    else if(this.x<o.x && this.y<o.y)
        return -1;
    else
        return 1;
}

public int getX() {
    return x;
}

public int getY() {
    return y;
}

}

Sample Input
5 E

2

Q 1 1 A1 B2

P 2 1 D4 C3

A1 B2 B2 B3

A1 B2 B3 A1 D1 E1 D4 D4 D5 D5

Rules
1. Player1 will fire first. Each player will get another chance till ( hit == successful ).
2. Battleships will be placed horizontally.
3. Type-Q ship requires 2 missiles hit to get destroyed.
4. Type-P ship requires 1 missile hit to get destroyed.
Input
First line of the input contains dimensions of battle area having width and height separated by space.
Second line will have number (B) of battleships each player has.
Then in the next line battleship type, dimensions (width and height) & positions (Y coordinate and X coordinate) for Player-1 and then for Player-2 will be given separated by space.
And then in the next line Player-1’s sequence (separated by space) of missiles target location coordinates (Y and X) will be given and then for sequence for Player-2.
Constraints:
1 <= Width of Battle area (M) <= 9
A <= Height of Battle area (N) <= Z
1 <= Number of battleships <= M * N
Type of ship = {‘P’, ‘Q’}
1 <= Width of battleship <= M
A <= Height of battleship <= N
1 <= X coordinate of ship <= M
A <= Y coordinate of ship <= N

A:

ok lets put hands on:
Class name for your StartGame is not helpful, rename it into a more matching name, i think like BattleShipGame and start the game instead from your controller
BattleShipGame game = new BattleShipGame();
game.start();

the init - method is far to big and it does no init but does even more things... so let's break that down a bit:

init should return a boolean (or a Result) that indicates that init was successful.
init looks like it's a delegate methode wich means ther should be very little logic insde - instead it is useful to put most work into methods
just init things and don't do any other things
use Player objects...
move the game logic out of the method

it could look like this then
private Player playerOne;
private Player playerTwo;

public boolean init(){

    playerOne = new Player("player1");
    playerTwo = new Player("player2");
    GameSetup setup = readFile(inputFile);

    ArrayList<BattleShips> p1bs = setup.getFirstBattleShips();
    ArrayList<BattleShips> p2bs = setup.getSecondBattleShips();
    playerOne.setBattleShips(p1bs);
    playerTwo.setBattleShips(p2bs);

    playerOne.setMissiles(setup.getFirstMissileCoordinates());
    playerTwo.setMissiles(setup.getSecondMissileCoordinates());

    playerOne.setBoard(new BattleShipBoard(setup.getDimension());
    playerTwo.setBoard(new BattleShipBoard(setup.getDimension());

    playerOne.placeShips();
    playerTwo.placeShips();

    return true;
}

NOTE: the init method could be shortenend far more, but i think i point out in a good way what init should really do...
as mentioned above you have moved the game logic out of your init method and put it in the playGame() method.
public Result playGame(){
    Result result = new Result();
    Scores score = new Score();
    while (!player1.isLost() && !player2.isLost()) {
        for (int i = 0; i < player1missiles.size();) {
            ...
        }
    }
    result.setWinner(playerOne);
    result.setScore(scores);
    return result;
}

the BattleShipGame would start now this manner:
public void start(){
    init();
    Result result = playGame();
    ... //do whatever you want with your result - for example print it into the console
}

for your BattleShip there are some more issuses wich can be talked about. I think it was a very good idea to use a class Coordinate which looks good at first glance. But you don't use it consequencically. think about how it would be if you used Coordinate for you ship instead of int[] that would make your code as well easier to read and the math would be much easier. And don't use a char for your shiptype, use a enum instead. But let's be honest, you don't have a 'position and width and height' what you really have is an rectangle - so use an rectangle!
public class BattleShips {

    private ShipType shipType;
    private Rectangle bounds;
    private int lifePoints;

    public BattleShips(ShipType typeOfShip, Coordinate pos) {
        super();
        shipType = typeOfShip;
        bounds = new Rectangle(shipType.getDimension, pos);
        lifePoints = shipType.getLifePoints();
    }

    public Rectangle getBounds() {
        return bounds();
    }

    ...
}

the dimension of the Rectangle (width/height) and the amount of lifepoints can be determind by the ShipType
public Enum Shiptype {
    DESTROYER(2,4,2), SUBMARINE(1,3,1), ...; //don't use shiptype P or shiptype Q

    private final Dimension dimension;
    final int lifePoints;

    public ShipType(int w, int h, int life){
        dimension = new Dimension(w,h);
        lifePoints = life;
    }

    public Dimension getDimension(){
        return dimension;
    }

    public int getLifePoints(){
        return lifePoints();
    }
}

The BattleArea is now far more easy to use, think about how simple you can placeShips now:
public class BattleArea {

    private Player owner;
    private Rectangle boardBounds;
    private List<BattleShips> battleShips;
    private List<Coordinates> board;

    public BattleArea(Player owner, Rectangle bounds, List<BattleShips> battleShips) {
        super();
        this.owner = owner;
        this.dimension = dimension;
        this.battleShips = battleShips;
        board = createBoard();
    }

    public void placeShips(){
        List<BattleShip> placedShips = new ArrayList<>();
        for(BattleShips ship:this.battleShips){
            Bound shipBounds = ship.getBounds();
            if(!boardBounds.contains(shipBounds)){
                throw new ProhibitedException(
                    "Ship cannot be placed in this location.",ErrorCode.OUTOFBATTLEAREA);
            }

            for (BattleShip placedShip: placedShips){
                if (bounds.intersects(placedShip.getBounds()){
                    throw new ProhibitedException(
                       "Ship cann't be placed in this location.",ErrorCode.ALREADYOCCUPIED);
                }
            }
            placedShips.add(battleShip);
        }
    }

    public boolean fireMissile(Coordinate c, BattleArea enemyBattleArea){
        BattleShip shipAt = enemyBattleArea.getShipAt(c);
        if(shipAt == null){
            return false;
        }else{
            handleDamge(shipAt, enemyBattleArea);
            return true;
        }
    }

    private void handleDamage(BattleShip opponent, BattleArea area){
        int lifePointsLeft = opponent.getLifePoints() - 1; //hardcoded damage (that's bad)
        if(lifPoints > 0){
            //Log damage done
        }else{
            //log destroyed
            area.removeBattleShip(opponent);
        }
    }
}

all code above has not been compiled so there may be some spelling errors and a lot of methods are not even implemented yet (like Rectangle.contains() or others).
summary
but let's look at what we have now:

you can change the ship type quite easily without modifing any code !!! (you simply have to add another shiptype in ShipType )
you have reduced the complexity of your code very far, you don't have dangerous calculations.
you have seperated concerns, the objects now do what they are supposed to do
you could easily change your code for another player (three-player game)
you could test your code now


Q:

Array subscript notation and derefencing

Hi all I have a question about the following code and want to verify some of my assertions.
int array[] = {1,2,3,4};
int* ptr = &array[1];

Does &array[1] mean I get the address of the array and add 1 to it, deference that address to see the actual integer and then take the address of the integer which is stored in that address?
How is this done?
Is there a operator[](int index) for array that returns a reference and then we takes its address?
I want to understand what the machine is actually doing and the language semantics for this.

A:

int* ptr = &array[1];

is equivalent to :
int* ptr = & ( *(array + 1) );

*(array+1) matches the second cell of your array. Then you're affecting the address of this cell to your pointer.
What you're doing is equivalent to :
int* ptr = array+1

A:

Does this mean get the address of the array and add 1 to it, dereference that address to see the actual integer and then take the address of the integer which is stored in that address?

Yes. Equivalently, it just means "add one to the address of the array", since dereferencing then taking the address gives you the address you started with.

How is this done? Is there a operator[](int index) for array that returns a reference and then we takes its address?

Almost. The built-in subscript operator, when used to apply an index to a pointer as p[i], is defined to give an lvalue referring to *(p+i). When applied to an array, the array is first converted to a pointer to its first element. That is one of the standard implicit conversions: the array-to-pointer conversion, sometimes referred to as "decaying". Taking the address of the lvalue gives a pointer to the array element.


Q:

Canon 80D - mirror lockup problem

I have a Canon 80. Bought last August, still in warranty. Never dropped it, was never exposed to high humidity / cold / heat / dust. I always treated it with great care.
Yesterday I used it for quite a while to take videos. Each single video was less than 10 mins on average. Maybe a bit over an hour of overall video taking but the camera was turned on for a longer time. I also shot 3 photos (but in liveview mode). Everything worked as usual. Room temperature was around 24 degrees, nothing extreme.
This morning when I tried to take a picture through the viewfinder the camera locked apparently.
After pressing the shutter the image was not previewed and then none of the controls would work anymore. I turned it off and heard the mirror unlocking. Turned it on again and shot some photos in live view, all fine.
I checked in the menu and turned off mirror lockup (I had turned it on in a previous session).
With mirror lockup off shooting with the viewfinder works fine.
Turning mirror lockup on caused the same problem again: shooting through the viewfinder locks the camera. When activating the shutter you can hear a small mechanical sound but not the complete sound that I usually hear. After restarting the camera I checked if the picture had been taken. It had not.
Previously I have used mirror lockup in a few occasions and it always worked fine.
What I would like to ask is: should I check other settings that would explain this behavior or should I just contact Canon maintenance service to have it fixed?
Thank you

A:

When taking still images with mirror lockup using the viewfinder, you must press the shutter button twice: once to raise the mirror and lock it there and a second time to activate the shutter. The only controls that will work during this time are the shutter button and the On/Off switch. None of the camera's other controls will be responsive while the camera is waiting for you to press the shutter button to take the photo.
If you do not press the shutter button again within thirty seconds of locking up the mirror, the mirror will reset (drop down).


Q:

mod_rewrite rules and content negotiation

I am relatively new to mod_rewrite, but have a site which I would like to have "pretty urls." Similarly to SO :).
I am attempting to have things like: "http://www.whatever.com/search/test" get rewritten to "http://www.whatever.com/search.php?q=test" and have had some limited success. I believe that content negotiation is getting in my way...
For starters here's my test .htaccess file:
RewriteEngine on
RewriteBase /~user/mysite/

RewriteRule ^search$ search/ [R]
RewriteRule ^search/([^/]*)/?$ search.php?q=$1 [L]

Which unfortunately, does redirect to search.php, but does not pass my param in the q variable. However this does work:
RewriteEngine on
RewriteBase /~user/mysite/

RewriteRule ^search$ search/ [R]
RewriteRule ^search/([^/]*)/?$ s.php?q=$1 [L] # here i've renamed the search.php to s.php to dodge the content negotiation that is happening..

In fact, if I remove the rules all together, I get the same result as with the first version of the file. So my conclusion is that since apache is happily redirecting "foo" to "foo.php" even without any mod_rewrite rules, that it must be the content negotiation that is taking care of it. (This is further verified by the fact if I renamed my foo.php to foo.html, it still will find the file if i just go to "foo").
So, the question is. How do I properly use mod_rewrite with regard to content negotiation? Can I disable it for a particular file? Is there a way to ensure that my mod_rewrite rules happen before the content negotiation happens?
If it is relevant, here is the conf file for the mod_userdir part of my apache conf (this test site is in my user's homedir/public_html):
# Settings for user home directories

<IfDefine USERDIR>
<IfModule userdir_module>

# UserDir: The name of the directory that is appended onto a user's home
# directory if a ~user request is received.  Note that you must also set
# the default access control for these directories, as in the example below.
UserDir public_html

# Control access to UserDir directories.  The following is an example
# for a site where these directories are restricted to read-only.
<Directory /home/*/public_html>
    AllowOverride FileInfo AuthConfig Limit Indexes
    Options MultiViews Indexes SymLinksIfOwnerMatch IncludesNoExec
    <Limit GET POST OPTIONS>
        Order allow,deny
        Allow from all
    </Limit>
    <LimitExcept GET POST OPTIONS>
        Order deny,allow
        Deny from all
    </LimitExcept>
</Directory>

# Suexec isn't really required to run cgi-scripts, but it's a really good
# idea if you have multiple users serving websites...
<IfDefine SUEXEC>
<IfModule suexec_module>
<Directory /home/*/public_html/cgi-bin>
    Options ExecCGI
    SetHandler cgi-script
</Directory>
</IfModule>
</IfDefine>

</IfModule>
</IfDefine>

A:

Look for this option in your configuration.
Options +Multiviews

It will look for
/foo/test
/foo/
/foo

and redirect them to
/foo.[any file]

based upon if it exists and if it fits the content-type requested.
Change the option to this to disable this.
Options -Multiviews


Q:

_idx and _tmp suffixed tables

we can see some tables have the suffix of _idx and _tmp in magento database,
but these tables doesn't have any data (whenever I see the tables using MySQL client),
what is the usage of these tables in magento ?

A:

They are used during indexing to prepare new data for the actual index tables and are truncated afterwards.


Q:

For $x^{2}$, how does one show that the $\delta$ which works at $-N$ or $N$ works anywhere else in $[-N,N]$?

We know that the function $f(x)=x^{2}$ is continuous at $a$ for all $a$. In other words, if $a$ is any number, then for every $\epsilon > 0$ there is some $\delta>0$ such that, for all $x$, if $|x-a|<\delta$, then $|x^{2}-a^{2}|<\epsilon$.
Of course, $\delta$ depends on $\epsilon$. But $\delta$ also depends on $a$-the $\delta$ that works at $a$ might not work at $b$. Indeed, it's clear that given $\epsilon>0$ there is no one $\delta >0$ that works for all $a$, or even for all positive $a$. In fact, the number $a+\delta/2$ will certainly satisfy $|x-a|<\delta$, but if $a>0$, then
$\biggl|(a+\dfrac{\delta}{2})^{2}-a^{2}\biggr|=\biggl|a\delta + \dfrac{\delta^{2}}{4}\biggr|\ge a\delta$,
and this won't be $< \epsilon$ once $a > \epsilon /\delta$. (This is just an admittedly confusing computational way of saying that $f$ is growing faster and faster!)
On the other hand, for any $\epsilon > 0$ there will be one $\delta >0$ that works for all $a$ in any interval $[-N,N].$ In fact, the $\delta$ which works at $N$ or $-N$ will also work everywhere else in the interval.

So when considering the function $f(x)=x^{2}$, I see how for any $\epsilon >0$, $\delta = \dfrac{\epsilon}{2N}$ works for all $a$ in any interval $[-N,N]$. Now, how would one go about showing that the $\delta$ which works at $N$ or $-N$ also works everywhere else in the interval?

A:

Intuitively, the $\delta$ that works at $a$ is $\frac \epsilon{|f'(a)|}$.  As $f'(x)=2x, |f'(x)|$ is increasing away from $0$ so the smallest $\delta$ comes at the furthest point from $0$, which is $\pm N$.  The fact that you can find such a $\delta$ says $f(x)=x^2$ is uniformly continuous over the interval.  This is important, as it is an assumption in many powerful theorems.
To prove it takes some care.  In fact, $\delta=\frac \epsilon{2N}$ would not be quite small enough if $x$ were allowed to go outside $[-N,N]$.  Let $N=1, \epsilon=0.01$.  Then $f(1)=1$ and you would claim $\delta=\frac \epsilon{f'(1)}=\frac {0.01}2=0.005$ works, but $f(1.005)-f(1)=1.010025-1=0.010025 \gt 0.01$.  The second degree term in the Taylor series kills you.
Aside from that detail, you can say let $a \in [-N,N]$.  Then $|f(a+\delta)-f(a)|=|(a+\delta)^2-a^2|=|2a\delta+\delta^2|\lt |2a\delta|+\delta^2\le 2N\delta+\delta^2$ so if $\delta$ works at $N$ it works at $a$.


Q:

If has class then remove class and add class

Having an issue here. This should be working... I have 4 elements in html that look like this

Although they are in different variations. So one could be header true and show faces true and the unique class would be ".h-t_dsf-t". The javascript should pick between them and tell which one is active and which one isn't. So only one has the .visible class at a time and the others have a .invisible class.
Thanks in advance!
My Javascript For The Show Faces Button (note .sf-no.click doesn't have anything in it yet but it will in the future I was just trying to get it to work for the yes button first.)
// Show Faces
$(document).ready(function() {
    $('.sf-yes').click(
        function() {
            $('.sf-yes').removeClass('btn-not-active btn-active').addClass('btn-active');
            $('.sf-no').removeClass('btn-not-active btn-active').addClass('btn-not-active');
            // Show Faces Yes &&& Show Header No
            if ($('.sf-yes.sh-no').hasClass('.btn-active')) {
                $('.h-f_dsf-t').removeClass('.invisible').addClass('.visible');
                $('.visible').removeClass('.visible').addClass('.invisible');
            }
            // Show Faces Yes &&& Show Header Yes
            if ($('.sf-yes.sh-yes').hasClass('.btn-active')) {
                $('.visible').removeClass('.visible').addClass('.invisible');
                $('.h-t_dsf-t').removeClass('.invisible').addClass('.visible');
            }
            // Show Faces No &&& Show Header Yes
            if ($('.sf-no.sh-yes').hasClass('.btn-active')) {
                $('.visible').removeClass('.visible').addClass('.invisible');
                $('.h-t_dsf-f').removeClass('.invisible').addClass('.visible');
            }
            // Show Faces No &&& Show Header No
            if ($('.sf-no.sh-no').hasClass('.btn-active')) {
                $('.visible').removeClass('.visible').addClass('.invisible');
                $('.h-f_dsf-f').removeClass('.invisible').addClass('.visible');
            }
        }
    );
    $('.sf-no').click(
        function() {
            $('.sf-no').removeClass('btn-not-active btn-active').addClass('btn-active');
            $('.sf-yes').removeClass('btn-not-active btn-active').addClass('btn-not-active');
        }
    );
});

A:

.hasClass('.btn-active')
should be
.hasClass('btn-active')
without dot .


Q:

How to allow Binary File download using GRAPE API

I want to allow downloading a binary file (.p12 file) using ruby's Grape API. This is what I am trying.
get '/download_file' do
  pkcs12 = generate_pkcsfile
  content_type('application/octet-stream')
  body(pkcs12.der)
end

The equivalent code using ActionController is
begin
  pkcs12 = generate_pkcsfile
  send_data(pkcs12.der,
            :filename => 'filename.p12')
end

The problem is the file downloaded using the API seems to be a text file with a '\ufffd' prefix embedded for every character, whereas the file downloaded using the browser seems to be binary file. How do I use the GRAPE API framework to allow downloading the same file that is downloaded via ActionController's send_data

A:

There are issues #412 and #418 have been reported to grape github page.
Which are related to return a binary file and override content type.
To return binary format like so:
get '/download_file' do
    content_type "application/octet-stream"
    header['Content-Disposition'] = "attachment; filename=yourfilename"
    env['api.format'] = :binary
    File.open(your_file_path).read
end


Q:

The definition of the Lorenz gauge condition

The inner product of two vectors in space-time is:
$$(x_1, y_1, z_1, t_1) \cdot (x_2, y_2, z_2, t_2) = x_1 x_2 + y_1 y_2 + z_1 z_2 - t_1 t_2$$
So
$$(\frac{\partial }{\partial x}, \frac{\partial }{\partial y}, \frac{\partial }{\partial z}, \frac 1c \frac{\partial }{\partial t}) \cdot (A_1, A_2, A_3, \phi) = \text{div}(\vec A) - \frac 1c \frac{\partial \phi}{\partial t}$$
is Lorentz invariant, where $\vec A=(A_1, A_2, A_3)$. But the [Lorenz gauge condition] (https://en.wikipedia.org/wiki/Lorenz_gauge_condition) is defined by $\text{div}(\vec A) + 1/c\  \partial_t \phi=0$.  Why has the minus changed into plus? So there is apparently no longer invariance.

A:

The Lorenz gauge condition is written as, $\partial_\mu A^\mu = 0$ which can be expanded as,
$$\partial_\mu A^\mu = \frac{\partial A^0}{\partial t} + \nabla \cdot \vec A = 0$$
in natural units, where we are simply doing what the Einstein summation convention instructed us to do, take a sum through the index, $\mu = 0, \dots, 3$. You can also write this as,
$$\partial_\mu A^\mu = \eta^{\mu\nu}\partial_\mu A_\nu$$
in which case you would get a minus sign, but notice the sum involves the co-vector $A_\nu$, a different quantity, related to $A^\mu$ by a change of sign, in flat spacetime since $\eta = \mathrm{diag}(\mp1,\pm1,\pm1,\pm1).$


Q:

How does Javascript's Scope work, getting unexpected behavior?

Heres a sample bit of code, similar to that that gave me grief:
for(var i=0;i<3;i++){
    var Proof = true
    if (i == 0){
        Proof = false
        //var CallBack = function(){alert(Proof);}; // true????
        var CallBack = function(){alert(i);};
    }
}

// Whatever happened to local scope? shouldn't CallBack be undefined now?
CallBack()// alert(3), should be 0?

CallBack isn't undefined, it alerts true or 3, could someone please explain to me what is going on that is making it act like this? is there some local keyword I am missing, or does JS not have scope? I am using no framework, and would appreciate some help on how to sort this out, and do this kind of thing properly...

A:

JavaScript doesn't have block scope at all (yet, see below). All variables are declared throughout the function in which they appear (or throughout the global scope, if they're at global scope).
Assuming the code you've quoted is the only code in its scope, it's exactly the same as this:
var i;
var Proof;
var Callback;

for(i=0;i<3;i++){
    Proof = true
    if (i == 0){
        Proof = false
        //CallBack = function(){alert(Proof);}; // true????
        CallBack = function(){alert(i);};
    }
}

// Whatever happened to local scope? shouldn't CallBack be undefined now?
CallBack()// alert(3), should be 0?

More (on my blog): Poor, misunderstood var

CallBack()// alert(3), should be 0?

No, 3 is correct, because that's the value of i as of when CallBack is called. CallBack is a closure over the context in which it was created. It has an enduring reference to the context (including the i variable), not a copy of what existed when it was created.
If you wanted to get 0 instead, you'd have to have CallBack close over something other than i, something that won't change. The typical way to do that is to use a builder function you pass a value into:
function buildCallBack(index) {
    return function() { alert(index); };
}

Then:
CallBack = buildCallBack(i);

The value of i is passed into buildCallBack as the argument index. buildCallBack creates a function closing over the context of that call to buildCallBack and using that index argument. Since that argument's value is never changed, the callback alerts 0 (in this case) rather than 3.
More (on my blog): Closures are not complicated

The reason I said "yet" above is that the next version of the spec (ES6) will introduce new block-scope semantics for the new let and const keywords and block function declarations. var will be unchanged, but if you use let to declare a variable instead, it has block scope rather than function/global scope.


Q:

Rails обратное разбиение на страницы c gem`ом kaminari

Пишу данный вопрос, так как столкнулся с данной задачей. В интернете пришлось потратить время на поиски данного решения (было найдено на stackoverflow). Решения, который описаны там довольно громоздкие. Я же объединив ответ со своим кодом нашел более быстрое решение.
Например, если обычная разбивка на страницы {a, b, c, d, e, f, g, h, i} по 3 элемента:
{a,b,c}, {d,e,f}, {g,h,i}

Тогда обратное разбиение на страницы выглядело бы так:
{g,h,i}, {d,e,f}, {a,b,c}

A:

У нас присутствуют пользователи, которых мы берем из базы и сортируем:
@users = users.page(params[:page]).per(3).order(id: :desc)

В дальнейшем во view - index.html.erb с помощью reverse возвращаем наш разбитый массив в обратном порядке:
 <%= render @users.reverse %>

По итогу мы получаем из: {a,b,c}, {d,e,f}, {g,h,i}, то, что нам надо :{g,h,i}, {d,e,f}, {a,b,c}


Q:

Passing state between EJB methods / @RequestScoped and @Stateless

I have a @RequestScoped CDI bean that I want to turn into an EJB to get declarative transactions.  (I'm on EJB 3.1, Java EE 6)
Currently, I am passing state between subroutines, under the assumption that the instance is only used in a single request.  If I add @Stateless now that assumption would change.
For example, I want to do something like
@Stateless
@Named
@RequestScoped
public class Foo {
  private String var1; // can't use instance vars in @Stateless?
  private String var2;

  public void transactionForRequest() {
    var1 = value;
    var2 = value;
    ....
    subroutine();
  }
}

I assume the above doesn't work- is that correct?
I am contemplating two alternatives:

Use @Stateful instead of @Stateless, along with @Named and @RequestScoped.
Keep @Stateless and use EJBContext.getContextData map to replace instance variables.

Which is better?  And is there some other alternative I'm not thinking of?  (Besides wait for Java EE 7 or switch to Spring. :-))

A:

While @Stateless, @Singleton and @MessageDriven can have scoped references injected via @Inject, they cannot be @RequestScoped or any other scope.  Only the @Stateful model is flexible enough to support scopes.  In other words, you can annotate the @Stateful bean class itself as @RequestScoped, @SessionScoped, etc..
In simple terms @Stateless, @Singleton have fixed "scopes" already.  @Singleton is essentially @ApplicationScoped and @Stateless would perhaps be some made-up scope like @InvocationScoped, if that existed.  The lifecycle of an @MessageDriven bean is entirely up to the Connector that drives it and is therefore also not allowed to have user-defined scope.
See also https://stackoverflow.com/a/8720148/190816

A:

I would go with SFSB instead of SLSB. You want to hold a state, so for me this is the most important information - this is a job for Stateful EJB.
Also I don't think that EJBContext#getContextData() would help you. As far as I remember, it's only valid for a duration of a call. Therefore, each invocation of a method on your EJB will create new context data map (at least it's what I would expect.)


Q:

When do engine type and mileage of a car affect pricing?

I'm currently designing a customer relationship management tool for auto shop owners and was wondering:

Does engine type or the odometer value of a car ever affect pricing for a customer?
What considerations must be made to accommodate these differences?

A:

The engine type can definitely affect the price of a service job. Something like a timing belt service can be simple on one engine type and horrendous on another, due to things like accessibility of the components. A water pump could be directly accessible on one engine type, but require removal of the whole front bumper for access on another.

A:

The odometer reading is one of the key factors for pricing of a used car. The combination of mileage, age and physical condition of the car are enough to vary the price anywhere down to a tiny fraction of the list price.
The engine size, while important, it's more like the difference an alternative model may have. One engine size might be known as the best one (eg the 2.8 Ford Capri)
Have a look at some used car websites and do your own comparison based on mileage and you will see how significant it is.


Q:

BigO bound on some pseudocode

AllDistinct(a1 , . . . , an )
if (n = 1)
return True
for i := n down to 2
   begin
   if (LinearSearch(a1 , . . . , ai−1 ; ai ) != 0)
     return False
   end
return True

Give a big-O bound on the running time of AllDistinct. For full credit, you must show
work or brieﬂy explain your answer.
So the actual answer for this according to the solution for this problem is O(n^2). However, since BigO is the worst case running time, could I have answered O(n^100000) and gotten away with it? Theres no way they can take points off for that since its technically the correct answer right? Although the more useful O(n^2) is obvious in this algorithm, I ask because we might have a more difficult algorithm on the upcoming exam, and incase I cant figure out the 'tight' bound, I could make up some extremely large value and it should still be correct, right?

A:

Yes, if a function is in O(n^2), it is also in O(n^1000).
Whether you'll get full (or any) credit for answering this way depends on the person grading your exam of course, so I can't tell you that (probably not though). But yes, it is technically correct.
If you do decide to go this way though, you should probably chose something like O(n^n) or O(Ackermann(n)), since for example exponential functions are not in O(n^1000).
Another problem is that you will probably be asked to proof the bound as well. This will be hard to do if you don't actually know the running time of the function. "n^n is really large, so the running time will probably be less than that" is not a proof. Though on the upside if you manage to correctly proof that the function is in O(n^n), you'll probably get at least partial credit.


Q:

Rails ActiveRecord Model.uniq.pluck :id doesn't work with postgres

I have an empty demo rails 4 app trying to do the following: Collection.order('created_at ASC').uniq.pluck :name It works under sqlite, but blows up in postgres with the following error:
(0.9ms)  SELECT DISTINCT "collections"."name" FROM "collections" ORDER BY created_at ASC
PG::Error: ERROR:  for SELECT DISTINCT, ORDER BY expressions must appear in select list
LINE 1: ...collections"."name" FROM "collections"   ORDER BY created_at...

Is this a bug or how can I fix it?

A:

I was actually trying to solve this issue on active_admin. https://github.com/gregbell/active_admin/issues/2324
Now the solution seems to be Collection.reorder('name asc').uniq.pluck :name, this will overwrite the default_scope or previous order, and order collections with name. What's weird here is reorder works, while as order causes the problem...


Q:

PayPal MECL inappropriate UX message issues on iOS and likely Android/other mobile platforms

We’re implementing the PayPal MECL library in a client’s app but we’re experiencing some poor user experience that we don’t seem to be able to change.
When the PayPal experience is complete, PayPal show a “Please wait while we transfer you to the business site...” message. Obviously this is an iOS app not a “business site”...
The flow functions by dismissing the web view on completion of the PayPal experience by listening for new URL requests within the UIWebViewDelegate method:
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType

This issue seems to be that PayPal update their web view with the message via editing the DOM (JS or some such) which does not create a new web request and therefor no shouldStartLoadWithRequest fired. Note: A new request is made after a second or so when redirected but that’s too late, the inappropriate copy has been presented to the user.
Has anyone working with MECL on iOS or Android managed to alter this copy/experience either via the SetExpressCheckout server call or configuration of the MECL URL get params?I ’ve been unable to find a resolution on this so far but will post a solution if we find one. Any help would be greatly appreciated as we don’t seem to be able to find a solution in PayPals documentation...
NOTE: Also we have a similar UX issue when pressing the cancel button on the PayPal web view that causes a redirect, but with a similar bad piece of copy presented before hand “Cancel this purchase and return to the seller’s website?”. This is worded as a confirmation dialogue but there are no buttons presented and it redirects anyway. Mad UX. Again if anyone knows a solution to either if these please post.

A:

Here’s the response from our friendly PayPal support team (paid retainer contract).
*"Hi _,
Unfortunately there really aren’t any customisable options on the MECL web views. They are essentially provided as is.
Thanks,
_"*
Looks like this is a closed box. Bad UX it is or another payment solution. I’m accepting this as the answer as it looks likely that nothing can be done here sadly.


Q:

Google's 2-line blobstore upload example not working

I know there are a ton of blobstore questions, but I've dropped back to the most basic situation and I'm stuck!
In the long run, I'm using pure Django on Google App Engine with Google Cloud SQL and I'd like to upload a file to the Blobstore (but I can't upload a file).
I'm trying to run the following example from Google's Blobstore overview (https://developers.google.com/appengine/docs/python/blobstore/overview)
from google.appengine.ext import blobstore
upload_url = blobstore.create_upload_url('/upload')

but I get the following:
$ python
Python 2.7.2+ (default, Jul 20 2012, 22:15:08)
[GCC 4.6.1] on linux2
Type "help", "copyright", "credits" or "license" for more information.
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<snip>/google_appengine_1.7.6/google/appengine/api/blobstore/blobstore.py", line 270, in create_upload_url
gs_bucket_name=gs_bucket_name)
File "<snip>/google_appengine_1.7.6/google/appengine/api/blobstore/blobstore.py", line 334, in create_upload_url_async
_get_result_hook, lambda rpc: rpc.response.url())
File "<snip>/google_appengine_1.7.6/google/appengine/api/blobstore/blobstore.py", line 223, in _make_async_call
rpc = create_rpc()
File "<snip>/google_appengine_1.7.6/google/appengine/api/blobstore/blobstore.py", line 217, in create_rpc
return apiproxy_stub_map.UserRPC('blobstore', deadline, callback)
File "<snip>/google_appengine_1.7.6/google/appengine/api/apiproxy_stub_map.py", line 405, in __init__
self.__rpc = CreateRPC(service, stubmap)
File "<snip>/google_appengine_1.7.6/google/appengine/api/apiproxy_stub_map.py", line 67, in CreateRPC
assert stub, 'No api proxy found for service "%s"' % service
AssertionError: No api proxy found for service "blobstore"

I've dropped back to the most basic situation: Google App Engine SDK 1.7.6 (most current right now) and Python 2.7.2.
My path is this:
>>> from pprint import pprint as p
>>> p(sys.path)
['',
'<snip>/google_appengine_1.7.6',
'<snip>/google_appengine_1.7.6/lib',
'<snip>/google_appengine_1.7.6/lib/yaml-3.10',
'<snip>/google_appengine_1.7.6/lib/django-1.4',
'/usr/lib/python2.7',
'/usr/lib/python2.7/plat-linux2',
'/usr/lib/python2.7/lib-tk',
'/usr/lib/python2.7/lib-old',
'/usr/lib/python2.7/lib-dynload',
'/usr/local/lib/python2.7/dist-packages',
'/usr/lib/python2.7/dist-packages',
'/usr/lib/python2.7/dist-packages/PIL',
'/usr/lib/python2.7/dist-packages/gst-0.10',
'/usr/lib/python2.7/dist-packages/gtk-2.0',
'/usr/lib/pymodules/python2.7']

Interestingly, if I try this with only the base GAE directory in the path, I get:
ImportError: No module named yaml

Could this indicate I have something misconfigured in the SDK?
I appreciate anything you can offer!

A:

it looks like you are trying this from a plain python prompt.
You have some serious work ahead of you to get this to work (ie probably won't get it to work if your new to appengine, I have been using appengine since it came out and I wouldn't bother trying ;-).
You should be using the remote_api_shell if you want to use a python shell, and be connected to a server (dev or prod appengine) and your just exploring.
The code fragments in the docs you refer to are for code to be run by app engine app, either under the dev server or in production.


Q:

amount of code in code review

In my experience, most teams in the company review the code of team member with a small amount
of code, always less than hundreds of lines.  Is it appropriate to review large amount of code, for example a module,  when the code is complete and ready to get reviewed once for all?

A:

The reason for the small code reviews is to maximize effectiveness.
Studies involving the Personal Software Process have found that reviewers are most effective, with respect to maximizing defects identified in the review, when they review no more than 150-200 source lines of code per hour. Given that empirical data, it becomes a matter of determining how long people can stay attentive. I don't have any empirical data, but I know my mind begins to wander after about 1 hour of reading something. To me, that indicates that code reviews should review less than 150 lines of code at a time.

A:

It's appropriate if it helps your team create a better product.
Some reasons that code reviews often focus on smaller chunks:

Properly reviewing a large amount of code requires each participant to spend quite a long time preparing, and that can be expensive.
The longer a review meeting goes (any meeting, really), the less people pay attention. Two hours is about as much as most people can stand, and keeping meetings shorter than that (say, an hour or 90 minutes tops) goes a long way toward making sure that everyone is at their best.
It's often not necessary to review every line. One reason to review code is to make sure that everyone is sticking to basically the same set of coding guidelines. A detailed review of a smaller amount of code works better for that purpose than a less detailed review of more code.

That said, if you find that reviewing more code is helpful, and if your team can stand it, then by all means give it a try. It'll help to make sure that there are some ground rules and someone acting as a facilitator to keep the meeting moving along. Also, consider having reviewers submit their comments beforehand so that you spend less time on nitpicky things like improper use of white space and more time discussing important and interesting issues.


Q:

Redirect Selected Console Output to File

I have a small Java program that is being invoked with java -jar via a bash script.  The program calls a SOAP webservice and I want to capture the SOAP messages in a file for future troublshooting.  The only way I've found to do this in a standalone Java app is by adding this to my client class:
static
{
    // Output the SOAP message to the console
    System.setProperty("com.sun.xml.ws.transport.http.client.HttpTransportPipe.dump", "true");
    System.setProperty("com.sun.xml.ws.transport.http.HttpAdapter.dump", "true");
}

This outputs the SOAP messages to system out.  I could just redirect system out to a file, but I have other messages going to system out that I want to be displayed on the console.  It's okay to include these messages in the file but the SOAP messages are just way too much to be displayed on the console.
Is there a way I can do some sort of selective redirect on console output?

A:

It seems unlikely that you'll be able to do this in-app as the SOAP code will be calling System.out.print.
If your main goal is to separate your output from the output from SOAP then you could  prepend your messages with a special symbol and then filter the output through an appropriate script.
If your print statements are spread across your code you could consider using AOP (i.e. AspectJ) to modify them to insert this special symbol. Personally I do all printing through my own utility methods so that I can change it all in one place if needed.


Q:

How to get rid of materials showing in the viewport when in solid mode

I modeled a mesh and gave it materials. But material colors get in the way; I'd like to go on modeling and just seeing a well-contrasted, solid-light object.

I find this setup uncomfortable and I'd like it to be just solid color, for instance:

I know this is the normal, default Blender behaviour; my question is not "Why my materials doesn't show in viewport", but:
Is there a way to get rid of materials showing in viewport when in solid mode, without removing them?
EDIT: I can use matcaps, I'm using BI. Same problem with Cycles. Apparently shading is ok. I'm trying to post the blend...
blend file
EDIT2: Cycles shows the same behavior. This has been tested with an untamed Blender 2.79a just downloaded.

A:

Actually I found that:
in edit mode, if I set show hidden wireframe, I get this:

In both object and edit mode, only matcaps work (by substituting materials, so little help).
So, afaik, unless there's some way to temporarily switch off materials, apparently there's no way.


Q:

Is China buying up the worlds arable land

Is there any reliable evidence to suggest that China is buying large quantities of farming land in other countries?
Furthermore is there any evidence if the above is true that the quantities they are buying in will cause food supply problems for those countries, whether this be minor or major?
Finally, is there any evidence this has been commissioned at a government level or are these just investors looking for opportunities for a product they see as a valuable asset in their country?
Here are some example headlines:

Chinese government quietly buying arable land abroad
Shocked Investor: Chinese Are Snapping Agricultural Land in Canada
Australian farms up for grabs - China's Government buyers

A:

The position is very difficult to identify.  UNCTAD published a major study a couple of years ago called Transnational Corporations, Agricultural Production and Development as part of its World Investment Report 2009.
In it, Figure III.13 suggested that China had the third highest outward foreign direct investment stock in agriculture (after the USA and Canada and well ahead of Japan).  This has probably grown since then.
The rest of the report discusses different forms of investment and potential consequences.  One of the conclusions was

In recent years, an increasing number
  of food importing countries have
  started pursuing a strategy of
  overseas agricultural production to
  secure food supply at home. Such
  strategies can contribute to creating
  value and generating export revenues
  in the host countries, but they can
  also have negative consequences for
  food supply in the exporting country,
  including depriving local farmers of
  land. However, a win-win situation can
  emerge if the institutional
  arrangements are carefully designed,
  and if the legislative framework and
  investment contracts ensure a fair
  sharing of the benefits between host
  countries and foreign investors.

Another point made by UNCTAD is that many of the positive effects of such investment can be achieved through other means such as free trade and contract farming.


Q:

storing the output of boost::bind in a boost::function

I currently have something like this
void asomeMethod(int q)
{
    std::cout << "Method with parameter " << q ;
}

int main()
{
     boost::function<void(int)> parfunct;
     parfunct = boost::bind(&asomeMethod,12);
     parfunct;  //Does not call asomeMethod ??
    return 0;
}

I want to call the function ptr but the method is not being called ? Any suggestions on what I might be doing wrong ?

A:

It has to be boost::function<void()>, since there's no remaining argument.
Then call it like a function:
parfunct();


Q:

Why am I getting this error in build.gradle in my Flutter Project in Android Studio?

I have added the Project-level build.gradle dependencies and also App-level build.gradle dependencies in my Flutter Project inorder to connect to Firebase. But then, I see errors and I don't see any Firebase connection messages while running. Where did it go wrong? What have I done? Please check the screenshot.

A:

The highlight error on the build.grade can be ignored since you are not running it as an android project.
What you need to pay attention to is any errors, if any, on the Run tab at the bottom of the screen.
Just continue following the process and add the google-services.json file onto your app folder, since I cannot see it on the screenshot, meaning Firebase is still not fully set up.


Q:

fatal: bad object HEAD

Can somebody help me to solve this problem. I had made a previous post about this but I couldn't solve it through those answers. Please help:)
I have tried to run git fsck --full and I get :
Checking object directories: 100% (256/256), done.
error: HEAD: invalid sha1 pointer 15044de63184bed22f9be9f48fd63a3a7652eea4
error: refs/heads/master does not point to a valid object!
notice: No default references
dangling blob f4ffb48ece75b45ec593146216a2ecae5a5b2194
dangling blob f37ffd41d80a2d07258d0b8fa7118d236d480fc0
dangling blob f1ff1fa538a538d9085e573f60ad11e8e7f5395e
dangling blob f9ff6bdaf08fdbf9001ff44d2aa1a49092c20ad1
dangling blob f97f1a223ef3ca33f55d51ae25d98d3b5b2f9ece

A:

In my case, I edited .git/refs/remotes/origin/HEAD.  I couldn't get git update-ref to work, but that seems to be the recommended way.
So if git checkout (<branch> | <commit>) doesn't work, you should try something like git update-ref HEAD ref:master or just try editing .git/HEAD.

A:

I had the same problem. Simply doing a git pull origin master fixed it, and left my local edits intact.

A:

"invalid sha1 pointer" in combination of git gc was seen before (git for windows issue 423)
git 2.7 (Q4 2015) will fix this:
See commit 14886b4, commit 8c845cd (28 Sep 2015) by Johannes Schindelin (dscho).
(Merged by Junio C Hamano -- gitster -- in commit 1018f3e, 15 Oct 2015)

"git gc" used to barf when a symbolic ref has gone dangling (e.g. the branch that used to be your upstream's default when you cloned from it is now gone, and you did "fetch --prune").

More precisely:

pack-objects: do not get distracted by broken symrefs
It is quite possible for, say, a remote HEAD to become broken, e.g. when the default branch was renamed.
We should still be able to pack our objects when such a thing happens; simply ignore broken symrefs (because they cannot matter for the packing
process anyway).


Q:

Mistake in Cover Letter

Before asking my question I searched this site and came across these two (1,2) pages that are similar to my problem, but also slightly different. It's not the misspelling of a word or stating the incorrect company name.
I'm currently job searching and applying to many jobs that have similar responsibilities, so I constructed a personal cover letter template with the following line:
I'm interested in applying for insert job title here.

I copied the job title and pasted it into my template, but I noticed this mistake:
I'm interested in applying for insert Data Entry Coordinator.

after I sent in my cover letter.
I've read other sites and here, that cover letters rarely get read and mistakes such as typos will get ignored unless it's for a writing position, my problem is, there is some indication that the cover letter will be read, because the job posting indicated I'm supposed provide my salary expectations.
Question:
Should I just move on and expect my resume/cover letter will be ignored?
Afterwards:
I saved my template in a text file so there was no special formatting or font color to indicate that line should be adjusted. I've corrected the problem by saving the template in another format, with red font, and yellow highlighting, so I'm more aware of what text has to be changed.
Edit: My problem doesn't "dramatically change perception". If anything, the above two links provided have more in common with my question, but as stated it's slightly different.

A:

Question: Should I just move on

Yes. What's done is done. The only option you have would be sending an updated cover letter. This may help or make it worse. You really don't know which, so I'd just let it be.

and expect my resume/cover letter will be ignored?

No. This is not the end of the world and it may go undetected or ignored or many people may just find it funny and human (which it is). It's a ding on your "attention to detail" score, but depending on culture and job this may not be a major problem. I wouldn't just give up because of that. Worst that can happen is they say "thanks, but no thanks". No harm in following up just the same way you would do with any other application


Q:

Como integrar uma tabela do banco de dados a outra?

Exemplo: Um sistema que registra clientes, compras e produtos, cada um em uma tabela diferente. Tendo um registro de compras que deve possuir os campos:

Cliente: indica qual cliente já cadastrado (em outra tabela do banco) que efetuou a compra.
Produtos: seleciona qual foi o produto (que também está em outra tabela) que foi vendido para o cliente.

Além disso devo colocar outros campos como data de venda etc, mas isso não vem ao caso, pois quero saber como faço essa integração entre tabelas? Pegar o registro de outra tabela e associar a um campo de um registro de outra tabela. Já tentei pesquisar sobre isso mas não consegui encontrar, se me derem um exemplo de como funcionaria ou termos que devo pesquisar eu agradeceria.
Peço que não ponham muito código em linguagem do banco de dados, pois não entendo nada disso, os bancos que crio são totalmente visuais, ou seja, criados automaticamente pelo Visual Studio.
Detalhes: Deveria funcionar da seguinte maneira, ao querer registrar uma compra, o usuário informaria a data da venda (essa parte eu sei como faz), o cliente que comprou aquilo (esse cliente tem um registro em outra tabela então deve-se buscar e associar o nome do cliente ao seus dados armazenados na outra tabela) e por fim o produto vendido (que também possui registro em outra tabela)

A:

A integração entre tabelas normalmente é feita por chaves estrangeiras. Uma chave estrangeira relaciona uma chave primária de uma tabela com a chave primária de outra tabela. Isto garante a integridade referencial entre tabelas.
Para o seu exemplo, uma compra deve relacionar produtos com um cliente. O ideal seria haver uma tabela associativa entre produtos e uma compra, tendo um campo adicional, o de quantidade. Ou seja, esta tabela associativa deve ter, além de sua chave primária, duas chaves estrangeiras, sendo uma apontando para uma compra e outra apontando para o produto que pertence a uma compra.


Q:

Steam + Call of Duty 4 problem

I just download Call of Duty 4 from Steam and every time I open up the multiplayer I get the following message:

Your computer appears to have changed since the last time you ran Call of Duty 4: Modern Warfare.  Would you like the game to configure itself optimally for your new hardware?

Is there a way I can fix this?

A:

It's likely that the game is trying to save your configuration settings and failing.  Try checking whether or not the files in your CoD4 directory are write protected or not.  By default, Steam installs CoD4 to:
C:\Program Files (x86)\Steam\steamapps\common\call of duty 4
But, this may vary depending on your Windows version, 32/64 bit, how you installed Steam, etc.
You will want to at least check all of the .cfg files, although one person had better luck making sure that all of the files in that directory are not write protected.
Some people speculate this is an issue with file permissions caused by the filesystem changes in Vista/Win7, although others have reported issues with Windows XP as well.
For reference, there's a help thread on the Activision site for this, but I doubt that the suggestions there would help.


Q:

Continuous Deployment using Visual Studio 2010

I have to deploy a website asap and then incrementally keep on adding some features, fixes. In Visual Studio 2008, I used to transfer/copy website where I could see in the dialog which file on my system is different from the server and deploy only that particular change.
But that dialog seems to have been taken down in Visual Studio 2010 and a one click publish has been put in place. How do I publish just the files I have added/modified. I am thinking of doing FTP client like FileZilla but keeping track of changes then becomes a headache.
What is the best way for site deployment in such a scenario?

A:

MSBuild
But if you fancy a quick & dirty solution (and since you haven't mentioned TFS or continuous integration, i assume you do), then write a robocopy script to only copy newer files.  But then again; Using Robocopy to deploy sites


Q:

Cannot set Outlook '13 as default mail client in Win10: "Either there is no default mail client or..."

Very aggravating issue on my work machine (Dell Optiplex 5050 - Windows 10 Enterprise x64, build 1803 - Spring Creators Update).
Every time I click as .MSG file I get this error:
Either there is no default mail client or the current mail client cannot fulfill the messaging request. Please run Microsoft Outlook and set it as the default mail client.
Outlook already is the default email program. Any ideas how to fix this? If it matters, our email server is Exchange 2007.
UPDATE: I have now tried a repair install of Office Pro '13 and deleting this registry key: HKEY_LOCAL_MACHINE\Software\Clients\Mail\Microsoft Outlook (via MS instructions, albeit very old ones: https://support.microsoft.com/en-us/help/813745/either-there-is-no-default-mail-client-or-the-current-mail-client-cann). Neither made a difference.

A:

Backup these registry keys with an export first, and then any keys labeled "Microsoft Windows MAPI Preview Handler" delete all or any that may exist in your environment. After this you should reboot the machine immediately before testing just to be thorough.

HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\PreviewHandlers
HKLM\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\PreviewHandlers
HKLM\SOFTWARE\Microsoft\Office\ClickToRun\REGISTRY\MACHINE\Software\Microsoft\Windows\CurrentVersion\PreviewHandlers

Source Idea

Further Resources

I checked any/all keys inside "PreviewHandlers" registry folders (I
  don't have click-to-run, but the other 2 were there) and deleted
  any/all *keys that referenced IMAP, mail, email, etc. I did not delete
  the "PreviewHandlers" registry folders themselves. –
  SamAndrew81

Either there is no default mail client or the current mail client cannot fulfil the messaging request. Please run outlook and set it as the default mail client
"This file cannot be previewed because there is no previewer installed for it" error ~