text:
Q: How do you load a saved game in FFVI So, I finally started playing Final Fantasy 6 (well, Final Fantasy 3 technically) and I'm really enjoying it. Except, now I've saved my game after a few hours of play, but when I (yes, you guessed it) restart my emulator and start the game, I'm given no option to load my game.
This is sort of debugging stuff. I'm trying to figure out if my EMU (ZSnes for Windows) corrupted the save, or if I'm just missing how you load the game. When I start it, I get the FF3 splash screen, I hit A, and I immediately get a new game fired up. Not ideal
During my first session, when I'd reach save points, it would show my already-saved game. When I'd die (which happened a few times), it would load my game successfully.
So idk what went south. If you have any ideas on the grand issue, I'm happy to hear them. Otherwise, simply, how do you load a game on FFVI?

A: It appears that the answer to my question is:
Once the game loads the splash screen, and then starts an (apparently) unskippable video where Terra and the two soldier guys chat on the cliffside, and then walk while more credits roll, after that the game will show you the load screen.
Man that's a terrible place for a load screen. I guess my Emulator was working correctly all along; I just didn't realize that FF3 would put a load screen so freakin deep into the game (it would be like a 5 minute wait if it weren't for the fast-forward button on my Emulator).
EDIT:
Jeez. I must not have been thinking too hard yesterday. As the comments indicated, YES, you can skip that intro video (default: 'x' in ZSNES).
Anyway, thanks for the help guys.


text:
Q: What is the difference between "rethink" and "think again"? I find that many people use:

Please think again.

But there is already the word rethink, so why do they use think again?

A: Telling someone to think again is stronger, and it implies that you know something they don't, or they've overlooked something crucial that invalidates their conclusions. Telling them to rethink merely expresses that you're not entirely happy with their conclusion, for whatever reason.
From Merriam Webseter online I get

Definition of think again
informal —used to say that what someone
believes, expects, etc., is not true or will not happen
eg. If you think you can get away with this, think again.
Definition of rethink
transitive verb
: to think about again : reconsider

'Think Again" carries the certainty that the other person is wrong, whereas 'please rethink' is simply a request that they reconsider.
As an aside, I would have thought saying "please think again" is an odd construction, with the deference of the 'please' sitting rather awkwardly beside the swagger of the 'think again'

A: As has already been pointed out in the answer from @bugcatchernakata, the two words can have different meanings, but I'd like to answer the question in a different way. In cases where the two have the same meaning, I would turn the question around:

But there is already think again, so why do they use rethink?

I do that, because 'think again' is the simple long-established English way of expressing the idea. Although the OED gives c.1700 as the date for the first recorded use of 'rethink', a Google ngram shows negligible use before the twentieth century. So I would say it is the more natural way for a native English speaker to talk, especially ordinary people.
Another point that can be made is the didactic quality of 'think again'. The two words give more emphasis. To take an example from a (relatively modern) patriotic song, much loved by Scots (not me) at sporting occasions:

And sent him homeward,
To think again.

Now try that with 'rethink'.
And, in general, I suspect that constructions with with 're-' are later and more Latinate than a traditional everyday use of the Anglo-Saxon 'again'. Although Humphrey Bogart never said:

"Play it again, Sam."

he most certainly would never have thought of saying:

"Replay it, Sam."

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to get the LineNumber of the opening tag given the LineNumber of the closing tag Given this sample xml node,
<employee id="emp_1">
    <fname>John</fname>
    <lname>Doe</lname>
</employee>
<supervisor>
    <fname>Jane</fname>
    <lname>Does</lname>
</supervisor>

i can use the two given variables:
lineNumber = 4;
colNumber = 12;

if i would locate the position, it will be right after the closing tag,
"</employee>"

is it possible to get/return the lineNumber of the corresponding opening tag of employee node?
please help.
Thanks

A: this might not be the best way but after giving it much thought, i just decided to get the nextline which will give me the nextnode. then using the nextnode, i got the previous sibling.
//...previous codes
lineNumber++;
var nextSibling = xElements.Where(elem => ((IXmlLineInfo)elem).LineNumber == lineNumber &&
                                           ((IXmlLineInfo)elem).LinePosition <= columnNumber).LastOrDefault();

var selectedNode = nextSibling.PreviousNode;
if (((IXmlLineInfo)selectedNode).HasLineInfo())
{
    lineNumber = ((IXmlLineInfo)selectedNode).LineNumber;
    columnNumber = ((IXmlLineInfo)selectedNode).LinePosition;
}

now the lineNumber will be the lineNumber for the opening tag of employee node

A: You can leverage XNode.CreateReader to re-parse current XElement. It requires more resource but does work.
foreach (XElement e in elements)
{
    using (var reader = e.CreateReader())
    {
        var lineInfo = ((IXmlLineInfo)reader);
        while (reader.Read())
        {
            if (reader.NodeType == XmlNodeType.EndElement && reader.Depth == 0)
            {
                Console.WriteLine($"{e.Name}"
                    + $" - Open({((IXmlLineInfo)e).LineNumber},{((IXmlLineInfo)e).LinePosition})"
                    + $" Close({lineInfo.LineNumber},{lineInfo.LinePosition})");
            }
        }
    }
}

LinePosition is tag start position. You can calculate end position by + tag name length.


text:
Q: Interfaces not matching in Fortran 90 I am having a hard time understanding Fortran interfaces. The test code code pasted at the end of the question compiles just fine on ifort <=version 15, but causes a catastrophic compiler error on versions 16 and later. Same on gfortran (seg fault while compiling). On g95, however, compilation ends with the following error
In file test.f90:79

 call rk4(y, dydx, x, h, yout1, der, pars,*10)
                                1
Error: Interface of actual procedure does not match interface of dummy procedure at (1)
In file test.f90:81

 call rk4(y, dydx, x, h/2.d0, yout2, der, pars,*10)
                                     1
Error: Interface of actual procedure does not match interface of dummy procedure at (1)
In file test.f90:85

 call rk4(yout2, dydx2, x+h/2.d0, h/2.d0, yout2, der, pars,*10)
                                                 1
Error: Interface of actual procedure does not match interface of dummy procedure at (1)

but I am not sure what I am doing wrong...
module RK

implicit none

contains

SUBROUTINE rk4(y, dydx, x, h, yout, der, pars, *)
IMPLICIT NONE
integer, parameter :: dp=kind(1.d0)
REAL(dp), DIMENSION(:), INTENT(IN) :: y,dydx,pars
REAL(dp), INTENT(IN) :: x,h
REAL(dp), DIMENSION(:), INTENT(OUT) :: yout
REAL(dp) :: h6,hh,xh
REAL(dp), DIMENSION(size(y)) :: dym,dyt,yt

INTERFACE
SUBROUTINE der(x,y,dydx,pars,*)
IMPLICIT NONE
integer, parameter :: dp=kind(1.d0)
REAL(dp), INTENT(IN) :: x
REAL(dp), DIMENSION(:), INTENT(IN) ::  pars
REAL(dp), DIMENSION(:), INTENT(IN) :: y
REAL(dp), DIMENSION(:), INTENT(OUT) :: dydx
END SUBROUTINE der
END INTERFACE

hh = h*0.5d0
h6 = h/6.d0
xh = x + hh

yt(:)=y(:)+hh*dydx(:)

call der(xh, yt, dyt, pars,*10)

yt(:)=y(:)+hh*dyt(:)

call der(xh, yt, dym, pars,*10)

yt(:)=y(:)+h*dym(:)

dym(:)=dyt(:)+dym(:)

call der(x+h, yt, dyt, pars,*10)

yout(:)=y(:)+h6*(dydx(:)+dyt(:)+2.d0*dym(:))

return
10 return 1

end subroutine

subroutine adaptive_RK4(y,dydx,x,h,yout2,yerr,der,pars,*)
implicit none
integer, parameter :: dp=kind(1.d0)
REAL (dp) :: h, x
REAL (dp), DIMENSION (:) ::  y, dydx, yout2, yerr, pars
REAL (dp), DIMENSION (size(y)) :: dydx2, yout1
intent(in) :: y, dydx, x, h, pars
intent(out) :: yout2, yerr
INTERFACE
SUBROUTINE der(x,y,dydx,pars,*)
IMPLICIT NONE
integer, parameter :: dp=kind(1.d0)
REAL(dp), INTENT(IN) :: x
REAL(dp), DIMENSION(:), INTENT(IN) :: pars
REAL(dp), DIMENSION(:), INTENT(IN) :: y
REAL(dp), DIMENSION(:), INTENT(OUT) :: dydx
END SUBROUTINE der
END INTERFACE

call rk4(y, dydx, x, h, yout1, der, pars,*10)

call rk4(y, dydx, x, h/2.d0, yout2, der, pars,*10)

call der(x+h/2.d0, yout2, dydx2, pars,*10)

call rk4(yout2, dydx2, x+h/2.d0, h/2.d0, yout2, der, pars,*10)

yerr(:)=yout2(:)-yout1(:)

yout2(:)=(16.d0*yout2(:)-yout1(:))/15.d0

return

10 return 1

end subroutine

end module

module derivative
implicit none
contains
    SUBROUTINE derr(x,y,dydx,pars,*)
    IMPLICIT NONE
integer, parameter :: dp=kind(1.d0)
    REAL(dp), INTENT(IN) :: x
    REAL(dp), DIMENSION(:), INTENT(IN) :: pars
    REAL(dp), DIMENSION(:), INTENT(IN) :: y
    REAL(dp), DIMENSION(:), INTENT(OUT) :: dydx

dydx=(pars+y)*x
return

END SUBROUTINE derr

end module

program test
use rk
use derivative
implicit none
integer, parameter :: dp=kind(1.d0)
real(dp), dimension(2) :: y,pars,dydx, yout, yerr
real(dp) :: x

y=(/0.1d0,2.d0/)
pars=(/0.7d0,3.d0/)
x=2.1d0

call derr(x,y,dydx,pars,*10)

write(*,*) dydx
call adaptive_RK4(y,dydx,x,0.0001d0,yout,yerr,derr,pars,*10)

stop
10 write(*,*) "some error"

end program

A: The code runs fine in gfortran version 6 and 7.
Gfortran version 4.8 crashes, but that is the compiler's problem. A compiler should never crash, even if the code is bad.
The same holds for Intel Fortran. If it crashes during compilation it is the compiler's fault.
Now, the code is really not great and uses features which may be difficult for the compiler. When it comes to things against standards, gfortran 6 complains of:
interface2.f90:81:9:

 call rk4(yout2, dydx2, x+h/2.d0, h/2.d0, yout2, der, pars,*10)
         1
Warning: Same actual argument associated with INTENT(IN) argument 'y' and INTENT(OUT) argument 'yout' at (1)

It is not allowed in Fortran to pass the same variable in to arguments in this way. The compiler will assume that the intent(in) argument never changes, but it does change when you modify yout. This can cause serious problems.
For the G95 compile time error, I think the compiler is wrong and the error message is bogus. The interface blocks in rk4 and adaptive_rk4 are exactly the same.
I strongly advise you to clean-up the code, get rid of the alternate exit feature and it will be much easier for the compilers to compile the code. I expect it is due to your excessive use of the alternate return feature which is not tested too much.

For your next questions, definitely read [mcve] very carefully. It is necessary to make your code much shorter for your future questions. THIS is the actual MCVE you should ask about and which can be used as a base for a bug report:
module m

  implicit none

contains

  subroutine a(d)
    interface
      subroutine d(*)
      end subroutine d
    end interface

    10 return 1
  end subroutine

  subroutine b(d)
    interface
      subroutine d(*)
      end subroutine d
    end interface

    call a(d)
  end subroutine
end module

Compare it with the very long code you gave us. This can't really be reduced any more without the compiler crash disappearing (both ifort 17 and gcc 4.8). The problem is clearly in the dummy procedure (even though it is not actually called anywhere), which uses the alternate return feature and the compiler cannot treat it properly.

A: I replaced the alternate returns from the instances of DERR / DER and then the compilation worked in Intel Fortran (XE 2017).
I also agree that it's advisable to (1) clean the code up and (2) avoid the use of alternate returns.


text:
Q: An isomorphism $f:G_1 \to G_2$ maps the identity of $G_1$ to the identity of $G_2$ Here is my attempted proof:
Suppose $e_1$ is the identity of $G_1$ and likewise $e_2$ is the identity of $G_2$. Then we have to show $f(e_1)=e_2$.
Since $f$ is an isomorphism, $f$ is bijective and hence surjective. Therefore, $f(x)=e_2$ for some $x\in G_1$.
Also, $f(x\cdot e_1)=e_2$. This implies $f(x)f(e_1)=e_2$. Also the product of $f(x)$ and $f(e_1)$ gives the identity, hence they must be inverses of each other, i.e. $f(e_1)=f(x)^{-1}$. But $f(x)=e_2$ and hence $f(e_1)=e_{2}^{-1}=e_2$.
Is my proof correct? Are there any alternative ways?

A: Your proof is correct, but you are explicitly using surjectivity. You don't actually need this, but instead all you need is for the map $f$ to be a homomorphism (so not necessarily a surjective or injective):

If $f: G_1\rightarrow G_2$ is a group homomorphism then $f(e_1)=e_2$.

Proof. Write $g:=f(e_1)$. Then $g^2=f(e_1)^2=f(e_1^2)=f(e_1)=g$. That is, $g^2=g$. Then:
$$\begin{align*}
g^2&=g\\
\Rightarrow
g^2\cdot g^{-1}&=g\cdot g^{-1}\\
\Rightarrow
g&=e_2
\end{align*}$$
Therefore, $f(e_1)=e_2$ as required.


text:
Q: Kivy multiple screen management I'm fairly new to Kivy ( been learning it two days ago) I was working on a basic calculator but came across a hurdle I couldn't jump over.
I would like to create multiple screens because I intend to add more to my calculator as I'm further learning Kivy & I don't know how to adjust ScreenManager in my code.
This is my .py file
import kivy

kivy.require('1.11.0')
from kivy.app import App
from kivy.uix.gridlayout import GridLayout
from kivy.uix.pagelayout import PageLayout
from kivy.core.window import Window

Window.clearcolor = .3,.3,.3,1

class RootWidget(GridLayout):
    def calculate(self, calculation):
        if calculation:
            try:
                self.display.text = str(eval(calculation))
            except Exception:
            self.display.text = "Error"
class kutuApp(App):
    def build(self):
        return RootWidget()
if __name__== '__main__':
    kutuApp().run()

And this is my .kv file
<CustButton@Button>:
    font_size: 35
    background_color: 0,0,0,0
    canvas.before:
        Color:
            rgba: (.4, .4, .4, 1) if self.state=='normal' else (0,.7,.7,1)
        RoundedRectangle:
            pos: self.pos
            size: self.size
            radius: [20, ]

<RawLayout@BoxLayout>:
     spacing: 8
     padding: 8
      size_hint: [1, .2]

<RootWidget>:
       id: calculator
      rows: 10
       display: entry
       spacing: 1

BoxLayout:
    size_hint: [1, .1]
    Label:
        text: 'Basic Calculator'
    Label:
        text: 'Made by Xrew'

BoxLayout:
    padding: 10
    TextInput:
        id: entry
        spacing: 1
        padding: 5
        font_size: 32
        multiline: True
        focus: False
#       background_color: 0, 0, 0, 1
#       foreground_color: [1, 0, 1, 1]

RawLayout:
    CustButton:
        text: '<'
        on_press: entry.text += self.text
    CustButton:
        text: '>'
        on_press: entry.text += self.text
    CustButton:
        text: '≈'
        on_press: entry.text += '=='

RawLayout:
    orientation: 'horizontal'
    CustButton:
        text: '('
        on_press: entry.text += '('
    CustButton:
        text: ')'
        on_press: entry.text += ')'
    CustButton:
        text: '√'
        on_press: entry.text += '**(.5)'
    CustButton:
        text: '¹/x'
        on_press: entry.text += '1/'
RawLayout:
    orientation: 'horizontal'
    CustButton:
        text: 'Del'
        on_press: entry.text = entry.text[:-1]
    CustButton:
        text: 'x²'
        on_press: entry.text += '**2'
    CustButton:
        text: 'xⁿ'
        on_press: entry.text += '**'
    CustButton:
        text: 'π'
        on_press: entry.text += '3.14'

RawLayout:
    orientation: 'horizontal'
    cols: 4
    CustButton:
        text: 'Clr'
        font_color: [255,0,0,1]
 #       background_normal: ' '
    #    background_color: 1, .3, .4, .85
        on_press: entry.text = ""
    CustButton:
        text: '+'
        on_press: entry.text += self.text
        font_size: 32
    CustButton:
        text: '÷'
        on_press: entry.text += '/'
    CustButton:
        text: '×'
        on_press: entry.text += '*'

RawLayout:
    rows: 1
    orientation: 'horizontal'
    CustButton:
        text: '7'
        on_press: entry.text += self.text
    CustButton:
        text: '8'
        on_press: entry.text += self.text
    CustButton:
        text: '9'
        on_press: entry.text += self.text
    CustButton:
        text: '-'
        on_press: entry.text += self.text

RawLayout:
    orientation: 'horizontal'
    rows: 1
    CustButton:
        text: '4'
        on_press: entry.text += self.text
    CustButton:
        text: '5'
        on_press: entry.text += self.text
    CustButton:
        text: '6'
        on_press: entry.text += self.text
    CustButton:
        text: '+'
        on_press: entry.text += self.text

RawLayout:
    orientation: 'horizontal'
    cols: 3
    CustButton:
        text: '1'
        size_hint: [.5, 1]
        on_press: entry.text += self.text
    CustButton:
        text: '2'
        size_hint: [.5, 1]
        on_press: entry.text += self.text
    CustButton:
        text: '3'
        size_hint: [.5, 1]
        on_press: entry.text += self.text
    CustButton:
        text: ' '
        size_hint: [.5, 1]
        background_normal: ' '
        background_color: 0, 0, 0, 0

RawLayout:
    orientation: 'horizontal'
    size_hint: [1, .2]
    CustButton:
        text: '0'
        on_press: entry.text += self.text
        size_hint: [.34, 1]
    CustButton:
        text: '.'
        on_press: entry.text += self.text
        size_hint: [.17, 1]
        font_size: 32
    CustButton:
        text: '='
        on_press: calculator.calculate(entry.text)
        size_hint: [.17, 2.4]
#       background_normal: ' '
    #   background_color:  0, .5, 95, 1

A: Kivy ScreenManager
The following steps illustrates how to expand a Kivy App with ScreenManager, Screen, and Button widgets, and one of Button's events (on_release, on_press).
Py File

*

*Add import statement, from kivy.uix.screenmanager import ScreenManager, Screen

*Declare a class with inheritance of ScreenManager, e.g. class ScreenManagement(ScreenManager):

*Declare two classes with inheritance of Screen, e.g. class MenuScreen(Screen): and class CalculatorScreen(Screen):

*Add pass as body of the three new classes because we are going to use kv language to design their views / presentation.

*Replace return RootWidget() with return ScreenManagement() because now the root of the App is a Kivy ScreenManager

*Rename class RootWidget to class Calculator
Snippets - py
from kivy.uix.screenmanager import ScreenManager, Screen

...

class Calculator(GridLayout):
    ...

class MenuScreen(Screen):
    pass

class CalculatorScreen(Screen):
    pass

class ScreenManagement(ScreenManager):
    pass

class kutuApp(App):
    def build(self):
        return ScreenManagement()

kv File

*

*Declare class rules, <MenuScreen>:, <CalculatorScreen>: <ScreenManagement>: which corresponds to class MenuScreen(Screen):, class CalculatorScreen(Screen):, and class ScreenManagement(ScreenManager): respectively in Python script

*Rename RootWidget to Calculator

*Instantiate Calculator: as child of class rule, <CalculatorScreen>:

*Instantiate MenuScreen: and CalculatorScreen: as children of class rule, <ScreenManagement>:

*Give name to MenuScreen: and CalculatorScreen: as name: 'menu' and name: 'calculator' respectively. This will enable us to reference them when switching screen.

Snippets - kv
<ScreenManagement>:
    MenuScreen:
        name: 'menu'
    CalculatorScreen:
        name: 'calculator'

<MenuScreen>:
    BoxLayout:
        Button:
            text: 'Goto Calculator'
            on_press: root.manager.current = 'calculator'
        Button:
            text: 'Quit'

<CalculatorScreen>:
    Calculator:

...
<Calculator>:
    id: calculator

Example
main.py
from kivy.app import App
from kivy.uix.gridlayout import GridLayout
from kivy.core.window import Window
from kivy.lang import Builder
from kivy.uix.screenmanager import ScreenManager, Screen

Window.clearcolor = .3, .3, .3, 1

class Calculator(GridLayout):
    def calculate(self, calculation):
        if calculation:
            try:
                self.display.text = str(eval(calculation))
            except Exception:
                self.display.text = "Error"

class MenuScreen(Screen):
    pass

class CalculatorScreen(Screen):
    pass

class ScreenManagement(ScreenManager):
    pass

Builder.load_file("main.kv")

class kutuApp(App):
    def build(self):
        return ScreenManagement()

if __name__ == '__main__':
    kutuApp().run()

main.kv
<ScreenManagement>:
    MenuScreen:
        name: 'menu'
    CalculatorScreen:
        name: 'calculator'

<MenuScreen>:
    BoxLayout:
        Button:
            text: 'Goto Calculator'
            on_press: root.manager.current = 'calculator'
        Button:
            text: 'Quit'

<CalculatorScreen>:
    Calculator:

<CustButton@Button>:
    font_size: 35
    background_color: 0,0,0,0
    canvas.before:
        Color:
            rgba: (.4, .4, .4, 1) if self.state=='normal' else (0,.7,.7,1)
        RoundedRectangle:
            pos: self.pos
            size: self.size
            radius: [20, ]

<RawLayout@BoxLayout>:
    spacing: 8
    padding: 8
    size_hint: [1, .2]

<Calculator>:
    id: calculator
    rows: 10
    display: entry
    spacing: 1

    BoxLayout:
        size_hint: [1, .1]
        Label:
            text: 'Basic Calculator'
        Label:
            text: 'Made by Xrew'

    BoxLayout:
        padding: 10
        TextInput:
            id: entry
            spacing: 1
            padding: 5
            font_size: 32
            multiline: True
            focus: False
    #       background_color: 0, 0, 0, 1
    #       foreground_color: [1, 0, 1, 1]

    RawLayout:
        CustButton:
            text: '<'
            on_press: entry.text += self.text
        CustButton:
            text: '>'
            on_press: entry.text += self.text
        CustButton:
            text: '≈'
            on_press: entry.text += '=='

    RawLayout:
        orientation: 'horizontal'
        CustButton:
            text: '('
            on_press: entry.text += '('
        CustButton:
            text: ')'
            on_press: entry.text += ')'
        CustButton:
            text: '√'
            on_press: entry.text += '**(.5)'
        CustButton:
            text: '¹/x'
            on_press: entry.text += '1/'
    RawLayout:
        orientation: 'horizontal'
        CustButton:
            text: 'Del'
            on_press: entry.text = entry.text[:-1]
        CustButton:
            text: 'x²'
            on_press: entry.text += '**2'
        CustButton:
            text: 'xⁿ'
            on_press: entry.text += '**'
        CustButton:
            text: 'π'
            on_press: entry.text += '3.14'

    RawLayout:
        orientation: 'horizontal'
        cols: 4
        CustButton:
            text: 'Clr'
            font_color: [255,0,0,1]
     #       background_normal: ' '
        #    background_color: 1, .3, .4, .85
            on_press: entry.text = ""
        CustButton:
            text: '+'
            on_press: entry.text += self.text
            font_size: 32
        CustButton:
            text: '÷'
            on_press: entry.text += '/'
        CustButton:
            text: '×'
            on_press: entry.text += '*'

    RawLayout:
        rows: 1
        orientation: 'horizontal'
        CustButton:
            text: '7'
            on_press: entry.text += self.text
        CustButton:
            text: '8'
            on_press: entry.text += self.text
        CustButton:
            text: '9'
            on_press: entry.text += self.text
        CustButton:
            text: '-'
            on_press: entry.text += self.text

    RawLayout:
        orientation: 'horizontal'
        rows: 1
        CustButton:
            text: '4'
            on_press: entry.text += self.text
        CustButton:
            text: '5'
            on_press: entry.text += self.text
        CustButton:
            text: '6'
            on_press: entry.text += self.text
        CustButton:
            text: '+'
            on_press: entry.text += self.text

    RawLayout:
        orientation: 'horizontal'
        cols: 3
        CustButton:
            text: '1'
            size_hint: [.5, 1]
            on_press: entry.text += self.text
        CustButton:
            text: '2'
            size_hint: [.5, 1]
            on_press: entry.text += self.text
        CustButton:
            text: '3'
            size_hint: [.5, 1]
            on_press: entry.text += self.text
        CustButton:
            text: ' '
            size_hint: [.5, 1]
            background_normal: ' '
            background_color: 0, 0, 0, 0

    RawLayout:
        orientation: 'horizontal'
        size_hint: [1, .2]
        CustButton:
            text: '0'
            on_press: entry.text += self.text
            size_hint: [.34, 1]
        CustButton:
            text: '.'
            on_press: entry.text += self.text
            size_hint: [.17, 1]
            font_size: 32
        CustButton:
            text: '='
            on_press: calculator.calculate(entry.text)
            size_hint: [.17, 2.4]
    #       background_normal: ' '
        #   background_color:  0, .5, 95, 1

Output


text:
Q: the import org.zkoss.zul cannot be resolved I am using the ZK framework and I need to import this:
import org.zkoss.zul.Label;
But I keep on getting this error:
the import org.zkoss.zul cannot be resolved
I already added the zul.jar to the classpath but the error still exists. What should I do?

A: I solved it. I just removed the zul.jar from the class path and added it again. It works now.


text:
Q: What is the right syntax to post sequentially named inputs in php? I am not a developer by trade or employ <-- just a disclaimer
So, I have an html form with several hundred inputs, in essence a limited, mock spreadsheet.
The form is 3 columns by 150 rows.
For demonstration's sake, let's say that the form/table structure looked like this:

        <input name="this_row_1" /><input name="that_row_1" /><input name="the-other_row_1" />

        <input name="this_row_2" /><input name="that_row_2" /><input name="the-other_row_2" />

        <input name="this_row_3" /><input name="that_row_3" /><input name="the-other_row_3" />

        <input name="this_row_150" /><input name="that_row_150" /><input name="the-other_row_150" />

When the form is posted to the PHP, I am looking for the right syntax to assign handlers (right word?) in a loop(s).
I don't know much in coding, but I have been playing and testing this type of variation/concept:
for ($i = 1; $i < $_POST['[name="this_row_' + i + '"]']; $i++)
{
   echo $_POST['[name="this_row_' + i + '"]'][$i] + "," + $_POST['[name="that_row_' + i + '"]'][$i] + "," + $_POST['[name="the-other_row_' + i + '"]'][$i];
}

But obviously it doesn't work, and if it isn't already hinted, I want to write a new CSV file with column headers as the end game.
Any help is appreciated.

A: Try this.
$file=fopen(<DIRECTORY_PATH>."file.csv","w");
 if(!$file){
    //error
 }

$this_row=$_POST['this_row'];//consider sanitizing/cleaning the data
$that_row=$_POST['that_row']; //consider sanitizing/cleaning the data
$the_other_row=$_POST['the_other_row']; //consider sanitizing/cleaning the data

$loop=count($this_row); // assuming count of all the other columns are same

$csv_data="";
for($i=0;$i<$loop; $i++){

    $csv_data.=$this_row[$i].", ".$that_row[$i].", ".$the_other_row[$i].", ";
    //remove the last comma
    $csv_data.="\n";
    }
}

fwrite($file,$csv_data);

A: Let's start with your markup.
If you have multiple fields that mean the same (i.e. should have the same name with numbers, like in your example). You should be naming them name="whateverNameYouWant[]" (yes, all of them, with the same name). This will cause PHP to tread those inputs as an array of inputs, and you'll be able to access them like so $_POST["whateverNameYouWant"][42].
When you do that, everything is simpler.
As for the CSV, PHP has functions to deal with CSV files. And now you can easily loop and access your $_POST variables as $_POST["this_row"][$i], etc.


text:
Q: Accessing GUI JTextField objects that are dynamically generated I am writing a program that contains a JButton. Every time the button is clicked, a new JTextField is added to a JPanel.
My problem is that, after the user has created all the JTextFields and filled them with information, I need to get the text of each field. How can I get access to the JTextFields when they are dynamically generated, as they don't have instance names? Is there a better way to get the text of each one, without knowing their instance name.
Here is the code of the actionPerformed event of the JButton...
private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {
    JTextField x = new JTextField();
    x.setColumns(12);
    p.add(x);
    validate();
}

A: You say you want to get the text from each field. So, when you create the new instances x, why don't you keep a collection of them, such as adding the JTextFields to an ArrayList?
Alternatively, assuming that p is a JPanel, you should be able to get all the children, which would be the JTextFields that you're adding. Try using getComponents() like so...
Component[] children = p.getComponents();
for (int i=0;i<children.length;i++){
    if (children[i] instanceof JTextField){
        String text = ((JTextField)children[i]).getText():
    }
}

A: You can find them all by looping through the components of the panel (or whatever "p" is). If necessary, check if each is a text box. That is, do p.getComponents and then loop through the returned array. Like:
Component[] components=p.getComponents();
for (Component c : components)
{
  if (c instanceof JTextField)
  {
    String value=((JTextField)c).getText();
    ... do whatever ...
  }
}

If they are interchangeable, that should be all you need. If you need to distinguish them, I think the cleanest thing to do would be to create your own class that extends JTextField and that has a field for a name or sequence number or whatever you need.


text:
Q: How can I show the System Tray across multiple monitors in Windows 8.1 In Windows 8.1, the taskbar is shared between all 3 of my monitors but the System Tray only shows up on my monitor that is noted as my "Main Display" in Screen Resolution settings.
Is there a way I can have the system tray show up on all of my monitors?
Edits:
I noticed this guy asked a similar question about the clock, so I doubt I'll get any different answers.
Display the taskbar clock on multiple screens in Windows?

A: I've been using Display fusion for a couple years now. It is well integrated with Windows 7/8/8.1 and adds many features that I didn't realise I wanted until I used them (e.g. window position snapping).
It even has the clock on the extended monitor.


text:
Q: How to check if a db entry contains something using ObjectQuery(Of T) Class I am using the new mvc4 ajax controller template and I don't know how to add a search to the database query that they have.
Let's say I have a model called Article, here is what the controller contains by default:
ObjectQuery<Article> articles = (db as IObjectContextAdapter).ObjectContext.CreateObjectSet<Article>();
articles = articles.OrderBy("it." + orderBy + (desc ? " desc" : ""));

This works fine, but I am not familial with IObjectContextAdapter and I don't know how to add a search (ie. to see if a Article contains a term.) Normally I would have something like this:
var articles = from a in db.Articles.ToList()
                           select a;
if(!String.IsNullOrEmpty(search))
{
    articles = articles.Where(a => a.Title.ToLower().Contains(search.ToLower())
                                       || a.FullArticle.ToLower().Contains(search.ToLower())
                                       || a.TagsAndKeywords.ToLower().Contains(search.ToLower()));
}
switch(orderBy)
{
    case "TimeStamp":
        if(desc)
            articles = articles.OrderByDescending(a => a.TimeStamp);
        else
            articles = articles.OrderBy(a => a.TimeStamp);
            break;
     case "Title":
     ...
}

Obviously the new way of doing this is more succinct so I would like to stick with this. I tried combining them, using the linq query to populate the var articles, but then I am not able to use the order by part, .OrderBy("it." + orderBy + (desc ? " desc" : "")).
So my question is what is the best way to search through my database? And what exactly is this .OrderBy("it." + orderBy + (desc ? " desc" : "")) doing? I'm only familial with using OrderBy with linq.
Edit
After a lot of reading I have a better understanding of what is going on, although I still can't get this to work.
According to this it seems like I need something similar to this:
articles = articles.Where("it.Title = @searchString");

although I think this would only work if searchString matched the title exactly. While I still don't quite understand what this is doing, I think it uses sql expressions so I thought that this may work:
articles = articles.Where("it.Title like '%@searchString%'");

But none of this worked, and I am only shooting in the dark since I am unfamiliar with this.

A: The most succinct way to query your model without changing mvc4 template code is to create an IQueryable object and query it, like this:
ObjectQuery<Article> articles = (db as IObjectContextAdapter).ObjectContext.CreateObjectSet<Article>();
articles = articles.OrderBy("it." + orderBy + ((bool)desc ? " desc" : ""));

IQueryable<Article> iArticles = articles;

if(!String.IsNullOrEmpty(search))
    iArticles = iArticles.Where(a => a.Title.Contains(search) ||
                                                  a.FullArticle.Contains(search));

Response.AppendHeader("X-Total-Row-Count", iArticles.Count().ToString());

return PartialView(iArticles.Skip(start).Take((int)itemsPerPage));

This keep the entries in the correct order, and be sure to return the new iArticles instead of the old Articles.


text:
Q: How to deal with ground connection impedance with BQ769x0? I am working on a battery management system using the TI BQ76920.
The document "bq769x0 Family Top 10 Design Considerations (Rev. A)" explains on pages 22f that depending on how ground is referenced, some inputs must be protected from falling below Vss as a result of ground impedance.
One situation is the following:

They write: "If VSS is referenced near the sense resistor, VC0 will tend to go below ground if connected to the cell and may need protection such as DVC0."
The VC0 to VSS absolute maximum rating is –0.3V to 3.6.
Am I right to assume that DVC0 should be a Schottky diode rather than a Zener diode as the schematic symbol suggests?

A: The Zener is present to both protect the voltage from going negative and to protect from the positive transients associated with Lpath when the current changes rapidly in this path.  Your point about the absolute maximum rating is a good one, so you might place a Schottky in parallel with a DVCO here.


text:
Q: Inserting e-mail address in MySQL using PHP The last few hours I've spent in struggling with a quite ridiculous error.
Simply what I'm making a registration form. User need to enter a e-mail and the mail will be stored in a mysql table. (I have to warn you - please disregard the security issue, the whole thing is just a exercise). But I constantly get the following error from the sql:

You have an error in your SQL syntax; check the manual that
  corresponds to your MySQL server version for the right syntax to use
  near '@gmail.com,blqh2@gmail.com,1)' at line 1

The html is as follows:
      <form method="post" action="createnew.php">
            user name
            <input name="login_id">

            password
            <input name="password" password>

                    ...some more stuff...
            Privet e-mail
            <input name="prv_email">

            Public e-mail
            <input name="pub_email">

            Are you a reseller
            <input type="checkbox" name="reseller">

            <input type="submit">
        </form>

Then comes the PHP:
$login_id=$_POST['login_id'];
$password=$_POST['password'];
...some more stuff...
$pub_email=$_POST['pub_email'];
echo $prv_email;
echo $pub_email;
if (array_key_exists('reseller',$_POST)) {
    $reseller=1;
}
else {
    $reseller=0;
}
$sql="INSERT INTO users".
    "(login_id,password,usr_phone,region,prv_email,pub_email,reseller)".
    "VALUES".
"($login_id,$password,$usr_phone,$region,$prv_email,$pub_email,$reseller)"

And finally the MySQL formatting for the mail field(practically they prv_email and pub_email are with the same formatting)
    Field     | Type         | Collation
    ----------|--------------|-------------------
    pub_email | varchar(255) | utf8_general_ci

I did try a lot off stuff but nothing seems to work. It always crushes at @.
and one more thing - I'm running this who code on localhost(using WAMP), not sure if this have anything to deal with the problem.
Please let me know if you need any other information and thanks a lot.

A: The following:
"($login_id,$password,$usr_phone,$region,$prv_email,$pub_email,$reseller)"

will be parsed as literals, rendering it the error you see above. You'll need to wrap each variable in single quotes for it to be seen as a string value instead.
I'd recommend that you have a look at PDO & Prepared Statements, as PDO provides an abstraction layer towards the database, as well as great security (for example via Prepared Statements).
Additionally, you're inserting to the field pub_email, but from your given output in the post, it's supposed to be pub_mail.

A: You have to enclose your values in single quotes (') Change this snippet of code:
$sql="INSERT INTO users".
    "(login_id,password,usr_phone,region,prv_email,pub_email,reseller)".    "VALUES".
    "($login_id,'$password','$usr_phone','$region','$prv_email','$pub_email','$reseller')"

A: You need to, at the very least, add ''s around the strings and do a mysql-real-escape-string() on all passed arguments.  Far better would be to use prepared statements with PDO or mysqli


text:
Q: Exporting range/paragraph of text from Outlook Email to Excel After searching around and using GMayor's helpful answers on a previous set of emails, I have a new set of emails I need to export into excel.
Following is an example of one such email;

Student First Name: Blueberry
Student Email: happyd62@happyemail.com.au
Student Mobile Number: 0444444444
What will you be doing in 2018?:
*Enrolling in Year 11

*Leaving school and seeking employment (work)
*Have Caring Responsibilities
Additional Comments: Blueberry hasn't been attending every day at school his past year as she has been caring for her siblings and has a child on the way
Student ID: student8
TSF Community: Adelaide
Please tell your sponsor about your hobbies, interests, family and friends: xbox
crocheting
knitting
family
dancing
hicking
reading
watching movies
An achievement in the last year that I'm proud of is..: knitting for my family
What elective subjects have you chosen to study next year?:
I would like to tell my sponsor: I enjoy crocheting

The problem I'm having is grabbing the info after "What will you be doing in 2018?:" and "Please tell your sponsor...". The "..doing in 2018?" field needs to be in a single cell, one per line.. The "Please tell your sponsor.." field needs to be comma separated.
Both these fields are variable. I thought I could grab everything between the texts "in 2018?:" and "Additional Comments:" (exclusive).
Follows in the script I used;
Option Explicit

Sub CopyToExcel()
Dim xlApp As Object
Dim xlWB As Object
Dim xlSheet As Object
Dim olItem As Outlook.MailItem
Dim vText As Variant
Dim sText As String
Dim vItem As Variant
Dim vNextA, vNextB, vNextC As Variant
Dim i As Long
Dim rCount As Long
Dim bXStarted As Boolean
Const strPath As String = "S:\SSOF1718\SSOF1718-Macro.xlsm" 'the path of the workbook

If Application.ActiveExplorer.Selection.Count = 0 Then
    MsgBox "No Items selected!", vbCritical, "Error"
    Exit Sub
End If
On Error Resume Next
Set xlApp = GetObject(, "Excel.Application")
If Err <> 0 Then
    Application.StatusBar = "Please wait while Excel source is opened ... "
    Set xlApp = CreateObject("Excel.Application")
    bXStarted = True
End If
On Error GoTo 0
'Open the workbook to input the data
Set xlWB = xlApp.Workbooks.Open(strPath)
Set xlSheet = xlWB.Sheets("SSOF")

'Process each selected record
 rCount = xlSheet.UsedRange.Rows.Count
  For Each olItem In Application.ActiveExplorer.Selection
    sText = olItem.Body
    vText = Split(sText, Chr(13))
    'Find the next empty line of the worksheet
     rCount = rCount + 1
    'Check each line of text in the message body
    For i = UBound(vText) To 0 Step -1
        If InStr(1, vText(i), "Student First Name:") > 0 Then
            vItem = Split(vText(i), Chr(58))
            xlSheet.Range("A" & rCount) = Trim(vItem(1))
        End If

        If InStr(1, vText(i), "Student Email:") > 0 Then
            vItem = Split(vText(i), Chr(58))
            xlSheet.Range("B" & rCount) = Trim(vItem(1))
        End If

        If InStr(1, vText(i), "Student Mobile Number:") > 0 Then
            vItem = Split(vText(i), Chr(58))
            xlSheet.Range("C" & rCount) = Trim(vItem(1))
        End If

        If InStr(1, vText(i), "What will you be doing in 2018?:") > 0 Then
            vItem = Split(vText(i), Chr(58))
            xlSheet.Range("D" & rCount) = Trim(vItem(1))
        End If

        If InStr(1, vText(i), "Additional Comments:") > 0 Then
            vItem = Split(vText(i), Chr(58))
            xlSheet.Range("E" & rCount) = Trim(vItem(1))
        End If

        If InStr(1, vText(i), "Student ID:") > 0 Then
            vItem = Split(vText(i), Chr(58))
            xlSheet.Range("F" & rCount) = Trim(vItem(1))
        End If

        If InStr(1, vText(i), "TSF Community:") > 0 Then
            vItem = Split(vText(i), Chr(58))
            xlSheet.Range("G" & rCount) = Trim(vItem(1))
        End If

        If InStr(1, vText(i), "Please tell your sponsor about your hobbies, interests, family and friends:") > 0 Then
            vItem = Split(vText(i), Chr(58))
            xlSheet.Range("H" & rCount) = Trim(vItem(1))
        End If

        If InStr(1, vText(i), "An achievement in the last year that I'm proud of is..:") > 0 Then
            vItem = Split(vText(i), Chr(58))
            xlSheet.Range("I" & rCount) = Trim(vItem(1))
        End If

       If InStr(1, vText(i), "What elective subjects have you chosen to study next year?:") > 0 Then
            vItem = Split(vText(i), Chr(58))
            xlSheet.Range("J" & rCount) = Trim(vItem(1))
        End If

        If InStr(1, vText(i), "I would like to tell my sponsor:") > 0 Then
            vItem = Split(vText(i), Chr(58))
            xlSheet.Range("K" & rCount) = Trim(vItem(1))
        End If

    Next i
    xlWB.Save
Next olItem
xlWB.Close SaveChanges:=True
If bXStarted Then
    xlApp.Quit
End If
Set xlApp = Nothing
Set xlWB = Nothing
Set xlSheet = Nothing
Set olItem = Nothing
End Sub

Thanks for your help.

A: You can use another loop inside the If block for the multiple line answers.
    If InStr(1, vText(i), What will you be doing in 2018?:") > 0 Then

Clear the vItem variable before the loop.
       vItem = ""

Loop from the current line (i) until the end of the array.  We will check for the next heading and exit the loop early.
        For ii = i + 1 To UBound(vText)

Assemble the text as needed.  Here I add a new line if needed.
           If Trim(vText(ii)) > "" Then
              If vItem <> "" Then vItem += vbCrLf
              vItem += vText(ii)
           Emd If

Check for exit condition.
           If InStr(1, vText(ii), "Additional Comments:") > 0 Then Exit For

        Next ii

Assign to cell.
        xlSheet.Range("D" & rCount) = Trim(vItem)

    End If

Note: I did not test my changes.  Please excuse any mistakes and debug as needed.


text:
Q: Parse any primitive type garnered using Reflection from a string I am retrieving values from text files to build several different types of objects and I'd like one central method of populating the property values for these objects. I would like for the resulting values to benefit from C#'s strong typing which means parsing the values.
The steps being

*

*Read the text file's key value pairs of

*Get a list of all the properties for the type I'm building using reflection.

*Set the property values to their corresponding key-value pair, converting the string based value to that of the property type.

My current implementation (which works) is:
 public void SetPrimitive(PropertyInfo property, T product, string value)
    {
        if (property.PropertyType == typeof(bool))
        {
            property.SetValue(product, bool.Parse(value));
        }
        else if (property.PropertyType == typeof(int))
        {
            property.SetValue(product, int.Parse(value));
        }
        else if (property.PropertyType == typeof(double))
        {
            property.SetValue(product, double.Parse(value));
        }
        else if (property.PropertyType == typeof(char))
        {
            property.SetValue(product, char.Parse(value));
        }
        else if (property.PropertyType == typeof(float))
        {
            property.SetValue(product, float.Parse(value));
        }
        else if (property.PropertyType == typeof(long))
        {
            property.SetValue(product, long.Parse(value));
        }
        else if (property.PropertyType == typeof(short))
        {
            property.SetValue(product, short.Parse(value));
        }
        else if (property.PropertyType == typeof(string))
        {
            property.SetValue(product, value);
        }
        else
        {
            throw new Exception($"Invalid type '{property.PropertyType}'. This class will need to be extended to support this.");
        }

As you can see this isn't very extensible, and fairly wordy.
I've tried working with Convert or TypeConverters, as is seen in several similar questions, to parse the appropriate values and just plain typecasting but, unlike with the developers asking those questions, I am retrieving the type to convert to via reflection using 'TypeOf(T).GetProperties' and it seems unwilling to convert the value, the compiler complaining that it isn't a recognized type. This, despite it being able to confirm or deny an objects type in the various if statements above.
My theory on it is this: It doesn't know at compile time since the method is building various different types that it doesn't know about till runtime. Hence me trying to code around property.PropertyType is causing compiler confusion. However it is easily able to match any type against another and confirm/deny whether it matches.
Is there a specific way I can write this to get TypeConverter or Convert to work as expected? I'd like this to work for all primitives out of the box and let other devs add on to it if they wanted to be able to set more complex types going forward.
TLDR; I have a working approach but its messy and it feels like there should be a better way to do this.

A: So converting the type this way is possible by using TypeCodes. More specifically by parsing the string to a corresponding enum. TypeCodes include all of the primitives (which was my minimum requirement) while also being able to parse some common, yet non-primitive (comparatively) complex types such as DateTime.
        public void SetProperty(PropertyInfo property, string value)
    {
        //Get the type we need to cast to.
        Enum.TryParse(property.PropertyType.Name, true, out TypeCode enumValue); //Get the type based on typecode
        //Cast to that type
        var convertedValue = Convert.ChangeType(value, enumValue); //Convert the value to that of the typecode
        //Assign
        property.SetValue(this, convertedValue); // Set the converted value

It constrains me to the types listed in the enum but it works rather nicely and is far cleaner.
It might be nice to manually compare these against all these types manually and add additional logic for each but for a catch-all generified solution I think this is definitely a step up!


text:
Q: Ubuntu 20.04 no longer boots on Dell XPS 2019: grub sees the vnme disk, but the kernel doesn't The machine is configured in dual boot Windows 10/Ubuntu 20.04.
Windows boots fine, but attempting to boot Ubuntu throws me to the (initramfs) prompt because it can't find the root partition, which it looks up by UUID.
If I go to grub's command line and do ls (hd0,7) it sees the ext* filesystem, and it has the correct UUID. I can load the kernel & initrd with
set root=(hd0,7)
linux /boot/vmlinuz root=/dev/nvme0n1p7
initrd /boot/initrd.img

But when I do boot, I end up in the initramfs prompt again. This happens both with vmlinuz and vmlinuz.old (and the corresponding initrd.img).
I tried booting off an USB key, and that works, but there are no /dev/nvme* devices.
This happens regardless of the secure boot setting in the BIOS.
Any ideas what may be going on?

A: Switching the disk mode to AHCI fixed the issue.
It required some recklessness, on my part, as switching modes brings up a scary message about this change potentially requiring a reinstall.
I have no idea how my machine got into that state, so I decided to blame Windows.


text:
Q: JFreeChart Null Pointer issue I'm just trying to run a demo of a 'simple' pie chart I found online. I'm running this in Eclipse Kepler and I keep getting,
Exception in thread "main" java.lang.NullPointerException
    at org.apache.fontbox.afm.AFMParser.main(AFMParser.java:304)

when I try to run the program. I would think, considering where I got the code (linked off of a JChart site), that it would run without issue. Just trying to see if anyone can see something I can't.
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartFrame;
import org.jfree.chart.JFreeChart;
import org.jfree.data.general.DefaultPieDataset;

public class BarChartDemo {
    public static void main(String[] args){
        DefaultPieDataset dataset = new DefaultPieDataset();
        dataset.setValue("Category 1", 50.0);
        dataset.setValue("Category 2", 50.0);
        JFreeChart chart = ChartFactory.createPieChart(
            "Sample Pie Chart",
            dataset,
            true,
            true,
            false
            );

        ChartFrame frame = new ChartFrame("First",chart);
        frame.pack();
        frame.setVisible(true);
    }
}

A: I was able to get the chart to appear without changing your code. Did you include both jars (jfreechart, jcommons) in your build path?

A: After some battling and researching (guessing), I came across this class via some Adobe Font Metrics googling. Incidentally I can't remember exactly where I found it, but it solved my issue. I'll spare the SO servers and not post the 1000(+)-line code, but here it is as a gist if anyone has the same problem. I just included it in my project source file as a separate class, and voila...
I'm still not sure why my project wouldn't run without this. It worked on other systems, but not my Eclipse Kepler (Mac OS 10.9). If anyone can tell me exactly why it kept failing, I'd be very thankful.


text:
Q: VLOOKUP with 2 columns for both search_key and range I am struggling to find a way to use a VLOOKUP where the both the search_key and range are 2 columns. In both sheets (seperate workbooks for which I am using IMPORTRANGE) I have 2 columns with First Name and Last Name. The Sheet1 also contains the Hire Date, and I would like to populate the Hire Date from Sheet1 into a column in Sheet2.
I accomplish what I want if I merge the First Name and Last Name into a single column on both sheets. Unfortunately, this cannot be a permanant solution since there are other dependancies where the names must remain seperate columns.
I have created a test worrkbook to showcase the issue.
https://docs.google.com/spreadsheets/d/1v3coBJRwJEbrrdgcflV4-dssKgknS-T2werWVjPwxEA

A: Put this formula in cell Sheet2!C1:
=arrayformula(
  iferror(
    vlookup(
      A1:A & B1:B,
      { Sheet1!A1:A & Sheet1!B1:B, Sheet1!C1:C },
      2, false
    )
  )
)

Then format the result column as Format > Number > Date.


text:
Q: Describing The Graph Of A Function In Two Variables I am currently reading about an example problem, of which is mentioned in the title of this thread.
The function is $f(x,y)= \sqrt{16-4x^2-y^2}$. The one part of the discussion I don't quite understand is why the range of this function is $0 \le z \le 4$
Also, as a side note, is the domain of a function of two variables, $z= f(x,y)$, the ordered-pairs (x,y), and the range is real numbers? That is, the function maps an ordered-pair to a real number, the real number being the z-value?

A: To see that the range of $z=f(x,y)$ is $0 \le z \le 4$, first note that $f(0,0)=4$ and $f(2,0)=0$ so the range is at least that.  Since the squares are at least zero, the value under the square root sign cannot be greater than $16$, so the maximum function value cannot be more than $4$.  The square root is defined to be greater than or equal to zero, so it cannot be less.  This shows the range is as claimed.
Your side not is correct:  the domain is the set of allowable inputs to the function, which here are ordered pairs $(x,y)$.  The range is the range of outputs of the function, in this case a set of real numbers.


text:
Q: Showing jars in maven dependencies section without doing mvn install in cmd I have added dependencies in pom.xml and immediately the corresponding jars started to show up in maven dependencies section of dynamic web project.
I just want to know that I have not done mvn install in cmd so how did they get saved in maven repository.
Another query I have, is that since jars are availble in maven dependencies folder of dynamic wep project, so my project runs successfully or not as depndencies are already satisfied without doing mvn install.

A: When you list a <dependency> in your project's POM, M2Eclipse (Eclipse's plugin in this case) will trigger Maven to resolve that declared dependency...meaning Maven will check your local repo first for that dependency, and if it's not found there it will pull it down from the next highest repo you have configured (possibly an agency-level repo, or Maven's default public repo on the web).
No mvn install is required, as the purpose of that would be to install your current project's packaged artifact into your local repo, rather than install any dependency.
Hope this helps to clarify why an install is not used to copy dependencies into your local repo.


text:
Q: The inverse function The function $g :\mathbb{Q} → \mathbb{Q}$ is defined by $g(r) = 4r + 1$ for each $r \in \mathbb{Q}$.
(a) Determine $g(\mathbb{Z})$ and $g(E)$, where $E$ is the set of even integers.
(b) Determine $g^{-1}(N)$ and $g^{−1}(D)$, where $D$ is the set of odd integers.
This is the answer:

I don't get why in (b)  $g^{-1}(N) = n/4$, i think it should be $(n-1)/4$, also for  $g^{-1}(D)$
Could any one explain this to me ?

A: The sets $\{n/4 : n\in\mathbb{Z}, n\geq 0\}$ and $\{(n-1)/4 : n\in\mathbb{N}\}$ are the same set. Every element added to the first one will be added to the second as well.
You can see some of what's going on by looking at a finite subset. Compare
$\{n/4 : n\in\{1,2,\ldots,5\}\}=\{1, .25, .5, .75, 1.25\}$
$\{(n-1)/4 : n\in\{1,2,\ldots,5\}\}=\{0, .25, .5, .75, 1\}$
Because of the $(n-1)$ the second version runs behind the first by one element. However, if you compare
$\{n/4 : n\in\{0,2,\ldots,4\}\}=\{0, .25, .5, .75, 1\}$
$\{(n-1)/4 : n\in\{1,2,\ldots,5\}\}=\{0, .25, .5, .75, 1\}$
You get roughly what is going on in your answer sheet. You have one version which starts counting at zero and then divides the integer by four. The other starts counting at one, subtracts one (which will send one to zero, two to one, etc.), and then divides.
(One of the easier ways to see they are equivalent might be by noticing that $\{n\in\mathbb{Z}, n\geq0\}$ is the same as $\{n-1 : n\in\mathbb{N}$).
In the case of $g^{-1}(D)$ the fact that odd integers are of the form $2k+1$ means that, since $g^{-1}(r)=(r-1)/4$, $g^{-1}(2k+1)=(2k+1-1)/4=2k/4=k/2$. This is the same as the set $\{(n-1)/4 : n\in D\}$, but not the same as $\{(n-1)/4 : n\in \mathbb{Z}\}$. (Why?)

A: you are right, either

*

*$(n-1)/4$ and $n\geq0$

*or $n/4$ and $n\geq-1$ (as $g(-1/4) = 0 \in N$)

for g-1(D), both sets (yours, and the one you mentioned) are equal


text:
Q: Filter a webpage html with the 'WebBrowser' in visual studio C# I am making a simple web browser in Visual Studio c# which when opened goes to my website, I want to be able to somehow cut out bits of the html that gets rendered on the webpage. So far my WebBrowser works perfectly fine, i just need to be able to somehow listen to the incoming html code of the page, i will then remove the bits i don't need. Is it possible to do this with the WebBrowser in Visual Studio c#? If so could someone explain how it could be achieved.
Thanks

A: A first approach would be getting the HTML with a web request:
HttpWebRequest myReq =
(HttpWebRequest)WebRequest.Create("http://whatever.com/");
WebResponse response = myReq.GetResponse();
Stream dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
string responseFromServer = reader.ReadToEnd(); //Here's the complete HTML content
reader.Close ();
response.Close ();

After that you parse the HTML for your needs (delete something you don't need etc.)
For HTML parsing see this.
In the end you simply pass that parsed HTML to your WebBrowser, for example like this:
myWebBrowser.DocumentText =
    "" + myParsedContent +
    "";


text:
Q: Java - Loop issues I'm writing a program that has a 1 in 5 chance to be correct and until it's correct it keeps going. It then should go and print the information to a file, however when I try to run it, it wont seem to run the second loop however many times I ask it to with the scanner. I need everything inside of the while loop to go the same amount of times as the for loop because I'm going to take it and find the percent average of how many times it takes to get the 20%. Any help on this topic would be greatly appreciated.
edit - The input that I'm giving to be specific is the variable trials, when I initiate the program if I set it to 1000 I expect to see the for loop repeat the loop and everything inside of it 1000 times.
edit 2 - I wanted to add what it was I'm going of off, I'm doing a project and here are my guidelines to go off of:

*

*Determine how many bottle caps each person has to open in order to find a winning cap.  (This represents one trial.)  Print this value to a text file.

*Prompt the user for the number of trials.  Conduct at least 1000 trials.

*Read back the data for all of the trials from the output file.

*Calculate the average number of caps opened in order to win a prize.

*Print the result to the screen.
import java.util.Random;
import java.util.Scanner;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.File;
public class BottleCapPrize
{
    public static void main (String [ ] args) throws IOException
{
PrintWriter outFile = new PrintWriter(new File("EBoost Chance.txt"));
Scanner in = new Scanner(System.in);
Random rand = new Random();

System.out.print("How many trials will you run? ");
int trials = in.nextInt();
int totalTrials = 0;

int randomNum = 0;
int winCounter = 0;
int counter = 0;
int bottleCap = 1;
int max = 5;
int min = 1;
double percentage = 0.0;

for (totalTrials = 0; totalTrials <= trials; totalTrials++)
{
    counter = 0;
    winCounter = 0;
    while (randomNum != 1)
    {
        randomNum = rand.nextInt((max - min) + 1) + min;
        if (randomNum == 1)
        {
            winCounter++;
            counter++;
            outFile.println("You would win in " + counter + " bottles.");
        }
        else if (randomNum != 1)
        {
            counter++;
        }
    }
}
outFile.close ( );

}
}

A: You need to reset randomNum every for loop iteration. Otherwise, the while loop will never be entered because randomNum will still equal 1 from the previous iteration.
import java.util.Random;
import java.util.Scanner;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.File;

public class Main
{
    public static void main(String[] args) throws IOException
    {

        PrintWriter outFile = new PrintWriter(new File("EBoost Chance.txt"));
        Scanner in = new Scanner(System.in);
        Random rand = new Random();

        System.out.print("How many trials will you run? ");
        int trials = in.nextInt();
        int totalTrials = 0;

        int bottleCap = 1;
        int max = 5;
        int min = 1;
        double percentage = 0.0;

        for (totalTrials = 0; totalTrials <= trials; totalTrials++)
        {
            int counter = 0;
            int winCounter = 0;
            int randomNum = 0;     // this was moved from outside the for
            while (randomNum != 1)
            {
                randomNum = rand.nextInt((max - min) + 1) + min;
                if (randomNum == 1)
                {
                    winCounter++;
                    counter++;
                    outFile.println("You would win in " + counter + " bottles.");
                }
                else if (randomNum != 1)
                {
                    counter++;
                }
            }
        }
        outFile.close();
    }
}


text:
Q: Postgres COUNT FILTER syntax error - why? can someone find me why this query is producing a syntax error? This is a simple ad database, it has categories and ads in them. The query is getting a list of ad categories, plus counts how many ads and how many active ads it has, the latter meaning ads not older than 2 weeks. PostgreSQL says:
Syntax error at or near "(" LINE 5: FILTER(WHERE ads....^
The other COUNT works just fine. I don't get what's its problem with the FILTER clause. Thanks!
    $data = pg_query($dbconn, 'SELECT categories.id,
                                  categories.name,
                                  COUNT(ads.id) AS ads_count,
                                  COUNT(ads.id)
                                      FILTER (WHERE ads.date > '.strtotime('-2 weeks').')
                                      AS ads_active_count
                           FROM erpatak.ads_categories AS categories
                           LEFT JOIN erpatak.ads AS ads ON ads.category = categories.id'
                           .$filter.'
                           GROUP BY categories.id, categories.name
                           ORDER BY name
                           OFFSET '.$offset.'
                           LIMIT '.$maxcount);

A: OK, I found the solution. As Kamil G. revealed to me, COUNT can't be FILTERed in version 9.1 which I have here. The solution is:
COUNT(CASE WHEN ads.date > '.strtotime('-2 weeks').' THEN 1 END) AS ads_active_count


text:
Q: How can i format this date for NSDateFormatter can anyone help me format this date "Tue, 09 Sep 2014" I've got "FFF, dd MMM yyyy" i got this of a NSDate table on some random forum :/ any help is greatly appreciated
Code:
for (NSString *rawDate in postDateraw){
            NSString *formattedRawDate = [rawDate substringToIndex:[rawDate length]-15];
            NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
            [dateFormatter setDateFormat:@"FFF, dd MMM yyyy"];
            NSDate *date = [dateFormatter dateFromString: formattedRawDate];
            dateFormatter = [[NSDateFormatter alloc] init];
            [dateFormatter setDateFormat:@"dd/MM/yyyy"];
            NSString *convertedString = [dateFormatter stringFromDate:date];                 NSLog(@"Converted String : %@",convertedString);
        }

A: The character for day-of-week is E, not F.  Thus:
[dateFormatter setDateFormat:@"EEE, dd MMM yyyy"];


text:
Q: Is there a way to debug line by line code written in a view function of django on the website itself? I have a view function in a django application on a webpage that a user himself writes code for (using a framework known to them). After uploading the code, they are redirected to the webpage for which they have written the code for. I want to have a way to visualize line by line the python code that is running on the view function as it gives a clear indication to the user how their code works. Is there a way to debug code on the website itself?

A: You can use print() function.
If you use print() function inside your view then when that view function is executed it prints on Command line or terminal.
in views.py
def indexView(request):
    productCat = Product_Cat.objects.order_by('name')
    upcoming = Upcoming_Product.objects.all()
    print(upcoming)
    return render(request,'website/index.html',{'productCat':productCat})

in terminal:
<QuerySet []>

A: You can use print() function to print the output of your code. Output will be redirected to the terminal.
To check valid attribute of returning object you can also use dir() function along with print().


text:
Q: LetsEncrypt Challenge failed for domain Running this with my domain:
sudo certbot certonly --standalone --preferred-challenges http --server https://acme-staging-v02.api.letsencrypt.org/directory --register-unsafely-without-email -d example.com

Saving debug log to /var/log/letsencrypt/letsencrypt.log
Plugins selected: Authenticator standalone, Installer None
Obtaining a new certificate
Performing the following challenges:
http-01 challenge for example.com
Waiting for verification...
Challenge failed for domain example.com
http-01 challenge for example.com
Cleaning up challenges
Some challenges have failed.

IMPORTANT NOTES:
 - The following errors were reported by the server:

   Domain: exxample.com
   Type:   connection
   Detail: correct.ip.address: Fetching
   http://example.com/.well-known/acme-challenge/jHPVDWvcICxX0vt7auklR1vR8osXbSOEqbidqE7JmcE:
   Timeout during connect (likely firewall problem)

   To fix these errors, please make sure that your domain name was
   entered correctly and the DNS A/AAAA record(s) for that domain
   contain(s) the right IP address. Additionally, please check that
   your computer has a publicly routable IP address and that no
   firewalls are preventing the server from communicating with the
   client. If you're using the webroot plugin, you should also verify
   that you are serving files from the webroot path you provided.

Note: Without using --standalone I am able to download the file wget http://example.com/.well-known/acme-challenge/8SPcqxypfvqpVz-koSWJxesGw4HuSOD84J6k5xnFPZ0
I have port forward working correct and in the Ubuntu server I did ufw 80 and ufw 443. But still note, that I am able to wget the file manually.
I have ipv4 records, but no AAAA ipv6 records - but I guess it should work with ipv4.
And I have no problem serving pyton3 -m http.server 80 and curl to the server.
Am I missing something?


text:
Q: How to manage the transaction(which includes File IO) when an IOException is thrown from the close file method I've recently begun using Spring's Data Source Transaction Manager. I have a problem now.
My transaction includes updates to a DB table and a write operation to a file.
It works fine but I have some doubts about file I/O. As you see below, I have configured openFile and closeFile methods of my bean as the init-method and the destroy-method respectively, which in turn provides those methods to be called just like a constuructor and a destructor. If the file is not closed properly, some of the records may not have successfully been written to the output.txt file which means that I have not been able to handle transaction management properly as well.
However, I'd like to rollback those DB updates which have not been appended to the flat file. With my solution, it looks impossible to add the fileClose method to the transaction. Does anyone know how to implement this desired action properly?
Any suggestions would be greatly appreciated
<!--XML CONFIGURATION -->
<bean id="myFileWriter" class="com.job.step.ItemFileWriter"  init-method="openFile" destroy-method="closeFile">
    <property name="jdbcTemplate" ref="jdbcTemplateProduct"/>
</bean>

public class ItemFileWriter implements ItemWriter<Item> {
private static final Logger log = Logger.getLogger(ItemFileWriter.class);
private BufferedWriter bw = null;
public void openFile() throws IOException {
    try {
        bw = new BufferedWriter(new FileWriter("C:\\output.txt"));
    } catch (IOException e) {
        //log.error(e);
        throw e;
    }
}
public void closeFile() throws IOException {
    if (bw != null) {
        try {
            bw.close();
        } catch (IOException e) {
            log.error(e);
            throw e;
        }
    }
}

@Transactional(rollbackFor = IOException.class)
public void write(List<? extends Item> itemList) throws IOException
{
    for (Iterator<? extends Item> iterator = itemList.iterator(); iterator.hasNext();) {
        Item item = (Item) iterator.next();

        String updateRtlnOutbound = "UPDATE SAMPLESCHEMA.SAMPLETABLE SET STATUS='TRANSFERRED' WHERE ID = ?";
        jdbcTemplate.update(updateRtlnOutbound, new Object[]{item.getID()});

        String item = String.format("%09d\n", item.customerNumber);
        bw.write(item);
    }
}
}

A: Generally speaking, file IO is not transactional (except for some OS-specific features).
So, the best you can do is to move open and close operation to write() method, in order to execute them inside a transaction and rollback the transaction if closing fails.
Note, however, that you can't rollback the file IO in the case of transaction rollback, so that under some circumstances you can get the correct file with items, whereas in the database these items are not marked as TRANSFERRED.
To sove this problem you can try to use low-level transaction management support and  try to delete the file in the case of rollback, but I think it still can't provide strong guarantees of consistency:
@Transactional(rollbackFor = IOException.class)
public void write(List<? extends Item> itemList) throws IOException
{
    openFile();
    TransactionSynchronizationManager().registerSynchronization(new TransactionSynchronizationAdapter() {
        public void afterCompletion(int status) {
            if (status = STATUS_ROLLED_BACK) {
                // try to delete the file
            }
        }
    });

    try {
        ...
    } finally {
        closeFile();
    }
}

A: You are doing operations over two different systems: file-system and database. Typically, XA transactions make it easy for us to combine different transactional systems into a single transaction.
Most databases can be made to participate in XA transactions. For file-system you can use XADisk to enable XA. Once you enable XA on both database (through right configuration of data-source) and file-system (through xadisk), you can be sure that both the file and database operations commit or both of them rollback.


text:
Q: jQuery - If certain text, then addClass I want to create a jQuery where if a certain text appears, then it will add a class.
Check my jsfiddle:
http://jsfiddle.net/uREUT/130/
I have removed all other sentences to make it work all the time, but I want the class to be added if the word "mener" is in the  div
var sentences = [
    'Jeg mener også at det er paent'];

var rand = sentences[Math.floor(Math.random() * sentences.length)];

$(document).ready(function () {
    $('#text').text(rand); {
        $("#text:contains('MENER')").addClass("#flaekke");
    }
});

.flaekke {
    background: #000;
    width: 200px;
    height: 200px;
}
#text {
    margin: 20px auto;
    width: 80%;
    font-size: 200%;
    text-align: center;
    z-index: 10;
    color: #000;
    text-transform:uppercase;
}

A: Remove the hash (#) from the class name. It also doesn't take much code to add a class to elements containing text.
This is all you should need:
var sentences = [
    'Jeg mener også at det er paent'];

var rand = sentences[Math.floor(Math.random() * sentences.length)];

$(document).ready(function () {
    $("#text").text(rand);

    $("#text:contains('MENER'), #text:contains('mener')").addClass("flaekke");
});

Here's a fiddle.

A: I made these changes to your code to make it work:

*

*Look for the string in the text you already have, not in the DOM (simpler and faster).

*Remove the # from the class name

*Make sure you're looking for the right case.  The actual "mener" text is lower case even though you have a text-transform to display it in upper case.

*Make sure your CSS priorities are correct.  I had to move the .flaekke rules after the #text rules and add one !important to make sure the desired `.flaekke rules took effect when I wanted them to.  Remember, a CSS rule specified by ID has higher precedence than a class so if you want the class to have priority, you have to modify the rule to make that happen.

It seems that you can just check for the word on the text you already have - you don't have to look in the DOM.  Also, you need to remove the # from your class name:
$(document).ready(function () {
    $('#text').text(rand);
    if (rand.indexOf("mener") !== -1) {
        $('#text').addClass("flaekke");
    }
});

Working demo: http://jsfiddle.net/jfriend00/s5FCL/

A: $(document).ready(function () {
    $('#text').text(rand);
    $("#text:contains('MENER')").addClass("flaekke");
});

this should work.

A: Aside from the incorrect class name, your specific problem comes from the fact that the text actually contains "mener", not "MENER".  jQuery :contains is case-sensitive and won't take into account the uppercase transform you have.
Here is a working solution:
http://jsfiddle.net/uREUT/136/
$(document).ready(function () {
    $('#text').text(rand);
    $("#text:contains('mener')").addClass("flaekke");
});

A: regular expressions are fun so heres an answer that uses them:
JS FIDDLE
var sentences = [
    'Jeg mener også at det er paent'];

var rand = sentences[Math.floor(Math.random() * sentences.length)];

$(document).ready(function () {
    $('#text').text(rand); {
        if(new RegExp("mener").test(rand)){
            $("#text").addClass("flaekke");
        }
    }
});

ps.  if you just want to add a class named flaekke you don't need the id selector, # or the class selector, ., just type in the name of the class you want to add and let jquery do its magic.

A: Just for completeness sake, I created a fiddle that randomizes the text on a button click and removes the class as well if mener is not present.
See working jsFiddle demo

jQuery
var $text = $('#text'),
    sentences =
    [
        'Jeg mener også at det er paent',
        'Jeg også at det er paent',
        'Jeg mener paent'
    ];

$("#randomize-button").on("click", function ()
{
    var rand = sentences[Math.floor(Math.random() * sentences.length)];

    if (rand.toLowerCase().indexOf('mener') != -1)
        $text.addClass("flaekke");
    else
        $text.removeClass("flaekke");

    $text.text(rand);
})
.click();

CSS
.flaekke
{
    background: black;
    color: white;
}

#text
{
    width: 80%;
    margin: 20px auto;
    padding: 10px;
    font-size: 200%;
    text-align: center;
    z-index: 10;
    text-transform:uppercase;
    border: solid 1px black;
}


text:
Q: Is it possible to play cooperatively? Some friends and I bought the Humble Bundle with Sims 3 (and expansions).
And we want to know if possible to play in a "cooperative mode". I mean, share the same neighbourhood, to interact between our sims...
Is this possible?
How would we do this?

A: The sims 3 is a pure singleplayer game, multiplayer is not an option. So no playing together.
The next part is speculation, I don't know if it is possible or not.
It might be possible to play sequentially by using the same save. But that would require you to send the save file manually after each session to the next person.
The system would be:

*

*Player 1 plays a session.

*Player 1 saves his game.

*Player 1 locates his save file and transfers it to player 2.

*Player 2 places the received save in the correct folder.

*Player 2 plays his session and saves.

*Player 2 passes the save to player 3.

*Player 3 receives and places the save correctly.

*Player 3 plays his session and send the save back to player 1.

*Go back to point 1.

This assumes that the players only manipulate their own sims though. And nothing stops a player to change anything an earlier player did.


text:
Q: Simple_form: Parameter not passing I am trying to implement a comment feature for a site. So far, I am able to pass the movie_id of the movie I want to comment to, to the page where I create the comment (which is the default scaffold view). After that, I try to pass the movie_id to the create method of the comments_controller but it will not pass. I tried assigning its class (params[:movie_id].class) to the comment attribute and it says NilClass.
My code:
comments_controller.rb
def create
    @comment = Comment.new
    @comment.comment = params[:comment].values.first
    @comment.user_id = current_user.id
    @comment.movie_id = params[:movie_id]
    #...
end

_form.html.erb (The one the new page renders)
<%= simple_form_for(@comment) do |f| %>
    <%= f.error_notification %>

      <%= f.input :comment, label: false, placeholder: 'Your opinion'%>
      <%= f.hidden_field :movie_id, input_html: { value: params[:movie_id] } %>

      <%= f.button :submit %>

<% end %>

The params[:movie_id] in the html file, is actually what I want it to be, I tried adding it as a placeholder and it has the correct value.
This will probably be a stupid mistake but, I am really stuck...
Thanks for your time.

A: You have an error in your html. The hidden field should either use proper rails syntax for a hidden field, or use simple form syntax.
Rails syntax:
 <%= f.hidden_field :movie_id, value: params[:movie_id] %>

Simple form syntax:
 <%= f.input :movie_id, as: :hidden, input_html: { value: params[:movie_id] } %>

In controller:
@comment.movie_id = params[:comment][:movie_id]

Btw, its good form to use strong parameters as follows
@comment.movie_id = comment_params[:movie_id]
private
def comment_params
  params.require(:comment).permit(:movie_id, ...(and others..)
end

A: <%= f.hidden_field :movie_id, params[:movie_id] %>

This should work?
I would nonetheless do, since in the controller you probably have @comment = Comment.new to use the form_for, @comment.movie_id = params[:movie_id] in the controller and then use @comment.movie_id in the form, just to have it cleaner?


text:
Q: Show default "new" page with visualforce when overriding new button? Is it possible to show the standard "new" for a standard object page with visualforce? Or do you have to recreate all fields in your VF page?
Something like <apex:detail > just for the new button.

A: When I've tried to recreate Page Layouts in the past using Visualforce, I turned to Field Sets. Here is the example in Working with Field Sets
:
<apex:page standardController="Contact">
    <apex:repeat value="{!$ObjectType.Contact.FieldSets.properNames}" var="f">
        <apex:outputText value="{!Contact[f]}" /><br/>
    </apex:repeat>
</apex:page>


text:
Q: How do I implement simple a RxJava call into a Runnable Thread? I'm try to add a simple RxJava call into a runnable thread so I can update the UI once the thread is completed.  How do I go about doing that?  Here is my Activity code:
public class PrintActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_printer);
        printZpl("^XA^LL360^POI^FO20,20^A0N,25,25^FDThis is a test of the ZPL file printing on " + Helper.getCurrDateTime() + "^FS^XZ");
    }
}

Here is the class which performs the runnable thread:
public class PrinterManager {
    private static void printZpl(final String body, final String footer) {
        new Thread(new Runnable() {
            public void run() {
                try {
                    Connection btCon = new BluetoothConnectionInsecure("AC:3F:A4:0E:22:05");
                    btCon.open();
                    btCon.write(body.getBytes());
                    Thread.sleep(500);
                    btCon.close();
                    // Insert RxJava return here to update the UI in the activity once the thread is completed.
                } catch (Exception e) {
                    Timber.e(e.getMessage());
                }
            }
        }).start();
    }
}

I simplified the code for this posting.  The actual code is much, much more complex...

A: Using RxJava2:
Completable.fromAction(() -> {
            Connection btCon = new BluetoothConnectionInsecure("AC:3F:A4:0E:22:05");
            btCon.open();
            btCon.write(body.getBytes());
            Thread.sleep(500);
            btCon.close();
        })
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe();

Use a Completable instead of an Observable since you do not emit anything but the completion event.

A: Wrap the asynchronous part of your code in an Observable like this:
public class PrinterManager {
    public static Observable<Void> printZpl(final String body, final String footer) {

    return Observable.fromCallable(new Callable<Void>() {
        @Override
        public Void call() throws Exception {
            try {
                Connection btCon = new BluetoothConnectionInsecure("AC:3F:A4:0E:22:05");
                btCon.open();
                btCon.write(body.getBytes());
                Thread.sleep(500);
                btCon.close();
            } catch (Exception e) {
                Timber.e(e.getMessage());
            }
            return null;
        }
    });
}
}

Then, in your Activity, subscribe to it, triggering the code inside:
public class PrintActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_printer);
        PrinterManager.printZpl("^XA^LL360^POI^FO20,20^A0N,25,25^FDThis is a test of the ZPL file printing on " + Helper.getCurrDateTime() + "^FS^XZ")
                      .subscribeOn(Schedulers.io())
                      .observeOn(AndroidSchedulers.mainThread())
                      .subscribe();
    }
}

If you haven't already, you will need to add the dependencies to your app.gradle file:
compile "io.reactivex:rxandroid:1.2.0"
compile "io.reactivex:rxjava:1.2.0"

If you want to update the UI, then pass an Observer to the subscribe method, instead of just using the empty one as in my example above.


text:
Q: change canvas images I like to change some canvas image (hat and jacket)
here is the code
document.ready = function() {

canvas = document.getElementById('canvasspace');
ctx = canvas.getContext('2d');

drawImage();

}

function drawImage(){

    var tempimage = new Image();
    tempimage.src = jackets_images[jacket_to_draw];
    tempimage.onload = function (){ ctx.drawImage(tempimage, 0, 0); };

    var tempimage2 = new Image();
    tempimage2.src = hats_images[hat_to_draw];
    tempimage2.onload = function (){ ctx.drawImage(tempimage2, 0, 0); };
}

the two image show up one over the other one, but making 2 time the code with 2 new Image(); does not seem fine to my eye ! but i dont know better.. please show me the light

A: var imageNames = new Array();
imageNames[0] = jackets_images[jacket_to_draw];
imageNames[1] = hats_images[hat_to_draw];

var drawnImages = new Array();

function drawImage(images) {
    for (var i = 0; i < images.length; i++) {
        drawnImages[i] = new Image();
        drawnImages[i].src = images[i];
        drawnImages[i].onload = function (){
            var thisImg = drawnImages[i];
            ctx.drawImage(thisImg, 0, 0);
        };
    }
}


text:
Q: What type of sensor (w/ bluetooth)? I own a cafe very close to a university campus. As such I get lots of students coming in to buy drinks/food and study during the day. However, a lot of the time all of the available places will fill up and I feel as if this turns off students from coming in because they don't know for sure that they'll be able to get a spot. To fix this I wanted to create a type of system with sensors (that can be connected via bluetooth low energy preferably) in which I'll receive real time updates with how many chairs are occupied/open.
Currently I'm torn between three different approaches but since this is more of a side project I also want to minimize the cost as much as possible. I was thinking of either a proximity detector (easily placed on the side/back/under the chair), a force/load sensor (tougher to set up since it will need to be under a load bearing part of the chair), or a vibration sensor (will return 'occupied' if it hasn't sensed any chair vibrations for a certain period of time eg. 2 minutes).
What would you guys recommend here taking price into consideration?

A: Chair vibrations has the potential to be hard.
A leg to floor sensor should be not too hard but you need to make it robust enough. A (gasp) microswitch and a slightly compressible pad on two legs would work. Seat surface deflection should be doable.
Light occlusion in seat area would usually work.
Piezo disc under chair leg(s) would do something. Robustness an issue.
Capacitive proximity is easy enough. Cost may be high for finished units. Doing it yourself with an IC designed for that or even a processor that has cap-sense software available could be low cost.
BLE is not the only way. An eg ESP2866 system that wakes the processor up occasionally (once a minute?) may suffice.
Ask more if desired ... .

A: How about an arduino with an ultrasonic range finder and a bluetooth (or other radio) module?
Place the sensor on the top of the chair back, facing toward the table (but pointed parallel to the ground.)
It will show a high range when no one is there.
When someone sits down, the range will drop.
The arduino reads the range periodically, and reports "seat available" if it has shown high range (or no detection) for some preset number of attempts.
Once you have a working prototype with the arduino, you can simplify the design by using a plain atmel processor of the same type as in your arduino, and combine all the other modules into one unit.
If you go bluetooth, you could use a cheap tablet with bluetooth to display the number of free seats.
If you go with some other radio type, you could use a RaspberryPi with a radio module to drive a display of some kind.


text:
Q: Obtaining the virtual key code from a WM_CHAR message I am getting text input and keypress input from the WM_CHAR and WM_KEYDOWN messages
What I want to do is filter out WM_CHAR messages the have the same VK_ code as the key that is bound to enable the control that you enter text in.
EG: Game uses ~ to enable console, key binding is done via VK_OEM3 and WM_KEYDOWN, but text input into the console needs text from WM_CHAR.
As the WM_KEYDOWN happens first, the console is activated, then a WM_CHAR of ~ is sent to the console buffer which I don't want.
I figured the best way to prevent this is to compare the VK_ from the WM_CHAR to the bound key for the control and filter it out.
Is there a way to get the VK_ from a WM_CHAR message?
I read that you can get the scancode out of Lparam at bits 16-23
But am unsure how to:

*

*Extract the value of the scancode from lparam

*Translate the scan code to a VK_ correctly

A: After some messing around I managed to extract the virtual key with the following code:
This code gets the address of lParam as a unsigned char array (one byte of length), then uses pointer arithmatic to address the 3rd byte (bits 16-23):
  unsigned char scancode = ((unsigned char*)&lParam)[2];

This code translates from the scancode to the virtual key:
  unsigned int virtualKey = MapVirtualKey(scancode,MAPVK_VSC_TO_VK);

A: Perhaps you migh use MapVirtualKey.
I am not sure how to extract scancode from lparam as documentation does not state that - either get entire lparam and count that this function knows which bits to look at, or use bitfield struct and just get right bits out of it. I think on of those methods should work - trying both shouldn't be difficult.


text:
Q: Multitasking illusion on a single threaded processor? What's the official explanation for that one? I always seem to forget.

A: Multi-tasking, or multi-threading on a single processor is also called perceived multi-threading. Obviously with one CPU, it is not possible to execute commands simultaneously. Instead we interleave processes, giving the illusion of multi-threading.
As @Journeyman Geek added, this uses preemption. This is where we have some sort of structure (think a queue) where the programs are stored and each process gets so many cycles to execute. Then the currently running program is preempted (or swapped out with another program) and then that program runs. There are many strategies to determining which programs execute when. We could be completely fair (ex: Round Robin) and each program receives a certain time-quantum or we could separate the programs by priority and only execute the lower priority program when there are no more higher-priority programs to execute (ex: Priority Queue).
This is helpful when say you are writing a GUI application and running a long background-task. If this were to be written as a single threaded app, the front-end of the GUI would freeze. However, with two threads, the GUI remains responsive. Even if there is only one CPU, the interleaving of the processes means that the GUI remains responsive while the background-process continues to run and make progress.

A: hyperthreading most likely, with modern systems - in short, part of, but not whole core is duplicated so more threads can be run, per core

A: Basically the operating system takes each application (and each thread within each application) in turn and runs it for a few CPU cycles. So if you have 10 applications running, over a 10 second period each will get 1 second's worth of time actually running.
It means that each application runs more slowly than it would if it were the only application running on the computer - but for the vast majority of applications most of their time is spent waiting for user input.
See Wikipedia for more information.

A: I'm not sure what you have in mind, but it brings to mind the user perception that applications are running in parallel. This effect is achieved by interleaving the demands of concurrent processes at such a rate that it looks like every, or at least most, processes are running at the same point in time.
Incidentally, in Unix parlance the focus shifts to the perception that the system appears dedicated to each user's requests. We call this simply "multiuser."

A: Basically when you run many application on a single threaded cpu the operating system switches the cpu between the application.This is done so quickly that an illusion of multitasking is created. So basically what happens is that the cpu gives its cycles to the required application and then moves to another and then back to first application. This all is done by operating system. When the cpu switches to another application which is running concurrently the state of pervious application is saved so that when the cpu comes again to that application it remembers the state of application where it was left.


text:
Q: Swift: How to detect when pan gesture is dismissed / cancelled? I have a custom table cell that is swipeable. I'm using this library to inherit from: https://github.com/alikaragoz/MCSwipeTableViewCell
In order to prevent 2 cells from being swiped at the same time, I have a global boolean that I just toggle true / false when ever something is swiped.
However, I can't find any callbacks for when the user starts a swipe but lets go, which essentially cancels the swipe. Is there a way to do this? I'm looking for a callback similar to gestureRecognizerShouldBegin, but for when a gesture is dismissed / cancelled.
typealias SwipeHandler = () -> ()

class OrderCellManager {
  static var swiping = false
}

class OrderPreparingTableViewCell: MCSwipeTableViewCell {
  override func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
    if (!OrderCellManager.swiping) {
      OrderCellManager.swiping = true
      return true
    } else {
      return false
    }
  }

  func displayOrder(order: AppState.Order, clock: Clock, fDone: @escaping SwipeHandler, fDelete: @escaping SwipeHandler) -> OrderPreparingTableViewCell {
    ..
    self.setSwipeGestureWith(lSwipe, color: Config.ColorSwipeDelete, mode: .exit, state: .state1, completionBlock:currySwipe(f: fDelete))
    self.setSwipeGestureWith(rSwipe, color: Config.ColorSwipeDone, mode: .exit, state: .state3, completionBlock:currySwipe(f: fDone))
    ..
  }

  // MARK: Private

  private func currySwipe(f: @escaping SwipeHandler) -> MCSwipeCompletionBlock {
    return { (a: MCSwipeTableViewCell?, b: MCSwipeTableViewCellState, c: MCSwipeTableViewCellMode) -> () in
      OrderCellManager.swiping = false

      f()
    }
  }

}

A: func pan(gesture: UIPanGestureRecognizer) {
        switch gesture.state {
        case .changed: fallthrough
        case .ended:
            // update anything that depends on the pan gesture using translation.x and .y
        case .cancelled:
            //do your thing here
        default: break
        }
    }

in your viewDidLoad method add this code
self.addGestureRecognizer(UIPanGestureRecognizer(
            target: view,action:#selector(MCSwipeTableViewCell.pan(gesture:))
))

A: Maybe like this:
if gesture.state == UIGestureRecognizerState.Ended { //code }

A: I eventually did this, made available by the table cell pod I'm using:
class OrderTableManager {
  static var swiping = false
}

class OrderPreparingTableViewCell: MCSwipeTableViewCell, MCSwipeTableViewCellDelegate {
  override func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
    if !OrderTableManager.swiping {
      OrderTableManager.swiping = true
      return true
    } else {
      return false
    }
  }

  // MARK: Public
  func swipeTableViewCellDidEndSwiping(_ cell: MCSwipeTableViewCell!) {
    OrderTableManager.swiping = false
  }

  func displayOrder(order: AppState.Order, clock: Clock, fDone: @escaping SwipeHandler, fDelete: @escaping SwipeHandler) -> OrderPreparingTableViewCell {
    ...

    self.delegate = self

    ...
  }


text:
Q: Using Calculate Field tool to calculate on null fields using ArcMap I am using ArcMap 10.1.  I want to use the Calculate Field tool in ModelBuilder on a table where, if field1 is null, it should take the value of field2.  If field1 has a value then it should stay as is.

A: This should do it, and also deals with any empty or space-filled strings.
Parser: Python
Pre-Logic Script Code:
def FixNull(Field1,Field2):
  if Field1 is None or Field1.strip() == "":
    return Field2
  else:
    return Field1

Field1 =
FixNull(!Field1!, !Field2!)

A: Null is a special value, doesn't use the = sign. You use the Is keyword. You need to test if Field1 Is Null. Probably the simplest way is to just select all records where Field1 Is Null, then calculate those to Field2.

A: The Update Cursors in arcpy both (da.UpdateCursor10.1, UpdateCursor10.1) have a spot for a SQL clause ("fieldX IS NULL" or "fieldX == """) to limit the extent of records updated.
If there are other updates to be done, the records can be tested to check if they are null (if x is None:)
import arcpy

fc = "\\...\\X.gdb\\your_feature_class"
fields = ["field1", "field2"]
#field1 is row[0]; field2 is row[1]

#example 1 with sql
rows = arcpy.da.SearchCursor(fc, fields, "", "", "field1 IS NULL")
# clause may be "field1 = """ if it's a blank text field
for row in rows:
    row[0] = row[1]
    rows.updateRow(row)
del rows

#example 2 without sql clause
rows = arcpy.da.SearchCursor(fc, fields)
for row in rows:
    if row[0] is None:
    # if row[0] == ""
            row[0] = row[1]
            rows.updateRow(row)
del rows


text:
Q: Use of multiple cc and/or bcc in google apps script MailApp.sendEmail When I run the program, only boss1@gmail.com gets bcc'ed.
I've debugged the program and each variable is logged correctly.
MailApp.sendEmail(
    EPEmail,
    "Internship Opportunity at "+OP,
    emailText,{
        cc:Manager1,
        cc:EPManager2,
        cc:EPManager3,
        bcc:Boss,
        bcc:"boss1@gmail.com"}
);

A: Requirement:
Send emails with multiple cc / bcc addresses.

Solution:
From the "Advanced parameters" section of sendEmail documentation:

a comma-separated list of email addresses to CC

This means we can concatenate the variables and separate them with commas using the + operator to achieve your goal.

Example:
MailApp.sendEmail(
    EPEmail,
    "Internship Opportunity at "+OP,
    emailText,{
        cc:Manager1+','+EPManager2+','+EPManager3,
        bcc:Boss+','+"boss1@gmail.com"}
);

Reference:

*

*sendEmail(recipient, subject, body, options)

A: function myFunction(){

  // html email
  var htmlEmailBody = HtmlService.createTemplateFromFile('html-template-name');

  // email title
  var subject = "sample title..";

  // this must be set or .sendEmail will not work. You can insert your own email address to get a copy of the email or just let it blank. Alternative you can delete bcc and just the emailAddress value to send 1 email only.
  var emailAddress = "";

  // same like emailAddress this must be set aswell. You can just keep it blank and use htmlBody for your html email. Alternative delete htmlBody and use normalBody for plain text email instead.
  var normalBody = "";

MailApp.sendEmail(emailAddress, subject, normalBody, {
  name: "Your Name",
  htmlBody: htmlEmailBody.evaluate().getContent(),
  bcc: 'sample1@gmail.com,sample2@web.de'
});

}