How do I print a Java array in gdb?

Question: I compiled a very simple java program with gcj-4.4 and -o option. I loaded it in gdb-7.2 and tried to do some debugging. I noticed at I could print the variables in int type but I could not print an array of int. I received this error message:
<code>(gdb) p orderFinish[0]
cannot find java.lang.Object
(gdb) p (int)orderFinish
$8 = -136261440
(gdb) p orderFinish[3]
cannot find java.lang.Object
(gdb) p in
$9 = 1
(gdb) whatis orderFinish
type = int[]
</code>
So my question is how can I print a Java array in gdb? My OS is openSUSE-11.1 x64-86bit. Thanks!
Answer: Its been a while since I used GDB but p *array-variable@length should work.
Source: http://www.yolinux.com/TUTORIALS/GDB-Commands.html
Comment: Works fine for me, this is straight out of the doco "p *array-variable@length Print first # values of array specified by length. Good for pointers to dynamicaly allocated memory." You may need to set print array on before this works.
Comment: It looks as if in my case missing debuginfos were the culprit.  After installing them, it seems to work.

How do I print a Java array in gdb?


JavaScript value not evaluated correctly when in a variable, but works correctly as a string

Question: I am not sure why this evaluation differs when it is only in a variable, versus a string. I don't see any logic.
const numRegex = /hundred|thousand|million|billion|trillion/ig;

const isNum = string => numRegex.test(string)

var word = 'hundred';
console.log('isNum with string:', isNum('hundred')); // true
console.log('isNum with variable:', isNum(word));    // false
console.log('words are equal:', word === 'hundred'); // true

Comment: @Ivar thanks, I couldn't find it…
Comment: The issue is the order, not whether it's a variable or not. You can copy the first console log, and will get the same results. You are reusing the regex, and due to the `g` flag, the regex' `lastIndex` gets updated, and stays changed in any subsequent calls.
Answer: isNum is returning false when it's called a second time on the same string. Change the order and see the same thing:
const numRegex = /hundred|thousand|million|billion|trillion/ig;

const isNum = string => numRegex.test(string)

var word = 'hundred';
console.log('isNum with variable:', isNum(word));    // true
console.log('isNum with string:', isNum('hundred')); // false
console.log('words are equal:', word === 'hundred'); // true

The g flag remembers where the last match was. Remove it to fix the problem:
const numRegex = /hundred|thousand|million|billion|trillion/i;

Mozilla talks more about this:

The sticky flag indicates that the regular expression performs sticky matching in the target string by attempting to match starting at RegExp.prototype.lastIndex.


How to stretch flex child so that background color matches the height of sibling

Question: I have two links in li, one with text which can be short or long, and the other is icon. The background-color of the icon should match the height of text link while text should have defined padding. It doesn't have to be flexbox, I just thought it should be easier.
http://codepen.io/anon/pen/GrQZKN
li {
  display: flex;
  justify-content: space-between;
  align-items: center;
  .first {
    background-color: #333;
    padding: 20px;
    color: #fff;
    flex: 1;
  }
  .second {
    background-color: orange;
    align-items: stretch;
    display: flex;
  }
}

    Link
    (icon)

    Longer LongerLonger Longer link
    (icon)

Answer: You can just do the below:

Remove align-items: center from li (for stretching the second)
Replace align-items: stretch with align-items: center in li.second (for vertical alignment)

See demo below:

body {
  max-width: 300px;
  background-color: #ddd;
}

li {
  display: flex;
  justify-content: space-between;
  /*align-items: center;*/
  border-bottom: 1px solid #eee;
}
li .first {
  background-color: #333;
  padding: 20px;
  color: #fff;
  flex: 1;
}
li .second {
  background-color: orange;
  align-items: center; /*CHANGED THIS*/
  display: flex;
}

    Link
    (icon)

    Longer LongerLonger Longer link
    (icon)


Update Tkinter panel over time

Question: I have Tkinter panels that I want to update over time. The main file executes a method on an imported class to draw the Tkinter panel and I want it to execute 5 times every second.
Here is the main script which calls the method to create the panel:
# Script to control updating the display
from tkinter import *
from settings import Settings
from main_panel import Main
import time

# Creates window
root = Tk()
root.configure(background = 'black')

# Establish settings variable
settings = Settings()

# Create panel class with settings
Main = Main(settings)

# Call panel function to create itself
Main.create(root)
root.mainloop()

Here is the method which creates the Tkinter panels:
def create(self,root):
    current = self.get_current_status()
    self.draw_icons(root,current)
    self.draw_days(root,current)
    self.draw_temps(root,current)
    self.draw_status(root,current)

Where do I do the 'root.after' call to have the panels update?
Answer: You've not provided enough code for a customized example, so here's a minimalist example of using root.after():
from tkinter import *

def update_counter():
    counter = label_variable.get()

    if counter > 0:
        label_variable.set(counter - 1)
        root.after(1000, update_counter)

root = Tk()

label_variable = IntVar()
label_variable.set(10)
Label(root, textvariable=label_variable, width=10).pack()

root.after(1000, update_counter)

root.mainloop()

Hopefully this will give you an idea of how to incorporate root.after() into your own code.

Update Tkinter panel over time


How to align hr with div below it?

Question: Trying to align an hr to a div below it. This is the css:
hr {
    display: block;
    height: 5px;
    border: 0;
    border-top: 10px solid #ccc;
    margin: 1em 0;
    padding: 0;
    width:80%;
}

the line is currently not aligned with the div#main it is too much to the left:

How can I align this with the div, get the same width and at the same time make it responsive?
codepen here
Answer: I guess here is what you want: codepen
you can also remove hr margin

Title<input id="title" type="text" placeholder="Title placeholder" name="title" value="">Temperature<input type="radio" id="c" class="spaceradio" value="metric" checked="">℃
            <input type="radio" id="f" class="spaceradio" value="imperial">℉

Wind<input type="radio" id="n" class="spaceradio" value="true">On<input type="radio" id="o" class="spaceradio" value="false" checked="">Off

65.34℉

.line {
    border-top: 10px solid #ccc;
    padding: 0 !important;
}

Comment: Good work, how did you come to add the padding? Why does this make the line the same width?
Comment: container class has different media queries so I used the same class. but it contains 15px padding. when you put a row (contains -15px padding) in container it makes divisions inside row same width with container.
Answer: Changed styles of hr to margin: 1 auto; But if only want to make it center and no need of margin at top , margin: auto is enough. Hope you got the answer
Answer: I changed this line from margin: 1em 0; to margin: 1 0;
Now hr is in center.
and width:95%;
Comment: forgot to mention it has to have to same width as the div.
Comment: Try adding the class "container" to the "hr" tag so it have similar style that main div.
Comment: `margin: 1 0` is invalid CSS, so what you really did is just change the `hr`'s margin back to the user agent default because the browser isn't applying your new style at all. Margins have to have units on them, unless you're using `auto`.

How to align hr with div below it?


Counting function evaluations

Question: I just finished the tutorial on reader and recorder. And I was wondering if there was a way to count the number of times each discipline is called. Below I use global variables to count this in Sellar problem. What would be a better way to do this ? Also if there is no solver in the problem, will the suggested way change ?
import numpy as np
import time
import openmdao.api as om

tic = time.perf_counter()
dc1 = 0
dc2 = 0

class SellarDis1(om.ExplicitComponent):
    def setup(self):
        self.add_input('z', val=np.zeros(2))
        self.add_input('x', val=0.)
        self.add_input('y2', val=1.0)
        self.add_output('y1', val=1.0)
        self.declare_partials('*', '*', method='fd')

    def compute(self, inputs, outputs):
        global dc1
        dc1+=1
        z1 = inputs['z'][0]
        z2 = inputs['z'][1]
        x1 = inputs['x']
        y2 = inputs['y2']
        outputs['y1'] = z1**2 + z2 + x1 - 0.2*y2

class SellarDis2(om.ExplicitComponent):

    def setup(self):
        self.add_input('z', val=np.zeros(2))
        self.add_input('y1', val=1.0)
        self.add_output('y2', val=1.0)
        self.declare_partials('*', '*',method='fd')

    def compute(self, inputs, outputs):
        global dc2
        dc2 +=1
        z1 = inputs['z'][0]
        z2 = inputs['z'][1]
        y1 = inputs['y1']
        if y1.real < 0.0:
            y1 *= -1
        outputs['y2'] = y1**.5 + z1 + z2

class SellarMDF(om.Group):
    def setup(self):
        indeps = self.add_subsystem('indeps', om.IndepVarComp(), promotes=['*'])
        indeps.add_output('x', 1.0)
        indeps.add_output('z', np.array([5.0, 2.0]))

        cycle = self.add_subsystem('cycle', om.Group(), promotes=['*'])
        cycle.add_subsystem('d1', SellarDis1(), promotes_inputs=['x', 'z', 'y2'],
                            promotes_outputs=['y1'])
        cycle.add_subsystem('d2', SellarDis2(), promotes_inputs=['z', 'y1'],
                            promotes_outputs=['y2'])

        cycle.linear_solver = om.ScipyKrylov()

        cycle.nonlinear_solver = om.NewtonSolver(solve_subsystems=False)

        self.add_subsystem('obj_cmp', om.ExecComp('obj = x**2 + z[1] + y1 + exp(-y2)',
                                                  z=np.array([0.0, 0.0]), x=0.0, y1=0.0, y2=0.0),
                           promotes=['x', 'z', 'y1', 'y2', 'obj'])

        self.add_subsystem('con_cmp1', om.ExecComp('con1 = 3.16 - y1'), promotes=['con1', 'y1'])
        self.add_subsystem('con_cmp2', om.ExecComp('con2 = y2 - 24.0'), promotes=['con2', 'y2'])

prob = om.Problem()
prob.model = SellarMDF()

driver = prob.driver = om.ScipyOptimizer()
prob.driver.options['optimizer'] = 'SLSQP'

prob.model.add_design_var('x', lower=0, upper=10)
prob.model.add_design_var('z', lower=0, upper=10)

prob.model.add_objective('obj')
prob.model.add_constraint('con1', upper=0)
prob.model.add_constraint('con2', upper=0)
prob.setup()
prob.set_solver_print(level=0)

prob.run_driver()

print('minimum found at')
print(prob['x'][0])
print(prob['z'])

print('Coupling Variables')
print(prob['y1'][0])
print(prob['y2'][0])

print('minumum objective')
print(prob['obj'][0])

toc = time.perf_counter()
print(f"You waited {toc - tic:0.4f} seconds")
print("Function Calls")
print('SellarDis1 : ', dc1)
print('SellarDis2 : ', dc2)

Edit: By better I mean "openmdao" way, like with recorder or something.
Answer: All OpenMDAO systems (the umbrella term for components and groups) have the iter_count attribute. Here is the documentation page for System, from which all components and groups inherit from. iter_count is the total number of calls to each compute() method, whereas iter_count_without_approx is the number of calls to the compute() method without including those due to gradient approximation. This method works for any solver hierarchy or driver setup.
The last two lines of your sample script would thus be:
print('SellarDis1 : ', prob.model.cycle.d1.iter_count)
print('SellarDis2 : ', prob.model.cycle.d2.iter_count)

This doesn't use the recorder, as you suggested. If you instead prefer a solution that uses the recorder, we can find a workable method. There's a lot of flexibility there and to get started you can check out this specific doc page on case reading, which could help postprocess a case to get the total number of calls.
Please let me know if anything's unclear!
Comment: I can address the difference.  iter_count only counts the number of times that `solve_nonlinear` is called.  On an ExplicitComponent, `apply_nonlinear` also calls compute. This is because, to calculate the norm of the residual for the current set of inputs and outputs, you need to run the component again, and the residual is the change in outputs.  This is definitely confusing though. To clear things up, we decided to add another counter that keeps track of the number of times `apply_nonlinear` is called. To get the total executes, you would sum iter_count and iter_count_apply. (cont.)
Comment: This new counter will be available in OpenMDAO versions 3.2.2 onward.
Comment: Thank you for your time. This exactly what I was looking for. The count when I use global variables is `SellarDis1 :  111, SellarDis2 :  89` and when I use `iter_count` it is `SellarDis1 :  64, SellarDis2 :  48`. Do you know what causes this huge difference ?
Comment: I don't have a good answer for that. I checked on my machine and I got the same results as you. If you change the nonlinear solver to NonlinearBlockGS, there's still a discrepancy, so I don't think it's related to the type of solver. I reached out to the OpenMDAO dev team and they're looking into it.
Comment: And here's their corresponding issue: https://github.com/OpenMDAO/OpenMDAO/issues/1651
Answer: Coverage tools like Coverage or PyTest-Cov can use hooks in the python interpreter to collect data about which code is running when during your program's execution, which often includes the number of "hits" per function or even individual lines. If you just want the numbers outside the program, this might already be enough for you.
If you need the numbers for use in the script itself, you can use some of the underlying APIs yourself. With sys.settrace you can register a function to be called on every function call in your program. The first argument to that function will be a frame object, which contains attributes you can use to check if this is the function you're interested in.
Here's a short example:
import sys

class A:
    def my_func(self, x):
        return x + 1

my_func_calls = 0

def tracefunc(frame, event, arg):
    global my_func_calls
    if event == 'call' and frame.f_code.co_name == 'my_func':
        my_func_calls += 1

sys.settrace(tracefunc)

if __name__ == '__main__':
    a = A()
    x = a.my_func(0)
    x = a.my_func(x)
    x = a.my_func(x)
    print("my_func_calls:", my_func_calls)

Since I don't see any way to get the actual function object associated with (which would give you the class using __self__.__class__), you may need to use frame.co_firstlineno to distinguish methods with the same name.
The nitty gritty details of this trace function are a bit tricky, you can reference coverage.py's implementation for inspiration on your options and possible problems.
Comment: Thank you. I did not know about this and it is helpful. However, I was hoping for something by using any Openmdao function. I only need the count outside the program. But I am not able to use global variables because I have two different files, each containing multiple classes (explicit component) and a group. I have a third file where I connect all into a top level group. Also the function name is "compute" in all the classes so `settrace` might not work. So what I want to ask is, if it is possible to somehow do the count in an openmdao-ish way (by recorder or some other in built function).

Counting function evaluations


Facebook login using access token

Question: Is there anyway to store an access token to be used later?
IE:
user1 logs in to my app then logs in with Facebook Dialog Auth
app stores facebook access token
user1 logs out of my app
user2 logs in to my app then logs in with Facebook Dialog Auth
user2 logs out of my app
user1 logs back into my app and continues to use facebook with access token stored originally stored from the first login?
===
I should clarify a bit...
I'm trying to figure out to have multiple facebook accounts tied into my app. So that when different users login, they can access their individual facebook accounts.
Comment: Yes - that's exactly how you do it too - but this only works if you decouple 'login to my site' from 'login using facebook' - you then store the most recent access token in your database and when they log back in continue to use it until it expires, at which time you need the user to go through the auth flow again
Comment: can you post a link to some tutorial or something where you can dynamically apply the access token like we're discussing here? I have only seen demonstrations where an access token is applied with a new login.
Comment: I don't really know how to give you an example - after the user logs into your app/site via your existing login code, retrieve their most recent Facebook access token from your database and use it when making calls to the Facebook API - if it expires you'll need them to go through the facebook auth flow again (which will need them to be logged into Facebook's site/app)
Comment: okay I think I understand now. so when I want to set the token I have this: `private Facebook mFb;` `mFb.setAccessToken(TOKEN);` and it should work? Is there anything else I have to do to reapply the token and continue operating as the previously signed in user?
Comment: I should clarify a bit...
I'm trying to figure out to have multiple facebook accounts tied into my app. So that when different users login, they can access their individual facebook accounts.
Answer: Access tokens expire, over time. So you should check if it is valid when the user logs back in and handle expired access tokens when encountered in the way mentioned here.
If you are looking to use offline_access to extend the expiration date, that is soon going away. Now, you will have to renew the access token as mentioned here.
The offline_access permission was deprecated and removed December 5th, 2012
Comment: isn't there an offline permission for facebook that makes the access token last indefinitely? If **user2** doesn't log into facebook I'd like **user1** to be able to log back into my app and the access token be reapplied.
Comment: The offline_access permission is deprecated and will be removed December 5th, 2012
Comment: if I used extend token, any idea how long that lasts? I'd like the user to only have to login to facebook once if they're using the same app login. The only time I would want a relog is if they log out of their current user on my app.
Comment: I should clarify a bit...
I'm trying to figure out to have multiple facebook accounts tied into my app. So that when different users login, they can access their individual facebook accounts.
Comment: Short-lived access token is around 2 hours. The long-lived one, you get when you use Server-side auth in your application, is 60 days.
Comment: Your direction has been most helpful. I think I'm going to start a new question for figuring out the rest of this. I'd appreciate it if you could provide any insight there: http://stackoverflow.com/questions/12961421/multiple-facebook-accounts-tied-into-one-app

Facebook login using access token


Wiring two receptacles to an existing one

Question: I have a 40 year old house. There is a receptacle in the garage that has two sets of wires coming into the box. One set is black, white and neutral. The other set is black, white, red and neutral.  If this receptacle is switched, I don't know from where. I wanted to replace the receptacle but mixed up the wiring. I don't need it to be switched.  How do I rewire the receptacle with both sets of wires?
I also wanted to use this receptacle to add two additional receptacles outside the garage.  When I rewired the receptacle, the circuit breaker trips right away. I found that another circuit breaker seems to be connected with it.  I am now having to switch circuit breaker 1 off and circuit breaker 2 on. If I want to use the receptacle I'm working on, I have to reverse the on/off between circuit breakers 1 and 2.
Could you please tell me how I should wire the original outlet and add the two outside outlet wiring
Comment: You say  "black, white and neutral", do you mean  black, white and (bare) ground?
Comment: Can you unwire the receptacle in question and measure the voltages black1-white1, black2-white2, red2-white2, black1-black2, black1-red2, and black2-red2 please?
Comment: Can you look at the old receptacle and say if any tabs have been broken off?
Answer: Normally when there is a switched receptacle only 1 of the 2 are switched. The cable that is black , white, red & ground.
the white is neutral Silver screw . the red goes to the switched hot Brass in color.
the tab between the top and bottom is broken on the hot side or the side that has the red and black wire.
The black wire normally always hot Is on the other brass connector.  The second cable is usually black to black , white to white and bare copper to bare copper.
This is how it would be wired when the power is going to the switch from the panel then the extra cable black white feeds another receptacle, to add another non switched receptacle tie to the black white ground.
If the room doesn't have a light fixture controlled by a switch you need to keep the switched receptacle for code compliance.
Comment: Look at the old receptacle and tell us if the removable side tabs which connect the two receptacles of the duplex are broken off. Did you replace the original receptacle with a new one?


Using a recursion tree to obtain an algorithm classification with n^2 time

Question: I'm having trouble getting the classification of this recurrence relation using a recursion tree.
$$T(n) = 3T(n/2) + n^2$$
I have the tree written out correctly (I hope):
<code>                                         n^2
                                      /   |   \
                                     /    |    \
                              (n/2)^2  (n/2)^2  (n/2)^2
                        /   |   \      /  |  \     /   |    \
                       /    |    \    /   |   \   /    |     \
               (n/4)^2   (n/4)^2 ...      ...         ...    (n/4)^2
                                         ...
                                         ...
              T(1) T(1) ... ... ... ... ... ... ... ... ... ... T(1) T(1)
</code>
And for each "level" I have the running times:
<code>                                Level         Time
                                  0            n^2
                                  1            3(n/2)^2
                                  2            9(n/4)^2
                                 log_2{n}      ???
</code>
So I'm having trouble getting the time for the base case at level $log_2{n}$, and after that I'm unsure of what I'm supposed to do with all the different times to get the overall running time. Do I add them all up? Do I just take the running time of the $log_2{n}$ level?
Thank you for any help you can give.
Comment: The following [MSE link](http://math.stackexchange.com/questions/319414) may be useful reading and can easily be adapted to your question, keeping in mind that the relation between work term and recursive term is different, but the method goes through the same.
Answer: At each level, the number of nodes triples and $n$ is cut in half. Extending the pattern in your table, we see that at level $k$, the time is $3^k(\tfrac{n}{2^k})^2 = (\tfrac{3}{4})^kn^2$. At the second-to-last level, we have $k = \log_2 n - 1$, which corresponds to the term $(\tfrac{3}{4})^{\log_2 n - 1}n^2$. At the last level when $k = \log_2 n \iff n = 2^k$, the base case kicks in. Assuming that $T(1) = c$ for some constant $c$, this level has running time $3^kT(1) = 3^{\log_2 n}c = cn^{\log_2 3}$.
Adding up all the levels, we observe that (other than the last level) we have a finite geometric series with initial term $a = n^2$, common ratio $r = \frac{3}{4}$, and a total of $N = \log_2 n$ terms. By applying the usual formula, we obtain:
\begin{align*}
T(n)
&= [n^2 + (\tfrac{3}{4})n^2 + (\tfrac{3}{4})^2n^2 + \cdots + (\tfrac{3}{4})^{\log_2 n - 1}n^2] + cn^{\log_2 3} \\
&= \frac{n^2(1 - (\frac{3}{4})^{\log_2 n})}{1 - \frac{3}{4}} + cn^{\log_2 3} \\
&= 4n^2\left(1 - \frac{3^{\log_2 n}}{4^{\log_2 n}}\right) + cn^{\log_2 3} \\
&= 4n^2\left(1 - \frac{n^{\log_2 3}}{n^{\log_2 4}}\right) + cn^{\log_2 3} \\
&= \left(4n^2 - 4n^2 \cdot \frac{n^{\log_2 3}}{n^2}\right) + cn^{\log_2 3} \\
&= 4n^2 + (c - 4)n^{\log_2 3} \\
\end{align*}
Notice that since $2 = \log_2 4 > \log_2 3$, it follows that $T(n) = \Theta(n^2)$.


Derive $u$ for an intersection between sphere and a segment of line $P1 + u(P2-P1)$

Question: If we have a segment defined by points $P1$ and $P2$ and a sphere defined by origin $P3$ and radius $r$. And the segment is part of a line defined by $P1 + u(P2-P1)$. Then if the segment and the sphere intersect, the intersection point lies between $u >= 0$ and $u <=1$. How do we derive the formula for u? The formula below I tried to derive is incorrect.
$$u = \frac{(P3-P1)(P2-P1)}{(P2-P1)(P2-P1)}$$
Do we need to extend the endpoints of the segment distance $r$ along the direction of the line and set the new endpoints in the equation above?
Answer: Calling $s_{12}(\lambda) = \lambda p_1 + (1-\lambda) p_2$ and given the sphere as $\|p-p_3\|^2 = r^2$ we have
$$
\|s_{12}(\lambda)-p_3\|^2 = \lambda^2\|p_1\|^2+2\lambda(1-\lambda)p_1\cdot p_2+(1-\lambda)^2\|p_2\|^2 - 2\lambda p_1\cdot p_3-2(1-\lambda)p_2\cdot p_3+\|p_3\|^2= r^2
$$
solving for $\lambda$. If $\ \ 0\le \lambda\le 1$ the segment intersects the sphere.
NOTE
$$
\lambda=\frac{\|p_2\|^2-p_1p_2+p_1p_3-p_2p_3\pm\sqrt{(\|p_2\|^2-p_1p_2+p_1p_3-p_2p_3)^2-\|p_1-p_2\|^2(\|p_3-p_2\|^2-r^2)}}{\|p_1-p_2\|^2}
$$
Attached a plot showing the solution for
$$
\cases{
p_1 = (2,1,1)\\
p_2 = (5,6,4)\\
p_3 = (1,0,0)\\
r=3
}
$$
giving $\lambda = \frac{1}{43} \left(54-\sqrt{379}\right)$ and after substitution into $\lambda p_1+(1-\lambda)p_2$...
Comment: Thanks! So we get a very long formula for $u$ or as you wrote it $λ$. What is $p_1p_2$ in this case, is it multiplication product or dot product?
Comment: It is a dot product.
Comment: I tested this and the formula for $λ$ does not seem to be correct unfortunately. I checked with formula in this article https://en.wikipedia.org/wiki/Line%E2%80%93sphere_intersection, and that seems as the correct solution.
Comment: To me the formula works fine. Attached an example. Remember that potentially the intersection can be double so we should check the two outcomes.


Android Virtual Device/ Android Emulator - Decryption Unsuccessful

Question: I just installed Android Studio, and I am very new with this program.
So when I run the Android Emulator it says: "To Start Android, enter your password", although I have never set a password. When I just enter a word with 4 letters it says "The Password you entered is correct, but unfortunately your data is corrupt".
After that, I have to Reset the Phone, but when I do that the same menu with "To Start Android, enter your password" appears.
Maybe it is just an easy mistake, but as I said I am new with this. I also did some research on the internet but I did not find anything useful.
this is the 2 images that it showe me:
1)
2)
and after i clicked on reset phone, nothing happened.
I would be very glad if someone has an answer for this.
Comment: I'm running into the same problem :s
Comment: for me, I encoutered this problem when entering wrong pw
Answer: This is a late response, but thought this simple fix might help anyone else who comes across this problem in the future.  What worked for me is the following:
In VS2017 ==> Tools ==> Android ==> Select: Android Device Manager
In the Android Device Manager window, you'll see your Android Emulator.

Make sure the far right column contains the button "Start" (if "Stop" appears, click "Stop")
Right Click the device, and select the "Factory Reset" option in the menu.

Your emulator should now be working.  Good luck.
Comment: Worked in VS 2019 too. Thank you.
Answer: open AVD and right click on the emulator choose ->Wipe data option.
Answer: Check that your avd folder path doesn't include national symbols (in my case it looked like C:\Users\Пользователь\.android).
After I changed this path everything is working.
See this post of how to change path:
Possible to change where Android Virtual Devices are saved?
Answer: Check out "Viewing and managing your Avds" part. Try wiping data of your emulator or create a new emulator for yourself.
https://developer.android.com/studio/run/managing-avds.html
Answer: Change the Android version. I was creating an emulator with Oreo 8.1 and got stuck in with the same issue.
I created another with Marshmallows 6.0 and no more asking for password.
Then if you are using Oreo 8.1 try with antoher.
Answer: I created a virtual device, and after, I had to reinstall the emulator.
When I booted the virtual device, I got this issue.
I deleted it and made a new one, and it worked fine.
Answer: Just go the AVD Manager and Wipe Data. The problem will be solved.
Answer: Here are the steps I followed after my device corrupted.

Close your emulator
Open AVD manager, right click on your device and click "Cold Boot Now" button.
Answer: Sorry for a very Late Answer. But you can't create a x64 Virtual Device on x64 System. Your device needs to be x86.
Comment: Shouldn't that be "you can't create an x64 virtual device on an x86 system"?
Comment: That too. But x64 on a x64 can't be created either. Only In case if your CPU allows Hardware Virtaulization (and is enabled in BIOS), then you can.
Comment: I'm not familiar with your field, but surely creating an x86 VM on an x64 system is easier than an x86 VM on an x64 system? And likewise, are you saying you can **only** create an x64 VM on an x86 system? That sounds back-to-front. Could you provide some documentation for this? I'd be interested to read into why that is.
Answer: Just a warning to anyone getting this error on an emulator instance that was working and you cold booted or something. I got this error and just stopped and cold booted again and it was gone! So try that first before wiping your emulator instance unnecessarily.
Answer: Deleted the device in the Device Manager and created a new  one with a higher OS version (Oreo -> Pie).  The error disappeared.   Did not find the real reason yet.
Answer: It's very nearly 2024 and this is still happening. The fix for me combined a couple of other answers.
I was trying to simulate a Pixel 2 on Android 8.1. I wanted it to be 64-bit (like the real device is) but it gave me the error the original question encountered. Only after I switched it down to 32-bit (x86) and then ALSO enabled Google API and Google Play Store (these options are disabled in 64-bit mode for some reason) did it start up properly (it's possible only one of either of those options is needed, but I don't care because it's working now).


Concentric circles(IMO 1988/Problem 1)

Question: Let us consider 2 concentric circle radii R and r (R > r) with centre O.We fix P on the small circle and consider the variable chord PA of the small circle. Points B and C lie on the large circle; B,P,C are collinear and BC is perpendicular to AP.
i.) For which values of $\angle OPA$ do you think is the sum $AB^2+BC^2+CA^2$ extremal?
ii.) What are the possible positions of the midpoints U of BA and V of AC as varies?
Source; IMO 1988/Problem 1.
I was thinking about some solution involving coordinate geometry but I am interested in other synthetic geometry solutions as well.(In fact, am I right when I believe the first question is asking for the possible values of the given sum?)
Thank you!
Comment: No, question 1 is asking for the values the angle OPA, such that the sum is maximum or minimum.
Comment: Thank you.In fact,I tried connecting A, B and C to O.With O(0,0) as the origin, I assigned coordinates to A, B and C and obtained relations of the type $p^2+q^2=R^2$ and so on.I tried using the Pythagoras theorem and used the previous results of the type I mentioned,but I always seemed to get stuck while trying to obtain the sum mentioned in the problem as expression independent of the co-ordinates I had specified.Your insight is appreciated!
Comment: @SabyasachiMukherjee Are you still looking for solution, I can write one up for you.
Answer:
let $OH//AP,\angle APO=\theta$,we have :
$OH=r\cos{\theta},AP=2OH=2r\cos{\theta},PH=r\sin{\theta},BH=\sqrt{BO^2-OH^2}=\sqrt{R^2-(r\cos{\theta})^2},BP=BH-PH=\sqrt{R^2-(r\cos{\theta})^2}-r\sin{\theta}, CP=BH+PH=\sqrt{R^2-(r\cos{\theta})^2}+r\sin{\theta},BC=2BH$
$AB^2=AP^2+BP^2=4r^2 \cos ^2{\theta}+R^2-r^2\cos ^2{\theta}+r^2\sin ^2{\theta}-2r\sin{\theta}\sqrt{R^2-(r\cos{\theta})^2}$
$AC^2=AP^2+CP^2=4r^2 \cos ^2{\theta}+R^2-r^2\cos ^2{\theta}+r^2\sin ^2{\theta}+2r\sin{\theta}\sqrt{R^2-(r\cos{\theta})^2}$
$AB^2+AC^2+BC^2=2R^2+6r^2 \cos ^2{\theta}+2r^2\sin ^2{\theta}+4R^2-4r^2 \cos ^2{\theta}=6R^2+2r^2$
so it is fixed value.
let $A(x_1,y_1),B(x_2,y_2),C(x_3,y_3), P(-r,0) \to U \left( x_{u}=\dfrac{x_1+x_2}{2},y_{u}=\dfrac{y_1+y_2}{2}\right), V \left(x_{v}=\dfrac{x_1+x_3}{2},y_{v}=\dfrac{y_1+y_3}{2}\right)$
$k_{BP}=\dfrac{y_2}{x_2+r}=k_{CP}=\dfrac{y_3}{x_3+r}=-\dfrac{1}{k_{AP}}=-\dfrac{x_1+r}{y_1} \to $
$y_2y_1+x_2x_1+r^2+(x_1+x_2)r=0,$ and  $y_3y_1+x_3x_1+r^2+(x_1+x_3)r=0$
$x_1^2+y_1^2+x_2^2+y_2^2=r^2+R^2 \to x_1^2+2x_1x_2+x_2^2+y_1^2+2y_1y_2+y_2^2+2r^2+2r(x_1+x_2)=R^2+r^2 \to (x_1+x_2)^2+2r(x_1+x_2)+r^2+(y_1+y_2)^2=R^2 \to 4x_u^2+4x_ur+r^2+4y_u^2=R^2 \to \left(x_u+\dfrac{r}{2}\right)^2+y_u^2=\left(\dfrac{R}{2}\right)^2$. with same method, $\left(x_v+\dfrac{r}{2}\right)^2+y_v^2=\left(\dfrac{R}{2}\right)^2$
, U and V on a circle, each take half circle.

Concentric circles(IMO 1988/Problem 1)


How to synchronize two scrollview in Android?

Question: I have two horizontal scrollview, and want to keep them always at the same position / distance. If user scrolls one, need to scroll programmatically the other. The challenge is, that an infinite loop will occur. One will raise the other, other will raise first. How can I set a state, indicate that a user initiated scroll is still in progress? So other scrollview should not execute the programmatic scroll.
One of them is a HorizontalScrollView other is a RecyclerView.
Tried solutions like below, without any success:
horizontalScrollView.getViewTreeObserver().addOnScrollChangedListener(new ViewTreeObserver.OnScrollChangedListener() {
        @Override
        public void onScrollChanged() {

            if (programmaticScrollEnable) {
                programmaticScrollEnable = false;
                // do programmatic scrolling here
                programmaticScrollEnable = true;
            }
        }
    });

Tried to change state in onScrollStateChanged method:
@Override
public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
    super.onScrollStateChanged(recyclerView, newState);

    /*if (newState == RecyclerView.SCROLL_STATE_IDLE) {
        MainActivity.programmaticScrollEnable = true;
    }*/
}

Answer: Try this...
horizontalScrollView.getViewTreeObserver().addOnScrollChangedListener(new ViewTreeObserver.OnScrollChangedListener() {

    @Override
    public void onScrollChanged() {

   recyclerView.scrollTo(horizontalScrollView.scrollTo(horizontalScrollView.getScrollX(), 0);

    }
});

Comment: any idea about this one : https://stackoverflow.com/questions/58848391/how-do-i-synchronize-scrollview-positions-of-dynamic-horizontal-scroll-views-ins
Answer:
The challenge is, that an infinite loop will occur.

You can avoid the infinite loop by registering the last touched ScrolledView in OnTouchListener. This touched ScrollView must not scroll programmatically; but the other(s) should be.
This can be tracked by setting a tag to each ScrollView and compare that tag during scroll event.
If you are API level 23 (Android M), you can register View.OnScrollChangeListener. And for APIs below that, you can register ViewTreeObserver.OnScrollChangedListener. But the latter is heavy on the resources; so you need to handle that.
For API levels 23+
// Tracking last touched SV
private var touchedSVTag = -1

// list of ScrollViews
val svs = arrayListOf(scrollview1, scrollview2)

val scrollListener =
    View.OnScrollChangeListener { view, scrollX, _, _, _ ->

        val currentSVTag = view!!.tag as Int

        if (currentSVTag == touchedSVTag) {
            for (svTag in 0 until svs.size)
                if (svTag != currentSVTag)
                    svs[svTag].scrollTo(scrollX, 0)
        }
    }

val itemTouchListener = View.OnTouchListener { sv, _ ->
    val svTag = sv.tag as Int

    if (touchedSVTag != -1 && touchedSVTag != svTag) {
        // stop scrollView in the middle of the scroll
        svs[touchedSVTag].fling(0)
    }

    touchedSVTag = svTag
    false
}

for (i in 0 until svs.size) {
    val sv = svs[i]
    sv.tag = i
    sv.setOnScrollChangeListener(scrollListener)
    sv.setOnTouchListener(itemTouchListener)
}

And for API levels below 23:
// Tracking last touched SV
private var touchedSVTag = -1

// list of ScrollViews
val svs = arrayListOf(scrollview1, scrollview2)

val scrollListener = {
    val scrolledSV = svs[touchedSVTag]
    for (svTag in 0 until svs.size)
        if (svTag != touchedSVTag)
            svs[svTag].scrollTo(scrolledSV.scrollX, 0)
}

val itemTouchListener = View.OnTouchListener { sv, _ ->
    val svTag = sv.tag as Int

    if (touchedSVTag != -1 && touchedSVTag != svTag) {
        // stop scrollView in the middle of the scroll
        svs[touchedSVTag].fling(0)
    }

    touchedSVTag = svTag
    false
}

for (i in 0 until svs.size) {
    val sv = svs[i]
    sv.tag = i
    sv.viewTreeObserver.addOnScrollChangedListener(scrollListener)
    sv.setOnTouchListener(itemTouchListener)
}


Calculating distance between two points shows wrong distance

Question: I use below two ways to calculate distance between two points in google maps using latitude and longitude.
<code>            TYPE I:
         function CalcDistanceBetween(lat1, lon1, lat2, lon2) {
//Radius of the earth in:  1.609344 miles,  6371 km  | var R = (6371 / 1.609344);
var R = 6371; // Radius of earth in Miles
var dLat = toRad(lat2-lat1);
var dLon = toRad(lon2-lon1);
var a = Math.sin(dLat/2) * Math.sin(dLat/2) +
        Math.cos(toRad(lat1)) * Math.cos(toRad(lat2)) *
        Math.sin(dLon/2) * Math.sin(dLon/2);
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
var d = R * c;
   alert("d==" + d);
return d;
}
  alert(CalcDistanceBetween(13.125511084202,80.029651635576,12.9898593006481,80.2497744326417));
                 function toRad(Value) {
            /** Converts numeric degrees to radians */
         return Value * Math.PI / 180;
         }

    TYPE II:

            var p1 = new google.maps.LatLng(13.125511084202,80.029651635576);
            var p2 = new google.maps.LatLng(12.9898593006481,80.2497744326417);

            alert(calcDistance(p1, p2));

           //calculates distance between two points in km's
                       function calcDistance(p1, p2){
                return (google.maps.geometry.spherical.computeDistanceBetween(p1, p2) /
                  1000).toFixed(2);
                }
</code>
Above both types gives 28 kms as distance.
But when i check in google maps with same langitude and longitude it returns 36.8 kms.
Sample Check in My Code & google maps Shown Below..:

Do u suggest me for get accurate results??
Answer: The distance given by Google is from the suggested route.  It's not a direct path from point A to point B.  The distance you computed is the direct path, which would only be the case if you flew directly from A to B.
If you want to get the result that Google outputs,  look here: An elegant way to find shortest and fastest route in Google Maps API v3?
Comment: He is right, distance from A to B is "Air Line" (directly and not includes routes and stuff).
Comment: yes you are right..but if u give sample code..it helpful for me
Answer: Could be i'm completely mistaken :) but it seems your method calculate the real distance between these 2 points and when you route with google it is the distance of the route you take.


Can Value Object have behaviour?

Question: I have a Value Objects - Money and ExchangeRatio. I want to convert one Money to another using ExchangeRatio. So is it good to build a convert behavior on Value Object ExchangeRatio like so:
ExchangeRatio.Convert(Money) returns Money.
Or should I delegate it to some Domain Service instead? In other words can I build a behaviour on Value Object that doesnt change its state but has some logic, mathematic or other different object creation(based on its state) in it?
Answer: What you are doing sounds perfectly reasonable to me.  Eric Evans uses an example of a Paint object in his book that does the same thing.  The mixIn method takes another Paint object as input and returns a new Paint object.
With the Paint sample he demonstrates side-effect free functions in the book.
Comment: I would put the convert method on the money object though as you are working with money, not with ExchangeRatio.
Thus `Money.ConvertTo(ExchangeRatio)`
Comment: Well, Radek, further on the `Paint` is further refactored to include a `Pigment`.  So the `Paint` *knows* about the pigment and uses a ratio internally.  So as long as the *closure of operations* business holds we should be good.  Anyway, as SneekyPeet has mentioned you could swop things around a bit as your example actually looks more like a domain service already ;) --- the answer still holds, though: you *can* have behaviour on your VO.
Comment: Ok, becuase Paint only knows about Paint instances in his behaviour. Here ExchangeRatio knows about Money, so its different case.

Can Value Object have behaviour?


How might I learn to write char device drivers for Linux?

Question: How to write char device drivers in Linux?
Answer: A very good example is the Linux "softdog", or software watchdog timer. When loaded, it will watch a special device for writes and take action depending on the frequency of those writes.
It also shows you how to implement a rudamentary ioctl interface, which is very useful.
The file to look at is drivers/watchdog/softdog.c
If you learn by example, that is a very good one to start with. The basic character devices (null, random, etc) as others suggest are also good, but do not adequately demonstrate how you need to implement an ioctl() interface.
A side note, I believe the driver was written by Alan Cox. If your going to learn from example, its never a bad idea to study the work of a top level maintainer. You can be pretty sure that the driver also illustrates adhering to proper Linux standards.
As far as drivers go (in Linux), character drivers are the easiest to write and also the most rewarding, as you can see your code working very quickly. Good luck and happy hacking.
Answer: Read this book: Linux Device Drivers published by O'Reilly.
Helped me a lot.
Answer: My favorite book for learning how the kernel works, BY FAR (and I've read most of them) is:
Linux Kernel Development (2nd Edition)
This book is fairly short, read it first, then read the O'Reilly book on drivers.
Comment: Now [Linux Kernel Development (3rd Edition)](http://www.amazon.com/Linux-Kernel-Development-Robert-Love/dp/0672329468/ref=dp_ob_title_bk)
Answer: Read linux device driver 3rd edition. And the good thing is start coding. I am just pasting a simple char driver so that you can start coding.
<code>#include<linux/module.h>
#include<linux/kernel.h>
#include<linux/fs.h> /*this is the file structure, file open read close */
#include<linux/cdev.h> /* this is for character device, makes cdev avilable*/
#include<linux/semaphore.h> /* this is for the semaphore*/
#include<linux/uaccess.h> /*this is for copy_user vice vers*/

int chardev_init(void);
void chardev_exit(void);
static int device_open(struct inode *, struct file *);
static int device_close(struct inode *, struct file *);
static ssize_t device_read(struct file *, char *, size_t, loff_t *);
static ssize_t device_write(struct file *, const char *, size_t, loff_t *);
static loff_t device_lseek(struct file *file, loff_t offset, int orig);

/*new code*/
#define BUFFER_SIZE 1024
static char device_buffer[BUFFER_SIZE];
struct semaphore sem;
struct cdev *mcdev; /*this is the name of my char driver that i will be registering*/
int major_number; /* will store the major number extracted by dev_t*/
int ret; /*used to return values*/
dev_t dev_num; /*will hold the major number that the kernel gives*/

#define DEVICENAME "megharajchard"

/*inode reffers to the actual file on disk*/
static int device_open(struct inode *inode, struct file *filp) {
    if(down_interruptible(&sem) != 0) {
        printk(KERN_ALERT "megharajchard : the device has been opened by some other device, unable to open lock\n");
        return -1;
    }
    //buff_rptr = buff_wptr = device_buffer;
    printk(KERN_INFO "megharajchard : device opened succesfully\n");
    return 0;
}

static ssize_t device_read(struct file *fp, char *buff, size_t length, loff_t *ppos) {
    int maxbytes; /*maximum bytes that can be read from ppos to BUFFER_SIZE*/
    int bytes_to_read; /* gives the number of bytes to read*/
    int bytes_read;/*number of bytes actually read*/
    maxbytes = BUFFER_SIZE - *ppos;
    if(maxbytes > length)
        bytes_to_read = length;
    else
        bytes_to_read = maxbytes;
    if(bytes_to_read == 0)
        printk(KERN_INFO "megharajchard : Reached the end of the device\n");
    bytes_read = bytes_to_read - copy_to_user(buff, device_buffer + *ppos, bytes_to_read);
    printk(KERN_INFO "megharajchard : device has been read %d\n",bytes_read);
    *ppos += bytes_read;
    printk(KERN_INFO "megharajchard : device has been read\n");
    return bytes_read;
}

static ssize_t device_write(struct file *fp, const char *buff, size_t length, loff_t *ppos) {
    int maxbytes; /*maximum bytes that can be read from ppos to BUFFER_SIZE*/
    int bytes_to_write; /* gives the number of bytes to write*/
    int bytes_writen;/*number of bytes actually writen*/
    maxbytes = BUFFER_SIZE - *ppos;
    if(maxbytes > length)
        bytes_to_write = length;
    else
        bytes_to_write = maxbytes;
    bytes_writen = bytes_to_write - copy_from_user(device_buffer + *ppos, buff, bytes_to_write);
    printk(KERN_INFO "megharajchard : device has been written %d\n",bytes_writen);
    *ppos += bytes_writen;
    printk(KERN_INFO "megharajchard : device has been written\n");
    return bytes_writen;
}

static loff_t device_lseek(struct file *file, loff_t offset, int orig) {
    loff_t new_pos = 0;
    printk(KERN_INFO "megharajchard : lseek function in work\n");
    switch(orig) {
        case 0 : /*seek set*/
            new_pos = offset;
            break;
        case 1 : /*seek cur*/
            new_pos = file->f_pos + offset;
            break;
        case 2 : /*seek end*/
            new_pos = BUFFER_SIZE - offset;
            break;
    }
    if(new_pos > BUFFER_SIZE)
        new_pos = BUFFER_SIZE;
    if(new_pos < 0)
        new_pos = 0;
    file->f_pos = new_pos;
    return new_pos;
}

static int device_close(struct inode *inode, struct file *filp) {
    up(&sem);
    printk(KERN_INFO "megharajchard : device has been closed\n");
    return ret;
}

struct file_operations fops = { /* these are the file operations provided by our driver */
    .owner = THIS_MODULE, /*prevents unloading when operations are in use*/
    .open = device_open,  /*to open the device*/
    .write = device_write, /*to write to the device*/
    .read = device_read, /*to read the device*/
    .release = device_close, /*to close the device*/
    .llseek = device_lseek
};

int chardev_init(void)
{
    /* we will get the major number dynamically this is recommended please read ldd3*/
    ret = alloc_chrdev_region(&dev_num,0,1,DEVICENAME);
    if(ret < 0) {
        printk(KERN_ALERT " megharajchard : failed to allocate major number\n");
        return ret;
    }
    else
        printk(KERN_INFO " megharajchard : mjor number allocated succesful\n");
    major_number = MAJOR(dev_num);
    printk(KERN_INFO "megharajchard : major number of our device is %d\n",major_number);
    printk(KERN_INFO "megharajchard : to use mknod /dev/%s c %d 0\n",DEVICENAME,major_number);

    mcdev = cdev_alloc(); /*create, allocate and initialize our cdev structure*/
    mcdev->ops = &fops;   /*fops stand for our file operations*/
    mcdev->owner = THIS_MODULE;

    /*we have created and initialized our cdev structure now we need to add it to the kernel*/
    ret = cdev_add(mcdev,dev_num,1);
    if(ret < 0) {
        printk(KERN_ALERT "megharajchard : device adding to the kerknel failed\n");
        return ret;
    }
    else
        printk(KERN_INFO "megharajchard : device additin to the kernel succesful\n");
    sema_init(&sem,1);  /* initial value to one*/

    return 0;
}

void chardev_exit(void)
{
    cdev_del(mcdev); /*removing the structure that we added previously*/
    printk(KERN_INFO " megharajchard : removed the mcdev from kernel\n");

    unregister_chrdev_region(dev_num,1);
    printk(KERN_INFO "megharajchard : unregistered the device numbers\n");
    printk(KERN_ALERT " megharajchard : character driver is exiting\n");
}

MODULE_AUTHOR("A G MEGHARAJ(firstname.lastname@example.com)");
MODULE_DESCRIPTION("A BASIC CHAR DRIVER");
//MODULE_LICENCE("GPL");

module_init(chardev_init);
module_exit(chardev_exit);
</code>
and this is the make file.
<code>obj-m   := megharajchard.o

KERNELDIR ?= /lib/modules/$(shell uname -r)/build
PWD       := $(shell pwd)

all:
    $(MAKE) -C $(KERNELDIR) M=$(PWD)

clean:
    rm -rf *.o *~ core .depend .*.cmd *.ko *.mod.c .tmp_versions
</code>
load script. make sure the major number is 251 or else change it accordingly.
<code>#!/bin/sh

sudo insmod megharajchard.ko
sudo mknod /dev/megharajchard c 251 0
sudo chmod 777 /dev/megharajchard
</code>
unload script,
<code>#!/bin/sh

sudo rmmod megharajchard
sudo rm /dev/megharajchard
</code>
also a c program to test the operation of your device
<code>#include<stdio.h>
#include<fcntl.h>
#include<string.h>
#include<malloc.h>

#define DEVICE "/dev/megharajchard"
//#define DEVICE "megharaj.txt"
int debug = 1, fd = 0;

int write_device() {
    int write_length = 0;
    ssize_t ret;
        char *data = (char *)malloc(1024 * sizeof(char));
    printf("please enter the data to write into device\n");
    scanf(" %[^\n]",data); /* a space added after"so that it reads white space, %[^\n] is addeed so that it takes input until new line*/
    write_length = strlen(data);
    if(debug)printf("the length of dat written = %d\n",write_length);
    ret = write(fd, data, write_length);
    if(ret == -1)
        printf("writting failed\n");
    else
        printf("writting success\n");
    if(debug)fflush(stdout);/*not to miss any log*/
    free(data);
return 0;
}

int read_device() {
    int read_length = 0;
    ssize_t ret;
        char *data = (char *)malloc(1024 * sizeof(char));
    printf("enter the length of the buffer to read\n");
    scanf("%d",&read_length);
    if(debug)printf("the read length selected is %d\n",read_length);
    memset(data,0,sizeof(data));
    data[0] = '0\';
    ret = read(fd,data,read_length);
    printf("DEVICE_READ : %s\n",data);
    if(ret == -1)
        printf("reading failed\n");
    else
        printf("reading success\n");
    if(debug)fflush(stdout);/*not to miss any log*/
    free(data);
return 0;
}

int lseek_device() {
    int lseek_offset = 0,seek_value = 0;
    int counter = 0; /* to check if function called multiple times or loop*/
    counter++;
    printf("counter value = %d\n",counter);
    printf("enter the seek offset\n");
    scanf("%d",&lseek_offset);
    if(debug) printf("seek_offset selected is %d\n",lseek_offset);
    printf("1 for SEEK_SET, 2 for SEEK_CUR and 3 for SEEK_END\n");
    scanf("%d", &seek_value);
    printf("seek value = %d\n", seek_value);
    switch(seek_value) {
        case 1: lseek(fd,lseek_offset,SEEK_SET);
            return 0;
            break;
        case 2: lseek(fd,lseek_offset,SEEK_CUR);
            return 0;
            break;
        case 3: lseek(fd,lseek_offset,SEEK_END);
            return 0;
            break;
        default : printf("unknown  option selected, please enter right one\n");
            break;
    }
    /*if(seek_value == 1) {
        printf("seek value = %d\n", seek_value);
        lseek(fd,lseek_offset,SEEK_SET);
        return 0;
    }
    if(seek_value == 2) {
        lseek(fd,lseek_offset,SEEK_CUR);
        return 0;
    }
    if(seek_value == 3) {
        lseek(fd,lseek_offset,SEEK_END);
        return 0;
    }*/
    if(debug)fflush(stdout);/*not to miss any log*/
return 0;
}

int lseek_write() {
    lseek_device();
    write_device();
return 0;
}

int lseek_read() {
    lseek_device();
    read_device();
return 0;
}

int main()
{
    int value = 0;
    if(access(DEVICE, F_OK) == -1) {
        printf("module %s not loaded\n",DEVICE);
        return 0;
    }
    else
        printf("module %s loaded, will be used\n",DEVICE);

    while(1) {
    printf("\t\tplease enter 1 to write\n \
                     2 to read\n \
                     3 to lseek and write\
                 4 to lseek and read\n");
        scanf("%d",&value);
        switch(value) {
            case 1 :printf("write option selected\n");
            fd = open(DEVICE, O_RDWR);
            write_device();
            close(fd); /*closing the device*/
            break;
            case 2 :printf("read option selected\n");
            /* dont know why but i am suppoesed to open it for writing and close it, i cant keep  open and read.
            its not working, need to sort out why is that so */
            fd = open(DEVICE, O_RDWR);
            read_device();
            close(fd); /*closing the device*/
            break;
            case 3 :printf("lseek  option selected\n");
            fd = open(DEVICE, O_RDWR);
            lseek_write();
            close(fd); /*closing the device*/
            break;
            case 4 :printf("lseek  option selected\n");
            fd = open(DEVICE, O_RDWR);
            lseek_read();
            close(fd); /*closing the device*/
            break;
            default : printf("unknown  option selected, please enter right one\n");
            break;
        }
    }
    return 0;
}
</code>
Answer: Have a look at some of the really simple standard ones - "null", "zero", "mem", "random", etc, in the standard kernel. They show the simple implementation.
Obviously if you're driving real hardware it's more complicated- you need to understand how to interface with the hardware as well as the subsystem APIs (PCI, USB etc) for your device. You might need to understand how to use interrupts, kernel timers etc as well.
Answer:
Just check the character driver skeleton from here http://www.linuxforu.com/2011/02/linux-character-drivers/....Go ahead and read all the topics here, understand thoroughly.(this is kinda a tutorial-so play along as said).
See how "copy_to_user" and "copy_from_user" functions work, which you can use in read/write part of the driver function callbacks.

Once you are done with this, start reading a basic "tty" driver.
Focus, more on the driver registration architecture first, which means:-

See what structures are to be filled- ex:- struct file_operations f_ops = ....
Which are the function responsible to register a particular structure with core . ex:- _register_driver.
Once you are done with the above, see what functionality you want with the driver(policy), then think of way to implement that policy(called mechanism)- the policy and mechanism allows you to distinguish between various aspects of the driver.
write compilation makefiles(its hard if you have multiple files- but not tht hard).
Try to resolve the errors and warnings,
and you will be through.

When writing mechanism, never forget what it offers to the applications in user space.


Akka - Creating an actor using reflection

Question: I need to create an actor whose exact type is only read at runtime from a configuration file. The constructor for that actor is non trivial, i.e. it requires some parameters which are defined in the configuration file.
Until now, I've tried to do this using reflection as follows:
val actor = actorOf(constructor.newInstance(parameters: _*).asInstanceOf[T]).start

Unfortunately, this results in an "akka.actor.ActorInitializationException: ActorRef for instance of actor [...] is not in scope. You can not create an instance of an actor explicitly using 'new MyActor'. [...]"!
Now, I understand this protects the framework from leaking a reference to the inner object, but how can I get past this problem? Alternatively, how else could I do what I'm trying to do in a way that will work?
Answer: Maybe use the Java interface for creating actors with parameters. The (Java) code for creation looks like this:
ActorRef actor = actorOf(new UntypedActorFactory() {
  public UntypedActor create() {
    return new MyUntypedActor("service:name", 5);
   }
});

So you pass a factory instead of a function. This might work better...


troubleshooting a hot tub/spa that won't heat up

Question: We have a Hotsprings/Watkins brand hottub/spa that came with the house we bought last September.  At the time that we bought it, the hot tub appeared to work and heat up properly.  However, now that we've unwinterized it and tried to use it, it no longer heats up and the water temperature stays at 70 F.  The power to the hottub works ok and the jets, light and control panel all seem to work ok.
At first we found that the circulation pump wasn't working and we though that this is why the water wasn't heating up. We bought a new pump and now the bubbles come out of the bottom circulation vent at the bottom of the tub, but the water still doesn't heat up.  Does this sound like a problem with the heating element?  We're not really familiar with hot tubs and aren't sure how to troubleshoot this other than look at the obvious. People online talk about breakers in the inside control panel, but I couldn't find any and the only fuse in there is in tact. The only breaker I know of is the external breaker in a breaker box outside the hot tub. Any ideas are appreciated.
Comment: Heh, that's funny, I thought this was a home improvement help site for Do-It-Yourselfers. I think I'm capable of making smart decisions about protecting myself from the dangers of electricity and am no stranger to working with it. I just have little experience with hot tubs. Also, the so called hot tub professionals might as well be amateur electricians from what I've seen.
Comment: Call a professional... water + electricity + amateur electrician = trouble.
Comment: this *is* a DIY help site, but most folks don't want to help somebody electrocute themselves.  It's nearly impossible to judge someones skill level based on their fist question on the site, so they typically get the "get help" answer/warning when asking a question involving electrical, plumbing, etc.
Comment: this is off topic - you need help from electricians.. not DIY'ers..
Comment: press the reset button -- did it work?
Comment: You didn't disconnect the power befor draining the spa. Heaters burn out if no water is present
Answer: Deltaray,
I have a Hotsprings Grandee 220V. I've experienced a few power related issues. Here are my thoughts:

Makse sure the thermostat is set higher than 70 degrees. Should be a no brainer but you never know.
Make sure the breaker for the heater is on. Mine has 2 breakers in the sub panel, one for the heater and one for the pumps and electronics.
Try resetting everything. Turn off the breakers, let it site for a minute, turn the breakers back on.
On mine the cover for the control box is easy to open with a screwdriver. Turn off the breakers and open the control box. Examine the wires that go to the heater. Make sure they are attached.
Mine also has a fuse or two on in the control box. Look to see if they are blown.
The heaters do not last forever. They are pretty simple to replace, especially if you already have experience replacing the circulation pump.
If you are comfortable with electricity it is easy to see if the heater is getting power at the control box. Use a volt meter to check for voltage.
If the circulation pump was not working, the heater could have overheated. Look for a reset button, or if you know the heater is getting power, replace the heater.

When the heater is working you should feel hot water coming out of the drain vent. Your electric meter should also be spinning pretty fast. My Grandee takes a few hours to heat up, but you should feel the hot water almost immediately.
What year/model do you have? 110V or 220V?
Comment: I have replaced quite a few heat elements over the years, depending on wattage they are usually around 50$ and are normally housed in a stainless tube with 2 lugs (the power to the heater element). The other item not so often bad I did not see mentioned is the pressure flow safety switch. This is a simple pressure switch that interrupts power to the contactor if the pump is not running. Pressure safety switches are usually under 20$.
Answer: Just throwing it out there, but many spa heaters, including mine, have an "overheat breaker" for the heater coil, which trips if the heater element gets too hot. For instance, if the pump wasn't well-primed before you turned the heater on, you can have air in the heater manifold which very quickly overheats the coil. Turning the element to its max setting can also cause this breaker to trip every so often.
The breaker should have a pretty simple reset; on mine it's just a small red button.
Answer: Just one more idea: my hot tub heater automatically resets to "warm" vs. "hot" if the filter needs to be changed. I have a different make/model, but check your filters.
Also, they can take hella long time to heat in cool weather.


WPF : The toggle button in my GridViewToggleRowDetailsColumn get visible when scrolling horizontally

Question: I have a radgridview with a GridViewToggleRowDetailsColumn and I can set the visibility of the GridViewToggleButton the way I want through the RowLoaded event for each row. It was working fine until I need to scroll horizontally. When the GridViewToggleRowDetailsColumn get out of the screen and I scroll back to it, the GridViewToggleButton are now all visible.
I tried to find any event triggered by this without success. Even the IsVisibleChanged event attached to the GridViewToggleButton seems to be triggered only on the visible one.
Does anyone faced the same issue or have any idea of what could produce this behavior ?
Edit: Found the answer. It was a virtualization issue. Adding EnableColumnVirtualization="False" in the gridview properties solved it.
Comment: I suggest you ask in the telerik forum. Their support is pretty good.
Answer: https://docs.telerik.com/devtools/wpf/controls/radgridview/features/ui-virtualization
After a few minutes of research, it appears that telerik WPF GridView uses virtualization to improve performace. This means that the state of what is in the screen is retained and as things leave your viewing area they are destroyed. This frees up memory space significantly, however can have some side effects as you are experiencing.
You can set EnableColumnVirtualization=false however Telerik has provided a help article that will likely answer your question more directly while not sacrificing the performance provided by the virtualizations. A link is below and following through the steps, it looks fairly straightforward.
https://docs.telerik.com/devtools/wpf/controls/radgridview/style-selectors/cell-style-selector
Answer: The recommended approach for customizing this behavior, and not turning off the virtualization, is to use a custom column. Try inheriting from GridViewToggleRowDetailsColumn and override CreateCellElement. It is the callback for creating the visual element in the cell, which is called, more or less, at the same time as RowLoaded. Then return null for those rows that you don't want to have a button for.


What should I use to fix chips in veneer plaster?

Question: I had some water issues in my shower and finally got fed up enough to remove the miss-cut plastic back-splash that previous contractor had tried to install using thin-set.
Upon removal I found a moldy rotten backer panel, so I began to sledge hammer it out with the intent to replace it with cement board.  However, as I got further away from the rot, my sledge hammer would occasionally bounce off the wall instead of punching though and it became apparent that there is a very hard plaster over what appears to be blue board.
I continued the demo to the edge of each panel abutting the tub, and tried to stop there, but occasionally some of the joints shattered in a way that removed the plaster covering the blue board above it.
How do I fix the shattered plaster so that my cement board will be flush with the the entire run of plaster coated blue board?

I'm only asking because I've gotten a bunch of mixed answers from various hardware stores

The most common is "I don't know" which at least is better than miss information

Some say Spackle; but my previous experience is that it doesn't want really want to adhere to the plaster and occasionally will fall out

Others have told me joint compound, but I'm not convinced it will be much different than Spackle, nor will it be as hard and water proof.

Finally, after insisting that I didn't want to use Spackle, one other associate told me to use Plaster of Paris, which Google seems to tell me is different than veneer plaster, and might set up too quickly.
Answer: I'd use veneer plaster. Your instinct about joint compound and spackling is on target, and you might get Plaster of Paris to work if you get the mix perfect - but why bother.
My guess is that the people you've been talking to at hardware stores either don't have a clue what you are looking for or want to direct you to something in stock.  I'd check at a building supply store (you might get lucky at a big box store, especially if they carry blue board) that contractors in your area use.
Veneer plaster is extremely uncommon in my area, and I can get it when I need it from any of the big chain stores (although I usually have to order it - they never stock it).
Comment: I thought there might be a reason they weren't giving me veneer plaster.  Spackle and joint compound work so poorly I've been using painters caulk to fill some dips.  For the project mentioned above, I decided the type of thin-set I bought is cement like enough that I could just use it instead of plaster when I skim coat.  It's drying now; I'll let you know how it looks later.


wxpython panel shrinks after plot created

Question: I have a very simple panel, where you click a button and a plot is created (using matplotlib) and the plot is saved as a .png in my working folder.
Once the plot is created my panel shrinks in size. Does anyone know why this is?
Below is the code, and then screenshots of before and after the button is clicked.
import wx
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

class MyApp(wx.App):
    def __init__(self):
        super().__init__(clearSigInt=True)
        self.InitFrame()

    def InitFrame(self):
        frame = MyFrame(parent=None, title='My Frame', pos = (100,100))
        frame.Show()

class MyFrame(wx.Frame):
    def __init__(self, parent, title, pos):
        super().__init__(parent=parent, title=title, pos=pos)
        self.OnInit()

    def OnInit(self):
        panel = MyPanel(parent=self)

class MyPanel(wx.Panel):
    def __init__(self, parent):
        super().__init__(parent=parent)

        button = wx.Button(parent=self, label = "Create plot", pos = (20,80))
        button.Bind(event=wx.EVT_BUTTON, handler=self.onSubmit)

    def onSubmit(self,event):
        ActivityDF = pd.DataFrame({
            'Activity': ['A','B','C','D'],
            'Count': [10,20,30,40]
        })
        fig, ax = plt.subplots(1)
        ax.barh(ActivityDF['Activity'], ActivityDF['Count'])
        fig.savefig('Figure.png',bbox_inches='tight', facecolor="None")

if __name__ == "__main__":
    app = MyApp()
    app.MainLoop()

Before button clicked
After button clicked
Comment: Welcome to StackOverflow. Please add some code to your question - its much easier to help when we can reproduce the problem in a meaningful way
Answer: Welcome to Stack Overflow.
First, your code is a little bit overcomplicated. There is no need to use so many classes.
Second, if you plan to use matplotlib with a GUI library then you need to import a backend so matplotlib works fine within the application you are writting.
Regarding why the panel is schrinking. I am not really sure. Perhaps an error when matplotlib tries to plot without the appropiate backend.
I simplified your code and added some comments to it.
import wx
import numpy as np

import matplotlib as mpl
## Import the matplotlib backend for wxPython
from matplotlib.backends.backend_wxagg import FigureCanvasWxAgg as FigureCanvas

## Only one class is really needed in this case. There is no need to have
## a class for the App, a class for the frame and a class for the panel
class MyWin(wx.Frame):
    def __init__(self, title, pos):
        super().__init__(parent=None, title=title, pos=pos)

        self.panel = wx.Panel(parent=self)
        self.button = wx.Button(parent=self.panel, label='Create plot', pos=(20, 80))

        self.button.Bind(wx.EVT_BUTTON, self.onSubmit)

    def onSubmit(self, event):
        x = np.arange(10)
        y = np.arange(10)
        ## This is to work with matplotlib inside wxPython
        ## I prefer to use the object oriented API
        self.figure  = mpl.figure.Figure(figsize=(5, 5))
        self.axes    = self.figure.add_subplot(111)
        self.canvas  = FigureCanvas(self, -1, self.figure)
        ## This is to avoid showing the plot area. When set to True
        ## clicking the button show the canvas and the canvas covers the button
        ## since the canvas is placed by default in the top left corner of the window
        self.canvas.Show(False)
        self.axes.plot(x, y)
        self.figure.savefig('Figure.png', bbox_inches='tight', facecolor='None')

if __name__ == '__main__':
    app = wx.App()
    win = MyWin('My Frame', (100, 100))
    win.Show()
    app.MainLoop()

Hope this helps.
Comment: This worked great thanks! Although, I now want to show the plot, but I would like it to open in a separate window, is there a way to do this?
Comment: @amme. Yes, it is possible. You could, for example, create a new class for the window showing the plot and create a new instance of the plot window using the onSubmit method. Take it step by step. First, learn how to use the onSubmit method to create a new MyWin instance. Then learn how to use the onSubmit method to create a completely different window using a different class, for example, My2Win. And finally, modify My2Win class to show the plot, basically move all the matplotlib code in onSubmit to the My2Win class.
Comment: The problem of the panel shrinking still occurs when using seaborn e.g. import seaborn as sns, sns.boxplot. The plots also save as blank plots. do you know why this is?
Comment: @amme I have never used the seaborn module. If the answer above solved your original problem you should consider accepting the answer by clicking the checkmark to the left of the answer. Since I have never used the seaborn module and I cannot help you with this, I think you should ask a new question using a short minimal example. You will have a higher probability of getting an answer this way.


existence of the directional derivative of a function

Question: Let
$$f:\mathbb R^2\rightarrow\mathbb R,(x,y)↦\begin{cases}1&(\exists z\in\mathbb R\setminus\{0\}:(x,y)=(z,z ^2)\\0 &(\textrm{else})\end{cases}$$
$f$ is obviously not differentiable in $(0,0)$.
But what about any directional derivative $v$ in $(0,0)$? So I have to consider $\lim_{h\rightarrow0}\frac{f(hv)}h$. But why does this limit always exists?
If $f(hv)=0$ for all $h$ the limit is obviously 0 and also for a finite number of $f(hv)=1$.
In the other case $f(hv)=f(h(v_1,v_2))=1$ for $hv_2=h^2v_1^2\Leftrightarrow v_2=hv_1^2$ and now I am stuck. Does this case exists? And what about the limit of $\frac{f(hv)}h$ ? Wouldn't I get "$\frac10$" ?
Answer: $\lim_{h\rightarrow 0} \frac{f(hv_1,hv_2)}{h}=0$,to prove it we show that for all $\epsilon>0$, there exists $\delta>0$ such that for all $h$ : $0<|0-h|<\delta$ implies $|\frac{f(hv_1,hv_2)}{h}-0|<\epsilon$. Setting $\delta=|\frac{v_2}{2v_1^2}|$ should make it work.
(Thanks for Sheldoor for pointing out a mistake in my previous solution)
Comment: two questions: 1) why do you have a $h'$? 2) how do you get $\delta$? I've tried to estimate the absolute value but didn't get along. And won't we get the problem of $f(-,-)=1$ for the limit?
Comment: @jul8 I was applying the defintion of a limit. As for h' I will write h instead. I did not mean to write it
Comment: okay, I see what you mean. but how did you get $\delta$ ?
Comment: @jul8 Is your question why does this delta work ? or you understand that it works and you want to ask how I got it ?
Comment: both ;) I still have problems with the points $(x,y)=(z,z^2)$ for the limit.
Comment: OK to see that it works verify that for all $\epsilon>0$ for all $h$ : $|0-h|<|\frac{v_2^2}{2v_1}|$ implies $|\frac{f(hv_1,hv_2)}{h}-0|<\epsilon$
Comment: okay, I think I got it that it works for $(x,y)=(z,z^2)$. All other points are obvious since $f=0$ there, e.g. $v=(0,1)$. But how did you find this $\delta$ ? Is there any special trick about it?
Comment: @jul8 OK the only worry is he case when $hv_1=h^2v_2^2$. To make sure this we choose $\delta$ such that $h$ is never equal to $v_2^2/v_1$ (hence $hv_1=h^2v_2^2$ cant be satisfied)
Comment: okay, since $v$ is fixed we "cut the case $f(-,-)=1$ off".
Comment: @Amr doesn't it have t be $|\frac{v_1}{v_2^2}|$ ?
Comment: @Sheldoor Yes you are right. I will edit it
Comment: @Amr I've just thought about it one more time and could it be that the first $\delta$ was correct? I've read all the comments and I think in one of you last comments it has to be $hv_2=h^2v^2_1$, doesn't it? And then the old $\delta$ would fit. Am I wrong?
Comment: @sheldoor I'll check it later.
Comment: did you check it? :)
Comment: @sheldoor I will check it now
Comment: @sheldoor It is true the way it is now.
Comment: thanks but why not the other way around? I thought it's $(x,y)=(t,t^2)$, and so $f(hv)=1$ iff $hv_2=h^2v_1^2$ and so $\delta=|\frac{v_2}{2v_1^2}|$ ? where's my mistake?
Comment: @sheldoor OK. you want to choose $\delta>0$ such that for all $h$ such that $0<|h|<\delta$ we have $f(hv_1,hv_2)=0$. Hence we want $hv_1\not= h^2v_2^2$ ,which is equivalent to making sure that $h\not= \frac{v_1}{v_2^2}$.
Comment: @sheldoor Choosing $\delta$ the way I chose it would make sure that this happens
Comment: right, but I thought it's $hv_2=h^2v_1^2$ for $f(hv)=1$...?
Comment: @sheldoor yes and we want to make sure that f(hv) is not $1$. we make sure by choosing delta that will not allow h to satisfy $hv_1=(hv_2)^2$
Comment: @sheldoor got it now ?
Comment: yes, I get the consequences that but Sorry, I don't understand at the moment why $hv_1=h^2v_2^2$. I think it has to be $hv_2=h^2v_1^2$. (because then $f(hv)=1$ and so we want $hv_2\neq h^2v_1^2$ and so we choose $\delta=|\frac{v_2}{2v_1^2}|$ That's the way I am thinking.)
Comment: @sheldoor OK. $f(x,y)=1$ iff $\exists z [x=z,y=z^2]$. This is equivalent to saying $y=x^2$. Thus we want to make sure $hv_2\not=h^2v_1^2$. OK you are right !
Comment: yes, that's what I've meant. Sorry for the complications ;)
Comment: @sheldoor I edited it.


Crystal report ModuleNames dispalyed horizontally

Question: I have data set with following columns
1. PRN
2. Name
3. Module name
4. Theory Marks
5. Total Marks
this data set is field with different modules of same course and data is comes from database
I have given this data set data to crystal report as data source
I want to display TheoryMarks and totalMarks under ModuleName in below format
<code>       ModuleName1              ModuleName2              ModuleName3
</code>
PRN Name Theory Marks TotalMarks   Theory Marks TotalMarks
I have tried group column using Module Name .I have also tried CrossTab Expert but its not allowing me to add theory marks and total marks
string reportPath;
    string pathText = "PGCourseResultCrystalreport";
<code>string path = "PGCourseResult.rpt";

if (pathText == "PGCourseResultCrystalreport")
{

    reportPath = Server.HtmlEncode(Request.PhysicalApplicationPath).ToString() + "MemberArea\\ResultReport\\" + path;
    rptDoc.Load(reportPath);
    error.Text += "reportdocloaded";
    //DataTable Resut = GetResultData();

    try
    {

        string query = "select P.PRN, P.[StudentName] ,P.TheoryMarks,L.TotalMarks,L.ModuleName from   [PGCoursesTheoryMarksMaster]  P,[ModulewiseLabInternalMarks] L  where L.PRN=P.PRN and P.Centre_ID=L.CentreId and P.Course_ID=L.Course_ID and P.Module_ID=L.Module_ID and P.Batch_ID=L.Batch_ID and P.Centre_ID=@centreId and P.Course_ID=@courseId   and P.Batch_ID=@batchId ";
        SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["aoldbConnectionString"].ConnectionString);

        string centreID = DDLCentreList.SelectedValue;
        //   string BatchID = BatchIdDropDown.SelectedValue;
        int  CourseId =  Convert.ToInt32( DropDownListCourse.SelectedValue);
        SqlCommand cmd = new SqlCommand(query, con);
        cmd.Parameters.AddWithValue("@CentreId", Convert.ToInt32(centreID));
        cmd.Parameters.AddWithValue("@courseId", CourseId);
        cmd.Parameters.AddWithValue("@batchId", batchId);
        if (con.State == ConnectionState.Open)
        {
            con.Close();
        }
        con.Open();
        using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
        {
            sda.Fill(CourseMarks, "MainResultData");
            foreach (DataRow row in CourseMarks.Tables[0].Rows)
            {
                error.Text += row["PRN"].ToString();
            }
</code>
I want to display result as explained .
Answer: CrossTab is the right approach.
Let the CrossTab do the totals.
In other words, instead of trying to select totals as the CrossTab values, select the detail data and let the CrossTab do the averaging, summing, etc.
Comment: Thanks for reply .I used cross tab formatting but borders appears to only those columns which have data .It does not look good.I want excel sheet like normal excel sheet where all rows and columns present .Please reply if you know settings or code


Ubuntu 18.04: vue command not found

Question: When I run:
vue --version

I get this error message:
Command 'vue' not found, did you mean:

  command 'vpe' from deb texlive-latex-extra

Try: sudo apt install <deb name>

Notes:
npm config get prefix
/home/begueradj/.nvm/versions/node/v12.8.0

and:
npm list vue
/home/begueradj
└── firstname.lastname@example.com

I previously run:
yarn global add @vue/cli
yarn global add @vue/cli-service-global

How to fix this ?
For the moment, when I add this to ~/.profile
export PATH="$(yarn global bin):$PATH"

and run: source ~/.profile
The issue is solved ... but only for the current Terminal session (I had to run source .profile each time I open a new Terminal session)
Answer: Here is the solution I found:
I had to add permanently the variable mentioned indirectly above (.yarn/bin) to /etc/environment:
:/.yarn/bin
I then restarted my laptop and got it work:
Answer: On ubuntu 22, I fixed the issue as shown below.
Check yarn global bin path using yarn global bin
this should show an output similar to
/home/username/.yarn/bin
Add this export command to your ~/.profile
export PATH="$PATH:`yarn global bin`"

Reload the profile using
source ~/.profile

Finally
vue --version

Comment: I did not try it, but makes sense to me. Useful feedback. Thank you.

Ubuntu 18.04: vue command not found


Advanced triangle inequality

Question: This problem came up in a series of Taylor series exercises and I have no idea where the correlation could be.
Let $a \in (0,1)$ and $u,v \in \mathbb{R}_{+}$, prove
$$ (u+v)^{a} \leq u^{a}+v^{a} $$
I have tried several things. The Binomial theorem is not applicable since the exponent is rational. I tried rewriting $a=1/x$ where $x \in {x \in \mathbb{N}\ \{0,1\}}$
so we get:
$$ (u+v)^{1/x} \leq u^{1/x}+v^{1/x} $$ which just makes it clearer that it is about roots but doesn't do much to solve it. Tricks like using the third binomial theorem are also not applicable as well, as they only work for square roots. I tried shifting around the terms a little bit, but it doesn't seem to do much.
I'm thinking, I'm supposed do something more "profound" than an elementary proof, but I have nowhere to start. I'd appreciate a hint on where to go from here
What I did in the exercise before( maybe it's relevant) : I showed for example, that $f_{a}:(-1,1)\rightarrow \mathbb{R}, x \mapsto (1+x)^{a}$ can be approximated at $x_0=0$ with the taylor series and that they are equal at that point.
Comment: Divide by $(u+v)^a$.
Answer: For $0<\alpha<1$ and $\dfrac12<x<1$, Let
$$f(x)=x^\alpha+(1-x)^\alpha$$
then $f'(x)=\alpha\big(x^{\alpha-1}-(1-x)^{\alpha-1}\big)>0$ that shows $f(x)<f(1)$ or
$$x^\alpha+(1-x)^\alpha\geq1$$
with $p>0$ and $q>0$ with $p+q=1$ then $$p^\alpha+q^\alpha\geq1$$
let $p=\dfrac{u}{u+v}$ and $q=\dfrac{v}{u+v}$ so $p+q=1$ and
$$(\dfrac{u}{u+v})^\alpha+(\dfrac{u}{u+v})^\alpha\geq1$$
then
$$(u+v)^\alpha\leq u^\alpha+v^\alpha$$
Comment: "For $x>\frac12$", we can't use something like $f(x)>f(0)$, which is beyond the specified domain.
Comment: @SimpleArt Thanks.
Answer: The fact follows from basic properties of exponentiation. Recall that if $0<A<1$, $0<B<1$ then
$$A<A^B$$
(for instance $0.25<\sqrt{0.25}=.5$).
With this in mind,
$$1=\frac{u}{u+v}+\frac{v}{u+v}\le \left (\frac{u}{u+v}\right )^a+\left (\frac{v}{u+v}\right )^a=\frac{u^a+v^a}{(u+v)^a}$$
which is equivalent to our claim.

Advanced triangle inequality


How are CS:GO eSport competitive leagues typically structured?

Question: I have a fairly firm grasp on how League of Legends eSport leagues work with the LCS, LPL, and OPL leagues culminating in a world championship. The Overwatch league is also quite similar. After recently attending the IEM Sydney event I'm not entirely clear on how CS:GO's eSports scene functions. Is there a common league, or is it more of an invitational circuit for players to grow their identity on an individual level?
Some guidance in this would be extremely appreciated.
Comment: Something like [this](http://liquipedia.net/counterstrike/Majors)? Or what exactly are you looking for? Listing a complete tournament structure would be pretty broad.
Answer: LoL and OW leagues are built pretty much like hockey and basketball.
You have a regular season, that feeds into playoffs, that crown a champion. Then sometimes those champions will go into a tournament of champions (like MSI for LoL)
In CSGO, it works more like Tennis. You have a few leagues that run like LCS and OWL, where theres a season and then playoffs; but most events are a 1-2 weekend tournament. Teams are set into groups, and then it feeds in a playoff tree and then it crowns a champion; but when that event is over, nothing really carries into the next one. You get a prize purse; and that's pretty much it. You might be making a name for yourself to get directly invited to other events and dont have to go through qualifiers, but you dont get points on a ladder or anything.
So:

LCS and OWL run like hockey, where teams are stuck in that league and won't be playing in other leagues with the same lineup (like if the Vegas Knights would be to play in the KHL, that would be weird.)
CSGO (and afaik, DOTA) leagues run more like Tennis, where you have things like the Masters, Winbeldon and the Rogers Cup. All tournaments where about the same players will play, but they are at most loosely related to eachother.

For CSGO, you might want to take a look at Majors, the tournaments that are maybe twice a year and they are the big one, that no team in their right mind will sit out.
Answer: Starting after the Boston major event in 2018, CSGO has majors, challengers stage, and minors. The top 8 teams from the last major are automatically invited to the next major. The bottom 8 teams from the last major drop to challenger status. The top two teams from minor events are also invited to the challenger stage. The challenger stage teams ultimately compete to see who will secure spots in the next major.
These events are hosted by various tournament organizers. Valve typical requests proposal from the usual organizers (ESL, MLG, FaceIt, ELeague, etc.) and selects one or more tournament operators to run these events.


Intel 8086, infinite loop

Question: I am trying to code a little application where a random number between 1-5 is generated using the system clock and the user has to guess the number and a message is displayed if the guess is correct.
Here is my code so far:
org 0x100

;Guess:
        MOV AH,2CH  ;DOS CALL TO GET SYSTEM CLOCK
        INT 21H     ;EXECUTE INTERRUPT 21H
        MOV AL,DL   ;RESULT RETURNED IN DL
        MOV AH,0    ;CLEAR THE HIGH BYTE
        MOV CL,20   ;GET DIVISOR
        DIV CL      ;DIVIDE VALUE IN AX BY VALUE IN CL
        MOV BL,AL   ;MOVE RESULT OF DIVISION INTO BL
        INC BL      ;INCREMENT BL TO GET NO BETWEEN 1-5

;Prompt:
        JMP START
        MSG DB "Enter a number between 1-5:$"

        START:

        MOV DX, OFFSET MSG
        MOV AH, 09h
        INT 21h

;User input:

        MOV AH, 1h  ;GET INPUT FROM THE KEYBOARD
        INT 21h     ;THE CHARACTER INPUT IS STORED IN AL

;The Comparison:

        ;MOV AX,AL   ;LOAD VALUE OF AL (USER INPUT)
        CMP AL,BL   ;COMPARE WITH BL

        JE Equal    ;IF EQUAL JUMP TO Equal
        JNE Not_Equal;IF NOT EQUAL JUMP TO Not_Equal

        Equal:

        ABC DB "Your guess was correct!$"
        MOV DX, OFFSET ABC
        MOV AH, 09h
        INT 21h

        Not_Equal:

        DEF DB "Your guess was incorrect!$"
        MOV DX, OFFSET DEF
        MOV AH, 09h
        INT 21h

My problem is that it just goes into an infinite loop.
Comment: You're looking for a conditional jump. `je`, `jz`, `jg` etc.
Comment: JE Equal    ;IF EQUAL JUMP TO Equal
    JNE Not_Equal;IF NOT EQUAL JUMP TO Not_Equal
Answer: You've got a few different problems in your code:
You can't mix code and data like this:
    ABC DB "Your guess was correct!$"
    MOV DX, OFFSET ABC

The CPU can't tell the difference between code and data and will try to execute whatever it encounters. Move the result strings to the same place where you've got the MSG string.

You're comparing numeric values with their corresponding ASCII characters:
    MOV AH, 1h  ;GET INPUT FROM THE KEYBOARD
    INT 21h     ;THE CHARACTER INPUT IS STORED IN AL

If you enter the digit 2 in the terminal you'd get the character '2' (which is equal to 50) in AL. To successfully compare that against what you've got in BL you have to subtract '0' from AL.

You'll always print the "Your guess was incorrect" string. After the code that prints the "Your guess was correct" string there's no jump to skip the next print:
    ABC DB "Your guess was correct!$"
    MOV DX, OFFSET ABC
    MOV AH, 09h
    INT 21h

    ; Execution will simply continue here since there's nothing that changes the
    ; flow of execution.

    Not_Equal:

You're not terminating the program properly. At the end of your program you should add something like:
MOV AX,4C00h
INT 21h    ; Terminate with exit code 00h

Intel 8086, infinite loop


Wiring new light fixture to 2-wire ceiling rose

Question: Any word of wisdom greatly appreciated. Wanted to install a new light in the living room and unexpectedly (for amateur as myself) i see 2 sets of wires in the ceiling rose i.e 2x L/N/E.
The room has 2 sets of lights, both will turn on/ off with a single switch, both on the same circuit. After some research and browsing through diagrams, i believe the wires i see suggest it's end of the loop wiring?
New light fixture has got only place for one set of L|N|E and not sure how to go about this now.
Yes i know. It Would be decent if i've done a picture of how the wires looked like connected initially… realised that a bit too late.
Answer: You're going to need to connect the two blue wires together with an additional piece of blue wire, the two brown together with an additional piece of brown wire and the same for the yellow/green. Use approved connectors, I don't think wire nuts are allowed. Then connect the single wire pieces to the light fixture. You should install a junction box there and not just screw the fixture into the wall.
Comment: It is yellow shrink tube, with a green stripe. That's on the list of legal ground colors even in North America. Also, the documentation with the new lamp, which was of course legitimate product acquired by a proper vendor and not straight-from-China, will say whether the terminals can support 2 wires.
Comment: @Ecnerwal  Thanks. Just zoomed in and saw the green. I thought it was a yellow shrink tube.


how to Populate fields from URL parameter in java Springboot

Question: I need to add support for passing field values to a form via a URL parameter when viewing a form which will be used to populate values into the form when it loads.  should support a JSON formatted value of field names and values.  Example:
https://web/form/view?id=1&data={'fieldname':'value'}

    @RequestMapping(value = "/form/view", method = RequestMethod.GET)
    public ModelAndView viewDomainForm(HttpSession session, @ModelAttribute("command") FormBean inFormBean) {

        Form form = formService.getForm(inFormBean.getId());

        FormInstance formInstance = formInstanceService.createFormInstance(form);

        String formInstanceId = (String) session.getAttribute("formInstanceId");
        if (formInstanceId != null && formInstanceId.length() > 0) {
            formInstanceService.deleteFormInstanceById(formInstanceId);
        }
        formInstanceId = formInstance.getId();
        session.setAttribute("formInstanceId", formInstanceId);

        FormBean formBean = prepareFormBean(form);
        formBean.setEmbed(inFormBean.isEmbed());
        formBean.setFormInstanceId(formInstance.getId());

        Map<String, Object> model = new HashMap<String, Object>();
        model.put("externalBaseUrl", configurationService.getValue("core.external.url.base"));
        model.put("fromTaskList", false);
        model.put("form", formBean);
        model.put("flow", new FlowBean());
        model.put("task", new TaskBean());
        return new ModelAndView("form-viewer", model);
    }

I have this method for viewing. what would be the best way to Populate fields from URL parameter?
 public String getData() {
        return data;
    }

    public void setData(String data) {
        this.data = data;
    }

// this is the value that will populate into the form when it loads.

Answer: First question, why not use POST with the JSON in the request body?
If the JSON will be large, then you will run in a URL limitation problem. And you have to encode your URL with % and different delimiters which will make it even less debuggable.
But it is doable.
Let's say that you correctly encoded your URL and the JSON is as a query param.
What you could do is receive it and either traverse it and create/populate your form or map it to an object and use that:
public ModelAndView viewDomainForm(... @RequestParam("data") String jsonDataInUrl...)
{
   // Work with jsonDataInUrl either through parsing it or through transforming it into a java bean.
   ...
}

Here is a URL decoder/encoder in case you need it.


JCombobox focusLost is not firing-why is that?

Question: I have a JCombobox in my code. I have added the FocusLost event. But it didn't fired anyway. I have tried lots of time but didn't find solution.
jcbItemType.addFocusListener(new java.awt.event.FocusAdapter() {
    public void focusLost(java.awt.event.FocusEvent evt) {
        jcbItemTypeFocusLost(evt);
    }
});

private void jcbItemTypeFocusLost(java.awt.event.FocusEvent evt)
    {
        // TODO add your handling code here:
        System.out.println("name=" + ((Component) evt.getSource()).getName());
        System.out.println("index=" + jcbItemType.getSelectedIndex());
    }

But nothing is printed in console. Please suggest me what I am doing wrong.
Answer: I have found a very simple way to solve this.
The JComboBox default editor has an internal class BasicComboBoxEditor$BorderlessTextField that is the component that gets and loses focus.
It can be accessed simply by
Component component = comboBox.getEditor().getEditorComponent();
if (component instanceof JTextField)
    JTextField borderlesstextfield = (JTextField) borderless;

Then add a focus listener like you would to any JTextField
borderlesstextfield.addFocusListener(new FocusListener()
{
   public void focusGained(FocusEvent e)
     {
     }
   public void focusLost(FocusEvent e)
     {
     }
}});

Now you have a FocusListener that will respond as expected to gain and loss of focus for the ComboBox
Comment: This worked perfectly and should be the accepted answer since it is far less convoluted!
Comment: I agree with @Xerus this answer is way more understandable and deserves to be the accepted answer
Answer:
FocusListener isn't proper Listener for JComboBox, altogether with another Listener(s) can creating endless loop (especially Editable JComboBox),
FocusListener is asynchronous, sometimes is too hard to catch events is right orders especially in the cases that JComponents has added another Listener(s) too

example how to listening for Focus from derived JTextField / JFormattedTextField
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class ComboBoxTwo extends JFrame implements ItemListener {

    private static final long serialVersionUID = 1L;
    private JComboBox mainComboBox;
    private JComboBox subComboBox;

    public ComboBoxTwo() {
        String[] items = {"Select Item", "Color", "Shape", "Fruit"};
        String[] subItems1 = {"Select Color", "Red", "Blue", "Green"};
        mainComboBox = new JComboBox(items);
        mainComboBox.addItemListener(this);
        mainComboBox.addFocusListener(fcsListener);
        add(mainComboBox, BorderLayout.WEST);
        subComboBox = new JComboBox(subItems1);
        subComboBox.setPrototypeDisplayValue("XXXXXXXXXXXXXXXXXXX");
        subComboBox.addItemListener(this);
        add(subComboBox, BorderLayout.EAST);
    }

    @Override
    public void itemStateChanged(ItemEvent e) {
        if (e.getStateChange() == ItemEvent.SELECTED) {
            if (e.getSource() == mainComboBox) {
                System.out.println("Source  : mainComboBox");
            } else if (e.getSource() == subComboBox) {
                System.out.println("Source  : subComboBox");
            }
        }
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                JFrame frame = new ComboBoxTwo();
                frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }
//
    private FocusListener fcsListener = new FocusListener() {

        @Override
        public void focusGained(FocusEvent e) {
            dumpInfo(e);
        }

        @Override
        public void focusLost(FocusEvent e) {
            dumpInfo(e);
        }

        private void dumpInfo(FocusEvent e) {
            System.out.println("Source  : " + name(e.getComponent()));
            System.out.println("Opposite : " + name(e.getOppositeComponent()));
            System.out.println("Temporary: " + e.isTemporary());
            final Component c = e.getComponent();//works for editable JComboBox too
            if (c instanceof JFormattedTextField) {
                SwingUtilities.invokeLater(new Runnable() {

                    @Override
                    public void run() {
                        ((JFormattedTextField) c).selectAll();
                    }
                });
            } else if (c instanceof JTextField) {
                SwingUtilities.invokeLater(new Runnable() {

                    @Override
                    public void run() {
                        ((JTextField) c).selectAll();
                    }
                });
            }
        }

        private String name(Component c) {
            return (c == null) ? null : c.getName();
        }
    };
}

Comment: I have previously used `itemStateChanged` but it is problematic for my purpose and hence i want to use FocusLost event. Your example didn't work for me although you have comment as *//works for editable JComboBox too*. But it isn't working for me. Please advise. I am searching it for long time.
Comment: @sarwar026 in this form works as I expected, rest is noticed in my answer, use ItemListener for JComboBox, for example in the form as I posted here,
Comment: @sarwar026 simple I don't understood for why reason you have to required FocusListener, for better help sooner edit your question with a [SSCCE](http://sscce.org/)