Ruby on Rails SystemStackError stack level too deep validate Wicked gem

Question: Calling validate :method_name causes an infinite loop SystemStackError.
Doing the validation directly inline allows the validation to pass without error.
There must be something I'm overlooking or doing wrong...
The validations worked fine when doing them directly in the model instead of within the conditional_reservation_validation.
Example code that causes SystemStackError stack level too deep
The basic process has been built following this example:
Building Partial Objects Step by Step
I know this needs to be refactored / cleaned up.
Snippet from model:
validate :conditional_reservation_validation

def conditional_reservation_validation
  if created_by_admin?
    validates_presence_of :vehicle_location
    validates_presence_of :pickup, :dropoff, :departure_date, :departure_time, :passengers
  else
    if active_or_parking?
      validates_presence_of :vehicle_location
      # SystemStackError occurs when validate :parking_agreement_if_location fires
      validate :parking_agreement_if_location
    end
    if active_or_pickup?
      # additional validations
    end
  end
  # ...
end

def parking_agreement_if_location
  if vehicle_in_special_parking_location(vehicle_location)
    if self.parking_agreement == true
      # ok
    else
      self.errors.add :base, "Must read and understand parking instructions."
    end
  end
end

def vehicle_in_special_parking_location(vehicle_location)
  parking_locations = Location.where(require_parking: true)
  if parking_locations.include?(vehicle_location)
    return true
  else
    return false
  end
end

# methods to check the step in process
def active_or_parking?
  status.include?('parking') || active?
end

Calling validate :parking_agreement_if_location triggers a SystemStackError
Example code that stops the error:
Just taking the code out of the :parking_agreement_if_location method and putting it directly inline stops the SystemStackError.
validate :conditional_reservation_validation

def conditional_reservation_validation
  if created_by_admin?
    validates_presence_of :vehicle_location
    validates_presence_of :pickup, :dropoff, :departure_date, :departure_time, :passengers
  else
    if active_or_parking?
      validates_presence_of :vehicle_location
      if vehicle_location
        locations = Location.where(require_parking: true)
        if locations.include?(vehicle_location)
          if parking_agreement == true
            # ok
          else
            self.errors.add :base, "Must read and understand parking instructions."
          end
          # validate :parking_agreement_if_location
        end
      end
    end

    if active_or_pickup?
      # These methods cause SystemStackError as well...
      validate :pickup_date_in_range
      validate :pickup_date_in_future
    end
  end
end

Controller update action:
def update

  params[:reservation][:status] = step.to_s
  params[:reservation][:status] = 'active' if step == steps.last

  case step
    when :parking
      @reservation.assign_attributes(reservation_params)
    when :pickup
      @reservation.assign_attributes(reservation_params)
    when :billing
      @reservation.assign_attributes(reservation_params)
  end
  render_wizard @reservation
end

Answer: You are using validations wrong way. They need to be invoked on class level.
You need to use conditional validations instead:
validates_presence_of :vehicle_location, if: :created_by_admin?
validates_presence_of :pickup, :dropoff, :departure_date, :departure_time, :passengers, if: :created_by_admin?
validates_presence_of :vehicle_location, unless: :created_by_admin?, if: :active_or_parking?
validate :parking_agreement_if_location, unless: :created_by_admin?, if: :active_or_parking?

Comment: Thank you MikDiet - I think I see now - I need to use use the active_or_pickup? methods to check for admin and skip as needed. Was having a brain fart!


MQTT Data Formatting of JSON object

Question: I am receiving the following JSON string over MQTT and want to extract the float values only.
The data in the str format, should I change the sending format over MQTT?
'{"data": [-0.0929368, 0.18385214, -0.0929368, 0.18385214, -0.0929368, 0.18385214, -0.0929368, 0.18287938, -0.0929368, 0.18287938, 0.07806691, 0.18287938, 0.17843866, 0.18287938, 0.28252788, 0.1848249, 0.37174721]}'
I only want to deal with the float arrays, but not finding the way to get it from the str objects.
Could someone help?
Kind regards
arun
Answer: If you are using python here's a way
<code>import json
data_string = '{"data": [-0.0929368, 0.18385214, -0.0929368, 0.18385214, -0.0929368, 0.18385214, -0.0929368, 0.18287938, -0.0929368, 0.18287938, 0.07806691, 0.18287938, 0.17843866, 0.18287938, 0.28252788, 0.1848249, 0.37174721]}'

#covert to Python
json_data = json.loads(data_string)

#extract the value 'data'
data = json_data["data"]
</code>

MQTT Data Formatting of JSON object


Threading and target function in external file (python)

Question: I want to move some functions to an external file for making it clearer.
lets say i have this example code (which does indeed work):
import threading
from time import sleep

testVal = 0

def testFunc():
   while True:
        global testVal
        sleep(1)
        testVal = testVal + 1
        print(testVal)

t = threading.Thread(target=testFunc, args=())
t.daemon = True
t.start()

try:
    while True:
        sleep(2)
        print('testval = ' + str(testVal))
except KeyboardInterrupt:
    pass

now i want to move testFunc() to a new python file. My guess was the following but the global variables don't seem to be the same.
testserver.py:
import threading
import testclient
from time import sleep

testVal = 0

t = threading.Thread(target=testclient.testFunc, args=())
t.daemon = True
t.start()

try:
    while True:
        sleep(2)
        print('testval = ' + str(testVal))
except KeyboardInterrupt:
    pass

and testclient.py:
from time import sleep
from testserver import testVal as val

def testFunc():
    while True:
        global val
        sleep(1)
        val = val + 1
        print(val)

my output is:

1
  testval = 0
  2
  3
  testval = 0 (testval didn't change)
  ...

while it should:

1
  testval = 1
  2
  3
  testval = 3
  ...

any suggestions? Thanks!
Answer: Your immediate problem is not due to multithreading (we'll get to that) but due to how you use global variables. The thing is, when you use this:
from testserver import testVal as val

You're essentially doing this:
import testserver
val = testserver.testVal

i.e. you're creating a local reference val that points to the testserver.testVal value. This is all fine and dandy when you read it (the first time at least) but when you try to assign its value in your function with:
val = val + 1

You're actually re-assigning the local (to testclient.py) val variable, not setting the value of testserver.testVal. You have to directly reference the actual pointer (i.e. testserver.testVal += 1) if you want to change its value.
That being said, the next problem you might encounter might stem directly from multithreading - you can encounter a race-condition oddity where GIL pauses one thread right after reading the value, but before actually writing it, and the next thread reading it and overwriting the current value, then the first thread resumes and writes the same value resulting in single increase despite two calls. You need to use some sort of mutex to make sure that all non-atomic operations execute exclusively to one thread if you want to use your data this way. The easiest way to do it is with a Lock that comes with the threading module:
testserver.py:
# ...
testVal = 0
testValLock = threading.Lock()
# ...

testclient.py:
# ...
with testserver.testValLock:
    testserver.testVal += 1
# ...

A third and final problem you might encounter is a circular dependency (testserver.py requires testclient.py, which requires testserver.py) and I'd advise you to re-think the way you want to approach this problem. If all you want is a common global store - create it separately from modules that might depend on it. That way you ensure proper loading and initializing order without the danger of unresolveable circular dependencies.


Is it possible to create compatible .aar and .a from Xamarin

Question: The official document has many tutorials about how to use existing Android and IOS libraries, but I can file document about generate .aar and .a, is it possible to write shared library for non-xamarin Android and IOS project ?
Answer: No.  Native Android and iOS projects cannot consume Xamarin libraries.


Smoke smell in basement stairwell, possibly associated with upstairs fireplace

Question: I have two fireplaces on different floors that share a chimney. I do not know whether they share a flue. This season, we burned some wood logs in the upstairs fireplace which were sold to us by a local man. These seem to burn a bit smoky. Last season, we only used store-purchased wood and fire logs (sawdust-based?) that did not have as strong a smell. The chimney downstairs has not been used in several years.
Interestingly, the stairwell between floors smells faintly like smoke on some mornings. It is unclear to me whether this is a thing to be concerned about. We stopped using the upstairs fireplace out of caution, but there's a possibility that the smoke is unrelated. The downstairs fireplace does not have a strong smell. I presume it would if there was smoke getting into its flue.
After we stopped using the fireplace, there was a period of two days that I did not smell smoke in the stairwell, followed by one where I did. It has been 3-4 more days and no new smell.
The neighbor has recently been using a new outdoor fire pit, and maybe his smoke is getting in, but he's still burning and I have no more smoke accumulation.
Should I be concerned? What should I look for? What work should I or a professional perform?
Comment: Would have chimney inspected and cleaned.  Smoke smell can last with different weather making it more noticeable.  Could be neighbours if the wind is blowing your way, but it should not last.  Use good well season(dry) wood.  CO gas does not have a smell, but is in smoke, so CO detectors should be in the house.
Comment: @crip659 Interesting, thank you. In addition to some smoke detectors, I have a dedicated CO monitor that I leave by the gas heating (also in the basement, but other side of the house). I could move it to the downstairs fireplace and run another fire upstairs to see if it screams.
Comment: The guy claimed the wood was a year old and the outside feels dry, but I recall hearing sounds during burning that make me think there's still some liquid in there.
Answer: Does it only happen when you run the dryer...bathroom fan...kitchen fan?
If so, the fan is pushing air out of the house and it may be sucking air in from the chimney.
Make sure the flue damper works and is closed.
Comment: You could test the flue damper with a stick of lit incense in front of the fireplace while you turn on the fan.
Comment: I use the downstairs bathroom exhaust fan pretty sporadically. It might be correlated. We do have a closed flue damper. I don't know how airtight they're supposed to be, but I can definitely tell the difference in sound levels between open and closed.


When `volatile` is needed when `longjmp()` is called?

Question: I am trying to make a minimal working example to show when volatile is needed. But the following example does not require the volatile. Could anybody show an example? Thanks.
#include <stdio.h>
#include <setjmp.h>

static jmp_buf buf;

int main() {
    volatile int local_var = 1;
    int local_var2 = 10;
    if(!setjmp(buf)) {
        local_var = 2;
        local_var2 = 20;
        longjmp(buf, 1);
    } else {
        printf("%d\n", local_var);
        printf("%d\n", local_var2);
    }

    return 0;
}

$ ./main.exe
2
20

Comment: You cannot in general show that `volatile` is needed by running an example program. It is needed because the standard says so.
Answer: Whenever the local variable could have changed between the setup-call to setjmp and the jump back.
18.104.22.168p3

All accessible objects have values, and all other components of the abstract machine249) have state, as of the time the longjmp
  function was called, except that the values of objects of automatic
  storage duration that are local to the function containing the
  invocation of the corresponding setjmp macro that do not have
  volatile-qualified type and have been changed between the setjmp
  invocation and longjmp call are indeterminate.

setjmp snapshots your registers. If the local variable was in a register and you change the variable after the setjmp call, when you jump back it'll have the snapshotted value.
On Linux x86_64 I get outputs 2 (up to date because volatile) and 10 (old value) iff I compile with optimization on.


Consistency of matrix equations for diagonalization/eigendecomposition with degenerate eigenvalues

Question: I have three equations that seem consistent at the abstract level, but when I implement them I am getting mistakes when there are degenerate eigenvalues. They are
$$A = Q D Q^T$$
$$B = (Q^{-1})^T D Q^{-1}$$
$$AB = Q D^2 Q^{-1}$$
where $A$, $B$, are real symmetric matrices. Notice that $Q$ is a the matrix whose columns are the eigenvectors of $AB$. On the surface these look okay. Clearly multiplying $A$ and $B$ gives $AB$.
Since $A$, $B$ are normal matrices, they should admit a decomposition $A = U \tilde{D} U^T$ for a orthogonal matrix $U$. $Q$ is not an orthogonal matrix. If it was, then that would imply that $AB$ is normal, which it is not in general. Equivalently, it would imply $A=B$ which again is not true in general.
I thought that if $A$ could be diagonalized via $Q D Q^T$, then it was unique up to permutation of diagonal entries and multiplication of the columns of $Q$. But it seems that $ U \tilde{D} U^T$ would also diagonalize $A$. Can I relate $Q$ to $U$ somehow? $U$ is special since $U^{-1} = U^T$, but $Q^{-1} \neq Q^T$, how can they possibly be related?
How can these equations be consistent? And are there certain problems when where are degenerate eigenvalues?
Answer: Generally the relation $A = Q D Q^T$ with $Q$ being invertible but not necessarily orthogonal is known as matrix congruence. A symmetric matrix is always congruent to a diagonal matrix, but note that the diagonal matrix $D$ does not (necessarily) consist of eigenvalues of $A$ in this case, but by Sylvester's law of inertia $D$ has the same number of positive sign, negative sign and zero-valued eigenvalues as $A$.
In this answer you can see a typical algorithm to find the matrices $D$ and $Q$ if you have $A$.
So just to sum up, the situation you have there: $Q$ diagonalizes $AB$ in the usual similarity sense, and $D^2$ contains the eigenvalues of $AB$. But the other two equations do not indicate diagonalization in the eigendecomposition sense, it just shows that $A$ and $B$ is congruent to $D$. Since congruence is also an equivalence relation this means $A$ and $B$ are congruent. All this allows us to say, is that $A$ and $B$ have the same number of positive, negative and zero-valued eigenvalues, no more...


Prove that $A^o \cap B^o = (A \cap B)^o$

Question: Prove that $A^o \cap B^o = (A \cap B)^o$.
I am able to prove that if $x \in A^o \cap B^o$, then $x \in (A \cap B)^o$. But this only implies that $A^o \cap B^o \subset (A \cap B)^o$. To show that $A^o \cap B^o = (A \cap B)^o$, I must now show that $A^o \cap B^o \supset (A \cap B)^o$. In other words, let $x \in (A \cap B)^o$, show that $x \in A^o \cap B^o$.
To me, however, it seems that once I prove it one way, then to prove it the other way, I simply "unwind" the previous proof. There seems to be nothing novel about it, which makes me feel that I am doing something wrong. Is that the way these proofs typically go?
Here's what I have:
Let $x \in A^o \cap B^o$.
Then $x \in A^o$ and $x \in B^o$.
Then $\exists$ $\alpha > 0$ and $\beta >0$ s.t. $B_{\alpha}(x) \subset A$ and $B_{\beta}(x) \subset B$. Take $r = \text{min}\{\alpha,\beta\}$. Then $B_r(x) \subset A$ and $B_r(x) \subset B$. Therefore, $B_r(x) \subset A \cap B$. Thus, $x \in (A \cap B)^o$.
Again, I see nothing novel about the reverse direction.
Comment: See http://en.wikipedia.org/wiki/De_Morgan%27s_laws#Formal_proof
Comment: Sorry, no. $A^o$ denotes the set of interior points of $A$.
Answer: Well, you wouldn't strictly reverse the steps because in the first direction, you took the minimum of two radii, and how can you reverse a "taking minimum" step?
But you are right, the proof in the reverse direction is just as easy and uses most of the same steps.  Still, you should write down these steps to convince yourself.
If $x \in (A \cap B)^{o}$, then there is some $\epsilon > 0$ such that $B_{\epsilon}(x) \subseteq A \cap B$.  But that means $B_{\epsilon}(x) \subseteq A$ and $B_{\epsilon}(x) \subseteq B$ since $A\cap B \subseteq A$ and $A \cap B \subseteq B$.  Thus, $x \in A^{o}$ and $x \in B^{o}$, so $x \in A^{o} \cap B^{o}$, as desired.
Answer: I think that's a general theme, for most "basic" results in most topics. We cut our teeth doing a lot of symbol-pushing, to build up a reserve of little lemmas and theorems that will help us more elegantly achieve more results. Once we have an arsenal of lemmas/theorems, we can start using them to prove more intermediate things, and don't need to resort to fighting in the trenches quite as much.
For example, proving De Morgan's laws in set theory is pretty mundane, but once we have it, we can use it, avoiding looking at elements of sets. In group theory, proving very basic results is again a lot of symbol-chasing, but as we progress, we chain these results together, to pay less attention to the group elements themselves.
So, in my opinion, the fact that "the intersection of interiors is the interior of the intersection" is a very basic result, and unsurprisingly has a rather uninspired proof. However, it will open doors in the future, to more abstract and elegant proofs, perhaps not using open balls, etc, quite as much.
Answer: Let $x∈(A∩B)^0$. So there exists a neighborhood $N_r(x)$ around $x$ which is a subset of $(A∩B)$. So $N_r(x)$ is a subset of both $A$ and $B$. So $x∈A^0$ and $x∈B^0$. This implies $x∈A^0∩B^0$. Hence Proved.
Answer: Let x∈(A∩B)0. So there exists a neighborhood Nr(x) around x which is a subset of (A∩B). So Nr(x) is a subset of both A and B. So x∈A0 and x∈B0. This implies x∈A0∩B0. Hence Proved.


Minecraft 1.8.8 fails when connecting via Direct Connect

Question: I am trying to join a family member's world.  We are both on PCs, one Windows 8.1 and one Windows 7. We both use Minecraft 1.8.8
My family member's PC firewall is open to Jave SE binary and to Minecraft on the Public network, which is how the household WiFi router is set up. My firewall is also open to same (Java, Minecraft), and network is also public.
My family member enters their local world, and opens it to LAN, so "Local game hosted on port 5xxxx" appears in chat. I open Minecraft, click Play Multiplayer, and it scans forever on my local network (we don't have an actual LAN, just share a WiFi router). So I do Direct Connect and enter IP:Port, where IP is from doing "ipconfig" on the hosting PC and using the IPv4 local IP (192.168.x.xx), and Port is the 5xxxx mentioned above.
When I join I get the following error:

java.net.ConnectException: Connection timed out:no further information:

Note that I can go to cmd window and ping either her local IP (192.168.x.x) or the external IP (found via WhatsMyIP.com) for her machine, and the ping yields an apparent success ("Reply from ...").
What else can I try to enable me to connect to the other computer?
Comment: Did you do [this](http://gaming.stackexchange.com/questions/133658/how-do-you-make-a-local-lan-server-in-minecraft)? Just opening a world doesn't allow LAN connections by default.
Comment: @dly Based on their description, they used the 'Open to LAN' function rather than the new server function. Also, their extensive troubleshooting shows that they *do* know what they're doing.
Comment: @YoYo Based on your description, you have tried everything that should be tried. I suggest rebooting both your computers and your WiFi and trying again. If that fails, try connecting the other way around: you can be the host and she can connect. If it is a specific world you require to play on, you can always copy it to the other computer.
Comment: I still believe it's the firewall.
Answer: Response

There are multiple complicated reasons for this, so, let me give you a few likely solutions instead of explaining.

1. Completely disable any other Firewalls you may have installed (Norton, Avira, Bitdefender, etc.).

2. This one requires a bit of trial and error. Check Windows Firewall, and make sure Javaw.exe, Java.exe, is allowed through. First, enable home, test it, disable home, test it, enable public, test it, and enable both, test it.

3. If your network reads Public, or shows a image of a bench, change your network to Home network. If it reads Home, or shows a picture of a house, do the opposite. After this, repeat step 2.
I hope I helped.


Applying large adhesive sheets onto surfaces without bubbles / creases

Question: I'm failing miserably at finding tutorials or videos on this.
I've bought some adhesive backed sign-makers' vinyl for applying to shelving, so it has a nice, even, bright gloss finish. But it's an awful lot more difficult than I expected to apply it without bubbles and creases, not to mention having it aligned properly. It's like trying to put a screen protector on a phone, but harder, given the size.
Any tips for doing this? I've tried applying it while the shelf (bare plywood) is vertical, horizontal, or at angles. Starting from the top, bottom, and side. Long side first and short side first. By hand, with a squeegee, and aluminium rod. It doesn't have lettering or anything, it's just a simple sheet with backing that peels off to reveal the adhesive side.
I'm sure it needs practice, but pretty pointless if you're not using a good technique to start with. How should this be done?
Thanks
Answer: What you can do by hand is fairly limited. Wallpaper is adhesive backed, but slightly repositionable. If what you have sticks strongly at first contact, your choices are limited. I would suggest the following,

Use a roller, as wide as possible, and of rubber. This should eliminate most bubbles and creases.
Go slow. This will allow you to catch and fix creases.
Pull the adhesive sheet tight.
You will probably still get bubbles, but they should be fairly small. Again, if it's a wet adhesive like wallpaper, you can usually push these out with a roller or straightedge. If it's an instant adhesive, you can prick them with a needle and collapse them.

In industries that do lamination, its done using rollers. Web tension is a primary parameter in helping prevent bubbles and creases. It's also common to use a bowed roll to help get tension in the transverse direction and prevent trapped air that causes bubbles.
Answer: Peel of the backing at a corner a bit and position that in the corresponding corner.
Then peel off more as you go and rub with a straight edged tool from the start to the end in short strokes. This way you make a dividing line between the portion already glued and the portion that's not yet glued (and still has the backing on it).
Minimize the exposed adhesive at a time.
The backing should curl under the unfinished portion and lift it up. The tool will push down controlled portions of it to stick down while at the same time pushing air bubbles away. You should pull more backing away when it threatens to make a fold.


Where to add code for a gridview hyperlink to delete a row by user's click?

Question: <dx:ASPxGridView ID="ASPxGridView1" runat="server" AutoGenerateColumns="False" DataSourceID="SqlDataSourceEditAdsPic">
        <Columns>
            <dx:GridViewDataTextColumn Caption="ترتیب عکس" FieldName="show_order" VisibleIndex="3">
            </dx:GridViewDataTextColumn>
            <dx:GridViewDataTextColumn Caption="شماره آگهی" FieldName="adver_no" VisibleIndex="0">
            </dx:GridViewDataTextColumn>
            <dx:GridViewDataHyperLinkColumn Caption="delete add" FieldName="show_order" VisibleIndex="4" >
                <PropertiesHyperLinkEdit Text="حذف">
                </PropertiesHyperLinkEdit>
            </dx:GridViewDataHyperLinkColumn>

            <dx:GridViewDataImageColumn Caption="عکس" FieldName="pic_path" VisibleIndex="2">

                <PropertiesImage ImageHeight="100px" ImageWidth="150px">
                </PropertiesImage>
            </dx:GridViewDataImageColumn>
        </Columns>
        <Settings ShowFilterRow="True" ShowGroupPanel="True" />
        <SettingsDataSecurity AllowDelete="False" AllowEdit="False" AllowInsert="False" />
    </dx:ASPxGridView>

I have a DevExpress gridview for which I have added a column for deleting rows. Where should I add the code for the event of a user clicking the delete. I double clicked on the link to show to method but it doesn't.
Answer: You can modify the code
<PropertiesHyperLinkEdit Text="حذف">
</PropertiesHyperLinkEdit>

And Write
<PropertiesHyperLinkEdit Text="حذف" ClientSideEvents-Click="function(s,e){s.DeleteRow(e.visibleIndex);}"></PropertiesHyperLinkEdit>

Please let me know if you have any questions related to the same.
Comment: Sorry for being late. I forgot to check this. I'll test your code and will surely accept it if it works.


C++ for-loop condition

Question: I  want to know why this loops runs even when result.bad_matches.size()=0
for (int i = 1; i <= result.badmatches.size() - 1; i++)
{
    ...
}

Also, is there any other way I could stop it from running when badmatches size is 0 without using an if condition?
Comment: The compiler might warn you here, that you mix signed and unsigned types.
Comment: The normal, zero-based, way to write a `for` loop would have helped you here: `for (int i = 0; i != result.badmatches.size(); ++i) // ...`. If you need a 1-based index, you can always make one inside the loop `int j = i + 1`.
Comment: Another general rule (not necessarily for this case, but in general) for inequalities is to avoid minus, e.g. like `i + 1 <= v.size()` etc.
Answer: This depends on the type size() returns. It is probably a standard container and thus will be an unsigned type and those types wrap around on overflow. That means it the result of subtracting one will be the maximum value of that type.
Either use a comparison that doesn't require you to subtract from the size (<, !=) or just use iterators or a for-auto loop. Under any circumstance you should at least use the same type for iterating as the nested size_type of the container and not int.
for(auto& x : result.badmatches) {
 // ...
}

Answer: use  while(result.badmatches.size()) to NOT execute it.
result.badmatches.size()-1 this will be converted to -1. If its an unsigned integer, then -1 is interpreted as 0xFFFFFFFF(on a 32 bit machine). This will make the loop run for 2^32 or 2^64 times. To avoid this, use while() as before IF you're certain that result.badmatches.size() will return 0.
Answer: size must be returning an unsigned so 0-1 is getting upgraded to unsigned and so is the left value.
So for int size of 4 bytes, -1 will be represented as 2^32 -1 in unsigned int.
If you don't want this behavior then just cast it like this : static_cast <signed int > (result.badmatches.size());
PS: I've not touched C++ for past 4 years pl. excuse little mistakes.
The right way is:
for (int i=0;i< result.badmatches.size() ;++i)
{

}

Answer: If you specifically don't want this loop to enter when the sise of the collection is zero then you could check for ! badmatches.empty() assuming that badmatches is an STL container. However, if you structure your code slightly differently, you'll probably overcome this issue without having to do that:
for (size_t i=0; i < result.badmatches.size(); i++)
{
}

I've changed the int to size_t which is the same type that size() returns (an unsigned integer), changed the initial value to 0 and the comparison so that it will exit if i >= result.badmatches.size() Generally, I'd say that this is the clearest way of presenting an indexed approach as it matches the natural indexing of collections and if you need 1, 2, 3 ... rather than 0, 1, 2 in your loop, then you can address that within it.
If you're still having problems, two questions:

Is there anything in your loop that might alter the value of result.badmatches.size()?
Is your code multithreaded with a possibility that result.badmatches.size() could change by actions on another thread?
Comment: `size_type` is usually but not necessarily the same as the `size_type` of a container. It works most of the time but will fail you in obscure situations.
Comment: You man `size_t` is usually the same as `size_type`? Yes, that's a fair point. So strictly it should be `size_type` for the container. I must admit I've never found a case where they're not the same.
Answer: After understanding the problem explained by @Prototype Stark @Aga , i came to a more simpler solution , using which i can keep my initial index to 1 .
for(int i=1;i+1<=result.badmatches.size();i++)

Thanks for all the help , it's much clearer now .

C++ for-loop condition


How to show products of a special category in left panel in home page in magento?

Question: I want to show products of a special category in left panel in home page.For that i have created a category in admin and added some products under that.But i don't know how to show in left panel of home page.
If anyone knows this,Please help me out.
Thanks!
Answer: You can use the following code in the layout xml for the homepage to display the product list for that special category:
<reference name="left">
        <block type="catalog/product_list" name="mycatblock" template="catalog/product/list.phtml">
            <action method="setData"><name>category_id</name><value>YOUR_CATEGORY_ID_HERE</value></action>
        </block>
</reference>

Note: this will display the products in the default template structure. You can pass your template file path in the above code to display it as per your need.
Alternatively, If you want to display it somewhere else in the content area on the homepage then you can simply use following line in the content section of home page(CMS page) in the admin panel:
{{block type="catalog/product_list" category_id="YOUR_CATEGORY_ID" template="catalog/product/list.phtml"}}

Hope this helps you.
Answer: go to your theme/layout/catalog.xml
under  tag under
<reference name="left">

  <block type="core/template" name="left.cat.product" template="custom/leftsideproduct.phtml">

</reference>

now go to your theme/template folder create a folder of name custom and create a file leftsideproduct.phtml
<?php     $catid=3; //go to admin click on category you have created check id and use here
    $category_prd = Mage::getModel('catalog/category')->load($catid);

                                }?>
                                <?php $prodCollection = $category_prd->getProductCollection();
                                foreach ($prodCollection as $product)
                                {
                                $prdIds[] = $product->getId(); //Array to store all the product ids
                                }

                                $allProducts = Mage::getModel('catalog/product')
                                          ->getCollection()
                                          ->addAttributeToFilter('entity_id', array('in' => $prdIds))
                                          ->addAttributeToSelect('price')->addAttributeToSelect('name')->addAttributeToSelect('image')->addAttributeToSelect('id');

                                foreach($allProducts as $product):?>

                                    <?php echo $product->getId();?>">
                                        <?php echo $product->getName();?>
    <img src="<?php echo Mage::helper('catalog/image')->init($product, 'image')->resize(150,150);?>"  title="<?php echo $product->getName();?>

                        <?php endforeach;?>

now go to admin under cms page click on homepage set layout 2columns-leftside bar and save it now check.
don't forget to like my ans if it was helpful


Hide some shipping methods if cart has more than 4 items from specific shipping class

Question: Here's the scenario:
I ship trays of drinks using UPS. However, it becomes very difficult to pack 5 trays of drinks into boxes. So I would like to disable UPS shipping method and only display Flat Rate Shipping if a customer orders 5 or more trays of drinks. I have about 7 different drinks, but I can add these drinks to a shipping class to simplify the code.
I want to expand this code to include the quantity of products in a specific the class or perhaps the number of times a product in the shipping class appears. So if the cart has 5 or more of a product in this specific shipping class, it should remove the shipping methods I've specified under array.
How do I expand this code to also include quantity of products?
// If we find the shipping class & quantity of product in the shipping class is equal to or greater than 5.
add_filter( 'woocommerce_package_rates', 'hide_shipping_method_based_on_shipping_class', 10, 2 );
function hide_shipping_method_based_on_shipping_class( $rates, $package )
{
    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return;

    // Shipping Class To Find
    $class = 182;

    // Number Of Shipping Class Items In Cart
    $amount = 5;

    // Shipping Methods To Hide
    $method_key_ids = array('wf_shipping_ups:07', 'wf_shipping_ups:08', 'wf_shipping_ups:11', 'wf_shipping_ups:54', 'wf_shipping_ups:65', 'wf_shipping_ups:70', 'wf_shipping_ups:74', 'free_shipping:2', 'request_shipping_quote');

    // Checking In Cart Items
    foreach( $package['contents'] as $item ) {
        // If We Find The Shipping Class and Number of Items
        if( $item['data']->get_shipping_class_id() == $class && count($package['contents']) >= $amount ){
            foreach( $method_key_ids as $method_key_id ){
                unset($rates[$method_key_id]); // Remove Targeted Methods
            }
            break; // Stop The Loop
        }
    }
    return $rates;
}

Edit - Addition:
Since I purchased the "WooCommerce UPS Shipping Plugin with Print Label" from PluginHive, I have access to their "Manage Shipping Methods" plugin which allows me to do the following:
Set multiple rules to exclude various shipping methods from various shipping classes.
Break the sequence on first occurrence.
The rules I have set-up are as follows:

For Class 150 (Break on First Occurrence) - Unset:

wf_shipping_ups:07,
wf_shipping_ups:08,
wf_shipping_ups:11,
wf_shipping_ups:54,
wf_shipping_ups:65,
wf_shipping_ups:70,
wf_shipping_ups:74,
free_shipping:2,
request_shipping_quote.

For Class 151 - Unset:
flat_rate:20,
flat_rate:21.

I've created a third class 182 in the above code for the products I want to target. It should be treated as class 151 only if less than 5 items of the class are added to the cart.
But it should be treated as Class 150 if 5 or more items are added to the cart.
That's my dilemma.
Potential Solution - Addition:
I figured out how to solve my problem. The code @LoicTheAztec assisted me with lets me unset shipping methods for a given shipping class if the product quantity in the cart is 5 or more.
What I need to do now is unset two other shipping methods (flat_rate:20 and flat_rate:21) which is causing the conflict, for the same shipping class (182) but this time for a product quantity in the cart of 4 or less (=<).
Then I can use the existing plugin to create the following rules:
Break on First Occurrence (Check)

For Class 150 - Unset:

wf_shipping_ups:07,
wf_shipping_ups:08,
wf_shipping_ups:11,
wf_shipping_ups:54,
wf_shipping_ups:65,
wf_shipping_ups:70,
wf_shipping_ups:74,
free_shipping:2,
request_shipping_quote.

For Class 182 - Unset:

Nothing - Because Both Codes Will Create The Logic

For Class 151 - Unset:

flat_rate:20,
flat_rate:21.
This should resolve the conflict caused by the plugin.
The million dollar question is...can I somehow use @LoicTheAztec 's solution to set some sort of minimum quantity?
Comment: What code have you written already? Please have a read of [this guide on producing code for a good quality question](https://stackoverflow.com/help/minimal-reproducible-example), then include and mark up your code in your question. Cheers!
Comment: Just updated the code. This is what I'm currently running for a different shipping class and it works fine. But I'm not sure how to include quantity for a new shipping class I created.
Comment: @LoicTheAztec I've updated the code but haven't tested it on staging yet. Thought I'd let you know.
Comment: @Joundill  I've updated the code but haven't tested it on staging yet. Thought I'd let you know.
Comment: @Joundill AS OP provided related code in his question, you can if you like remove downvote and closing.
Answer: The following will hide specific defined shipping methods if total items from specific shipping class are 5 or more:
add_filter( 'woocommerce_package_rates', 'hide_shipping_method_based_on_shipping_class', 10, 2 );
function hide_shipping_method_based_on_shipping_class( $rates, $package ) {
    $targeted_class_ids = array(182); // Shipping Class To Find
    $allowed_max_qty    = 4; // Max allowed quantity for the shipping class
    $shipping_rates_ids = array( // Shipping Method rates Ids To Hide
        'wf_shipping_ups:07',
        'wf_shipping_ups:08',
        'wf_shipping_ups:11',
        'wf_shipping_ups:54',
        'wf_shipping_ups:65',
        'wf_shipping_ups:70',
        'wf_shipping_ups:74',
        'free_shipping:2',
        'request_shipping_quote'
    );

    $related_total_qty  = 0;

    // Checking cart items for current package
    foreach( $package['contents'] as $key => $cart_item ) {
        if( in_array( $cart_item['data']->get_shipping_class_id(), $targeted_class_ids ) ){
            $related_total_qty += $cart_item['quantity'];
        }
    }

    // When total allowed quantity is more than allowed (for items from defined shipping classes)
    if ( $related_total_qty > $allowed_max_qty ) {
        // Hide related defined shipping methods
        foreach( $shipping_rates_ids as $shipping_rate_id ) {
            if( isset($rates[$shipping_rate_id]) ) {
                unset($rates[$shipping_rate_id]); // Remove Targeted Methods
            }
        }
    }
    return $rates;
}

Code goes in functions.php file of your active child theme (or active theme). Untested it should works.

Refresh the shipping caches:

This code is already saved on your functions.php file.
In a shipping zone settings, disable / save any shipping method, then enable back / save.
You are done and you can test it.

Handling number of items instead of items cumulated quantity:
Replace:
$related_total_qty += $cart_item['quantity'];

by
$related_total_qty++;

Comment: I've just added a commented to the end of my initial question. It's a bit of a conundrum, so let me know if it's not clear enough.
Comment: This works perfectly but it seems to be causing conflict with the other rules I've set for two other shipping classes. I'm going to attempt to modify your code and replace class id with product id. There's only 7 products so I'll give it a bash. Thank you for the assistance.
Comment: @WanderlustConsulting please make an edit at the end of your question and add the code that you were using for it, then notify me here once done… I will merge both to make that work.
Comment: I've figured out how to resolve this. Check out the edit for my proposed solution.


Wii U disc drive spitting out disk after making noises

Question: My Wii U is behaving like the one in this video:

I have no idea why it's behaving that way, I have kept my Wii U in great condition since I bought it 2 years ago, and I have never had any problems with previous consoles. I have never dropped my Wii U and I always handle with care, which is my I'm really confused and I'm freaking out as to how it broke.
Any disk that I put in (Wii U or Wii), will be spit out from the Wii U (as seen in the video). However, my Wii U still works: the Wii U I bought came with Super Mario 3D World downloaded onto it, and I can play that game perfectly fine, so I have reason to believe it has something to do with disk drive in. My warranty expired (because it's been 2 years), and I wouldn't like to spend $120 to fix it, I'd like to find some cheaper alternative. Is it possible to fix it by opening it up? If so, what should I be looking for Also, if this isn't the place to ask this, what's a better site I can ask this question?
UPDATE: This is what I have tried. I tried a "cleaning disk", but my Wii U just spit out the disk like in the video. I opened up the disk drive and I didn't see anything abnormal (no dust in the disk drive, no small items lodged in), and I noticed whenever I put in any disk that the disk doesn't spin, again I have no idea why this happens. Right now I'm trying the reformatting method, and if that fails well the only thing to do is buy a new disk drive.
UPDATE 2: None of the proposed solutions worked, so I guess I'm going to replace the disk drive.
Comment: You've mentioned that your warranty expired, but it's always worth following this up with Nintendo - just in case. I had a disk drive problem with my Wii some years ago; they sent a freepost sticker, and I sent it away. A week later it was back, good as new, and I never got a bill. Worth checking the official route, even if just to make sure it'll cost you.
Comment: What do you mean by a freepost sticker? The only reason I said it would cost me $120 is because I contacted nintendo support about this and the guy on the phone told me it would be $100 to fix it plus $20 shipping and handling.
Comment: A postage label I printed out and attached to the parcel, meaning I didn't pay for shipping. It probably depends on a lot of factors - this was at least 3 years ago, and in the UK, so things may be different or may have changed over time. If you've already been in touch with Customer Support, then there probably isn't much to be done about the price.
Comment: @RubberDucky - Please don't pressure users to award bounties. They are already notified many times about their bounty expiry, and can choose to award it or not, that is their perogative. Plus a lot of users will wait until the last moment to award bounties as this gives the question and it's answers more time in the spotlight.
Answer: Before you go and open up the Wii U or send it in for repairs, it might be worth trying a cleaning CD, as described here.
Based on the information given there, it looks like any CD-R will work as a cleaning disc. The Wii U will then clean out its disc drive, so if the problem here is a dirty disc drive, this should fix it.
If that fails to fix your issue, it might be worth opening up your Wii U and replacing the disc drive (assuming you are comfortable doing this, as I've botched some hardware operations in the past, myself). You can get a replacement disc drive from sites like Amazon (I found a listing for less than $30).
However, this also may not work.
Unfortunately, your best bet to get your Wii U fixed is to send it into Nintendo for repairs. I realize this is less than desirable, as you're no longer covered under warranty.

My personal recommendation would be definitely try out a cleaning disc, just to make sure the fix isn't super simple, then send it in for repairs if that doesn't work. I'm a bit wary on self-service, because according to Nintendo support, if you try to fix your Wii U yourself and are unsuccessful, they will not repair it for you.

Q: I opened my system to try to repair it myself, but was unsuccessful. Can Nintendo still repair it for me?
A: No. Any system that is found to have been tampered with, modified, otherwise altered, or counterfeit is permanently damaged and cannot be brought back to its original working condition.

Thus, unless you're really sure that you will be able to fix it yourself, I wouldn't risk it.
Comment: Well I'm never going to spend 100+ bucks to fix my system, I might as well buy a new one, so I will try what you said and comment what the results are. You say any CD-R, this means any music CD essentially?
Comment: @VishwaIyer according to the post I linked, yeah, it looks like it. Although, even if the system doesn't recognize it as a cleaning CD, it won't harm your Wii U.
Comment: Alright good to know
Comment: @VishwaIyer any luck with the cleaning CD?
Comment: I'm gonna try in a couple of hours. I'm at work right now.
Comment: Well the cleaning CD did the same thing the regular Wii U CDs did: went in and then went out.
Comment: @Vemonus read my update please
Comment: @VishwaIyer sorry, man, I'm not really sure what else you can do. At this point, I'd just send it into Nintendo for repairs or get a new console. :/
Answer: As Vemonus said in his answer, the best way would probably be to go for a cleaning CD and to contact Nintendo in the worst case. Do not try to repair it yourself by opening it. I have read enough threads with people talking about how they tried to repair it and didn't succeed (or managed to make it worse).
Additionally to those propositions, there is another kinda extreme solution that seems to have worked for some: formatting the system memory of your Wii U. The idea is that you format your Wii U so that the system nearly gets back to the same state it was when you bought your console.
For this option, this tutorial would help you. Basically, you have to go in the Wii U "System Settings" menu, and then select "Delete All Content & Settings". After going through the system setup, it seems like the disk ended up staying in for some users, fixing the issue.
Do note though that you should go for this solution only if the cleaning disk option didn't work and if Nintendo has not been able to do anything for you. Do also note that you will lose your data by using this solution. Yet, if none of the other solutions seemed to have worked, this can still be a potential option to fix your Wii U and make the disc drive working again.
Another possibility might be that something else than dust or such is stuck in your disk drive. I read some topics about people ended up making it work after finding out there was a little leaf in the front of the disk drive, while others found a penny in it because of a kid who put it in there. While I do not think you stuck a penny in your disk drive, it might have happened than a piece of paper accidentally ended up there. Maybe you can then try to check if you can see something in your disk drive opening, and try to carefully remove it from there.
Comment: How would reformatting the system memory fix an issue with the disk drive, feels like a hardware problem for me, not a software problem.
Comment: @VishwaIyer That's what I ended up finding on some threads about the matter, and it solved the problem for some people apparently. We are trying to gather as many solutions as possible there to solve the problem, so I'd rather not put a possible option on the side. Sometimes problems that seem coming from the hardware in the first place can come from the software itself. Just trying to help you there. If it ends up being the only solution to solve your problem, I would have been happy to have put the option there.
Comment: I didn't mean to be rude, I was just asking. I will still try it, as a last resort.
Comment: @Vishwalyer Do not worry, I didn't say you were rude or anything! Sorry if I sounded like it was the case. I seriously hope for you that Vemonus' solutions will be able to solve your problem and that you won't need to go through something that annoying.
Comment: Also just as a question: I had Super Mario 3D World come with my Wii U as a bundle, meaning I don't have a disk for it and it came with the Wii U. If I "Delete All Content & Settings", will I still have the game or will it be gone forever. Also, I'm copying all of my data from the Wii U to a flash drive, but if I "Delete All Content & Settings", I won't be able to copy this data to the Wii U (according to the site)?
Comment: @VishwaIyer [The answer](http://gaming.stackexchange.com/a/296384/136461) to the question you asked about this exact matter is what I would have answered on that point.
Comment: read my update please
Comment: @VishwaIyer Arg. I'm really sorry than none of the answers worked there. I don't remember finding any other ideas, so I guess the best would be to contact Nintendo now. I am sorry for this.
Answer: I found a similar issue here: http://www.neogaf.com/forum/showthread.php?t=910163
Basically, you have to get it replaced.
-=-=-=-=-=-=-=-=-=-=-
BUT>>> Nothing is unfixable!
Ifixit has your back: https://www.ifixit.com/Guide/Nintendo+Wii+U+DVD+Drive+Replacement/12811
^basically tells you how to take it apart and replace the dvd drive^
Comment: When I remove the DVD Drive, can I open it up to see what's wrong with my Wii U? I see screws on the top so I believe I can open the top. If I can, what should I be looking for (if you know) in order to fix my Wii U? I'm kinda against replacing the DVD drive because I'm confused as to how it broke in the first place. Most of the problems I've seen involve sticking a toy in the DVD drive, but I can assure you I haven't done that.
Comment: You can probably open it up. If you break it, no problem because it probably had to be replaced. If you can find the problem and fix it, good for you!


Show that a star-like region is simply connected.

Question: A set S is called star-like if there exists a point $\alpha\in S$ such that the line segment connecting $\alpha$ and z is contained in S for all $z\in S$. Show that a star-like region is simply connected.
My answer
Show that
$γ:γ(t)=tz+(1−t)α, t≥1$ is contained in the complement for any z in the complement
Let $\gamma$ represents the portion of the ray from $\alpha$ through z to $\infty$, starting at z. Thus, if z is in the complement of S, so is all of $\gamma$. For, if any $z_{1}\in \gamma$ belonged to S, so would the entire segment connecting $\alpha$ and $z_{1}$, including z.
Could anyone help to formalize the answer?
Comment: The assertion in your answer is false. The set $S=[-1,1]$ in $\Bbb R$ is star-like from the point $\alpha=0$, and $2$ is in the complement of $S$, but the ray from $0$ through $2$ includes the interval $[0,1]$, which is in $S$. To show that a star-like region $S$ is simply connected, you must show (1) that it is path-connected (which is easy), and (2) that every continuous map of the unit circle to $S$ is contractible to a point in $S$.
Comment: I'm working on the complex plane
Comment: Doesn't matter: you can easily find similar examples there.
Comment: I found the part that confuses the issue, to prove esque follow the suggestion of the book and what I proved but did not put it paste that I should prove, but already corrected
Answer: Here's a stronger algebraic-topological argument.  We can show that a star-shaped set $S$ is not just simply connected, it is contractible.  There is an $\alpha$ so for each $p\in S$ the line segment $\gamma_p(t) = tp + (1-t)\alpha$ has $\gamma_p\in S$ for all $t$.  Now define $H(p,t):S\times [0,1]\to S$ by $(p,t)\mapsto \gamma_p(t)$.  This is a strong deformation retract of $S$ onto $\{\alpha\}$, so $S$ has the homotopy type of a point.
For every topological space $X$, every map $f:X\to S$ is homotopic to the constant map $X\to\{\alpha\}$.  The intuition here is to just "slide" the map to $\alpha$, more precisely via the homotopy $F(x,t) = H(f(x),t)$.  So in particular we can see that any map $\phi:\mathbb{S}^1\to S$ can be contracted to the constant map $\phi:\mathbb{S}^1\to \{\alpha\}$, hence $\pi_1S = 1$.
Answer: If I recall right (see this), you only have to show that your star set is path connected and that all such paths are homotopic, i.e. that one path can be deformed continuously into the other.
Here's one way to do it : Let $z_1, z_2 \in S$. Then the path connecting $z_1$ to $\alpha$ and then $\alpha$ to $z_2$, is a continuous path between $z_1$ and $z_2$. Given any two paths, the first one between $z_1$ and $z_2$, and the other one between $z_3$ and $z_4$, just deform your first path continuously into a point at $\alpha$, and then "expand it" in a path from $z_3$ to $z_4$, which gives you the homotopy you need.
Hope that helps,
Comment: If you wanna go formal on this, just parametrize the paths and parametrize the homotopy.
Answer: I believe that the question should be "is every star shaped domain in the complex plane simply connected", and the answer is in the affirmative. However, not every simply connected domain is star shaped.


Get variable value from aspx and use it in code behind

Question: I am having a little issue. I have a drop down list which can have multiple values selected. I did that by simply adding a $('#id').attr('multiple','multiple');
I know there is a simple way of accessing variable from code behind to aspx page but now i need the opposite thing, because when I multiselect it, from the code file it doesn't recognize the multiselection but only takes 1 value. So basicly I was hoping for something like
var temp  = $('#id').val(); --- It takes the selected items correctly
<% simplevariable= %> = temp;

Answer: You can add a HiddenField
<asp:HiddenField ID="hiddenField" runat="server" />

Set its value like
$("#<%=hiddenField.ClientID%>").val($('#id').val())

You can use HiddenField.Value in code behind


Can not call Swap.AllInstances() more than once on a type

Question: I have a test case that has a problem where the exception in the title is thrown.
The exception is only thrown when the static methods fake is also present in the test.
My presumption is that StaticMethods fake is also doing the swap.  If this is the case, how can I fake static methods and also replace instances with my instance fake?
[Test]
[Isolated]
[Factory("TruckDispatchData")]
public void TruckDispatchTest(
    IEnumerable<DeliveryInfo> deliveryInfo,
    bool expectedResult)
{
    Isolate.Fake.StaticMethods(typeof(Order), Members.MustSpecifyReturnValues);
    var order = Isolate.Fake.Instance<Order>(Members.MustSpecifyReturnValues, ConstructorWillBe.Ignored, BaseConstructorWillBe.Ignored);
    Isolate.Swap.AllInstances<Order>().With(order);

Answer: I work at Typemock,
Just checked this issue and I can confirm that this is a bug.
The workaround for this issue is pretty simple, you just have to switch the order of the calls. e.g.
var order = Isolate.Fake.Instance<Order>(Members.MustSpecifyReturnValues, ConstructorWillBe.Ignored, BaseConstructorWillBe.Ignored);
Isolate.Swap.AllInstances<Order>().With(order);
Isolate.Fake.StaticMethods(typeof(Order), Members.MustSpecifyReturnValues);

It will be fixed in future versions.
Answer: Can't say for sure, as didn't use TypeMock library, but I think that the problem is in your Swap method:
Isolate.Swap.AllInstances<Order>()

As you call the all instances of Order class, the static methods aren't involved (as they aren't Order instance methods, they are Type of typeof(Order) instance methods), so, may be, Swap approach can be used in some different way, something like this:
Isolate.Swap.Static_SOMETHING_HERE.With(order);

Comment: The static method faking is to allow access to the static methods of the object type as you point out.  However, the swap is only swapping the instances of the object order with the faked instance version.  I am not trying to swap a static order with an instance, I am trying to swap instance for instance, and separately access static methods of the type.  I think the implementation of StaticMethod faking must also perform a swap to get the error in question


Ranking System: How Does it Work?

Question: How does the ranking system work in Rocket League currently?
It seems that I when I win 9 or 10 games in a row and then lose 1, my ranking remains the same. I'm currently Challenger Rank 3.
Answer: Almost all of these systems used in game for ranking are based on an ELO formula (see elo rating system) - it comes from chess.
The basics of it are this: if you are seriously outmatched and lose, you lose 1 point, if you are seriously outmatched and win, you gain 32 points. If you are even and lose, you lose 16 points. If you are even and win you gain 16 points.
There are various shades in there ranging from 1-32 points, but hopefully you get the point. If you win 8 games against easy opponents you may only gain several points, however if on the ninth you lose to an easier opponent (by ranking) then you can easily negate your 8 wins, or at least most of those points.
If I had to guess, it would look something like this

900: Prospect I
1000: Prospect II
1100: Prospect III
1200: Prospect Elite
1300: Challenger I
1400: Challenger II
1500: Challenger III
1600: Challenger Elite
1700: Rising Star
1800: Shooting Star
1900: All-Star
2000: Superstar
2200: Champion
2400: Super Champion
2600: Grand Champion
Comment: How many points equates a Rank in RL, though?
Comment: Unfortunately there isn't really a good way to tell that, @Will. As Rocket League only displays a named rank instead of the numeric value, we can only guess. Usually the range in an ELO system will go from 1000 points to 3000 points, give or take depending on the variety of players. So, we could make estimates given that distribution. Perhaps something along the lines of 100 points per rank, where most players probably leave unranked at a rating of 1400. I edited in a very rough guess.
Comment: @Travisj - Thanks for explaining the ELO system, very helpful.
Comment: Also are you sure you are actually winning that many games in a row? I find it hard to believe you won 9-10 straight and barely progressed in rankings. I was ranked Prospect Elite at the beginning of a season, and after going an average of 2 wins to every loss, I was up to Challenger III within a day or two.
Answer: Rocket League Ranked works in a way to prevent getting dragged to higher ranks.
To constantly get up, you constantly have to be the best of your team (hence proof that you are better than your rank) This usually starts at Challenger 3.

Ranking System: How Does it Work?


On the definition of continuous time martingales Stroock Varadhan $\times$ Kallenberg

Question: In the definition of martingales, one finds in Stroock and Varadhan (Multidimensional Diffusion processes - page 20) the strange request that it be right-continuous process.

However no such requirement is made in the wiki
https://en.wikipedia.org/wiki/Martingale_%28probability_theory%29

nor in Kallenberg (Foundations of modern probability - page 96)

Isn't this strange of the part of Stroock and Varadhan? Has the notion of martingales evolved?
Answer: These still aren't the most general definitions for martingales. The most general definition I know of is:
Let $I$ be a poset. A Family $F$ of sigma-algebras is said to be a filtration if for all $s, t \in I$ with $s \le t$ the inclusion $F_s \subset F_t$ holds. A family $X_i$ of (quasi)integrable random variables is called a martingale with respect to $F$, if:

$X_i$ is $F_i$-measurable for all $i \in I$
If $s \le t$, then $E[X_t | F_s] = X_s$

The problem with this definition: It is rarely necessary to use it. In most cases $I = \mathbb{N}$, $I = \mathbb{Z}$ or $I$ is an interval in $\mathbb{R}$. It is not uncommon for an author to omit the most general definition, if he only uses some special instances.
For example, your quote from Kallenberg's book is only an introduction. He later defines martingales on the real numbers and only needs these types of martingales in the book. The book of Stroock and Varadhan mainly deals with stochastic analysis. Herein, the assumption of right-continuity is useful and a prerequisite for many theorems. They need the special assumptions, so they simply add them to the definition of martingales.
Answer: Processes that are not right-continuous are a gigantic pain to deal with. Most likely they include right-continuous in their definition because they always intend to work under that assumption, and don't want to have to keep writing it. As with any mathematical term, there doesn't have to be a universal "correct" definition of martingale; authors are free to adopt their own variants.


How to display new lines in Chrome development tools network preview tab?

Question: I seem to have inadvertently toggled a setting somewhere with the result that the Network > Preview tab in Chrome's developer tools no longer displays new lines in responses containing, say, the contents of PHP's var_dump(). New lines are displayed however when using Firefox. I'm using Chrome 61.0.3163.100.
I have the following code:
<?php
var_dump((object)[
    'bar' => 123,
    'baz' => 'test'
]);

Whose output is displayed in Chrome's Network > Preview tab:

How can I change Chrome's settings so that the output is displayed with new lines, like with Firefox:
Comment: https://crbug.com/767393 - this is fixed in Chrome Canary which you can install separately.
Answer: Maybe you can try this instead the var_dump():
function dda($item = null, $live = null, $multiple = false){
    $debug = debug_backtrace();
    foreach($debug as $value){
        if($value['function'] == 'dda'){
            $location = $value['file'].' - '.$value['line'];
            echo $location;
            echo PHP_EOL;
            break;
        }
    }

    if($multiple && is_array($item)){
        foreach($item as $value) echo var_export($value);
    }else{
        echo var_export($item);
    }

    if(!$live) die();
}


remove certain parts of an array

Question: I am making a Dropbox file browser to practice using API's and have come up against a problem. Here is my code:
<?php
    $fileMetadata = $dbxClient->getMetadataWithChildren("/upload");
    $headings = array_keys($fileMetadata['contents'][0]);
?>

            <?php foreach( $headings as &$heading ): ?>
                    <?php echo $heading; ?>
                <?php endforeach; ?>

            <?php foreach( $fileMetadata['contents'] as &$file ): ?>

                    <?php foreach( $file as &$data ): ?>
                        <?php echo $data; ?>
                    <?php endforeach; ?>

            <?php endforeach; ?>

And I would like to cut out some of the un-needed columns such as rev, thumb_exists etc, etc...
This is the print_r of the array:
Array
(
    [hash] => d023a1738d460f667d383cb4f57bc769
    [revision] => 65
    [rev] => 411389e826
    [thumb_exists] =>
    [bytes] => 0
    [modified] => Wed, 28 Aug 2013 20:28:34 +0000
    [path] => /upload
    [is_dir] => 1
    [icon] => folder
    [root] => app_folder
    [contents] => Array
        (
            [0] => Array
                 (
                    [revision] => 81
                    [rev] => 511389e826
                    [thumb_exists] => 1
                    [bytes] => 1996564
                    [modified] => Wed, 28 Aug 2013 21:32:10 +0000
                    [client_mtime] => Wed, 28 Aug 2013 21:32:11 +0000
                    [path] => /upload/08-nigellas-chocolate-chip-muffins.jpg
                    [is_dir] =>
                    [icon] => page_white_picture
                    [root] => dropbox
                    [mime_type] => image/jpeg
                    [size] => 1.9 MB
                )

            [1] => Array
                (
                    [revision] => 79
                    [rev] => 4f1389e826
                    [thumb_exists] => 1
                    [bytes] => 22848
                    [modified] => Wed, 28 Aug 2013 21:14:39 +0000
                    [client_mtime] => Wed, 28 Aug 2013 21:14:39 +0000
                    [path] => /upload/1376243030_guestion.png
                    [is_dir] =>
                    [icon] => page_white_picture
                    [root] => dropbox
                    [mime_type] => image/png
                    [size] => 22.3 KB
                )

            [2] => Array
                (
                    [revision] => 80
                    [rev] => 501389e826
                    [thumb_exists] =>
                    [bytes] => 54772
                    [modified] => Wed, 28 Aug 2013 21:26:19 +0000
                    [client_mtime] => Wed, 28 Aug 2013 21:26:19 +0000
                    [path] => /upload/BT_screen_quiz.java
                    [is_dir] =>
                    [icon] => page_white_cup
                    [root] => dropbox
                    [mime_type] => text/x-java
                    [size] => 53.5 KB
                )

           [3] => Array
               (
                    [revision] => 77
                    [rev] => 4d1389e826
                    [thumb_exists] =>
                    [bytes] => 1679
                    [modified] => Wed, 28 Aug 2013 20:59:53 +0000
                    [client_mtime] => Wed, 28 Aug 2013 20:59:53 +0000
                    [path] => /upload/login.php
                    [is_dir] =>
                    [icon] => page_white_php
                    [root] => dropbox
                    [mime_type] => text/php
                    [size] => 1.6 KB
                )

            [4] => Array
                (
                    [revision] => 78
                    [rev] => 4e1389e826
                    [thumb_exists] =>
                    [bytes] => 2037
                    [modified] => Wed, 28 Aug 2013 21:00:56 +0000
                    [client_mtime] => Wed, 28 Aug 2013 21:00:56 +0000
                    [path] => /upload/signup.php
                    [is_dir] =>
                    [icon] => page_white_php
                    [root] => dropbox
                    [mime_type] => text/php
                    [size] => 2 KB
                )

        )

    [size] => 0 bytes
)

please could you tell me how I would go about removing certain coloumns from the table or removing those parts from the array.
Thanks,
Marcus
Comment: Have you tried something so far ? Give an example of which part of the array you would like to remove. (Ok, just seen that little line between your screenshots !)
Comment: try adding conditions in your foreach loop to continue if your heading are in one of the unwanted columns
Answer: We meet again! Since I'm lurking here, I might as well give an answer. For the least amount of effort changing around what you already have and instead of digging through your array to unset values, you can make an array of headings/columns to remove and use it to check your foreach values.
<?php
    $fileMetadata = $dbxClient->getMetadataWithChildren("/upload");
    $headings = array_keys($fileMetadata['contents'][0]);

    //Add field names to remove in array below
    $remove = array( 'is_dir', 'client_mtime' );
?>

        <?php foreach( $headings as &$heading ): ?>

            <?php if( !in_array($heading, $remove) ): ?>
                <?php echo $heading; ?>
            <?php endif; ?>

        <?php endforeach; ?>

    <?php foreach( $fileMetadata['contents'] as &$file ): ?>

            <?php foreach( $file as $key => &$data ): ?>

                <?php if( !in_array($key, $remove) ): ?>
                    <?php echo $data; ?>
                <?php endif; ?>

            <?php endforeach; ?>

    <?php endforeach; ?>

Might not be the prettiest method, but it's probably one of the easiest ways to go about it.
If you want to do it proper, having a recursive function to unset any fields you specify might help. In this case, you could do this:
function removeFields( $fields, &$array )
{
    foreach( $array as $key => &$value ) {

        if( is_array($value) ) {

            removeFields( $fields, $value );
        }
        else {

            if( in_array( $key, $fields ) ) {

                unset( $array[$key] );
            }
        }
    }
}
//Still have to define values you don't want
$remove = array( 'thumb_exists', 'is_dir', 'root' );

removeFields( $remove, $fileMetadata );

print_r( $fileMetadata );

The above should be done before you retrieve $headings = array_keys($fileMetadata['contents'][0]);, that way it doesn't get headings before they are removed.
Answer: Being not specific to Dropbox, you can use unset (http://php.net/manual/en/function.unset.php) to remove elements from arrays.
For example, to remove the columns rev and thumb_exists you can cycle on $fileMetadata['contents'] values (the code is not tested):
while(list($key,$value)=each($fileMetadata['contents'])) {
    unset($fileMetadata['contents'][$key]['rev']);
    unset($fileMetadata['contents'][$key]['thumb_exists']);
}

remove certain parts of an array


react-testing-library - How do you test for the existence of text if it is wrapped contained in other child html tags?

Question: Given the example html:
const fragment = (
Hello world. How are you doing?
)
Is there a way to ignore all the child html tags with react-testing-library?
like so (psuedo-code)
expect(fragment).toHaveTextContent(/hello world. how are you doing/)
Answer: First solution:
You can use @testing-library/jest-dom this library provides a set of custom jest matchers that you can use to extend jest and react-testing-library. Here is the link:
https://github.com/testing-library/jest-dom#tocontainelement

const ancestor = getByTestId('ancestor')
const descendant = getByTestId('descendant')
const nonExistantElement = getByTestId('does-not-exist')

expect(ancestor).toContainElement(descendant)
expect(descendant).not.toContainElement(ancestor)
expect(ancestor).not.toContainElement(nonExistantElement)

Second solution:
import { render, within } from '@testing-library/react'

const { getByLabelText } = render(<MyComponent />)
const signinModal = getByLabelText('Sign In')
within(signinModal).getByPlaceholderText('Username')


Obtaining uniform randomness from non-uniform probabilities

Question: Suppose I have a coin that has a weird weight. The coin is weighted such that, when I flip it, one side is heavier than the other so I have a higher probability of getting H than I have of getting T. My probability of getting H is $p_1$ and my probability of getting T is $p_2$, with $p_1 + p_2 = 1$ and $p_1 \neq p_2$. What I want to do is create some method that guarantees a uniformly random outcome (where I flip my coin and my chances of writing down H or T are both $0.5$.)
Here is my idea. I flip the coin twice, which results in one out of four outcomes: If I get HT, I write down "H". If I get TH, I write down "T". If I get HH or TT, I start over and don't write anything down.
Will this ensure uniform randomness? My reasoning is that if I see HH or TT then the result occurred with a nonuniform probability (either $p_{1}^2$ or $p_{2}^2$) and I ignore it, but if I see HT or TH then the result occurred with probability $p_{1}p_{2}$ or $p_{2}p_{1}$, which are equal so I record it.
Comment: Yes, your idea works.  I think it is well explained.
Comment: Your reasoning is sound.
Comment: Just don't discard TT/HH yet if you get them. Keep them and if you get HH/TT on the next 2 throws produce a bit T/H. This way, you continue only if you get TTTT/HHHH hence speeding up the process a little bit.
Answer: Yes.   Your reasoning is sound.
Alternatively:
The probability of seeing HT given that you repeat the experiment until you see either HT or TH is:
$$\begin{align} & = p_1p_2 + (p_1^2+p_2^2)(p_1p_2+(p_1^2+p_2^2)(p_1p_2+ (p_1^2+p_2^2)(\ldots))) \\[1ex] & = p_1p_2 +(1-2p_1p_2 )(p_1p_2 +(1-2p_1p_2 )(p_1p_2 +(1-2p_1p_2 )(\ldots)))
\\[1ex] & = p_1p_2\big(1+(1-2p_1p_2)+(1-2p_1p_2 )^2+(1-2p_1p_2)^3+\cdots\big)
\\[1ex] & = \frac{p_1p_2 }{1-(1-2p_1p_2)}
\\[1ex] & = \frac 1 2\end{align} $$


OpenTracing+Jaeger Language Agnostic

Question: I have three services A, B, and C that communicate like so
<code>       HTTP       HTTP
   A +------> B +------> C
nodejs      nodejs      java
</code>
I'm using OpenTracing and Jaeger for distributed tracing. The problem is these services are in different languages, but I'm still trying to propagate the information that A is the parent span so that the span tree looks like this.
<code>A +----------------+
B +-------+
C         +--------+
</code>
Right now, A, B, and C are being reported as individual traces with no causality relations. All the examples I've seen involved propagating causality between different microservices in the same language and in the same project build. None involved entirely separate services.
Answer: It doesn't really matter in which language your individual microservices are written, you should see them all in the same trace. Given that you are seeing three traces instead of one trace with three spans, it appears that the context propagation isn't working. Check your HTTP client in your nodejs services, they should perform the "inject" operation. Your service "B" and "C" should then perform the "extract" operation.
If you haven't yet, check Yuri Shkuro's OpenTracing Tutorial. The lesson 3 is about the context propagation, including the inject and extract operations.
I'm not quite sure how it works in the NodeJS world, but in Java, it should be sufficient to have the opentracing-contrib/java-web-servlet-filter instrumentation library in your classpath, as it would register the necessary pieces in the right hooks and make the trace context available for each incoming HTTP request.

OpenTracing+Jaeger Language Agnostic


How to summon an item frame facing a specific direction in Minecraft?

Question: I am working on a map and I need to summon an item frame in a specific place. I'm using the command:
/summon item_frame -1242 58 219
but "it is on the ground" and I need it to face north.
Answer: You need to summon the entity with custom NBT: /summon minecraft:item_frame -1242 58 219 {Facing:2}
The Facing part is what is added. The default number is 1, which is facing up. 2 is facing north, which you are looking for. If you try different numbers, you will find that it will face different directions.


How to correctly use and reference Entity Framework Core in another project?

Question: So I am building a REST API in .Net core with the following architecture and I'm wondering how to reference Entity Framework Core.

These are three projects, referencing each other the way it's shown on the image. All the queries are stored in DAL (Data Layer), so this is where I defined DbContext.
But at the same time, I also need to add DbContext to the ConfigureServices on WebAPI Startup (services.AddDbContext<MyDBContext>();).
So the main issue is, is that I cannot access DbContext in WebAPI, because WebAPI doesn't directly reference DAL.
I would appreciate very much any tips, suggestions or workarounds, that wouldn't impact the architecture in any major ways.
Comment: In your services and DAL you need to create extension methods that register their dependencies with your DI container.   These extension methods can then be called from your ConfigureServices function.
Comment: I recommend to read about clean architecture https://blog.cleancoder.com/uncle-bob/2012/08/13/the-clean-architecture.html and https://github.com/ardalis/CleanArchitecture
Comment: The Repository Pattern is a common approach to this.
Comment: What does `services pipeline` do in WebAPi? what are their purposes? It would be great if you share some code of `services pipeline`
Comment: It's the ConfigureServices method.
Comment: Add a project to the top of the hierarchy and set-up the DI container to register all services for all projects. that's the best practice.
Answer: Add the DAL project as reference to the WebApi project, from there you can get access to DbContext, to access the queries of DAl from WebApi you need to used the repository pattern. Here is a nice medium article on how to build a multi layer Asp.Net Core project
https://medium.com/swlh/building-a-nice-multi-layer-net-core-3-api-c68a9ef16368


IdleConnectionHandler removing a connection that never existed in my android app

Question: My android app keeps logging this warning :
IdleConnectionHandler removing a connection that never existed

What does that mean? Is that a big problem? What should I do to avoid this?
My app makes many http connections in AsyncTask, is that related?
EDIT:
I found that this call was the reason of this message :
httpclient.getConnectionManager().closeIdleConnections(30, TimeUnit.SECONDS);

So maybe it tries to close some connections that don't exist?
Answer: It sounds like there is a logic error in your code. You may be able to track down the problems using this Android tool called ARO. You can find out more about it here http://developer.att.com/developer/legalAgreementPage.jsp?passedItemId=9700312
It will help you to understand more about how your application is using the network and how you can improve that part of your application to make it more efficient.
Is there a reason you need to make many http connections at once?
Answer: I got that error too, but my app uses internet only for ad loading. Currently I have no permission that my app can use internet, so that is why it says "Removing a connection that never existed". That may be one of the reason for this warning.


Installing TensorFlow on ubuntu16.04 and lots of warnnings

Question:
Environment : Ubuntu 16.04 / tensorflow 1.14.0/ python 3.5.3

I installed TensorFlow using this command.
sudo pip install --upgrade https://storage.googleapis.com/tensorflow/linux/cpu/tensorflow-0.7.1-cp27-none-linux_x86_64.whl

This is the result of it.
DEPRECATION: Python 2.7 will reach the end of its life on January 1st, 2020. Please upgrade your Python as Python 2.7 won't be maintained after that date. A future version of pip will drop support for Python 2.7. More details about Python 2 support in pip, can be found at https://pip.pypa.io/en/latest/development/release-process/#python-2-support
WARNING: The directory '/home/hanbit-o/.cache/pip/http' or its parent directory is not owned by the current user and the cache has been disabled. Please check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag.
WARNING: The directory '/home/hanbit-o/.cache/pip' or its parent directory is not owned by the current user and caching wheels has been disabled. check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag.
Collecting tensorflow==0.7.1 from https://storage.googleapis.com/tensorflow/linux/cpu/tensorflow-0.7.1-cp27-none-linux_x86_64.whl
  Downloading https://storage.googleapis.com/tensorflow/linux/cpu/tensorflow-0.7.1-cp27-none-linux_x86_64.whl (13.8MB)
Requirement already satisfied, skipping upgrade: wheel in /usr/local/lib/python2.7/dist-packages (from tensorflow==0.7.1) (0.33.4)
Requirement already satisfied, skipping upgrade: protobuf==3.0.0b2 in /usr/local/lib/python2.7/dist-packages (from tensorflow==0.7.1) (3.0.0b2)
Requirement already satisfied, skipping upgrade: six>=1.10.0 in /usr/lib/python2.7/dist-packages (from tensorflow==0.7.1) (1.10.0)
Requirement already satisfied, skipping upgrade: numpy>=1.8.2 in /home/hanbit-o/.local/lib/python2.7/site-packages (from tensorflow==0.7.1) (1.16.4)
Requirement already satisfied, skipping upgrade: setuptools in /usr/lib/python2.7/dist-packages (from protobuf==3.0.0b2->tensorflow==0.7.1) (20.7.0)
Installing collected packages: tensorflow
  Found existing installation: tensorflow 0.7.1
    Uninstalling tensorflow-0.7.1:
      Successfully uninstalled tensorflow-0.7.1
Successfully installed tensorflow-0.7.1

in this time there is a warning of python2
Actually, I want to use TensorFlow at the python3
I think because of installing TensorFlow at python2.
There are lots of comments on the prompt.
Python 3.5.3 (default, Aug 28 2019, 20:35:32)
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import tensorflow
/home/hanbit-o/.local/lib/python3.5/site-packages/tensorflow/python/framework/dtypes.py:516: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.
  _np_qint8 = np.dtype([("qint8", np.int8, 1)])
/home/hanbit-o/.local/lib/python3.5/site-packages/tensorflow/python/framework/dtypes.py:517: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.
  _np_quint8 = np.dtype([("quint8", np.uint8, 1)])
/home/hanbit-o/.local/lib/python3.5/site-packages/tensorflow/python/framework/dtypes.py:518: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.
  _np_qint16 = np.dtype([("qint16", np.int16, 1)])
/home/hanbit-o/.local/lib/python3.5/site-packages/tensorflow/python/framework/dtypes.py:519: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.
  _np_quint16 = np.dtype([("quint16", np.uint16, 1)])
/home/hanbit-o/.local/lib/python3.5/site-packages/tensorflow/python/framework/dtypes.py:520: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.
  _np_qint32 = np.dtype([("qint32", np.int32, 1)])
/home/hanbit-o/.local/lib/python3.5/site-packages/tensorflow/python/framework/dtypes.py:525: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.
  np_resource = np.dtype([("resource", np.ubyte, 1)])
/home/hanbit-o/.local/lib/python3.5/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:541: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.
  _np_qint8 = np.dtype([("qint8", np.int8, 1)])
/home/hanbit-o/.local/lib/python3.5/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:542: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.
  _np_quint8 = np.dtype([("quint8", np.uint8, 1)])
/home/hanbit-o/.local/lib/python3.5/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:543: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.
  _np_qint16 = np.dtype([("qint16", np.int16, 1)])
/home/hanbit-o/.local/lib/python3.5/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:544: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.
  _np_quint16 = np.dtype([("quint16", np.uint16, 1)])
/home/hanbit-o/.local/lib/python3.5/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:545: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.
  _np_qint32 = np.dtype([("qint32", np.int32, 1)])
/home/hanbit-o/.local/lib/python3.5/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:550: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.
  np_resource = np.dtype([("resource", np.ubyte, 1)])
>>>

and i tried to ignore it.
>>> hello = tf.constant('Hello, TensorFlow!')
>>> sess = tf.Session()
2019-10-09 21:40:31.902027: I tensorflow/core/platform/cpu_feature_guard.cc:142] Your CPU supports instructions that this TensorFlow binary was not compiled to use: AVX2 FMA
2019-10-09 21:40:31.926393: I tensorflow/core/platform/profile_utils/cpu_utils.cc:94] CPU Frequency: 3398000000 Hz
2019-10-09 21:40:31.929440: I tensorflow/compiler/xla/service/service.cc:168] XLA service 0x42f31d0 executing computations on platform Host. Devices:
2019-10-09 21:40:31.929480: I tensorflow/compiler/xla/service/service.cc:175]   StreamExecutor device (0): <undefined>, <undefined>
>>> sess.run(hello)
]b'Hello, TensorFlow!'
>>> a = tf.constant(10)
>>> b = tf.constant(32)
>>> sess.run(a+b)
2019-10-09 21:41:28.143676: W tensorflow/compiler/jit/mark_for_compilation_pass.cc:1412] (One-time warning): Not using XLA:CPU for cluster because envvar TF_XLA_FLAGS=--tf_xla_cpu_global_jit was not set.  If you want XLA:CPU, either set that envvar, or use experimental_jit_scope to enable XLA:CPU.  To confirm that XLA is active, pass --vmodule=xla_compilation_cache=1 (as a proper command-line flag, not via TF_XLA_FLAGS) or set the envvar XLA_FLAGS=--xla_hlo_profile.
42

It is works(?), and why there lots of warnning?
Comment: Try `pip3 install tensorflow`, you used `pip` which works with python 2 (2.7 for your situation) to use python3, use `pip3`.
Answer: First, to use tensorflow with python 3, you have to install it using pip3.  If you don't have pip3 installed, you can install it using sudo apt install python3-pip
Then, you can simply install tensorflow by running the following command pip3 install tensorflow, you don't need to use sudo.
Second, you have the warnings because of the numpy version, you probably have numpy version (1.17 or 1.15) that is not supported by the version of tensorflow that you installed.
So to solve these warnings, you can:

Install tensorflow 2.0 which works fine with the latest version of numpy. The command is pip3 install --upgrade tensoflow

OR

Downgrade the numpy to 1.13.3<=numpy<=1.14.5 and keep the current version of tensorflow. The cammand is pip3 install nupmpy==1.14

N.B: The warnings that you have do not mean that your installation failed. Tensorflow works fine, you can simply ignore them and everything will work fine.


The infamous "sticky" :hover on iPad - how does Google fix it?

Question: I have unfortunately stumbled on the issue where, on iPad, a pop-up menu summoned by way of :hover does not disappear from the screen when the user touches an empty area of the page.
The problem is the same described here:
Hover Behavior on Desktop vs iPad
The menu is part of a template I bought, namely:
http://html.realia.byaviators.com/
But... wait a minute... it WORKS on the template's home page? And only on that page -- it doesn't work on any other page of that same template.
I was able to track the behavior down to the point where I found that the reason why it works is the following: initializing a Google map makes the menu behave properly. Just the simplest of maps, with the default options.
Now my question to the experts is: what is that Google does in the map initialization code in order to fix the :hover behavior?
Thank you very much in advance for your help!
Answer: Well, can't tell what is that Google does, however the solution is documented in mobile Safari developer's reference.
For a click event to be generated on an area of the document, there must be a click handler attached. For example, clicking on a div will generate a click event only if an onclick="void(0)" handle is presente:

Clicking here triggers event in mobile Safari


Should I insulate my unfinished basement ceiling?

Question: Question
Are there any negative effects from insulating a basement ceiling?
Story
I have an unfinished basement, with a family member living in a make-shift room.
In my efforts to retain heat in his area I put up some insulation above him (with a few other things). He swears that it has helped drastically.
The unexpected benefit was the floor above him, is warmer (so my wife says). I'm just happy that some of the noise he makes stays in the basement.

Expectations
So my expectations for insulation the basement ceiling, maybe a warmer main floor... and some sound proofing.
Why I'm asking
I started googling around and some articles said insulating the basement ceiling could potentially cause moisture/plumbing problems. Others said that it wouldn't hurt, but don't expect much of a return on the investment. One even said don't insulate both the ceiling and the walls....
My home
Its divided into two different sides, one side is the living room and kitchen, the other part of the house has the bedrooms and bathrooms. The overall shape is an "L" The basement is 100% unfinished, there are two heating vents down there that I leave open... but other than that its just bare concrete walls.  I don't know if this makes a difference but figured more information can't hurt.
Comment: I'm confused by your mission. You can't make the basement *and* the upstairs more comfortable by insulating between them. In fact, the only way that would have any effect is if you intended to *not* heat one or the other.
Comment: It's unlikely that the basement loses much heat through the ceiling. Most is lost through the concrete walls, the stairwell, and other penetrations. What *would* help is insulation on the concrete walls. (I think both your wife and your tenant are the victims of "positive thinking". :) )
Comment: Well the basement gets its own heat through two different vents. But because its unfinished and underground, it is much cooler than the upstairs...
Comment: I sort of agree that the benefit won't be huge. It may help to provide two separate comfort zones. I the person downstairs wants 18C and the person upstairs wants 22 or vice versa. If soundproofing is your actual goal, well there might be more effective solutions for that.
Comment: @isherwood lol positive thinking. Yea, The walls are the next big project. Building a wall is simple, permits/electric/ductwork is the PITA I've been putting off.  Can I just pay someone to do all of the administrative work (design, permits) and I'll do the work and stick to the plan... then have an electrician and hvac guy come in before I insulate and close the walls up?
Comment: @BigElittles - I have never heard of needing a permit to frame a basement.  Yes for electric and plumbing or finishing but not framing.  Now someone may check your framing but there is no need to not frame your outer walls right now.  Any plans you have in the future will surely have outer walls.   Also the framing being up is only marginally helpful in insulating properly.
Answer: The insulation in the ceiling will have almost no effect on Uncle Bob's living experience, other than he may not hear as much noise from people upstairs.
What you need to do is insulate the perimeter of the basement.  This would be all framing that meets with the outside of the house that is above ground level.  By just stuffing fiberglass or roxul into the joist gaps a good foot thick you will achieve 70-80% of your basement insulation needs for maybe $200 for a large basement.
Also this needs to be done all the way around, not in just the area Bob lives.  I would certainly do his area first but even a small area not done can sabotage the effectiveness of the rest of the basement.  Also note that dirt is a pretty good insulator unless you are in an extremely cold climate so no use in doing the whole wall.
And back to ceiling insulation.  In actuality if the basement does not have zoned heating and air, the insulation will probably make the area cooler in the winter.  The warm air from the first floor will not be able to infiltrate the lower level as well.  So if sound isn't an issue then I would not even think about going there.   (Most people would insulate the ceiling in a cold climate because they do not want the cold air from basement moving to first floor - not because they want to make basement warmer)
Comment: @mmathis - in general true, however the stack effect should actually make the basement cooler.  Not sure if you have ever walked through an attic with leaky walls in the middle of the summer - I have too many times.  Attic might be a good 120-130F and a small opening will give you a jet stream of cold air due to the different air pressures.  Well the cold air is actually the warmer air from the house (but still much cooler than the attic).  Same thing for basement, the "warmer" air will push up via stack effect - albeit not as pressurized.
Comment: Warm air from the first floor doesn't tend to infiltrate the lower level in any case, as warm air tends to rise not sink.