text:
Q: Simple router in ReactJS without ReactRouter I've read that ReactRouter sucks.
How can I render different components strictly based on particular routes, i.e, with:
ReactDOM.render(<Game />, document.getElementById("root"));

How could I change this to use something like this that I found here:
const routes = [
  { path: '/', action: () => <HomePage /> },
  { path: '/game', action: () => <Game /> },
  { path: '/game2', action: () => <Game2 /> }
];

I feel like this should NOT be that complicated.

A: Here is what I have done for a simple app I have:
class SimpleRouter extends React.Component {
  render() {
    {this.getContainer()}
  }

  getContainer() {
    const url = window.location.href;

    const routes = [
      { path: '/', action: () => <HomePage /> },
      { path: '/game', action: () => <Game /> },
      { path: '/game2', action: () => <Game2 /> }
    ];

    const route = routes.find(r => url.endsWith(r));

    if (route && route.action) {
      return route.action();
    } else {
      return <DefaultContainer />;
    }
  }
}


text:
Q: How to detect if screen has rounded corners in react-native How can I detect whether device screen has rounded corners and also estimate the radius of the corners (if possible) ?
I want to modify my view more typically cardview to adapt these screens. I have successfully retrieved the screen width and height by using Dimensions
width: Dimensions.get('window').width,
height: Dimensions.get('window').height

I am not able to adapt my parent view according to the curves at 4 corners with above approach. If I give static radius to the parent view it give bad look & feel on rectangular screens and it's not acceptable.
One approach I thought of is generate a list of all devices with rounded corners and apply border radius to only these devices. But it's harder to maintain the list and adapt the list with newcomers in the market.
Can anyone help me with it ? Any sort of approach or guideline will really help me. Thank you in advance

A: After struggling with it, I came with a much easier solution that why shouldn't I ask user whether he/she has rounded cornered screen when the app starts first time and later giving an option in settings under my app to change whenever user wanted.
I stored user's selection in local storage and modified my view based on that flag. Now I don't have to maintain a list of all devices instead it will cover all use cases.

A: Currently there is no option to get corner radius from Dimensions. There is only 4 values in Dimensions object given below.
{ width: 384, height: 592, scale: 2, fontScale: 1 }

A: Even if you have answered and accepted your own answer already, it is not really a solution for the original post.
I think basically all phones with notches have round corners while devices without notches typically do not have round corners. If you have notches, you have an inset in your Safe Area. If you are using react-native-safe-area-context for example, you can get the insets with
const insets = useSafeAreaInsets();
const hasNotch = insets.top || insets.bottom || insets.right || insets.left;

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to unit test P/Invoke mappings? Assume two related projects.

*

*Functionality.dll is a C++ library that contains an Extern "C" API with multiple functions

*Interop.dll is a C# library that has static public p/invoke declarations to call into the C++ library.

I would like to have unit tests that fail whenever the mapping is outdated (because the C function changed), without having to test the functionality (that is, without having to provide valid input data for all the C functions).
How can I do this? Is there a way to test if a P/Invoke call / mapping is correct without having to actually perform the call?


text:
Q: Why doesn't returning false from OnClientClick cancel the postback I have a LinkButton where I use the OnClientClick property to ask the user whether he really wants to perform an action, e.g:
<script>
function confirmDelete() {
  return confirm('Do you really want to delete?');
}
</script>

<asp:LinkButton runat="server" OnClientClick="return confirmDelete()" ... />

This pattern usually works, but on this specific page, it doesn't. No matter whether I click OK or Cancel in the confirm dialog, the postback is executed.

Just for completeness (to answer pst's question): the rendered HTML is OK. E.g. it looks like this:
<a id="ctl00_c1_content_btnDelete" onclick="return confirmDelete();"
 href="javascript:WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions(..))"
... >
  Delete
</a>

A: The reason for the behavior was another piece of javascript, where a handler for the link(button)'s click event was registered via jquery, e.g. something similar to this:
<script>
$(document).ready(function() {
  $('a').click(function() {
    // ...
    return (someCondition == true);
  });
});
</script>

It seems this click-handler was called after the one registered by OnClientClick, and when this one returned true, then the postback occurred, independent of the result of the first click-handler (the confirm dialog).

A: Here is something which worked for me.
<asp:LinkButton runat="server" OnClientClick="return (!confirmDelete()){return false;}" />

Javascript
    function confirmDelete(){
    if(something == true){
    return true;
    }
    else{
    return false;
    }
    }


text:
Q: Jenkins build crash on android Emulator (functional tests) I have the following message on each build (headless server):

Test failed to run to completion. Reason: 'Instrumentation run failed
  due to 'Process crashed.''. Check device logcat for details Tests on
  hudson_en-US_240_WVGA_android-18_armeabi-v7a(AVD) - 4.3 failed:
  Instrumentation run failed due to 'Process crashed.'

This is the emulator command:

emulator64-arm -no-boot-anim -ports 5629,5630 -prop persist.sys.language=en -prop persist.sys.country=US -avd hudson_en-US_240_WVGA_android-18_armeabi-v7a -no-snapshot-load -no-snapshot-save -no-audio

Im using Jenkins with Android emulator and xvnc plugins. When the build is being running the functional tests, its always crashes. I don`t know why, and it is very confusing. Already tried a lot of things, like:
- with or without -no-window

A: I can check the exact config 4 you at Monday, but the problem was where, that emulator shows a dialog above our application, so the tests was not able to touch the screens :) Second: make a large emulator, where all the contents fits on the screen, just for sure.


text:
Q: Air core solenoid Melting when given 3amps with neodymium magnets as core I'm currently using magnets and ferrofluid in an art project. I'm not experienced with electrical engineering but maybe that will be obvious after reading this question.
I'm currently using this air core solenoid
https://www.schoolspecialty.com/science-first-air-core-solenoid-532015?gclid=CjwKCAjwyMfZBRAXEiwA-R3gM5FUxM-X6lp6yX7O-YWdqZLMyAb1wgY1hNIZ70pZ9scEdL1RDXTGBRoCHm0QAvD_BwE
hooked up to this power adapter https://www.amazon.com/gp/product/B078RY7BPL/ref=oh_aui_detailpage_o02_s00?ie=UTF8&psc=1
The power adapter outputs 3 Amps and the air core solenoid supposedly can take 5 amps. The positive terminal was hooked directly to the power adapter and the negative terminal was hooked up to a relay which in turn was connected to the power adapter.
Inside the core I have a stack of 20 neodymium magnets found here
https://www.amazon.com/gp/product/B071ZKQ2X5/ref=oh_aui_detailpage_o02_s00?ie=UTF8&psc=1
I have a sensor hooked up to an arduino that turns the relay on and off based on input. This makes the strength of the magnets inside the core increase and decrease in power based on whether the power supply is turned on.
In this sense it actually works great. Unfortunately it ended up heating up so much the plastic inside the solenoid melted.
Is there something wrong? Do I need to supply it with a weaker power supply? Does it have to do with the power of my magnets?

A: You have a power supply rated at 3A maximum, however you did not do anything to limit the current to the coil. There is no guarantee that you didn't draw considerably more than 3A from the power supply (overloading it and the coil).
To limit the current you would need at least something like a series resistor, or you could use a lab power supply in current limit mode. In any case you should measure the current to ensure you are not exceeding the maximum.
We are assuming here that the coil is actually capable of handling 5A continuous, but that may not in fact be true. It's possible it does not meet the stated specification, but without a measurement it's impossible to be sure.

A: Most likely you're using Fine wire that has a resistance more than eight ohms otherwise you would be current limiting.
But in any case the "Ampacity" of that wire (look up) depends on the free convection cooling of a straight wire , not confined to a small coil space so you're clearly overloading it.
Try a high velocity  fan but beware the magnetic field will load ( interfere with) the fan motor so use a longer shaft.
What you have is not an air coil, but a speaker without the diaphragm.


text:
Q: Web app development - How to transfer text in real time from one logged-in session to another? I'm developing a web app with vanilla Javascript/PHP, which is mostly supposed to be used on desktop. The user can create and edit notes, and I added an option to make it possible to dictate your notes from microphone input using webkitSpeechRecognition.
I'd like to enable the user to use their mobile device's microphone in case they don't have one for the PC. They'd do it by logging in the app from the phone; if the app detects an open note editing session on PC, it offers the user a button to record, recognize and send over the text to the PC session in real time.
Recognizing the open editing session from the mobile app and enabling speech recognition is rather straightforward. What I'm struggling about is finding an efficient way of sending over the text in real time. I thought about having a database entry for the text, which the phone feeds to and the PC session reads from constantly (by sending tons of XMLHttpRequests), but that seems too cumbersome of an approach.
Is there any other more efficient way of doing this?


text:
Q: supposed infinite loop - cleart.contnts run time error 1004 As an everlasting VBA newbe, I am here again to ask for your help.
I wrote this code:
Public ANNO As String

Sub FIFO_new()
Worksheets(15).Select
Call FifoCanc
Dim fifodest As Worksheet, fifosource As Worksheet
Dim ColumnA As Variant, ColumnB As Variant, ColumnE As Variant, ColumnF As Variant, ColumnL As Variant
Dim ColumnR As Variant, ColumnS As Variant, ColumnQ As Variant, ColumnU As Variant, ColumnT As Variant
Dim E As Integer, F As Integer
INIZIO:

'-----------------------------------------------
Set fifodest = Worksheets(15)
F = fifodest.Range("M2").Value
'------------------------------------------------
'AGGIUNGI/TOGLI RIGHE A FOGLIO VUOTO
If F = 0 Or F = -1 Then
    D = Range("D3").End(xlDown).Row
Else
    D = Range("D3").End(xlDown).End(xlDown).Row
End If
D = D - 1
With Range("A3:A" & D)
.NumberFormat = "dd/mm/yyyy"
End With
With Range("E3:E" & D)
.NumberFormat = "##,###,##0.00 ""KG"""
End With
With Range("F3:F" & D)
.NumberFormat = "##,##0.00 ""€/KG"""
End With
With Range("G3:G" & D)
.NumberFormat = "€ #,##0.00"
End With

If D < 14 And (F = 0 Or F = -1) Then
    MsgBox ("RIGHE INSUFFICIENTI")
    Range("A" & (F + 3)).Select
    H = ActiveCell.Row
    Do Until D = 15
        If F = 0 Or F = -1 Then
            F = 4
        End If
        Range("A" & F & ":L" & F).Select
        Range("A" & F & ":L" & F).Insert shift:=xlDown
        If F = 0 Or F = -1 Then
            D = Range("D3").End(xlDown).Row
        Else
            D = Range("D3").End(xlDown).End(xlDown).Row
        End If
    Loop
ElseIf D > 15 And (F = 0 Or F = -1) Then
'    D = Range("D1048576").End(xlUp).Row
    K = (D - 15)
    If F = 0 Or F = -1 Then
        F = 3
    End If
    Range("A" & F & ":L" & (F + K)).Delete shift:=xlUp
End If
'------------------------------------------------

li:
C = InputBox("INIZIO INTERVALLO (DA 1 A 12)")
D = InputBox("FINE INTERVALLO (DA 1 A 12)")
C = C + 1
D = D + 1
If D - C < 0 Then
    MsgBox ("iniziale sempre < di finale")
    GoTo li
End If

For I = C To D
Set fifosource = Worksheets(I)
E = fifosource.Range("V6").Value
If E = 0 Then
    GoTo vainext
End If
Set ColumnR = fifosource.Range("R7:R" & (E + 6))
Set ColumnS = fifosource.Range("S7:S" & (E + 6))
Set ColumnQ = fifosource.Range("Q7:Q" & (E + 6))
Set ColumnU = fifosource.Range("U7:U" & (E + 6))
Set ColumnT = fifosource.Range("T7:T" & (E + 6))

'AGGIUNGI RIGHE---------------------------------------
F = fifodest.Range("M2").Value
If F = 0 Or F = -1 Then
    L = Range("D3").End(xlDown).Row
Else
    L = Range("D3").End(xlDown).End(xlDown).Row
End If
L = L - 1
    If L < 14 Then
        GoTo INIZIO
        I = Nothing
    ElseIf L < (14 + (E + (F + 1))) Then
            If F = 0 Or F = -1 Then
                M = 4
            Else
                M = F + 3
            End If
            Range("A" & M & ":L" & (M + (E - 1))).Insert shift:=xlDown
'            D = Range("D1048576").End(xlUp).Row
    End If
'------------------------------------------------------

If F = 0 Or F = -1 Then
    M = 3
End If
Set ColumnA = fifodest.Range("A" & M & ":A" & (E + (M - 1)))
ColumnA.Select
ColumnA.Value = ColumnR.Value
Set ColumnB = fifodest.Range("B" & M & ":B" & (E + (M - 1)))
ColumnB.Value = ColumnS.Value
Set ColumnE = fifodest.Range("E" & M & ":E" & (E + (M - 1)))
ColumnE.Value = ColumnQ.Value
Set ColumnF = fifodest.Range("F" & M & ":F" & (E + (M - 1)))
ColumnF.Value = ColumnU.Value
Set ColumnL = fifodest.Range("L" & M & ":L" & (E + (M - 1)))
ColumnL.Value = ColumnT.Value
Call Gformula
vainext:
Next
fifodest.Select

Set fifodest = ActiveSheet '------

F = fifodest.Range("M2").Value
If F <= 0 Then
    L = Range("D3").End(xlDown).Row
Else
    L = Range("D3").End(xlDown).End(xlDown).Row
End If
L = L - 1

'elimina righe in eccesso
If F > 0 And L - F > 7 Then
K = (L - (F + 2)) - 7
Range("A" & (F + 4) & ":L" & (F + 2 + K)).Delete shift:=xlUp
End If

'calcolo valori ultima riga
F = fifodest.Range("M2").Value
If F <= 0 Then
    L = Range("D3").End(xlDown).Row
Else
    L = Range("D3").End(xlDown).End(xlDown).Row
End If

''L = L + 1
Range("A" & L).ClearContents
Range("A" & L).Value = Range("A" & (F + 2)).Value
Range("A" & L).Font.Bold = True

UserForm1.Show

For Each cell In Range("A3:A" & L)
If cell.Value <> "" Then
    cell.Value = Left(cell, 6) & ANNO 'Right(cell, 4) = ANNO
End If
Next

With Range("A3:A" & L)
.NumberFormat = "dd/mm/yyyy"
.NumberFormat = "mm/dd/yyyy"
.HorizontalAlignment = xlCenter
.VerticalAlignment = xlCenter
End With

With Range("H3:K" & L)
.NumberFormat = "#,##0.00"
.Interior.ColorIndex = 2
End With

With Range("D" & L)
.ClearContents
.Value = "Totali"
.Font.Bold = True
End With

With Range("E" & L)
.ClearContents
.Value = WorksheetFunction.Sum(Range("E3:E" & (L - 1)).Value)
.Font.Bold = True
.NumberFormat = "##,###,##0.00 ""KG"""
End With

With Range("G" & L)
.ClearContents
.Formula = "=SUM(G3:G" & (L - 1) & ")"
.Font.Bold = True
.NumberFormat = "€ #,##0.00"
End With

With Range("L" & L)
.ClearContents
.Value = WorksheetFunction.Sum(Range("L3:L" & (L - 1)).Value)
.Font.Bold = True
End With

Call WidthColonna
B = 0
For I = C To D
A = Worksheets(I).Range("V6").Value
B = A + B
Next
F = Range("M2").Value
If B <> F Then
    Range("M2").Interior.ColorIndex = 3
Else
    Range("M2").Interior.ColorIndex = 10
End If
ActiveSheet.Protect Password:="ponzio"
End Sub

Sub Gformula()
Dim cella As Range, cella2 As Range
B = Range("M2").Value + 1
If F <= 0 Then
    A = Range("D3").End(xlDown).Row
Else
    A = Range("D3").End(xlDown).End(xlDown).Row
End If
A = A - 1

Set cella = Range("G3")
    cella.Select
    If cella.FormulaArray <> "" And cella.Row = 3 Then
        GoTo dopo
    End If
    cella.ClearContents
    cella.FormulaArray = "=IF(RC5>=0,RC[-2]*RC[-1],-(MAX(IF(R2C8:RC8<-SUMIF(R2C5:RC5,""<0""),R2C9:RC9))-(SUMIF(R2C5:RC5,""<0"")+MAX(IF(R2C8:RC8<-SUMIF(R2C5:RC5,""<0""),R2C8:RC8)))*INDEX(R2C6:RC6,MATCH(MIN(IF(R2C8:RC8>=-SUMIF(R2C5:RC5,""<0""),R2C8:RC8)),R2C8:RC8,0))+1111))"
    cella.Replace "1111", "SUMIF(OFFSET(G3,-1,0,-ROW(G3)+1,1),""<0"")"
dopo:
Range("G4:G" & A).ClearContents
If B = 1 Then
   GoTo qui
End If
Range("G3").Select
    Selection.AutoFill Destination:=Range("G3:G" & (B + 1)), Type:=xlFillDefault
qui:
Set cella2 = Range("G3:G" & A)
'    For Each cell In cella2
'        If WorksheetFunction.IsNA(cell) = True Then
'            cell.Value = cell.Offset(0, -5).Value * (cell.Offset(-1, -3).Value / cell.Offset(-1, -5).Value)
'        End If
'    Next

Call Dformula
End Sub

Sub Dformula()
Dim cella As Range, cella2 As Range
B = Range("M2").Value + 1
If F <= 0 Then
    A = Range("D3").End(xlDown).Row
Else
    A = Range("D3").End(xlDown).End(xlDown).Row
End If
A = A - 1
Set cella = Range("D3")
    cella.Select
    If cella.FormulaArray <> "" And cella.Row = 3 Then
        GoTo dopo
    End If
    cella.ClearContents
    cella.FormulaArray = "=IF(E3>0,""Entrata"",IF(E3<0,""Uscita"",""-""))"

dopo:
Range("D4:D" & A).ClearContents
If B = 1 Then
   GoTo qui
End If
Range("D3").Select
    Selection.AutoFill Destination:=Range("D3:D" & (B + 1)), Type:=xlFillDefault
qui:
Call Hformula
End Sub

Sub Hformula()
Dim cella As Range, cella2 As Range
B = Range("M2").Value + 1
If F <= 0 Then
    A = Range("D3").End(xlDown).Row
Else
    A = Range("D3").End(xlDown).End(xlDown).Row
End If
A = A - 1
Set cella = Range("H3")
    cella.Select
    If cella.FormulaArray <> "" And cella.Row = 3 Then
        GoTo dopo
    End If
    cella.ClearContents
    cella.FormulaArray = "=SUMIF($E$3:$E3,"">0"")"
dopo:
Range("H4:H" & A).ClearContents
If B = 1 Then
   GoTo qui
End If
Range("H3").Select
    Selection.AutoFill Destination:=Range("H3:H" & (B + 1)), Type:=xlFillDefault
qui:
Call Iformula
End Sub

Sub Iformula()
Dim cella As Range, cella2 As Range
B = Range("M2").Value + 1
If F <= 0 Then
    A = Range("D3").End(xlDown).Row
Else
    A = Range("D3").End(xlDown).End(xlDown).Row
End If
A = A - 1
Set cella = Range("I3")
    cella.Select
    If cella.FormulaArray <> "" And cella.Row = 3 Then
        GoTo dopo
    End If
    cella.ClearContents
    cella.FormulaArray = "=SUMIF($E$3:$E3,"">0"",$G$3:$G3)"
dopo:
Range("I4:I" & A).ClearContents
If B = 1 Then
   GoTo qui
End If
Range("I3").Select
    Selection.AutoFill Destination:=Range("I3:I" & (B + 1)), Type:=xlFillDefault
qui:
Call Jformula
End Sub

Sub Jformula()
Dim cella As Range, cella2 As Range
B = Range("M2").Value + 1
If F <= 0 Then
    A = Range("D3").End(xlDown).Row
Else
    A = Range("D3").End(xlDown).End(xlDown).Row
End If
A = A - 1
Set cella = Range("J3")
    cella.Select
    If cella.FormulaArray <> "" And cella.Row = 3 Then
        GoTo dopo
    End If
    cella.ClearContents
    cella.FormulaArray = "=IF(ROW(RC10)=3,RC5,R[-1]C10+RC5)"
dopo:
Range("J4:J" & A).ClearContents
If B = 1 Then
   GoTo qui
End If
Range("J3").Select
    Selection.AutoFill Destination:=Range("J3:J" & (B + 1)), Type:=xlFillDefault
qui:
Call Kformula
End Sub
Sub Kformula()
Dim cella As Range, cella2 As Range
B = Range("M2").Value + 1
If F <= 0 Then
    A = Range("D3").End(xlDown).Row
Else
    A = Range("D3").End(xlDown).End(xlDown).Row
End If
A = A - 1
Set cella = Range("K3")
    cella.Select
    If cella.FormulaArray <> "" And cella.Row = 3 Then
        GoTo dopo
    End If
    cella.ClearContents
    cella.FormulaArray = "=IF(ROW(RC11)=3,RC7,R[-1]C11+RC7)"
dopo:
Range("K4:K" & A).ClearContents
If B = 1 Then
   GoTo qui
End If
Range("K3").Select
    Selection.AutoFill Destination:=Range("K3:K" & (B + 1)), Type:=xlFillDefault
qui:
End Sub

Sub WidthColonna()
With Worksheets(15)
.ColumnS(5).ColumnWidth = 15
.ColumnS(7).ColumnWidth = 12
.ColumnS(8).ColumnWidth = 12
.ColumnS(9).ColumnWidth = 12
.ColumnS(10).ColumnWidth = 12
.ColumnS(11).ColumnWidth = 12
.ColumnS(12).ColumnWidth = 8
End With
H = Range("M2").Value
If H > 4990 Then
    MsgBox ("ATTENZIONE: LINEE RECORDS > 5000")
    Exit Sub
End If

End Sub

Sub FifoCanc()
Worksheets(15).Select
ActiveSheet.Unprotect Password:="ponzio"
F = Range("m2").Value

If F > 0 Then
    D = Range("D3").End(xlDown).End(xlDown).Row - 1
ElseIf F = -1 Or F = 0 Then
    D = Range("D3").End(xlDown).Row - 1
End If
G = InputBox("CANCELLO TUTTO? (S/N)")
G = UCase(G)
If G = "S" Then
    Range("A3:L" & D).ClearContents
End If
End Sub

When it calls the fifocan subroutine, in the line where clear contents is required, it's stuck and returns

run time error 1004 clear contents method of range class failed.

The same thing happens in the other called sub routines:

*

*Gformula

*Hformula etc.

when it reaches the line with range.clear contents it's stuck.
There is surely an infinite loop somewhere.


text:
Q: tkinter 'NoneType' object has no attribute 'config' I got an error for AttributeError: 'NoneType' object has no attribute 'config' when I run a Treasure Island game I created (very original). I've looked at other posts about this and tried the same thing to no solution, anyway, here's the code:
import tkinter
window = tkinter.Tk()

window.title("Treasure Island")
window.geometry("500x500")

text = tkinter.Label(window, text='''
          |                   |                  |                     |
 _________|________________.=""_;=.______________|_____________________|_______
|                   |  ,-"_,=""     `"=.|                  |
|___________________|__"=._o`"-._        `"=.______________|___________________
          |                `"=._o`"=._      _`"=._                     |
 _________|_____________________:=._o "=._."_.-="'"=.__________________|_______
|                   |    __.--" , ; `"=._o." ,-"""-._ ".   |
|___________________|_._"  ,. .` ` `` ,  `"-._"-._   ". '__|___________________
          |           |o`"=._` , "` `; .". ,  "-._"-._; ;              |
 _________|___________| ;`-.o`"=._; ." ` '`."\` . "-._ /_______________|_______
|                   | |o;    `"-.o`"=._``  '` " ,__.--o;   |
|___________________|_| ;     (#) `-.o `"=.`_.--"_o.-; ;___|___________________
____/______/______/___|o;._    "      `".o|o_.--"    ;o;____/______/______/____
/______/______/______/_"=._o--._        ; | ;        ; ;/______/______/______/_
____/______/______/______/__"=._o--._   ;o|o;     _._;o;____/______/______/____
/______/______/______/______/____"=._o._; | ;_.--"o.--"_/______/______/______/_
____/______/______/______/______/_____"=.o|o_.--""___/______/______/______/____
/______/______/______/______/______/______/______/______/______/______/_____ /
''')

text.pack()
text = text.config(font=('length',15))

line1 = tkinter.Label(window, text="Welcome to Treasure Island,\n"
                                   "Your goal is to find the buried Treasure!")

line1.pack()
line1 = text.config(font=('length',15))

window.mainloop()

Exact error:
    line1 = text.config(font=('length',15))
AttributeError: 'NoneType' object has no attribute 'config'

A: You should check this from tkinter documents, but I suppose that tkinter.Label().config() -method does not return anything (or put it another words, it returns None).
text.pack()

## Here you set text as return value from config method
# text = text.config(font=('length',15))
## Try this intestad
text.config(font=('length',15))

line1 = tkinter.Label(window, text="Welcome to Treasure Island,\n"
                                  "Your goal is to find the buried Treasure!")

line1.pack()

## Here you try to re-use the value which is None
#line1 = text.config(font=('length',15))
## Try this instead

line1.config(font=('length',15))

window.mainloop()


text:
Q: Fermat Auto Check Script I am trying to create a script which will automatically cycle through a set of numbers and check them against the Fermat counterexample. I already have a script which takes an input of numbers from the user and checks them against the counterexample. What I would like to do is to get this system to be automated and take numbers in a specific range check all the possible combinations of these numbers in the counterexample an+bn=c**n where n>2. I was thinking of graphing the equation and having it run all the on that graph. if you have any other ideas for how to do this please help. I have already checked some other sources but can't get a real grasp on how to get a graph into the code.
def prompt_yesno(prompt):
   return input(prompt) in 'Yy'

def prompt_int(prompt, min=None):
    while True:
        try:
            ans = int(input(prompt))
            if min is None or min <= ans:
                return ans
        except ValueError:
            print("Input must be an integer.")

def is_fermat_counterexample(a, b, c, n):
    return n > 2 and a**n + b**n == c**n

def fermat_demo():
    print("Let's see if Fermat was right.")
    print("He claims that a^n + b^n = c^n cannot be true for any n > 2.")
    a = prompt_int('Give a positive integer for "a": ', 1)
    b = prompt_int('Give a positive integer for "b": ', 1)
    c = prompt_int('Give a positive integer for "c": ', 1)
    n = prompt_int('Give an integer bigger than 2 for exponent "n": ', 3)
    print("Fermat was incorrect"
      if is_fermat_counterexample(a, b, c, n) else
      "No, that does not work!")

while True:
    fermat_demo()
    if not prompt_yesno("Would you like to try again?\n"
                    "Type 'Y' to continue and 'N' to exit: "):
        break

A: It would be good to take range for a,b and n only and calculate c.
If range of a,b is [1 to X] and range of n is [3 to N] then call following method for every combination of (a, b, n) to find a counter example -
def is_fermat_counterexample(a, b, n):
    value = a**n + b**n
    c = value**(1/n)
    return (c.is_integer() and (int(c) > 0))


text:
Q: Is there a way to use super() to call the __init__ method of each base class in Python? Let's suppose I have a bit of Python code:
class Mother:
    def __init__(self):
        print("Mother")

class Father:
    def __init__(self):
        print("Father")

class Daughter(Mother, Father):
    def __init__(self):
        print("Daughter")
        super().__init__()

d = Daughter()

This script prints "Daughter". Is there anyway to ensure that all of the __init__ methods of the bases classes are called? One method I came up with to do this was:
class Daughter(Mother, Father):
    def __init__(self):
        print("Daughter")
        for base in type(self).__bases__:
            base.__init__(self)

This script prints "Daughter", "Mother", "Father". Is there a nice way to do this using super() or another method?

A: Raymond Hettinger explained this really well in his talk Super Considered Super from PyCon 2015.  The short answer is yes, if you design this way, and call super().__init__() in each class
class Mother:
    def __init__(self):
        super().__init__()
        print("Mother")

class Father:
    def __init__(self):
        super().__init__()
        print("Father")

class Daughter(Mother, Father):
    def __init__(self):
        super().__init__()
        print("Daughter")

The name super is unfortunate, it really works its way through the base classes.


text:
Q: How to select specific row by foreign key? I have two table:
class symbol(models.Model):
    ticker = models.CharField(max_length=40)
    instrument = models.CharField(max_length=64, default='stock')
    name = models.CharField(max_length=200)
    sector = models.CharField(max_length=200, default=None)
    currency = models.CharField(max_length=64, default='USD')
    created_date = models.DateTimeField(auto_now=True)
    last_updated_date = models.DateTimeField(auto_now=True)

class daily_price(models.Model):
    symbol = models.ForeignKey(symbol)
    price_date = models.DateTimeField()
    created_date = models.DateTimeField()
    last_updated_date = models.DateTimeField()
    open_price = models.DecimalField(max_digits=19, decimal_places=4)
    high_price = models.DecimalField(max_digits=19, decimal_places=4)
    low_price = models.DecimalField(max_digits=19, decimal_places=4)
    close_price = models.DecimalField(max_digits=19, decimal_places=4)
    adj_close_price = models.DecimalField(max_digits=19, decimal_places=4)
    volume = models.BigIntegerField()

I want to select table strategyceleryapp_daily_price's rows.
I want to use read_sql_query to select specific row by symbol's ticker(foreign key)
con = sqlite3.connect("/home/leo/github/StrategyCeleryWebsite/db.sqlite3")
df = pd.read_sql_query("SELECT * from strategyceleryapp_daily_price", con)

# verify that result of SQL query is stored in the dataframe
print(df.head())

con.close()

In django, I can use daily_price.objects.get(symbol__ticker='AAPL').
But I don't know how to write the command from sql command.
How should I write this command?
Thank you very much.

A: in SQL, you join tables and check for value:
SELECT dp.* from strategyceleryapp_daily_price dp INNER JOIN strategyceleryapp_symbol s on dp.symbod_id=s.id where s.ticker='AAPL'

You can check a query that django create with:
python manage.py dbshell

and then:
print(daily_price.objects.get(symbol__ticker='AAPL').query)


text:
Q: html form sending GET instead of POST on form submit Pardon my web skills but i have a very rudimentary problem.
I have this html form which should ideally call my /login url with post but for some reason it always sends a get request to that url and fails. I can't figure out how that is happening.
This is my html form
<!DOCTYPE html>

    <title>Login - MobileMedic</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta name="description" content="">
    <meta name="author" content="" />

    <link rel="stylesheet" href="http://fonts.googleapis.com/css?family=Open+Sans:400italic,600italic,800italic,400,600,800" type="text/css">
    <link rel="stylesheet" href="./css/font-awesome.min.css" type="text/css" />
    <link rel="stylesheet" href="./css/bootstrap.min.css" type="text/css" />
    <link rel="stylesheet" href="./css/jquery-ui-1.9.2.custom.min.css" type="text/css" />
    <link rel="stylesheet" href="./css/App.css" type="text/css" />
    <link rel="stylesheet" href="./css/Login.css" type="text/css" />
    <link rel="stylesheet" href="./css/custom.css" type="text/css" />

Welcome to Apprick Technologies.

Please sign in to get access.

            <form method="post" action="/login" id="login-form" class="form parsley-form" data-validate="parsley">

                    <input type="email" class="form-control" id="email" placeholder="Email" required="required">

                    <input type="password" class="form-control" id="password" placeholder="Password" required="required">

                    <input type="submit" class="btn btn-primary btn-block" name= "Signin" value="Signin"/>

            </form>

To make the question more clear i use express js with parse.com and here are the two routing defined
app.get('/login', function(req, res) {
    res.send('get is called');
});

app.post('/login', function(req, res) {
    res.send('post is called');
});

Now no matter what i provide in my form method i always get "get is called" in the browser on submitting the button.
I also tried to debug what is happening in by the developer console and this is what i get

A: I tried your code and it is working as a "POST" request. Try changing your request to "GET" and you can notice in the URL that it has something like this at the end "?Signin=Signin".
Include a "name" attribute to your input tags.
Sample:
<input type="email" name="email" class="form-control" id="email" placeholder="Email" required="required">

And you can see something like this upon submitting the form:
/login?email=testemail%40test.test&Signin=Signin


text:
Q: How do you check if a Loader is still loading or running? How do you do this normally? What I want is to check the "state" of the loader: if it is running, or it has stopped. There are not enough questions on this issue which I think it fairly important

A: getLoaderManager().getLoader(id).isStarted() is about as far as I can see using the available APIs. If you need something more refined, you'll probably have to subclass whichever Loader you are using now to add some extra state information, then cast to that after calling getLoader(id).


text:
Q: GridView with base adapter not responding to the first click on the first item in the GridView until i scroll Am using a base adapter that create the child views for the grid and the holder view has more than one clickable control each perform an action.
here is the getView() method code
public View getView(final int position, View convertView, ViewGroup parent) {
        if (convertView == null) {

            inflater = (LayoutInflater) mContext
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            convertView = inflater.inflate(R.layout.book_item_to_download, parent, false);
            convertView.setFocusable(true);
            convertView.setClickable(true);

            holderGridView = new BooksViewHolder();

            holderGridView.BookImage = (ImageView) convertView.findViewById(R.id.bookBackground);
            holderGridView.BookName = (TextView) convertView.findViewById(R.id.bookName);
            holderGridView.BookItemWraper = (LinearLayout) convertView.findViewById(R.id.book_item_wraper);
            holderGridView.BookDownload=(ImageView) convertView.findViewById(R.id.download);
            holderGridView.BookProgress=(CircularProgressBar) convertView.findViewById(R.id.demo_mpc);

            Typeface custom_font = Typeface.createFromAsset(getActivity().getAssets(), "fonts/Isra-Thin.ttf");
            holderGridView.BookName.setTypeface(custom_font);
            convertView.setTag(holderGridView);
        } else {
            holderGridView = (BooksViewHolder) convertView.getTag();
        }

        holderGridView.BookItemWraper.setLayoutParams(new android.widget.AbsListView.LayoutParams((int) Math.round(ScreenWidth / 2.1), (int) Math.round(ScreenHeight / 2.5)));
        holderGridView.BookImage.setImageDrawable(getResources().getDrawable(R.drawable.book_background));
        holderGridView.BookName.setText(bookCovers.get(position).getBookTitle());

        ImageView image = holderGridView.BookImage;

        //DisplayImage function from ImageLoader Class
        imageLoader.DisplayImage(bookCovers.get(position).getBookImageURL(), image);

            if(bookCovers.get(position).isDownloaded)
            {
                holderGridView.BookDownload.setVisibility(View.GONE);
                holderGridView.BookProgress.setVisibility(View.GONE);
                holderGridView.BookItemWraper.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        for(int i=0;i<app.bis.size();++i)
                        {
                            if(app.bis.get(i).identifier.equals(bookCovers.get(position).getBookID()+""))
                            {
                                openBookViewer(app.bis.get(i));
                                break;
                            }
                        }
                    }
                });
            }
            else if(bookCovers.get(position).isDownloading)
            {
                holderGridView.BookDownload.setVisibility(View.GONE);
                holderGridView.BookProgress.setVisibility(View.VISIBLE);
                holderGridView.BookProgress.setProgress(bookCovers.get(position).downloadProgress);
                holderGridView.BookItemWraper.setOnClickListener(null);
            }
            else {
                holderGridView.BookDownload.setVisibility(View.VISIBLE);
                holderGridView.BookProgress.setVisibility(View.GONE);

                holderGridView.BookItemWraper.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent openDetails = new Intent(getActivity(), WaitingBookDetails_Activity.class);
                        openDetails.putExtra(Constants.BOOK_COVER, Parcels.wrap(bookCovers.get(position)));
                        startActivity(openDetails);
                    }
                });

                holderGridView.BookDownload.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        new downloadEPUB_Task(bookCovers.get(position), position).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
                    }
                });
            }

        return  convertView;
    }

when the GridView first initialize if i click on first item on any control in the holder view it wont respond until i scroll the GridView slightly, Note: only the first click on the first item when initially the app opens than the rest of the clicks are fine and am using LazyLoading to load images to the ImageView in the holder view and the scrolling performance is great even on slow devices so its not a memory thing i guess.
Thanks in advance for any help.

A: remove below line from getView() method and try it;
convertView.setFocusable(true);
convertView.setClickable(true);

add  the below  click listner outside  else part of your code and try it,
holderGridView.BookItemWraper.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent openDetails = new Intent(getActivity(), WaitingBookDetails_Activity.class);
                    openDetails.putExtra(Constants.BOOK_COVER, Parcels.wrap(bookCovers.get(position)));
                    startActivity(openDetails);
                }
            });

            holderGridView.BookDownload.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    new downloadEPUB_Task(bookCovers.get(position), position).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
                }
            });


text:
Q: Apache: SSL certificate not working with www, how to remove? Im trying to setup our VPS with a newly installed SSL certificate. The certificate is for only domain.com, not www.domain.com. So when a user visits https://www.domain.com they now get an "insecure page" warning - which I of course don't want to have. I want to redirect the user to https://domain.com, but I keep getting stuck in infinite loops all the time..
Here's my virtual host file..
<VirtualHost *:80>
     ServerAdmin my@email.com
     ServerName domain.com
     ServerAlias domain.com
     Redirect permanent / https://domain.com/
     DocumentRoot /var/www/domain.com/
     <Directory /var/www/domain.com/>
        AllowOverride ALL
     </Directory>
     ErrorLog /var/www/logs/domain.com/error.log
     CustomLog /var/www/logs/domain.com/access.log combined
</VirtualHost>

<VirtualHost *:443>
     ServerAdmin my@email.com
     ServerName domain.com
     ServerAlias domain.com
     DocumentRoot /var/www/domain.com/
     <Directory /var/www/domain.com/>
        AllowOverride ALL
     </Directory>
     ErrorLog /var/www/logs/domain.com/error.log
     CustomLog /var/www/logs/domain.com/access.log combined
     SSLEngine on
     SSLProtocol all
     SSLCertificateFile /etc/ssl/mycert.crt
     SSLCertificateKeyFile /etc/ssl/mykey.key
     SSLCACertificateFile /etc/ssl/myca.crt
</VirtualHost>

Im a beginner at this, and I can't seem to find a solution besides buying a wildcard certificate which I really cannot afford..
Thank you very much in advance!

A: You might needed to redirect all your www url calls to non-www.. Try the following rewrite rules with your .htaccess
RewriteEngine On
RewriteCond %{HTTP_HOST}  ^www.example.com [nocase]
RewriteRule ^(.*)         http://example.com/ [last,redirect=301]

Replace example.com with your domain name and make sure to put this in the .htaccess at the document root of your website.


text:
Q: MixHash working usefully - but need some clarifications This is a (slightly belated) follow up to Does Baggy add (+) work on MixHash weights? . MixHash is a great tool for Unit comparisons - since I know that my dmix => ("m"=>2,"kg"=>1,"s"=>-2).MixHash is the same for 'kg m2 per s2' and 'kg.m^2/s^2', and so on.
Here is the threefold clarity I seek:

*

*I still need to coerce the result of MixHash (+) MixHash to MixHash (the default result is an immutable Mix) - is it still the intent for the result of ops on one or more MixHashen to be a MixHash?

*The result if MixHash (+) Any sneaks in a naughty unwanted element dmix => ("m"=>2,"kg"=>1,"s"=>-2,"MixHash"=>1) - this is a bug, right. [I have patched by setting the deflation default to empty set... MixHash $.dmix is rw = ∅.MixHash;]

*The docs https://docs.raku.org/language/setbagmix show (+) as Baggy addition, but (-) as Set Difference. When I do MixHash (-) MixHash I seem to get Baggy subtraction - which is what I want. Hopefully this is an oversight in the docs??

Let me know if I can provide code or should submit a bug report...

A: *

*Yes, if either side of a set operator is a mutable version, then the result should also be a mutable version.  If it is not, it is a bug.

*Any is a value, albeit an undefined one.  So effectively, the right hand side is acting as if it is a Any.MixHash (which is (Any=>1).MixHash).  So this is not a bug.  Also, alternately, you could say has %.dmix is MixHash

*This is indeed a problem in the docs.  Not really an oversight, but actually a failure to update, because in an older implementation of the set operators, that was the behaviour.


text:
Q: How can I modify the "header" section in ActiveAdmin, in each request? I'm a bit of a newbie to ActiveAdmin, and I'm trying to show big and bold warnings when some situations arise.
I have no idea how to do this after reading the documentation.
The best I managed to do was selectively register pages or not register them, based on some conditions. The objective of that was to add menu elements selectively.
This worked in dev, but fails in production where code doesn't get reloaded in every request.
if warnings
  main_menu_title = fatal ? "Fatal Warnings" : "Warnings"

  ActiveAdmin.register_page main_menu_title do
    menu :priority => 99
  end
  ActiveAdmin.register_page "Warnings_job_count" do
    menu :label => "#{delayed_job_count} delayed jobs", :parent => main_menu_title, :priority => 1
  end
  ActiveAdmin.register_page "Warnings_job_errors" do
    menu :label => "#{delayed_job_error_count} delayed jobs with errors", :parent => main_menu_title, :priority => 2
  end
end

So, in short, the question is...
Is it possible to declare a block somewhere, that will be executed in every request, in all pages, and that has the ability to either add elements to the menu, or somehow modify the header section?
Thank you very much!
Daniel

A: You can use something this this as explained here https://stackoverflow.com/a/7218598/807442
# app/admin/views/header_renderer.rb
module ActiveAdmin
    module Views
      class HeaderRenderer
        def to_html
          title + custom_block + global_navigation + utility_navigation
        end

        def custom_block
          # Your custom block
        end
      end
    end
  end

You can also add items to the menu like this:
current_menu.add(main_menu_title , url_symbol, priority)

# For sub-items
main_menu = current_menu[main_menu_title]
main_menu.add(sub_item_title, url_symbol, priority)

However, if you add these, they will remain there in future requests. so you may need to also remove them, in each request, and then only add it necessary. To do that, add this:
module ActiveAdmin
  class Menu
    def remove(name)
      item = self[name]
      return if item.nil?
      @items.delete(item)
    end
  end
end

and you can remove by name.


text:
Q: C# Databound Windows Forms control does not retain value unless you leave the field I saw the answer in Databound Windows Forms control does not recognize change until losing focus.
But this doesn't fully answer the question for me. I have the exact same situation. On ToolStrip_click, I go through all of my controls and I force "WriteValue()", but it still reverts to the previous value before the save. Can anyone suggest how I can fix this? Did I implement this incorrectly?
(See code for current (non-working) solution.)
private void menuStrip1_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
{
    // Make sure that all items have updated databindings.
    foreach (Control C in this.Controls)
    {
        foreach (Binding b in C.DataBindings)
        {
            // Help: this doesn't seem to be working.
            b.WriteValue();
        }
    }
}

The code is now much simpler, but it is a considerable hack. I'd be very happy to know if there is a more "proper" fix for this.
private void menuStrip1_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
{
    // Make sure that all text fields have updated by forcing everything
    // to lose focus except this lonely little label.
    label44.Focus();
}

A: A ToolStripButton does not take the Focus when clicked. You could add some code to (temporarily) focus another control. You can Focus a Label (as a neutral dummy).

A: What are you binding to? If it's a DataSet, DataTable, etc., or better yet, a BindingSource, you should call EndEdit:
private void menuStrip1_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
{
    // Assuming that you are binding to bindingSource1:
    bindingSource1.EndEdit();
}

I implement an ISave interface on my forms to handle dirty state and saving and whenever the dirty state is checked (whenever IsDirty is called), I always EndEdit on my binding source:
interface ISave
{
    bool IsDirty;
    bool Save(bool force);
}

With this interface, when, say, the application is shutting down, I can easily iterate through my open MdiChild windows checking to see if any information has been saved by casting the child form to ISave and checking the value of IsDirty. Here, I call EndEdit on either the appropriate binding source or, if applicable, the binding control (for example, a grid).
And forgive the ramble, but I thought this might be helpful. The rest works like so:
Save() takes a parameter of "force", so I can have a "Save & Close" button a form (saves the user an extra click or confirmation asking if they want to save their changes). If force is false, the Save() method is responsible for asking the user if they want to save. If it's true, it's assumed the user has already decided they definitely want to save their information, and this confirmation is skipped.
Save() returns bool- true if it's safe to continue executing the calling code (presumably a Form_Closing event). In this case, (if force was false), given a YesNoCancel MessageBox, the user either selected Yes or No and the save itself did not throw an error. Or, Save() returns false in the event the user chose Cancel or there was an error (in other words, telling the calling code to cancel a form close).
How you handle the errors depends on your exception-catching conventions - this could either be caught in the Save() method and displayed to the user or perhaps in an event such as FormClosing where e.Cancel would then be set to true.
Used with a form closing event it would look like this:
private void form1_FormClosing(object sender, CancelEventArgs e)
{
    if (IsDirty)
        e.Cancel = !Save(false);
}

Used with a forced save from a Save & Close button, it would look like this:
private void btnSaveAndClose_Click(object sender, EventArgs e)
{
     if (IsDirty)
        if (Save(true))
            Close();
}

Anyway, a little more than you asked for, but I hope this helps!

A: The problem is probably that your databound controls are set to update on validation.
You need to set the DataSourceUpdateMode of each of the databound controls to DataSourceUpdateMode.OnPropertyChanged.  For example, a databound textbox:
this.textBox1.DataBindings.Add(new System.Windows.Forms.Binding("Text",
    this.someBindingSource, "SomeProperty", true,
    System.Windows.Forms.DataSourceUpdateMode.OnPropertyChanged));

You can also set the datasource update mode in the designer by :
Selecting the control and going to the Property Window -> (DataBindings) -> (Advanced)
-> Set the [Data Source Update Mode] in the dropdownlist to OnPropertyChanged.
cheers

A: Try this:
private void menuStrip1_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
{
    // Make sure that all items have updated databindings.
    foreach (Control C in this.Controls)
    {
        C.SuspendLayout();
        foreach (Binding b in C.DataBindings)
        {
            // Help: this doesn't seem to be working.
            b.WriteValue();
        }
        C.ResumeLayout();
    }
}

A: This has stumped me in the past. In addition to the DataSourceUpdateMode being set to OnPropertyChanged, the underlying column in the data source must not be read only.
Check it for your column in a DataTable:
dataTable.Columns("ColumnName").ReadOnly
I even made a function that sets all columns to not be ReadOnly, which has come in handy more than once:
Public Function MakeReadOnlyFalse(ByVal dt As DataTable) As DataTable

    For Each col As DataColumn In dt.Columns
        If col.ReadOnly Then
            col.ReadOnly = False
        End If
    Next

    Return dt
End Function

A: For me this is worst. If i set the update source mode to OnPropertyChanged on combobox, it behave just like if i had set this to Onvalidation mode! Bindings are far more better in wpf.


text:
Q: Cassandra Data Centers and Cluster(s) Ring(s) relation I have a Cassandra cluster with 8 nodes in 2 datacenters respectively 4-4 nodes in DC1 and DC2.
I've created a keyspace:
CREATE KEYSPACE mykeyspace
  WITH REPLICATION = {
   'class' : 'NetworkTopologyStrategy',
   'DC1' : 2,
   'DC2' : 2,
  };

As far as I understand, both DC1 and DC2 will have all the data, with other words in case of whole DC1 goes offline, DC2 will capable to serve all data.
Question
Should we say that based on the previous fact both DC1 and DC2 are a "complete" ring in their own? (regarding the whole hash -2^63-1 .. +2^63 will be presented by nodes on DC1 and the same is true for DC2)
Why I am asking this?
My answer would be no, this is still one cluster, so one ring, regardless there are two subset of nodes which are contain all the data. However many image and illustrations represent the nodes in the two datacenters with two "circles" which hints the term two "rings". (obviously not two clusters)
see for example:
DataStax: Multiple datacenter write requests
PS: If it is possible do not bring to the picture the consistency levels. I understand that the inter node communication workflow depends on if the operation is write or read, and also depends on the consistency level.
A practical question which depends on the answer:
Say in DC1 num_tokens: 256 for all nodes and DC2 num_tokens: 32 for all nodes. Those numbers will be relative to each other if the 8 node are in one token ring, but in case of DC1 and DC2 are two separate token rings those number (256 and 32) are nothing to do with each other...

A: Look, if you use SimpleStrategy it work as just one ring.
If you use NetworkTopology looks like two or more rings. You can use nodetool ring to see tokens vs nodes and nodetool getendpoints keyspace table partition_key to see where your partition key will be located.
[root@ip-20-0-1-226 ~]# nodetool ring

Datacenter: dc1
==========
Address     Rack        Status State   Load            Owns                Token
                                                                           8037128101152694619
20.0.1.50   rack1       Up     Normal  456.32 MiB      41.66%              -9050061154907259251
20.0.1.50   rack1       Up     Normal  456.32 MiB      41.66%              -8877859671879922723
20.0.1.226  rack2       Up     Normal  608.99 MiB      58.34%              -8871087231721285506
20.0.1.50   rack1       Up     Normal  456.32 MiB      41.66%              -8594840449446657067
20.0.1.226  rack2       Up     Normal  608.99 MiB      58.34%              -2980375791196469732
20.0.1.226  rack2       Up     Normal  608.99 MiB      58.34%              -2899706862324328975
20.0.1.50   rack1       Up     Normal  456.32 MiB      41.66%              -2406342150306062345
20.0.1.226  rack2       Up     Normal  608.99 MiB      58.34%              -2029972788998320465
20.0.1.50   rack1       Up     Normal  456.32 MiB      41.66%              -1666526652028070649
20.0.1.226  rack2       Up     Normal  608.99 MiB      58.34%              1079561723841835665
20.0.1.226  rack2       Up     Normal  608.99 MiB      58.34%              1663305819374808009
20.0.1.50   rack1       Up     Normal  456.32 MiB      41.66%              4099186620247408174
20.0.1.50   rack1       Up     Normal  456.32 MiB      41.66%              5181974457141074579
20.0.1.226  rack2       Up     Normal  608.99 MiB      58.34%              6403842400328155928
20.0.1.226  rack2       Up     Normal  608.99 MiB      58.34%              6535209989509674611
20.0.1.50   rack1       Up     Normal  456.32 MiB      41.66%              8037128101152694619

[root@ip-20-0-1-44 ~]# nodetool ring

Datacenter: dc1
==========
Address     Rack        Status State   Load            Owns                Token
                                                                           8865515588426899552
20.0.1.44   rack1       Up     Normal  337.81 MiB      100.00%             -5830638745978850993
20.0.1.44   rack1       Up     Normal  337.81 MiB      100.00%             -4570936939416887314
20.0.1.44   rack1       Up     Normal  337.81 MiB      100.00%             -4234199013293852138
20.0.1.44   rack1       Up     Normal  337.81 MiB      100.00%             -3212848663801274832
20.0.1.44   rack1       Up     Normal  337.81 MiB      100.00%             -2683544040240894822
20.0.1.44   rack1       Up     Normal  337.81 MiB      100.00%             6070021776298348267
20.0.1.44   rack1       Up     Normal  337.81 MiB      100.00%             7319793018057117390
20.0.1.44   rack1       Up     Normal  337.81 MiB      100.00%             8865515588426899552

Datacenter: dc2
==========
Address     Rack        Status State   Load            Owns                Token
                                                                           7042359221330965349
20.0.1.150  rack1       Up     Normal  323.66 MiB      100.00%             -6507323776677663977
20.0.1.150  rack1       Up     Normal  323.66 MiB      100.00%             -2315356636250039239
20.0.1.150  rack1       Up     Normal  323.66 MiB      100.00%             -2097227748877766854
20.0.1.150  rack1       Up     Normal  323.66 MiB      100.00%             -630561501032529888
20.0.1.150  rack1       Up     Normal  323.66 MiB      100.00%             2580829093211157045
20.0.1.150  rack1       Up     Normal  323.66 MiB      100.00%             4687230732027490213
20.0.1.150  rack1       Up     Normal  323.66 MiB      100.00%             4817758060672762980
20.0.1.150  rack1       Up     Normal  323.66 MiB      100.00%             7042359221330965349

[root@ip-20-0-1-44 ~]# nodetool getendpoints qa eventsrawtest "host1","2019-03-29","service1"
20.0.1.150
20.0.1.44

CREATE KEYSPACE qa WITH replication = {'class': 'NetworkTopologyStrategy', 'dc1': '1', 'dc2': '1'}  AND durable_writes = true;
CREATE TABLE eventsrawtest (
        host text,
        bucket_time text,
        service text,
        time timestamp,
        metric double,
        state text,
        PRIMARY KEY ((host, bucket_time, service), time)
  ) WITH CLUSTERING ORDER BY (time DESC)

A: The short answer is: Both DC will have 2 replicas. Then 4 replicas for your data.
Cassandra is smart enough to understand your topology and distribute data.
It's also important distribute data between racks (rack awareness), since Cassandra will write one replica in each rack. Then you will be sure that your data is spread and you can loose up to 6 nodes without losing data (considering all your keyspaces with mentioned replication factor).
DC1
- rack1
-- 2 nodes
- rack2
-- 2 nodes

DC2
- rack1
-- 2 nodes
- rack2
-- 2 nodes

Finally, you can have distinct num_tokens between DCs. It will not affect replication factor.
If you can check doc, it's recommended a smaller value.
https://cassandra.apache.org/doc/latest/cassandra/getting_started/production.html


text:
Q: OpenConnect "Unknown form id frmTotpToken" Error on Login I'm on Ubuntu 18.04.1 LTS. I'm trying to login to VPN using Juniper / Pulse Network connect.
 After setting up the connection in the network manager, when I tried to login I got  Unknown form id frmTotpToken  error.
How do I solve this?
Thanks

A: It seems that this has been addressed in a fork of openconnect.  See this commit for details.


text:
Q: Formatting string dates to always follow yyyy-mm-dd format (non-epoch) I have 3 different clients (Android, iOS and Web) all hitting the same endpoint parsing a date string which needs to be stored as yyyy-mm-dd. Android and iOS date pickers both seem to be parsing the correct format but excluding the zeros for months and days in the single digits i.e 2019-8-9 instead of 2019-08-09.
Moment.js does't seem to have a solution to this. I would like a solution that can be handled server side in vanilla js so as to not need updates to be made to the Android and iOS apps functions that parse the data.
This is my current solution. Works as it should. Curious to see if anyone can come up with a cleaner/leaner solution.
function checkDateFormat(date){
    return new Promise (resolve=>{
        if(date.length == 8){
            // Both month and day are single digits and should be fixed
            var firstFix = date.substr(0, 5) + "0" + date.substr(5);
            var secondFix = firstFix .substr(0, 8) + "0" + firstFix.substr(8);
            resolve(secondFix);
        } else if (date.length == 9){
            if(date.substr(6,1) == "-"){
                // Month is single digit and should be fixed
                var monthFix = date.substr(0, 5) + "0" + date.substr(5);
                resolve(monthFix);
            } else {
                // Day is single digit and should be fixed
                var dayFix = date.substr(0, 8) + "0" + date.substr(8);
                resolve(dayFix);
            }
        } else {
            resolve(date);
        }
    });
}

Should resolve string consistently as yyyy-mm-dd and never yyyy-m-dd or yyyy-mm-d

A: If you know that's the only formatting issue you can expect, you could just make a function to shove a zero at the start of any digit smaller than 10, and another to split the string so you can parse the day and month values.

let goodDate = "2019-08-09";
let badDate = "2019-8-9";

function paddedZero(str){
  return parseInt(str) > 9 ? str : `0${parseInt(str)}`;
}

function formatDateStr(str){
  let [year, month, day] = str.split("-");
  return `${year}-${paddedZero(month)}-${paddedZero(day)}`;
}

console.log(formatDateStr(goodDate));
console.log(formatDateStr(badDate));

A: I would do it like this:
function padZero(str) {
  return str.length === 1 ? '0' + str : str;
}

function checkDateFormat(date){
    date = date.split("-");
    date[1] = padZero(date[1]);
    date[2] = padZero(date[2]);
    return date.join("-");
}

A: Simple regular expression replace would be enough :

console.log( '2000-1-2'.replace(/\b\d\b/g, '0$&') )

A: First of all, I'm not sure why you need a Promise here since I can't see any real async code, but anyway, the core part would be:
const ensureDateFormat = (date) =>
  new Date(date).toISOString().substr(0, 10);

If you want to return a promise, you could always return a resolved promise:
const ensureDateFormat = (date) =>
  Promise.resolve(new Date(date).toISOString().substr(0, 10));

Notice that this is assume you don't have year prior 0 or after 9999. See https://en.wikipedia.org/wiki/ISO_8601


text:
Q: Calculate Thevenin voltage in a Common Emitter Circuit
I am confused on how to proceed with the above problem. I have solved many problems on thevenin voltage but never faced one involving BJT. Please help me with this problem.
EDIT: I have 2 approaches in my mind.
1st Approach is short ckt a and b and get Isc. Calculate Voc for open circuit case and divide Voc by Isc to get Rth.

2nd Approach is to calculate re using DC Analysis. Then draw small signal model short circuiting DC and use this circuit to get Rth.

Both approaches look perfectly fine. Which one is correct and why?

A: It's been +25 years but I gonna give it a try ...
\$R_{th}=\dfrac{V_{oc}}{I_{sc}}\$

Calculating \$I_{sc}\$ :
\$I_{b}=\dfrac{10.7V - 0.7V}{10k\Omega}=1mA\$
\$I_{c}=I_{b}\cdot\beta =1mA\cdot100=100mA\$
\$I_{sc}=I_{b}+I_{c}=1mA+100mA=101mA\$

Calculating \$V_{oc}\$ :
\$-10.7+10000\cdot I_{b}+0.7+1000\cdot(\beta+1)\cdot I_{b}=0\$
\$10000\cdot I_{b}+1000\cdot101\cdot I_{b}=10\$
\$I_{b}=\dfrac{1}{11100} A\$
\$I_{e}=(\beta+1)\cdot I_{b}=\dfrac{101}{11100}A\$
\$V_{oc}=I_{e}\cdot 1k\Omega=\dfrac{101\cdot1000}{11100}V=\dfrac{1010}{111}V\$

\$R_{th}=\dfrac{V_{oc}}{I_{sc}}=\dfrac{\dfrac{1010}{111}V}{101mA}=90.09\Omega\$

PS : It's 5:49AM here, time to get some sleep.


text:
Q: Connectedness condition by basis\sub-basis I know that some basic topological properties like compactness, $T_0$ and $T_1$ are among the properties which can be tested by a basis of the topology. I was wondering whether there is such a condition for connectedness of certain topological spaces?
For example, clearly if $\mathcal{B}$ is a sub-basis and $E,E^c\in \mathcal{B}$, then the space is not connected. It seems likely that we should be able obtain some sort condition and thought that perhaps someone here would know of such a condition.


text:
Q: Is the probability of the union of $N$ sets increasing in all terms? i.e., $P(A\cup B)=P(A)+P(B)-P(A)P(B)$ is increasing in $P(A)$ and $P(B)$ I wonder if the pprobability of the union of $N$ independent events $P(A_1\cup A_2\cup ...A_N)$ is increasing in all its terms when it is decomposed. To be more precise Let $N=2$ then the intersection of two tests can be given as $P(A\cup B)=P(A)+P(B)-P(A)P(B)$, which  can be translated to some function of two variables  $f(x,y)=x+y-xy$. It is obvious that $f(x,y)$ is increasing in both $x$ and $y$. In a similar way, if we write the intersection of $3$ events we will have the function $$f(x,y,z)=x+y+z-(xy+xz+yz)+xyz$$ which is also increasing in all $3$ terms $x$, $y$ and $z$. If $N$ is $4$ or $5$ or in general $N$, do we have any proof which shows that $f(x,y,z,...)$ is increasing in $x,y,z,..$?
Thanks in advance.
Sorry for previous confusing post.

A: If the events $(A_i)$ are independent, then
$$
P(A_1\cup A_2\cup\cdots\cup A_N)=1-P(A_1^c\cap A_2^c\cap\cdots\cap A_N^c)=1-\prod_{i=1}^NP(A_i^c),
$$
hence
$$
P(A_1\cup A_2\cup\cdots\cup A_N)=G(P(A_1),P(A_2),\ldots,P(A_N)),
$$
where
$$
G(x_1,x_2,\ldots,x_N)=1-\prod_{i=1}^N(1-x_i),
$$
that is, yes, $P(A_1\cup A_2\cup\cdots\cup A_N)$ is a nondecreasing function of each argument $P(A_i)$.


text:
Q: How to pass a JSON object from Svelte to Quarkus I'm playing with Svelte on the frontend and Quarkus on the backend.
I'm finding myself unable to get an object passed from the front to the backend's search method.
Help is appreciated.
   let endpoint = "http://localhost:8080/api/users/search";

   async function apiCall() {
      try {
        const res = await axios.post(endpoint, {
           headers: {},
           params: {name: 'John', surname: 'Doe'}
        });

        //...
      } catch (e) {
      }
   }

@Path("/api/users")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public class UserResource {

    //...

    @POST
    @Path("/search")
    public Response search(User user) {
        String name = user.getName();
        //This throws a NullPointerException because user is null

        //...
    }

}

A: Problem solved.
Simply:
let data = {name: 'John', surname: 'Doe'};
const res = await axios.post(endpoint, data)


text:
Q: Network structure for online programming game with webSockets Problem
I'm making a game where you would provide a piece of code to represent the agent program of an Intelligent Agent (think Robocode and the like), but browser-based. Being an AI/ML guy for the most part, my knowledge of web development was/is pretty lacking, so I'm having a bit of a trouble implementing the whole architecture. Basically, after the upload of text (code), naturally part of the client-side, the backend would be responsible for running the core logics and returning JSON data that would be parsed and used by the client mainly for the drawing part. There isn't really a need for multiplayer support right now.
If I model after Robocode's execution loop, I would need a separate process for each battle that then assigns different agents (user-made or not) to different threads and gives them some execution time for each loop, generating new information to be given to the agents as well as data for drawing the whole scene. I've tried to think of a good way to structure the multiple clients, servers/web servers/processes [...], and came to multiple possible solutions.
Favored solution (as of right now)
Clients communicate with a Node.js server that works kinda like an interface (think websocketd) for unique processes running on the same (server) machine, keeping track of client and process via ID and forwarding the data (via webSockets) accordingly. So an example scenario would be:

*

*Client C1 requests new battle to server S and sends code (not necessarily a single step, I know);

*S handles the code (e.g. compiling), executes new battle and starts a connection with it's process P1 (named pipes/FIFO?);

*P1 generates JSON, sends to S;

*S sees P1 is "connected" to C1, sends data to C1 (steps 3 and 4 will be repeated as long as the battle is active);

*Client C2 requests new battle;

*Previous steps repeated; C2 is assigned to new process P2;

*Client C3 requests "watching" battle under P1 (using a unique URL or a token);

*S finds P1's ID, compares to the received one and binds P1 to C3;

This way, the Server forwards received data from forked processes to all clients connected to each specific Battle.
Questions
Regarding this approach:

*

*Is it simple enough? Are there easier or even more elegant ways of doing it? Could scalability be a problem?

*Is it secure enough (the whole compiling and running code — likely C++ — on the server)?

*Is it fast enough (this one worries me the most for now)? It seems a bit counter intuitive to have a single server dealing with the entire traffic, but as far as I know, if I'd assign all these processes to a separate web server, I would need different ports for each of them, which seems even worse.

A: Since this is a theoretical and opinion based question... I feel free to throwing the ball in different directions. I'll probably edit the answer as I think things over or read comments.

*

*A process per battle?
sounds expensive. Also, there is the issue of messages going back and forth between processes... might as well be able to send the messages between machines and have a total separation of concerns.
Instead of forking battles, we could have them running on their own, allowing them to crash and reboot and do whatever they feel like without ever causing any of the other battles or our server any harm.

*Javascript? Why just one language?
I would consider leveraging an Object Oriented approach or language - at least for the battles, if not for the server as well.
If we are separating the code, we can use different languages. Otherwise I would probably go with Ruby, as it's easy for me, but maybe I'm mistaken and delving deeper into Javascript's prototypes will do.

*Oh... foreign code - sanitization is in order.
How safe is the foreign code? should it be in a localized sped language that promises safety of using an existing language interpreter, that might allow the code to mess around with things it really shouldn't...
I would probably write my own "pseudo language" designed for the battles... or (if it was a very local project for me and mine) use Ruby with one of it's a sanitizing gems.

*Battles and the web-services might not scale at the same speed.
It seems to me that handling messages - both client->server->battle and battle->server->client - is fairly easy work. However, handling the battle seems more resource intensive.
I'm convincing myself that a separation of concerns is almost unavoidable.
Having a server backend and a different battle backend would allow you to scale the battle handlers up more rapidly and without wasting resources on scaling the web-server before there's any need.

*Network disconnections.
Assuming we allow the players to go offline while their agents "fight" in the field ... What happens when we need to send our user "Mitchel", who just reconnected to server X, a message to a battle he left raging on server Y?
Separating concerns would mean that right from the start we have a communication system that is ready to scale, allowing our users to connect to different endpoints and still get their messages.
Summing these up, I would consider this as my workflow:

*

*Http workflow:

*

*Client -> Web Server : requesting agent with identifier and optional battle data (battle data is for creating an agent, omitting battle data will be used for limiting the request to an existing agent if it exists).
This step might be automated based on Client authentication / credentials (i.e. session data / cookie identifier or login process).

*

*if battle data exists in the request (request to make):
Web Server -> Battle instance for : creating agent if it doesn't exist.

*if battle data is missing from the request:
Web Server -> Battle Database, to check if agent exists.

*Web Server -> Client : response about agent (exists / created vs none)

*

*If Agent exists or created, initiate a Websocket connection after setting up credentials for the connection (session data, a unique cookie identifier or a single-use unique token to be appended to the Websocket request query).

*If Agent does't exist, forward client to a web form to fill in data such as agent code, battle type etc'.

*Websocket "workflows" (non linear):

*

*Agent has data: Agent message -> (Battle communication manager) -> Web Server -> Client
It's possible to put Redis or a similar DB in there, to allow messages to stack while the user is offline and to allow multiple battle instances and multiple web server instances.

*Client updates to Agent: Client message -> (Battle communication manager) -> Web Server -> Agent


text:
Q: .Get status of visible rows in ag-grid I am using Ag-grid in my React app, I need to trigger an action when the user reaches the 90% of the rows visibles (no matter if they made scroll or click the 'next' button). How can I know that? which event should I use?
My thoughts are that everytime that the user reaches the 90% of the rows loaded then I will trigger the defined action.
Thank you very much.
EDIT:
<AgGridReact
          columnDefs={this.state.columnDefs}
          rowData={this.props.rowData }
          ViewportChangedEvent={this.onScroll.bind(this)}
          enableSorting
          enableFilter
          showToolPanel
          pagination
          paginationAutoPageSize
          singleClickEdit
          sizeColumnsToFit
          enableColResize
          onGridReady={this.onGridReady}
          rowHeight={48}
          onSomeEvent={some.handler}
          />

That's what I have and it's diplaying the data correctly, now I need an event onSomeEvent={some.handler} that allow me to know which is the row that he is seeing to know when he reaches the 90% of the total rows that are loaded.


text:
Q: How apply function to all columns with specifis data types I have big DataFrame with string and numeric columns. In string columns values have accents, I need convert them to "normal" letters. How can I apply a function to all specific type columns (in this case I need all string columns) in pandas DataFrame?
import unicodedata

def strip_accents(text):

    try:
        text = unicode(text, 'utf-8')
    except NameError: # unicode is a default on python 3
        pass

    text = unicodedata.normalize('NFD', text)\
           .encode('ascii', 'ignore')\
           .decode("utf-8")
    return str(text)

import pandas as pd
data = [['Tóm','Čiž', 34], ['Ničk','Jóšš', 65], ['Julí', 'Álmó', 24]]
df = pd.DataFrame(data, columns = ['Name', 'City', 'Age'])

I need output like: Tom, Ciz, Nick,...

A: Try:
Firstly filter out columns:
col=df.columns[df.dtypes=='object']

Finally use applymap() method:
df[col]=df[col].applymap(strip_accents)

output of df:
    Name    City    Age
0   Tom     Ciz     34
1   Nick    Joss    65
2   Juli    Almo    24


text:
Q: Is this line correct "why does he have to be from America?"
Why does he have to be from america?

I have a little bit doubt about that sentence. Is it correct?
Here is the context: Someone posted a picture in his profile and caption it "He must have returned from America."
If I comment with that question will it be okay?

A: "America" should have a capital A. Other than that, it is grammatically correct.
But I don't think that's what you want to say. The question,

Why does he have to be from America?

means that you know that he is from America (that is, America is his home), and you want him to be from somewhere else. That kind of question is often used when someone is sad that a person is from somewhere else because they want to have a romantic relationship with that person. But a native English speaker might be able to figure out that is not what you really mean...
Just like me: I don't think that's what you mean. It sounds like you don't understand why the caption says "He must have returned from America" and you want to understand.
In that case, you could ask,

Why do you think he returned from America?

Keep in mind that it could be a joke. In that case, you could simply say,

I don't get it.

Which means you don't understand the joke, and maybe someone will explain for you.


text:
Q: Async Await Promise  I know this question been asked for many times but as I'm still very new i dont quite understand the answers on previous places.
const publicIp = require('public-ip');

// getting ip address
async function GetIpAddress() {
var a = await publicIp.v4();
return await a;
// it will return my public ip as string
}

however ,as its non blocking i understand if i do something like this as below
var a = GetIpAddress();
console.log(a);

it will probably go promise pending. so what i did was
async function hi(){
var a = await GetIpAddress();
console.log(a);
}

hi();

But here's my question. How do i return it back to my variables without making another function to cover it up? please see code below
var zmq = require('zmq'),
    requester = zmq.socket('req'),
    publicIp = require('public-ip');

const PORT = "3222";
var IP = GetIpAddress();
console.log(`${IP}:${PORT}`);
// IP will return promise pending?? how i do fix this without making another
// function?

requester.connect('tcp://127.0.0.1:5433');

requester.on('message', function (msg) {
    // arr = str.split(",");
    console.log(msg.toString());

});

requester.send(
    `${IP}:${PORT}`
);

async function GetIpAddress() {
    var a = await publicIp.v4();
    return a
}

As the full code above shown.. var IP will definitely be promise pending as it will take time. therefore how do it get the function return value without making another function?
EDIT: please understand the duplication is entirely not what i want.. I understand that my knowlege on callbacks , promises and async await wasnt strong but from a guy who comes from synchronous language such as Python itself . I'm very curious onto how do i take variable out. as what i research and saw are mostly
promises within promises or callbacks within callbacks.
what i want is if i can rereplicate what was shown as per below ( python )
def f(x):
    return x+1

var1 = 5
var1 = f(var1)
# var1 is now 6

which is bringing callbacks / promises / async await variable out of its own function rather than
var IP = GetIpAddress().then((IP) => {
    requester.connect('tcp://127.0.0.1:5433');
    console.log('Worker connected to port 5433');

    requester.on('message', function (msg) {
        // arr = str.split(",");
        console.log(msg.toString());

    });

    requester.send(
    `${IP}:${PORT}`
    );
    console.log(`${IP}:${PORT}`);
});

A: Change:
var IP = GetIpAddress();
console.log(`${IP}:${PORT}`);

to:
GetIpAddress().then((IP) => {
    console.log(`${IP}:${PORT}`);
  }
);

You can read 6 Reasons Why JavaScript's Async/Await Blows Promises Away (Tutorial)
Update:
Option 1 put everything in the then:
GetIpAddress().then((IP) => {
    requester.connect('tcp://127.0.0.1:5433');
    console.log('Worker connected to port 5433');

    requester.on('message', function (msg) {
        // arr = str.split(",");
        console.log(msg.toString());

    });

    requester.send(
    `${IP}:${PORT}`
    );
    console.log(`${IP}:${PORT}`);
});

Option 2 is to wrap everything in an async function:
async function hi(){
var a = await GetIpAddress();
console.log(a);
}

hi();

Option 2 is the one I would opt for as it provides a cleaner way of writing things.

A: you need to add await before the method call. the main method also need to async.
var IP = await GetIpAddress();
try to use
new promise(function (accept, reject){   // if Ip found
accept("ipaddress")   //else reject("error log")
 }).then(function(response){ // this is accept , print IPaddress
 }).catch(function(err){ // this is reject. } );


text:
Q: Is it worth it to translate an Android app into Spanish and other languages? I have the "user's side" of the story, I think they want it better if it's on Spanish. But, what about the programmers? Do you make your programs multi-language? Why? Why not?
Who translate your software? Are you ok with paying somebody to translate your app or you prefer doing it yourselves? Is the benefit bigger than the costs?

A: There's really only one question you need to answer:

Is there a demand for the application to be translated into one (or more) other language?

If the demand is there then you need to look into translation. There may be political (both with a lower case "p" and upper case "P" - bilingual countries like Canada spring to mind), social or ethical reasons that need to be considered as well as the cost.
As to the methodology - when I worked on software that was translated we got our German and French distributors to do the translation. The benefit of this is that you are using someone who knows the product and will (hopefully) choose the most appropriate translation when more than one is available.
If you don't have distributors familiar with the language then there are services available that will do the translation for you.
Failing that there's always Google Translate :)

A: Often not, for a couple reasons:

*

*If the English is simple, it's often best to leave it as-is. Computer users are generally quite tolerant of having English here and there. Japanese people live with having English on our computers all the time, and our English education is notoriously poor.
Unless you expect to target a not-very-English-tolerant sector of the Spanish market, you may be able to get away with having no translation at all.

*When something goes wrong or when we get lost, it's often better that the labels and error messages are all in one language so that the user can find help more easily.
For instance, I'll get more helpful results on Google if I query for "An unhandled exception has occured" than if I query for "キャッチされていない例外が発生しました".
I think the general rule of thumb is that if your app is targeted to techies or otherwise relatively internationally inclined people, you can save yourself some time and money by not translating.

A: I believe one should also consider the negative consequences of providing localizations.

*

*People will be offended by bad translations, especially if they could use the English version before and now they are auto-detected and forced to use the translated version.

*Users of languages left out will feel offended if you provide a translation for another language, especially again if you force them to use it through regional/linguistic match.

*

*French <-> Belgian Dutch

*Simplified Chinese <-> Traditional Chinese

*European French <-> Canadian French

*and many more

A: If you are selling a reasonable number of units already and you have no reason to believe that the app would be any less applicable to Spanish speakers, then I think it's probably worthwhile to give it a go.  If you are using the Android strings.xml resource to separate the text from the application, it is straightforward to add more languages.
There are online translation bureaus (such as this one) that will do translations for a few cents per word.  I haven't tried them yet, so I can't vouch for them, but it's something I'm considering.
Unless you have a very wordy application, you can probably get it translated for less than $50, in which case you'd only need a modest increase in sales from Spanish-speakers to make it worthwhile.
In my own modest Android sales, 95%+ of orders come from English-speaking countries (over 90% of sales are from just the UK, US and Australia). That massive skew suggests to me that I would sell more if the apps were available in French and German too.


text:
Q: Why am I getting ReferenceError: boxes is not defined error I have declared a global variable and am using it to capture a value from a multiple select event. However, I am confused why I am getting this error in my modal window. Funny thing is, that the other vars dept, address are working fine.
In firebug console I can see the values are being displayed correctly. I would be grateful if someone could point out my error. Thanks
code that declare var boxes;

Error is in this code

A:


text:
Q: Election Query Hopefully last one This query is working fine:
select  rc.[race number],
    max(case when seqnum = 1 then [candidate num] end) as Winner,
    max(case when seqnum = 1 then Votes end) as WinningVotes,
    max(case when seqnum = 1 then party end) as WinningParty,
    max(case when seqnum = 1 then leader end) as Winner1,
    max(case when seqnum = 1 then [leader percent] end) as WinnerPercent,
    max(case when seqnum = 2 then [candidate num] end) as Loser,
    max(case when seqnum = 2 then Votes end) as LosingVotes,
    max(case when seqnum = 2 then party end) as LosingParty,
    max(case when seqnum = 2 then leader2 end) as Loser2,
    max(case when seqnum = 2 then [leader2 percent] end) as LoserPercent

from
(
select  rc.[race number],
        rc.[candidate num],
        rc.[Votes],
        rc.[winner],
        c.[party],
        r.[leader],
        r.[leader percent],
        r.[leader2],
        r.[leader2 percent],
            row_number() over (partition by rc.[race number] order by votes desc) as seqnum
    from    dbo.[RACE CANDIDATES] rc
    inner join dbo.[CANDIDATE] c    on  rc.[candidate num]  = c.[candidate number]
    inner join dbo.[RACE] r
     on rc.[race number] = r.[race number]
) rc
group by rc.[race number]

Now I have one more field from the RACE CANDIDATES TABLE that needs to show up in the query. It returns a 0 for the loser and a 1 for the winner. This column is named Winner.
When I run the following query:
select  rc.[race number],
    max(case when seqnum = 1 then [candidate num] end) as Winner,
    max(case when seqnum = 1 then Votes end) as WinningVotes,
    max(case when seqnum = 1 then party end) as WinningParty,
    max(case when seqnum = 1 then leader end) as Winner1,
    max(case when seqnum = 1 then winner end) as WinnerSelected,
    max(case when seqnum = 1 then [leader percent] end) as WinnerPercent,
    max(case when seqnum = 2 then [candidate num] end) as Loser,
    max(case when seqnum = 2 then Votes end) as LosingVotes,
    max(case when seqnum = 2 then party end) as LosingParty,
    max(case when seqnum = 2 then leader2 end) as Loser2,
    max(case when seqnum = 2 then [leader2 percent] end) as LoserPercent,
    max(case when seqnum = 2 then winner end) as LoserSelected

from
(
select  rc.[race number],
        rc.[candidate num],
        rc.[Votes],
        rc.[winner],
        c.[party],
        r.[leader],
        r.[leader percent],
        r.[leader2],
        r.[leader2 percent],
            row_number() over (partition by rc.[race number] order by votes desc) as seqnum
    from    dbo.[RACE CANDIDATES] rc
    inner join dbo.[CANDIDATE] c    on  rc.[candidate num]  = c.[candidate number]
    inner join dbo.[RACE] r
     on rc.[race number] = r.[race number]
) rc
group by rc.[race number]

I get an error that states: "Msg 8117, Level 16, State 1, Line 6
Operand data type bit is invalid for max operator."
Does this mean I may be screwed? Because in my first statement I have candidate num aliased as Winner, perhaps if I changed this it would go away. Is that what is causing the error? Or is it because of the "0" or the "1" being returned?
When I run SELECT * FROM [RACE CANDIDATES] it returns the winner column with the correct "0" or "1".
This is my last issue, I promise.
Thanks to all who have guided me through this disaster.

A: Since BIT column is 1 or 0, you can't apply MAX() to it. The only option I saw in other forums is to cast it as tinyint. Like so. See if this works.
select  rc.[race number],
    max(case when seqnum = 1 then [candidate num] end) as Winner,
    max(case when seqnum = 1 then Votes end) as WinningVotes,
    max(case when seqnum = 1 then party end) as WinningParty,
    max(case when seqnum = 1 then leader end) as Winner1,
    max(case when seqnum = 1 then CAST(winner AS tinyint) end) as WinnerSelected,
    max(case when seqnum = 1 then [leader percent] end) as WinnerPercent,
    max(case when seqnum = 2 then [candidate num] end) as Loser,
    max(case when seqnum = 2 then Votes end) as LosingVotes,
    max(case when seqnum = 2 then party end) as LosingParty,
    max(case when seqnum = 2 then leader2 end) as Loser2,
    max(case when seqnum = 2 then [leader2 percent] end) as LoserPercent,
    max(case when seqnum = 2 then CAST(winner AS tinyint) end) as LoserSelected

from
(
select  rc.[race number],
        rc.[candidate num],
        rc.[Votes],
        rc.[winner],
        c.[party],
        r.[leader],
        r.[leader percent],
        r.[leader2],
        r.[leader2 percent],
            row_number() over (partition by rc.[race number] order by votes desc) as seqnum
    from    dbo.[RACE CANDIDATES] rc
    inner join dbo.[CANDIDATE] c    on  rc.[candidate num]  = c.[candidate number]
    inner join dbo.[RACE] r
     on rc.[race number] = r.[race number]
) rc
group by rc.[race number]


text:
Q: How to prevent jQuery sortable stop event from being cached In my PHP backend I provided a way to sort all articles for a page.
I use twitter-bootstrap and so I made each <div class="col-md-4> sortable. The articles are wrapped inside panels which are the sortable items.
I bound the stop event of the sortable to a function that lets a button appear that says "Apply Sorting". The idea is to be able to shuffle articles as often as needed and then click on the "Apply Sorting" button to run a single ajax call to PHP which updates the sorting field for each article.
This is my code:
    // cols are all bootstrap column divs
    cols.sortable({
      items: '.panel-default',
      delay: 50,
      cancel: ".adder",
      beforeStop: function() {
         cols.sortable('refreshPositions');
      },
      stop: addSortButton,
     });

     function addSortButton() {
      // if button exists do not add another one
       var button = $('.sorter');
       if (button.length === 0) {
          $('.seperate').prepend('<button class="btn btn-sm btn-primary sorter">Apply Sorting</button>');
       }
       $('.sorter').one('click', function(e) {
          applySorting();
       });
     };

     function applySorting() {
        var articles = cols.find('article');
        var holder = new Array();
        for (var i = 0; i < articles.length; i++) {
            var sorting = i + 1;
            $(articles[i]).attr('data-sorting', sorting);
            var id = $(articles[i]).attr('data-id');
            holder[id] = sorting;
        }
        $('.sorter').prepend(spinner);
        $.ajax({
           type: 'POST',
           url: '/admin/nodes/sort',
           data: {
             'values': holder
           },
        }).done(function(msg) {
            $('.sorter').html('Apply Sorting');
            if (msg === 'ok') {
               alert('Sorting update ran successful!');
            }
        }).fail(function(xhr, status, error) {

       });
     };

My problem is:
For example when I only move one article one ajax call is made. which is fine. But when I decide to move more articles and maybe switch 4 of them to different locations I get 4 ajax calls. I thought I could prevent this behavior by the jQuery one() function but it is not working. Also the berforeStop event has no effect trying to clear that.


text:
Q: bootstrap-datepicker - Enabling only odd or even dates? I am using Stefan Petre's Bootstrap-Datepicker found at Github
It has a property 'daysOfWeekDisabled' which allows me to disable specific days of the week, but I now need to enable only Odd or only Even dated days within the calendar.
Does anyone know if there is a way to do this ? Google search and a search through the datepickers docs on Github Doc hasn't produced a solution for me.

A: UPDATE:
http://jsfiddle.net/mw4kyc9p/1/
use beforeShowDay
$('#date').datepicker({
        beforeShowDay: function (Date) {
            var day = Date.getDate();
            //enable even
            if (day % 2 == 0) return true;
            //disable odd
            else return false;
        }
    });


text:
Q: Approach in solving this First Order Nonlinear ODE The 1st Order Nonlinear ODE in question is given by
$$3xy^2y'+3y^3=1$$
I tried separating it but I just couldn't seem to work it out. The integrals just become so complicated when being evaluated.
What could be another approach to solve this DE?

A: Notice that you can rewrite as
$$x(y^3)'+3x'y^3=1$$ and the LHS is an exact derivative except for the factor $3$.
Then multipying by $x^2$, we have
$$x^3(y^3)'+(x^3)'y^3=(x^3y^3)'=x^2.$$
The rest is easy.

A: Another way to solve this ODE is to notice that it is separable,
$$
\frac{3y^2y'}{1-3y^3}=\frac1x\implies 1-3y^3=\frac{C}{x^3}.
$$

A: Given differential equation can be written as $$ \frac{dy}{dx}+\frac{y}{x}=\frac{1}{3xy^2} $$ which is Bernoulli Equation and after the substitution $y^3 = z$ can be converted into first order linear differential equation of the form:
$$ \frac{dz}{dx}+\frac{3z}{x}=\frac{1}{x}. $$
Which can be solved easily by finding integrating factor.


text:
Q: Resetting the navigation stack on a UITabBarController doesn't work I'm trying to reset the navigation stack on a subclass of UITabViewController embedded in a UINavigationController but it doesn't work.
My navigation stack, which I create programmatically, is like this:

UINavigationController => ControllerA (a subclass of UIViewController) =>
  ControllerB (a subclass of UIViewController) => ControllerC (a
  subclass of UITabBarController).

When users press on the "Back" button or swipe back from ControllerC, the app should go back to ControllerA, not ControllerB.
Usually, when I want to reset the navigation stack, I do this in the Controller's viewDidLoad() method:
override func viewDidLoad() {

  super.viewDidLoad()

  // usually work, but not in a subclass of UITabBarController as self.navigationController is nil
  if let navigationController = self.navigationController {

    // keep only the root controller (0) and the current controller
    navigationController.viewControllers = [navigationController.viewControllers[0], self]
  }
}

but this doesn't work in ControllerC (the subclass of UITabViewController) as self.navigationController is nil.
If I do this instead (still in ControllerC's viewDidLoad() method):
/// ControllerC's viewDidLoad
override func viewDidLoad() {

  super.viewDidLoad()

  if let navigationController = UIApplication.shared.keyWindow?.rootViewController as? UINavigationController {

    // keep only the root controller (0) and the current controller
    navigationController.viewControllers = [navigationController.viewControllers[0], self]
  }
}

This works, but then there is no animation between ControllerB and ControllerC when I do:
controllerB.navigationController?.pushViewController(ControllerC(), animated: true)

I also tried to override ControllerC's viewWillDisappear() method:
/// ControllerC's viewWillDisappear
override func viewWillDisappear(_ animated: Bool) {

  super.viewWillDisappear(animated)

  if self.isMovingFromParent {

    if let navigationController = UIApplication.shared.keyWindow?.rootViewController as? UINavigationController {

     navigationController.popToRootViewController(animated: true)
  }
}

This works, but ControllerB is briefly visible before ControllerA is shown.
Any help would be greatly appreciated!

A: In the ControllerC instead of trying to override viewWillDisappear() method you can override viewDidAppear() like that:
override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)

        if let navC = UIApplication.shared.keyWindow?.rootViewController as? UINavigationController {
            // keep only the root controller (0) and the current controller
            navC.viewControllers = [navC.viewControllers[0], self]
        }
    }

And ControllerB won't be briefly visible before ControllerA when you navigate backwards.


text:
Q: Running Tor with Selenium webdriver in Java I'm a bit new to selenium and I was looking to use it to run various automated tasks through Tor. I'm on Windows 10 using Java through Eclipse with the Selenium packages as referenced libraries. I've checked out several other tutorials and forum threads detailing how to set up Tor in selenium. I started out trying to use the following code:
    System.setProperty("webdriver.gecko.driver", "D:\\geckodriver-v0.10.0-win64\\geckodriver.exe");
    String torPath =
            "C:\\Users\\Dave\\Desktop\\Tor Browser\\Browser\\firefox.exe";
    String profilePath =
            "C:\\Users\\Dave\\Desktop\\Tor Browser\\Browser\\TorBrowser\\Data\\Browser\\profile.default";
    FirefoxProfile torProfile = new FirefoxProfile(new File(profilePath));
    FirefoxBinary binary = new FirefoxBinary(new File(torPath));
    WebDriver driver = new FirefoxDriver(binary, torProfile);
    driver.get("https://www.google.com");

Using that code produces this error:
Exception in thread "main" org.openqa.selenium.WebDriverException: Cannot find firefox binary in PATH. Make sure firefox is installed.

I tried referencing this thread for a solution. I then used the following code based off of that thread:
    System.setProperty("webdriver.gecko.driver", "D:\\geckodriver-v0.10.0-win64\\geckodriver.exe");
    String torPath =
            "C:\\Users\\Dave\\Desktop\\Tor Browser\\Browser\\firefox.exe";
    String profilePath =
            "C:\\Users\\Dave\\Desktop\\Tor Browser\\Browser\\TorBrowser\\Data\\Browser\\profile.default";
    FirefoxProfile torProfile = new FirefoxProfile(new File(profilePath));
    FirefoxBinary binary = new FirefoxBinary(new File(torPath));
    torProfile.setPreference("webdriver.load.strategy", "unstable");
    try
    {
        binary.startProfile(torProfile, new File(profilePath), "");
    }
    catch (IOException e)
    {
        e.printStackTrace();
    }
    FirefoxProfile profile = new FirefoxProfile();
    profile.setPreference("network.proxy.type", 1);
    profile.setPreference("network.proxy.socks", "127.0.0.1");
    profile.setPreference("network.proxy.socks_port", 9150);
    WebDriver driver = new FirefoxDriver(binary, profile);
    driver.get("https://www.google.com");

Using that code launches Tor for me; however, I still receive the same error as before and the driver cannot control that Tor window.
I would appreciate any help or advice.


text:
Q: Frame transition animation works conditionally I am trying to make child view which contains string array moves back and forth with animation as button on parent view is toggled.
However, child view just show up and disappeared without any animation at all.
struct ParentView: View {
  @State isToggle: Bool

  var body: some View {

     ChildView(isToggle: isToggle)
         .onTabGesture {
            withAnimation {
               isToggle.toggle()
            }
         }
  }
}

struct ChildView: View {

  let values = [one, two, three, four]

  var isToggle: Bool

  var body: some View {

    HStack {
       ForEach(values) { value in
            Text("\(value)")
                     .frame(width: UIScreen.main.bounds.width / 3)
       }
   }
    .frame(width: UIScreen.main.bounds.width, alignment: isToggle ? .trailing : .leading)
}

I changed code(stored property to viewmodel) as below. and It works as expected.
class ViewModel: ObservableObject {

  @Published var values = [one, two, three, four]

}

struct ParentView: View {
  @State isToggle: Bool

  var body: some View {

     ChildView(isToggle: isToggle)
         .onTabGesture {
            withAnimation {
               isToggle.toggle()
            }
         }
  }

}

struct ChildView: View {

  @EnvironmentObject private vm: ViewModel

  var isToggle: Bool

  var body: some View {

    HStack {
       ForEach(values) { vm.value in
            Text("\(value)")
                     .frame(width: UIScreen.main.bounds.width / 3)
       }
   }
    .frame(width: UIScreen.main.bounds.width, alignment: isToggle ? .trailing : .leading)
}

I thought that toggling state redraws view only when with stored property.
But, child view with viewmodel is still redrawn when toggle state changes.
Data itself not changed at all. Please kindly let me know why this is happening.

A: there are some minor typos in your first code. If I correct them the code runs, and the animation works:
struct ContentView: View {
    @State private var isToggle: Bool = false

    var body: some View {
        ChildView(isToggle: isToggle)
            .onTapGesture {
                withAnimation {
                    isToggle.toggle()
                }
            }
    }
}

struct ChildView: View {
    let values = ["one", "two", "three", "four"]
    var isToggle: Bool

    var body: some View {
        HStack {
            ForEach(values, id: \.self) { value in
                Text("\(value)")
                    .frame(width: UIScreen.main.bounds.width / 3)
            }
        }
        .frame(width: UIScreen.main.bounds.width, alignment: isToggle ? .trailing : .leading)
    }
}