text:
Q: Why does my flutter app crash on Android 12? We are experiencing issues with our Flutter based app on Android 12 specifically. No other system seems affected.
The issues that occur cause a hard crash of the app and nothing reaches our exception monitoring tool.
One example stack trace:
onSignalStrengthsChanged signalStrength=SignalStrength:{mCdma=Invalid,mGsm=Invalid,mWcdma=Invalid,mTdscdma=Invalid,mLte=CellSignalStrengthLte: rssi=-95 rsrp=-94 rsrq=-7 rssnr=19 cqiTableIndex=2147483647 cqi=12 ta=2147483647 level=4 parametersUseForLevel=0,mNr=Invalid,SignalBarInfo{ lteLevel=4 },rat=14,primary=CellSignalStrengthLte} level=4
onSignalStrengthsChanged signalStrength=SignalStrength:{mCdma=Invalid,mGsm=Invalid,mWcdma=Invalid,mTdscdma=Invalid,mLte=CellSignalStrengthLte: rssi=-99 rsrp=-98 rsrq=-7 rssnr=17 cqiTableIndex=2147483647 cqi=12 ta=2147483647 level=4 parametersUseForLevel=0,mNr=Invalid,SignalBarInfo{ lteLevel=4 },rat=14,primary=CellSignalStrengthLte} level=4
onSignalStrengthsChanged signalStrength=SignalStrength:{mCdma=Invalid,mGsm=Invalid,mWcdma=Invalid,mTdscdma=Invalid,mLte=CellSignalStrengthLte: rssi=-99 rsrp=-98 rsrq=-7 rssnr=17 cqiTableIndex=2147483647 cqi=12 ta=2147483647 level=4 parametersUseForLevel=0,mNr=Invalid,SignalBarInfo{ lteLevel=3 },rat=14,primary=CellSignalStrengthLte} level=3
notifyListener: enabled=true, connected=true, dataConnected=false, networkType=LTE (4G), emergencyOnly=false, roaming=false, isDefault=false, fiveGAvailable=false, mmWave=false, showDisabledDataIcon=false, voWifiConnected=false, dataActivity=, simState=LOADED, cardOperator=OTHERS, simCardActivated=1
onSignalStrengthsChanged signalStrength=SignalStrength:{mCdma=Invalid,mGsm=Invalid,mWcdma=Invalid,mTdscdma=Invalid,mLte=CellSignalStrengthLte: rssi=-93 rsrp=-93 rsrq=-7 rssnr=16 cqiTableIndex=2147483647 cqi=12 ta=2147483647 level=4 parametersUseForLevel=0,mNr=Invalid,SignalBarInfo{ lteLevel=3 },rat=14,primary=CellSignalStrengthLte} level=3
onSignalStrengthsChanged signalStrength=SignalStrength:{mCdma=Invalid,mGsm=Invalid,mWcdma=Invalid,mTdscdma=Invalid,mLte=CellSignalStrengthLte: rssi=-91 rsrp=-91 rsrq=-10 rssnr=19 cqiTableIndex=2147483647 cqi=12 ta=2147483647 level=4 parametersUseForLevel=0,mNr=Invalid,SignalBarInfo{ lteLevel=3 },rat=14,primary=CellSignalStrengthLte} level=3
03-25 21:02:13.784 F/libc    (22599): Fatal signal 11 (SIGSEGV), code 2 (SEGV_ACCERR), fault addr 0x7308479630 in tid 23041 (1.raster), pid 22599 (aidhere.zanadio)
03-25 21:02:14.163 F/DEBUG   (23318): *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
03-25 21:02:14.163 F/DEBUG   (23318): Build fingerprint: 'samsung/beyond1lteeea/beyond1:12/SP1A.210812.016/G973FXXUEGVB4:user/release-keys'
03-25 21:02:14.163 F/DEBUG   (23318): Revision: '26'
03-25 21:02:14.163 F/DEBUG   (23318): ABI: 'arm64'
03-25 21:02:14.163 F/DEBUG   (23318): Timestamp: 2022-03-25 21:02:13.865217058+0100
03-25 21:02:14.163 F/DEBUG   (23318): Process uptime: 67s
03-25 21:02:14.163 F/DEBUG   (23318): Cmdline: lang.product.organisation
03-25 21:02:14.163 F/DEBUG   (23318): pid: 22599, tid: 23041, name: 1.raster  >>> lang.product.organisation <<<
03-25 21:02:14.163 F/DEBUG   (23318): uid: 10349
03-25 21:02:14.163 F/DEBUG   (23318): signal 11 (SIGSEGV), code 2 (SEGV_ACCERR), fault addr 0x7308479630
03-25 21:02:14.163 F/DEBUG   (23318):     x0  000000730847a110  x1  000000730847a110  x2  000000730847ac00  x3  0000000000000000
03-25 21:02:14.163 F/DEBUG   (23318):     x4  0000000000000000  x5  0000007308479620  x6  000000730847a110  x7  0000000000000008
03-25 21:02:14.163 F/DEBUG   (23318):     x8  00000073084efa50  x9  00000073084efa50  x10 0000000000000000  x11 0000007308479620
03-25 21:02:14.163 F/DEBUG   (23318):     x12 00000000000000af  x13 000000730847ac00  x14 00000000447a0000  x15 0000000039800000
03-25 21:02:14.163 F/DEBUG   (23318):     x16 00000000000000af  x17 00000000000000ac  x18 000000731a49c000  x19 000000758536f930
03-25 21:02:14.164 F/DEBUG   (23318):     x20 00000000000000a5  x21 00000000000000a2  x22 0000007585360afc  x23 00000000000000a5
03-25 21:02:14.164 F/DEBUG   (23318):     x24 00000000000000ac  x25 00000000000000af  x26 000000000000000d  x27 0000000000000007
03-25 21:02:14.164 F/DEBUG   (23318):     x28 0000000000000000  x29 000000000000014d
03-25 21:02:14.164 F/DEBUG   (23318):     lr  000000731c96e220  sp  0000007385789c70  pc  000000731c96e3fc  pst 0000000020000000
03-25 21:02:14.164 F/DEBUG   (23318): backtrace:
03-25 21:02:14.164 F/DEBUG   (23318):       #00 pc 00000000003543fc  /data/app/~~2eiiCJ7Ak-ZC7Z6U7SE2lA==/lang.product.organisation-dtglboqK8ZK11lr4ek7Rgg==/split_config.arm64_v8a.apk!libflutter.so (BuildId: 72e477eb571a57ba1286df3d00a067adb310a1cd)
03-25 21:02:14.164 F/DEBUG   (23318):       #01 pc 00000000003541b8  /data/app/~~2eiiCJ7Ak-ZC7Z6U7SE2lA==/lang.product.organisation-dtglboqK8ZK11lr4ek7Rgg==/split_config.arm64_v8a.apk!libflutter.so (BuildId: 72e477eb571a57ba1286df3d00a067adb310a1cd)
03-25 21:02:14.164 F/DEBUG   (23318):       #02 pc 00000000004d7e10  /data/app/~~2eiiCJ7Ak-ZC7Z6U7SE2lA==/lang.product.organisation-dtglboqK8ZK11lr4ek7Rgg==/split_config.arm64_v8a.apk!libflutter.so (BuildId: 72e477eb571a57ba1286df3d00a067adb310a1cd)
03-25 21:02:14.164 F/DEBUG   (23318):       #03 pc 00000000004724f4  /data/app/~~2eiiCJ7Ak-ZC7Z6U7SE2lA==/lang.product.organisation-dtglboqK8ZK11lr4ek7Rgg==/split_config.arm64_v8a.apk!libflutter.so (BuildId: 72e477eb571a57ba1286df3d00a067adb310a1cd)
03-25 21:02:14.164 F/DEBUG   (23318):       #04 pc 000000000046b014  /data/app/~~2eiiCJ7Ak-ZC7Z6U7SE2lA==/lang.product.organisation-dtglboqK8ZK11lr4ek7Rgg==/split_config.arm64_v8a.apk!libflutter.so (BuildId: 72e477eb571a57ba1286df3d00a067adb310a1cd)
03-25 21:02:14.164 F/DEBUG   (23318):       #05 pc 000000000046b420  /data/app/~~2eiiCJ7Ak-ZC7Z6U7SE2lA==/lang.product.organisation-dtglboqK8ZK11lr4ek7Rgg==/split_config.arm64_v8a.apk!libflutter.so (BuildId: 72e477eb571a57ba1286df3d00a067adb310a1cd)
03-25 21:02:14.164 F/DEBUG   (23318):       #06 pc 000000000034b744  /data/app/~~2eiiCJ7Ak-ZC7Z6U7SE2lA==/lang.product.organisation-dtglboqK8ZK11lr4ek7Rgg==/split_config.arm64_v8a.apk!libflutter.so (BuildId: 72e477eb571a57ba1286df3d00a067adb310a1cd)
03-25 21:02:14.164 F/DEBUG   (23318):       #07 pc 0000000000602af4  /data/app/~~2eiiCJ7Ak-ZC7Z6U7SE2lA==/lang.product.organisation-dtglboqK8ZK11lr4ek7Rgg==/split_config.arm64_v8a.apk!libflutter.so (BuildId: 72e477eb571a57ba1286df3d00a067adb310a1cd)
03-25 21:02:14.164 F/DEBUG   (23318):       #08 pc 00000000002faa7c  /data/app/~~2eiiCJ7Ak-ZC7Z6U7SE2lA==/lang.product.organisation-dtglboqK8ZK11lr4ek7Rgg==/split_config.arm64_v8a.apk!libflutter.so (BuildId: 72e477eb571a57ba1286df3d00a067adb310a1cd)
03-25 21:02:14.164 F/DEBUG   (23318):       #09 pc 00000000002faabc  /data/app/~~2eiiCJ7Ak-ZC7Z6U7SE2lA==/lang.product.organisation-dtglboqK8ZK11lr4ek7Rgg==/split_config.arm64_v8a.apk!libflutter.so (BuildId: 72e477eb571a57ba1286df3d00a067adb310a1cd)
03-25 21:02:14.164 F/DEBUG   (23318):       #10 pc 0000000000329d34  /data/app/~~2eiiCJ7Ak-ZC7Z6U7SE2lA==/lang.product.organisation-dtglboqK8ZK11lr4ek7Rgg==/split_config.arm64_v8a.apk!libflutter.so (BuildId: 72e477eb571a57ba1286df3d00a067adb310a1cd)
03-25 21:02:14.164 F/DEBUG   (23318):       #11 pc 000000000032a5e8  /data/app/~~2eiiCJ7Ak-ZC7Z6U7SE2lA==/lang.product.organisation-dtglboqK8ZK11lr4ek7Rgg==/split_config.arm64_v8a.apk!libflutter.so (BuildId: 72e477eb571a57ba1286df3d00a067adb310a1cd)
03-25 21:02:14.164 F/DEBUG   (23318):       #12 pc 000000000032a07c  /data/app/~~2eiiCJ7Ak-ZC7Z6U7SE2lA==/lang.product.organisation-dtglboqK8ZK11lr4ek7Rgg==/split_config.arm64_v8a.apk!libflutter.so (BuildId: 72e477eb571a57ba1286df3d00a067adb310a1cd)
03-25 21:02:14.164 F/DEBUG   (23318):       #13 pc 0000000000331b28  /data/app/~~2eiiCJ7Ak-ZC7Z6U7SE2lA==/lang.product.organisation-dtglboqK8ZK11lr4ek7Rgg==/split_config.arm64_v8a.apk!libflutter.so (BuildId: 72e477eb571a57ba1286df3d00a067adb310a1cd)
03-25 21:02:14.164 F/DEBUG   (23318):       #14 pc 00000000002fd09c  /data/app/~~2eiiCJ7Ak-ZC7Z6U7SE2lA==/lang.product.organisation-dtglboqK8ZK11lr4ek7Rgg==/split_config.arm64_v8a.apk!libflutter.so (BuildId: 72e477eb571a57ba1286df3d00a067adb310a1cd)
03-25 21:02:14.164 F/DEBUG   (23318):       #15 pc 00000000002fff20  /data/app/~~2eiiCJ7Ak-ZC7Z6U7SE2lA==/lang.product.organisation-dtglboqK8ZK11lr4ek7Rgg==/split_config.arm64_v8a.apk!libflutter.so (BuildId: 72e477eb571a57ba1286df3d00a067adb310a1cd)
03-25 21:02:14.164 F/DEBUG   (23318):       #16 pc 0000000000016bb0  /system/lib64/libutils.so (android::Looper::pollInner(int)+912) (BuildId: 176a88c64d70f517a4c1c58b40932d90)
03-25 21:02:14.164 F/DEBUG   (23318):       #17 pc 00000000000167b8  /system/lib64/libutils.so (android::Looper::pollOnce(int, int*, int*, void**)+112) (BuildId: 176a88c64d70f517a4c1c58b40932d90)
03-25 21:02:14.164 F/DEBUG   (23318):       #18 pc 0000000000017284  /system/lib64/libandroid.so (ALooper_pollOnce+100) (BuildId: 246f3516484d421035372a67caa5a740)
03-25 21:02:14.164 F/DEBUG   (23318):       #19 pc 0000000000300030  /data/app/~~2eiiCJ7Ak-ZC7Z6U7SE2lA==/lang.product.organisation-dtglboqK8ZK11lr4ek7Rgg==/split_config.arm64_v8a.apk!libflutter.so (BuildId: 72e477eb571a57ba1286df3d00a067adb310a1cd)
03-25 21:02:14.164 F/DEBUG   (23318):       #20 pc 00000000002fc950  /data/app/~~2eiiCJ7Ak-ZC7Z6U7SE2lA==/lang.product.organisation-dtglboqK8ZK11lr4ek7Rgg==/split_config.arm64_v8a.apk!libflutter.so (BuildId: 72e477eb571a57ba1286df3d00a067adb310a1cd)
03-25 21:02:14.164 F/DEBUG   (23318):       #21 pc 00000000002fe830  /data/app/~~2eiiCJ7Ak-ZC7Z6U7SE2lA==/lang.product.organisation-dtglboqK8ZK11lr4ek7Rgg==/split_config.arm64_v8a.apk!libflutter.so (BuildId: 72e477eb571a57ba1286df3d00a067adb310a1cd)
03-25 21:02:14.164 F/DEBUG   (23318):       #22 pc 00000000000b4ad8  /apex/com.android.runtime/lib64/bionic/libc.so (__pthread_start(void*)+264) (BuildId: 721f9a1e738668c9f29a0ef6a2870cb9)
03-25 21:02:14.164 F/DEBUG   (23318):       #23 pc 0000000000052c08  /apex/com.android.runtime/lib64/bionic/libc.so (__start_thread+64) (BuildId: 721f9a1e738668c9f29a0ef6a2870cb9)
onSignalStrengthsChanged signalStrength=SignalStrength:{mCdma=Invalid,mGsm=Invalid,mWcdma=Invalid,mTdscdma=Invalid,mLte=CellSignalStrengthLte: rssi=-95 rsrp=-94 rsrq=-11 rssnr=14 cqiTableIndex=2147483647 cqi=12 ta=2147483647 level=4 parametersUseForLevel=0,mNr=Invalid,SignalBarInfo{ lteLevel=3 },rat=14,primary=CellSignalStrengthLte} level=3
onSignalStrengthsChanged signalStrength=SignalStrength:{mCdma=Invalid,mGsm=Invalid,mWcdma=Invalid,mTdscdma=Invalid,mLte=CellSignalStrengthLte: rssi=-91 rsrp=-90 rsrq=-10 rssnr=16 cqiTableIndex=2147483647 cqi=12 ta=2147483647 level=4 parametersUseForLevel=0,mNr=Invalid,SignalBarInfo{ lteLevel=3 },rat=14,primary=CellSignalStrengthLte} level=3
onSignalStrengthsChanged signalStrength=SignalStrength:{mCdma=Invalid,mGsm=Invalid,mWcdma=Invalid,mTdscdma=Invalid,mLte=CellSignalStrengthLte: rssi=-95 rsrp=-94 rsrq=-10 rssnr=16 cqiTableIndex=2147483647 cqi=12 ta=2147483647 level=4 parametersUseForLevel=0,mNr=Invalid,SignalBarInfo{ lteLevel=3 },rat=14,primary=CellSignalStrengthLte} level=3
onSignalStrengthsChanged signalStrength=SignalStrength:{mCdma=Invalid,mGsm=Invalid,mWcdma=Invalid,mTdscdma=Invalid,mLte=CellSignalStrengthLte: rssi=-99 rsrp=-98 rsrq=-10 rssnr=17 cqiTableIndex=2147483647 cqi=12 ta=2147483647 level=4 parametersUseForLevel=0,mNr=Invalid,SignalBarInfo{ lteLevel=3 },rat=14,primary=CellSignalStrengthLte} level=3
onSignalStrengthsChanged signalStrength=SignalStrength:{mCdma=Invalid,mGsm=Invalid,mWcdma=Invalid,mTdscdma=Invalid,mLte=CellSignalStrengthLte: rssi=-95 rsrp=-94 rsrq=-10 rssnr=15 cqiTableIndex=2147483647 cqi=12 ta=2147483647 level=4 parametersUseForLevel=0,mNr=Invalid,SignalBarInfo{ lteLevel=3 },rat=14,primary=CellSignalStrengthLte} level=3
onSignalStrengthsChanged signalStrength=SignalStrength:{mCdma=Invalid,mGsm=Invalid,mWcdma=Invalid,mTdscdma=Invalid,mLte=CellSignalStrengthLte: rssi=-91 rsrp=-91 rsrq=-11 rssnr=16 cqiTableIndex=2147483647 cqi=12 ta=2147483647 level=4 parametersUseForLevel=0,mNr=Invalid,SignalBarInfo{ lteLevel=3 },rat=14,primary=CellSignalStrengthLte} level=3

We've tried updating dependencies (incl. Flutter version up until 2.10.3).
One key problem we are facing is that the issue is not consistently reproducible and no developer had the problem so far. Only actual app users seem affected and the problem also does not appear to occur the same way for the affected users. For example: After deleting data / cache for the app users are able to work with the app as expected for a day or so and then misbehaviour starts again.
Can you think of anything specific that might be causing such a problem?


text:
Q: Python 3.x how to get http version (using requests library) Preferably using the requests library
HTTP/1.1 200 OK        <-- I want this...
Content-Type: text/html; charset=utf-8

That property doesn't seem to be provided http://docs.python-requests.org/en/master/api/#requests.Response
Is there a way to access the raw response string?
I found http://docs.python-requests.org/en/master/user/quickstart/#raw-response-content
but I'm not seeing any content
r = requests.head(uri, stream=True)
print(r.raw.read(10)) # -> b''

A: I think what you want is this. Calling version on raw will give you HTTP version. (I found the example of server running HTTP 1.0 using Shodan for testing purposes)
>>> import requests
>>> response = requests.get("http://104.71.136.252/", timeout=60, verify=False)
>>> response.raw.version
10
>>> response = requests.get("http://stackoverflow.com", timeout=60, verify=False)
>>> response.raw.version
11

This is not mentioned in the docs directly, I found it by using PyCharm's autocomplete feature. But I have looked into it. The reason why is HTTP version returned as integer is historical.
Requests for python3 uses urllib3. Urllib3's class urllib3.response.HTTPResponse is backwards compatible with httplib's HTTPResponse see urllib3 docs
Now if it's backwards compatible you have to check documentation for httplib and if you search you'll find

HTTP protocol version used by server. 10 for HTTP/1.0, 11 for HTTP/1.1.

Here is the exact link HTTPResponse.version

redpajama_set_name: RedPajamaStackExchange


text:
Q: get data from third table Who can help me with my code.
I have 3 tables for example teams, players and lineups.
teams
+--+------+
|ID| TEAM |
|1 |Yellow|
|2 |Green |
|3 |Blue  |
|4 |Red   |
+--+------+

Players
+--+------+
|ID| NAME |
|1 |Ben   |
|2 |Mike  |
|3 |Jason |
+--+------+

Lineups
+---+---+
|PID|TID|
|1  |3  |
|2  |1  |
|2  |4  |
|3  |2  |
+--+----+

This is my query
SELECT teams.id teamsid, teams.team teamname, lineup.tid
FROM teams
LEFT JOIN lineup ON (lineup.tid = teams.id AND lineup.pid = 2)
ORDER BY team ASC

<?php
$result = mysqli_query($connection, $sql);
while($row = mysqli_fetch_assoc($result)){
    $checked = ($row['tid'] === NULL ? '' : ' checked="checked"');
?>

    <input type="checkbox" <?php echo $checked; ?>><?php echo $row['teamname']; ?>
<?php
}
?>

This results
<input type="checkbox">Blauw
<input type="checkbox">Geel
<input type="checkbox" checked="checked">Groen
<input type="checkbox" checked="checked">Rood

So my question is how can I get the playername in the same query from the players table?
For the result above the name has to be "Mike".
Thanks a lot.

A: Just join one more time to bring in the players table:
SELECT
    t.id teamsid,
    t.team teamname,
    l.tid,
    p.name player_name
FROM teams t
LEFT JOIN lineup l ON l.tid = t.id
LEFT JOIN players p ON p.id = l.pid AND p.id = 2
ORDER BY t.team

Notes:

*

*do you really mean left join? this will produce empty values in the resultset for teams that have no lineup. I suspect that you want INNER JOINs (and you could move the filer on p.id = 2 to the WHERE clause for more readability

*parentheses around the join conditions are superfluous

*ASC is the default ORDER BY direction

*table aliases are handy - they make the query shorter to write


text:
Q: How to list all Unicode strings starting and ending with a particular character? I am trying to list all the words have particular ending and  starting.
This is  ണ്  my ending character and വി is my starting character.
this is my input
പാമോലിന് കേസിന്റെ വിചാരണ നടപടികള് ഹൈക്കോടതി രണ്ടുമാസത്തേക്ക് സ്‌റ്റേചെയ്തു. കേസ് പിന്‍വലിക്കണമെന്ന ആവശ്യം നിരസിച്ച തൃശ്ശൂര് വിജിലന്‍സ് കോടതി ഉത്തരവിനെതിരെ വിജിലന്‍സ് സമര്‍പ്പിച്ച ഹര്‍ജിയിലാണ് ഇടക്കാല ഉത്തരവ്.

The expected output is
വിചാരണ

How can I write regular expression for it ?
re.findall(ur'\bവി\w+ണ\b', inputtext, flags=re.UNICODE) won´t work

I still don´t understand why its  not working like English, Please add this fact to the answer so that I could get better understanding of the problem

A: Your input text is full of a mix of word and non-word characters, so the only way to determine a word boundary is to look behind and ahead for spaces:
re.findall(ur'(?<![^ ])വി[^ ]+ണ്?(?![^ ])', inputtext, flags=re.UNICODE)

where inputtext is a Unicode value. The (?<!...) and (?!...) are negative lookbehind and lookahead assertions; the match locations in the text that are not preceded or followed by a non-space character, respectively.
Within your boundary text, we match non-spaces as well.
This matches your expected input:
>>> print re.findall(ur'(?<![^ ])വി[^ ]+ണ്?(?![^ ])', inputtext, flags=re.UNICODE)[0]
വിചാരണ

A: ... or, if you want something more verbal
original_list = ('abc', 'ccbd', 'abbc')
filtered = tuple(filter(lambda x: x.startswith('a') and x.endswith('c'), original_list))
filtered
('abc', 'abbc')

but it definately doesn't answer your question.


text:
Q: Garbage Keyboard Information in SDL 2.0 I have the following code to test SDL keyboard input on version 2.0:
while (SDL_PollEvent(&evnt))
        {
            if (evnt.type == SDL_KEYDOWN)
            {
                board = evnt.key;
                key = board.keysym.sym;

                switch (key)
                {
                    case SDLK_a:
                        printf("a key!\n");
                        break;

                    case SDLK_d:
                        printf("d key!\n");
                        break;

                    default:
                        printf("Code: 0x%X\n", board.keysym.scancode);
                        printf("Name: %s\n", SDL_GetKeyName(key));
                        printf("Hex:  0x%02X\n", key);
                        printf("Uni:  %c\n\n", (char)board.keysym.unicode);
                }
            } else if (evnt.type == SDL_QUIT)
                running = false;
        }

However, following is the output for the sequence 'qwerty':
Code: 0x460001
Name: ¶
Hex:  0x14
Uni:

Code: 0x460001
Name: →
Hex:  0x1A
Uni:

Code: 0x460001
Name: Backspace
Hex:  0x08
Uni:

Code: 0x460001
Name: §
Hex:  0x15
Uni:

Code: 0x460001
Name: ↨
Hex:  0x17
Uni:

Code: 0x460001
Name: ∟
Hex:  0x1C
Uni:

Am I just doing something stupid?
Also, this is not an ideal method for my program. I would prefer to do
if (ispressed['k'])
{ }
etc...
Is there an ability to do this form of input processing in SDL or will I need to write my own class to manage it?

A: The switch statement basically is just an if statement.
If you really want to do it your way, it would look like
if (event.type == SDL_KEYDOWN)
        {
            board = evnt.key;
            key = board.keysym.sym;

            if(key==SDLK_a)
            {
                //do stuff here
            }

If you want it to look exactly like what you said above, you would need to define a MAP of bools, called isPressed, and whenever you get a key event, pass it to a helper that would set the values in the map based on the key pressed. I'll tell you now - get used to the way SDL 'wants' you to do this. When you are more comfortable with it you'll realize it makes more sense.
As for the bug you are experiencing - I'm not too sure about part of it, but try putting SDL_EnableUNICODE(); in your init. Then test on the same input and report back - I expect that to at least fix your unicode problem.


text:
Q: Check if newer Version of AppxPackage is installed I wanted to know if can check if a newer Version of a Package is installed in Powershell.
I wanted to install the Package "Microsoft.VCLibs.x86.14.00.appx" via powershell.
I do that by the command: Add-AppxPackage .\Microsoft.VCLibs.x86.14.00.appx
but then I get the error: HRESULT: 0x80073D06, The Package could not be installed because a higher version f this package is already installed.
I checked with
Get-AppxPackage * Microsoft.vclibs.14*
and yeah there is a higher Version.
So is there a way to access the version and compare them? and than decide to install the Package or not?
like a script where I get the installed packages via "Get-AppxPackage * Microsoft.vclibs.14*" und foreach the result and access the version?

A: $FilePath = ".\Microsoft.VCLibs.x86.14.00.appx"
$FileVersion = (Get-ItemProperty -Path $FilePath).VersionInfo.ProductVersion
$HighestInstalledVersion = Get-AppxPackage -Name Microsoft.VCLibs* |
    Sort-Object -Property Version |
    Select-Object -ExpandProperty Version -Last 1

if ( $HighestInstalledVersion -lt $FileVersion ) {
    Add-AppxPackage $FilePath
}


text:
Q: Unable to upload image first time, it works in the second time I am uploading any type of file from my code but the problem is when I run my code for the first time and try to upload an image, the image not being uploaded in that time. If I upload a file first, e.g. a PDF file, it is being uploaded successfully and after that when I upload an image, it is uploaded successfully as well. I don't understand anything about the problem. Please help.
Here is the code for uploading an image/file.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
    if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED) {
        showFileChoser();
    } else {
        if (ActivityCompat.shouldShowRequestPermissionRationale(getActivity(), Manifest.permission.CAMERA)) {
            Toast.makeText(getActivity(), "App requires Phone permission.\nPlease allow that in the device settings.", Toast.LENGTH_LONG).show();
        }

        ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.CAMERA}, STORAGE_PERMISSION_CODE);
    }
} else {
    showFileChoser();
}

And the showFileChoser function.
private void showFileChoser() {
    Intent intent = new Intent();
    intent.setType("*/*");
    intent.setAction(Intent.ACTION_GET_CONTENT);
    startActivityForResult(Intent.createChooser(intent, "Select document"), PICK_DOCUMENT);
}

The onActivityResult.
// Handling the ima chooser activity result
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if (requestCode == PICK_PDF_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
        filePath = data.getData();
        // uploadMultipart();

        try {
            execMultipartPost();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

And onRequestPermissionsResult is...
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {

    //Checking the request code of our request
    if (requestCode == STORAGE_PERMISSION_CODE) {

        //If permission is granted
        if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            //Displaying a toast
            Toast.makeText(getActivity(), "Permission granted now you can read the storage", Toast.LENGTH_LONG).show();
        } else {
            //Displaying another toast if permission is not granted
            Toast.makeText(getActivity(), "Oops you just denied the permission", Toast.LENGTH_LONG).show();
        }
    }
}

The file uploading function is the following.
private void execMultipartPost() throws Exception {

    RequestBody requestBody;
    pBar.setVisibility(View.VISIBLE);

    final SessionManager session = new SessionManager(getActivity());
    final HashMap<String, String> loggedDetail = session.getLoggedDetail();
    HashMap<String, String> params = new HashMap<String, String>();

    String api_token = loggedDetail.get("api_token");

    if (filePath != null) {
        String path = FilePath.getPath(getActivity(), filePath);
        requestBody = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart("identity_file", path)
                .addFormDataPart("training", edtTraining.getText().toString())
                .addFormDataPart("user_id", loggedDetail.get("id"))
                .addFormDataPart("experience", experience)
                .addFormDataPart("skills", edtSkills.getText().toString())
                .addFormDataPart("address_file", "")
                .addFormDataPart("cv_file", "")
                .addFormDataPart("dbs_file", "")
                .build();
    }
}

A: As far as I can assume, you are calling the requestPermissions function from a Fragment. As you are using ActivityCompat.requestPermissions for asking permission from the user, the onRequestPermissionsResult is not being invoked in the Fragment. Here is a similar problem which indicates the Fragment's onRequestPermissionsResult not being called and the calling Activity's onRequestPermissionsResult is being called instead. I assume this is what happens in your case as well.
Now to get rid of this problem, you need to use
requestPermissions(new String[]{Manifest.permission.CAMERA}, STORAGE_PERMISSION_CODE);

instead of
ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.CAMERA}, STORAGE_PERMISSION_CODE);

Do not use ActivityCompat.requestPermissions in your Fragment, as this will invoke the onRequestPermissionResult of your calling Activity which is launching the Fragment.
Hope that helps.


text:
Q: Нужно решить проблему с копированием файла в диски python Мне нужно чтобы мой код при запуске автоматически определял буквы дисков, которые есть на компьютере у пользователя и копировал туда текстовый файл, желательно чтобы после этого сразу копировал в каждом диске в каждую папку и подпапку этот же текстовый файл
import os
import sys
import shutil
import time

file = open("Открой меня.txt", "w")
file.write("Hello World")
file.close()

time.sleep(7)

def function_global():
    try:
        def function1():
            try:
                shutil.copyfile('Открой меня.txt', 'Q:/Открой меня.txt')
            except:
                function1()
        function1()

        def function2():
            try:
                shutil.copyfile('Открой меня.txt', 'R:/Открой меня.txt')
            except:
                function2()
        function2()

        def function3():
            try:
                shutil.copyfile('Открой меня.txt', 'E:/Открой меня.txt')
            except:
                function3()
        function3()

        def function4():
            try:
                shutil.copyfile('Открой меня.txt', 'W:/Открой меня.txt')
            except:
                function4()
        function4()

        def function5():
            try:
                shutil.copyfile('Открой меня.txt', 'T:/Открой меня.txt')
            except:
                function5()
        function5()

        def function6():
            try:
                shutil.copyfile('Открой меня.txt', 'Y:/Открой меня.txt')
            except:
                function6()
        function6()

        def function7():
            try:
                shutil.copyfile('Открой меня.txt', 'U:/Открой меня.txt')
            except:
                function7()
        function7()

        def function8():
            try:
                shutil.copyfile('Открой меня.txt', 'I:/Открой меня.txt')
            except:
                function8()
        function8()

        def function9():
            try:
                shutil.copyfile('Открой меня.txt', 'O:/Открой меня.txt')
            except:
                function9()
        function9()

        def function10():
            try:
                shutil.copyfile('Открой меня.txt', 'P:/Открой меня.txt')
            except:
                function10()
        function10()

        def function11():
            try:
                shutil.copyfile('Открой меня.txt', 'A:/Открой меня.txt')
            except:
                function11()
        function11()

        def function12():
            try:
                shutil.copyfile('Открой меня.txt', 'S:/Открой меня.txt')
            except:
                function12()
        function12()

        def function13():
            try:
                shutil.copyfile('Открой меня.txt', 'D:/Открой меня.txt')
            except:
                function13()
        function13()

        def function14():
            try:
                shutil.copyfile('Открой меня.txt', 'F:/Открой меня.txt')
            except:
                function14()
        function14()

        def function15():
            try:
                shutil.copyfile('Открой меня.txt', 'G:/Открой меня.txt')
            except:
                function15()
        function15()

        def function16():
            try:
                shutil.copyfile('Открой меня.txt', 'H:/Открой меня.txt')
            except:
                function16()
        function16()

        def function17():
            try:
                shutil.copyfile('Открой меня.txt', 'J:/Открой меня.txt')
            except:
                function17()
        function17()

        def function18():
            try:
                shutil.copyfile('Открой меня.txt', 'K:/Открой меня.txt')
            except:
                function18()
        function18()

        def function19():
            try:
                shutil.copyfile('Открой меня.txt', 'L:/Открой меня.txt')
            except:
                function19()
        function19()

        def function20():
            try:
                shutil.copyfile('Открой меня.txt', 'Z:/Открой меня.txt')
            except:
                function20()
        function20()

        def function21():
            try:
                shutil.copyfile('Открой меня.txt', 'X:/Открой меня.txt')
            except:
                function21()
        function21()

        def function22():
            try:
                shutil.copyfile('Открой меня.txt', 'V:/Открой меня.txt')
            except:
                function22()
        function22()

        def function23():
            try:
                shutil.copyfile('Открой меня.txt', 'B:/Открой меня.txt')
            except:
                function23()
        function23()

        def function24():
            try:
                shutil.copyfile('Открой меня.txt', 'N:/Открой меня.txt')
            except:
                function24()
        function24()

        def function25():
            try:
                shutil.copyfile('Открой меня.txt', 'M:/Открой меня.txt')
            except:
                function25()
        function25()

    except:
        function_global()
function_global()

к сожалению код не работает должным образом, если в первой функций есть буква моего диска, то он делает копирование, если же поменять на любую другую букву диска, который у меня не создан, тогда он не копирует, а просто завершает программу


text:
Q: What is the difference between those two declarations? I'm new to the C language and i can't figure out what is the difference between char* stc[4]; and char stc[4];..
I know char stc[4]; will create an array with 4 items but what creates the first one is a mystery to me..
Thanks in advance!

A: char *stc[4]; creates an array of 4 pointers to char. (Any introduction to C should explain pointers and declarations.)

A: char* stc[4] is an array of pointers which stores addresses of 4 char datatype variables.
int main ()
{
   char  stc[] = {'a', 'b', 'c','d'};
   char *ptr[4];
   int i;

   for ( i = 0; i < 4; i++)
   {
      ptr[i] = &stc[i]; /* assign the address of char array elements. */
   }

}

A: You should learn first what a pointer is in C. The first declaration allocates memory for holding 4 pointers to char values. The second declaration allocates memory for holding 4 char values.
A quick answer for what a pointer is, think about a library. A library contains items of type "book", and the librarian will give you a pointer (a post-it or a piece of paper) with information about the location of a book you are interested in. So, in analogy, the first declaration reserves memory for 4 post-its, and the second one reserves memory for 4 books.


text:
Q: Query only base class Having the following structure:

*

*Article : IArticle

*SuperArticle : Article

*AwesomeArticle : Article
Article is not abstract, some items are just articles, other are derived types. Here's my NHibernate config, following table-per-hierarchy strategy (because subclases are also on the main table, and may or may not contain aditional data in other tables):
<class name="IArticle" table="Articles" >
<id name="Id" column="IdArticle"/>
 <discriminator type="string" formula="(CASE WHEN IdTipoDef LIKE 'DefProd8' THEN 'SUPER' ELSE CASE WHEN IdTipoDef LIKE 'DefProd9' THEN 'AWESOME' ELSE  'ARTICLE' END END)"/>
<property name="Description" column="Descrip"/>
<subclass name="SuperArticle" discriminator-value="SUPER">
    <join table="otherTable">
        ...
    </join>
</subclass>
<subclass name="AwesomeArticle" discriminator-value="AWESOME">
    <join table="otherOtherTable">
      ...
    </join>
</subclass>
<subclass name="Article" discriminator-value="ARTICLE">
</subclass>
</class>

The problem is when I try to query the ones that are just Article, that it returns also its subclasses, and if I try to count I get an error:
 [TestMethod]
    public void EncuentraArticulosTest()
    {
        ISession session = NHibernateHelper.GetSession();
        session.BeginTransaction();
        Debug.Write(session.QueryOver<Article>().Where(a => a.GetType() == typeof(Article)).RowCount());
        Assert.IsTrue(session.QueryOver<Article>().RowCount() > 0);
        session.Close();
    }

This (either the Assert or the Debug) gives the following exception:
Seguimiento de la pila de Result:
en NHibernate.Impl.AbstractQueryImpl.UniqueElement(IList list)
en NHibernate.Impl.CriteriaImpl.UniqueResult[T]()
en NHibernate.Criterion.QueryOver`1.SingleOrDefault[U]()
en NHibernate.Criterion.QueryOver`1.NHibernate.IQueryOver<TRoot>.RowCount()
en MyCompany.Test.NHibernateTests.EncuentraArticulosTest() en ...\NHibernateTests.cs:línea 36
Mensaje de Result:
El método de prueba MyCompany.Test.NHibernateTests.EncuentraArticulosTest produjo la excepción:
NHibernate.NonUniqueResultException: query did not return a unique result: 7

A: This happens by design because your derived classes are base types.  This is classic object oriented polymorphism.
See this ticket if you really need to get only base class entities back.
NHibernate: Load base class objects only

A: Finally I found this answer from Java's version (Hibernate):
How to perform a non-polymorphic HQL query in Hibernate?


text:
Q: Which browsers can properly handle non-mouse/keyboard input devices? (Eg touchscreens, graphics tablets, etc) A W3C Recommendation (24 February 2015) defines events and related interfaces for handling hardware agnostic pointer input from devices including a mouse, pen, touchscreen, etc. Essentially letting web pages know when somebody is using something like a touchscreen, or a graphics tablet.
On Windows, IE10+ has this ability, but I haven't found any information about this on Linux environments. Do any browsers  in Ubuntu support this yet?
NOTE: There is a Wacom plugin for their tablets but this only works with Wacom and is not standardized.

A: Can I use pointer events?

Firefox support is disabled by default and only supports mouse input.
  On Windows only, touch can be enabled with the
  layers.async-pan-zoom.enabled and dom.w3c_touch_events.enabled flags

None of the other browsers seem to do so at the moment.


text:
Q: Is it a bad practice to mix query and body params in POST request? It's a just curiosity. If it's really bad practice to mix query and body params in POST request.
Just for example:
/someservice/create/{id}?idApp=989898
RequestBody: {par1: par1, par2: par2}

A: Oversimplifying, the URI is there to identify the resource and the request body is there so you can send information with the request. So for instance:

POST /modify/whatsit?id=123
Body: Data for modifying the whatsit

is fine. The URI is saying what to modify (whatsit 123), and the body is the information for that.
Your example uses create in the URI, so I wouldn't expect it to also have an idApp parameter, since IDs are normally assigned as/when the item is created. So in that particular example, I wouldn't expect to find query parameters in the URI. I'd normally expect any additional information for the create operation to be in the request body.
That said, sometimes people put the identifying information in the request body instead. One advantage to having it in the URI is that logs containing the URI but not the post body tell you not just that a resource was modified (/modify/whatsit), but which resource was modified (/modify/whatsit?id=123).


text:
Q: jQuery Each Loop Not updating HTML in variable I have a variable html that stores HTML:

    0
    0

    0
    0

    250
    0

Basically I need to add the values for the td with the class starting with charge to the values for the td with the class starting with nc and replace the value in the td with class starting with nc with the sum. The values in both td's in each row could change, so the code needs to be dynamic. So for this example, the resulting HMTL in the variable should be:

    0
    0

    0
    0

    250
    250

In this example, the only row that actually changes is the third row. The td starting with class nc now shows 250 instead of the original 0.
I have to use the variable html later in the code with the updated td information if it did change.
This is the code that I have, but it's not working:
var html = $('#chargetable').html();
console.log(html);
$('[class*=nc]', html).each(function(){
    var ncamount = $(this).html();
    var chargeamount = $(this).parents('tr').find('[class*=charge]').html();
    var totalnc = parseFloat(chargeamount) + parseFloat(ncamount);
    $(this).html(totalnc);
    console.log(chargeamount + ' ' + ncamount + ' ' + totalnc);
});
console.log(html);

This is the results of the console's log:

    0
    0

    0
    0

    250
    0

0 0 0
0 0 0
250 0 250

    0
    0

    0
    0

    250
    0

The html variable isn't being updated, but I can't for the life of me figure out how to get it to update, short of splitting the variable, replacing the td with class nc, and recreating the html variable on each iteration. I'm thinking there's got to be a better way to do this.
Any help is very much appreciated.

A: The problem with you code is that you cannot use html variable in this line
$('[class*=nc]', html)
the second parameter is used to define scope in which jQuery searches for the selector.
So, like document,parent.document(if its iframe etc..)
If you need the original dom you can use jQuery .clone() to store the original dom like this
//if you require the original code for later clone it
var htmlclone = $('#chargetable').clone().html();
console.log(htmlclone);
$('#chargetable [class*=nc]').each(function(){
    var ncamount = $(this).html();
    var chargeamount = $(this).parents('tr').find('[class*=charge]').html();
    var totalnc = parseFloat(chargeamount) + parseFloat(ncamount);
    $(this).html(totalnc);
    console.log(chargeamount + ' ' + ncamount + ' ' + totalnc);
});
console.log(htmlclone);

Here is a fiddle http://jsfiddle.net/z4n7kjcf/

A: $(function () {
    var $chargeTable = $("#chargetable");
    var $chargeTableCloned = $chargeTable.clone();
    var $chargeTableRows = $("tr", $chargeTableCloned);

    $.each($chargeTableRows, function(i, $tr){
        var $tdCharge = $("td[class^='charge']", $tr);
        var $tdNc = $("td[class^='nc']", $tr);
        var charge = parseInt($tdCharge.text(), 10);
        var nc = parseInt($tdNc.text(), 10);
        $tdNc.text(charge + nc);
    });

    $chargeTable.after($chargeTableCloned);
});

Example


text:
Q: edit background layer in png I have an image here a guy http://andybriggs.com/img/streetguy.png. I'm not good at image editing so I don't know if I'm explaining this right. The image is a rectangle and is one layer when opened in gimp. I want to change the white background to gray so it will match the background color on my website. Does that make sense?

A: Never mind I figured it out on GIMP:
From the toolbar: Layer >> New from Visible; This gives you the foreground layer (the guy) and another layer with the white background.
Then click the second layer, the background, and go to the paint bucket and click it on the image.
Then go to the Layers, Channels window and in the layers pane click the eye image on the first layer to make it invisible. Then go to Image >> Flatten Image and it's done


text:
Q: Delete items on hand when added to cart with Laravel I am building a small e-commerce site out and want to be able to have the stock on hand be updated when items are added or deleted from someone's cart. In my cart controller, I have four functions: one to add an item, one to increase the item, one to decrease the item, and one to remove an item. Here is the code for that:
     public function addItemToCart(Request $request, $id) {

    $prevCart = $request->session()->get('cart');
    $cart = new Cart($prevCart);

    $product = Product::find($id);
    $cart->addItem($id, $product);
    $request->session()->put('cart', $cart);

    return redirect()->route("home");

}

public function increaseSingleProduct(Request $request, $id) {

    $prevCart = $request->session()->get('cart');
    $cart = new Cart($prevCart);

    $product = Product::find($id);
    $cart->addItem($id, $product);
    $request->session()->put('cart', $cart);

    return redirect()->back();
}

public function decreaseSingleProduct(Request $request, $id) {

    $prevCart = $request->session()->get('cart');
    $cart = new Cart($prevCart);

    if( $cart->items[$id]['quantity'] > 1) {
        $product = Product::find($id);
        $cart->items[$id]['quantity'] = $cart->items[$id]['quantity']-1;
        $cart->items[$id]['totalSinglePrice'] = $cart->items[$id]['quantity'] * $product['price'];
        $cart->updatePriceAndQunatity();

        $request->session()->put('cart', $cart);
    }
    return redirect()->back();
}

public function deleteItemFromCart(Request $request, $id) {

    $cart = Session::get('cart');

    if(array_key_exists($id, $cart->items)){
        unset($cart->items[$id]);
    }
    $prevCart = $request->session()->get("cart");
    $updatedCart = new Cart($prevCart);
    $updatedCart->updatePriceAndQunatity();

    $request->session()->put("cart",$updatedCart);

    return redirect()->route('shopping cart');
}

The quantity here does not refer to the quantity on hand, it refers to the quantity in the cart. In the products table, I have a column that is called stock_quantity. Ideally, this is what I would like to get updated as each function is performed.

A: I may not be getting the complexity of your question. Don't you just have to find the product and increment or decrement?
$product = Product::findOrFail($item_id);
$product->stock_quantity++; // or --
$product->save();

I wouldn't be doing this as you add to the cart though. I'd do it on checkout instead so that you don't leave your stock committed with an abandoned cart. Alternatively, if you really need to commit your stock while someone has something in the cart, implement a function to remove the committed stock if it's abandoned.


text:
Q: Kubernetes EndPointSlice for service without selector I cannot solve this problem.
Kubernetes version: 1.23.1
My cluster is divided into three zones:

*

*zone1

*zone2

*zone3

There are three mysql databases. They are not in kubernetes

*

*192.168.0.101

*192.168.0.102

*192.168.0.103

I made a service for them without selectors.
And added endpointslice. But I get connection refused. Please tell me what I did wrong, thanks.
To test it, I made 3 pods with a mysql client, which, depending on the zone, should go to the required database.
apiVersion: v1
kind: Service
metadata:
  name: test-mysql
  annotations:
    service.kubernetes.io/topology-aware-hints: auto
spec:
  ports:
    - protocol: TCP
      port: 3306
      targetPort: 3306

---

apiVersion: discovery.k8s.io/v1
kind: EndpointSlice
metadata:
  name: test-mysql
  annotations:
  labels:
    kubernetes.io/service-name: test-mysql
addressType: IPv4
ports:
 - name: mysql
    protocol: TCP
    port: 3306
endpoints:
 - addresses:
      - "192.168.0.101"
    conditions:
      ready: true
    zone: zone1
    hints:
      forZones:
        - name: "zone1"
 - addresses:
      - "192.168.0.102"
    conditions:
      ready: true
    zone: zone2
    hints:
      forZones:
        - name: "zone2"
 - addresses:
      - "192.168.0.103"
    conditions:
      ready: true
    zone: zone3
    hints:
      forZones:
        - name: "zone3"

Nginx just for testing, I put mysql-client on it
apiVersion: apps/v1
kind: Deployment
metadata:
  name: nginx-deployment
spec:
  selector:
    matchLabels:
      app: nginx
  replicas: 3
  template:
    metadata:
      labels:
        app: nginx
    spec:
      affinity:
        podAntiAffinity:
          requiredDuringSchedulingIgnoredDuringExecution:
          - labelSelector:
              matchExpressions:
              - key: app
                operator: In
                values:
                - web-store
            topologyKey: "kubernetes.io/hostname"
      containers:
      - name: nginx
        image: nginx:1.14.2
        ports:
        - containerPort: 80

Labels nodes:
kubectl label nodes node1 node2 topology.kubernetes.io/zone=zone1
kubectl label nodes node1 node2 kubernetes.io/zone=zone1

A: TopologyAwareHints available since 1.24
For 1.23 you need to enable --feature-gates=TopologyAwareHints=true
https://kubernetes.io/docs/reference/command-line-tools-reference/feature-gates/#:~:text=1.23-,TopologyAwareHints,-true
Simple example:
Label nodes:
kubectl label nodes $NODE_ZONE_1 topology.kubernetes.io/zone=zone1
kubectl label nodes $NODE_ZONE_2 topology.kubernetes.io/zone=zone2
kubectl label nodes $NODE_ZONE_3 topology.kubernetes.io/zone=zone3

Service:
apiVersion: v1
kind: Service
metadata:
  name: galera
  annotations:
    service.kubernetes.io/topology-aware-hints: auto
spec:
  ports:
    - port: 3306
      name: mysql
      protocol: TCP
      targetPort: 3306
---
apiVersion: discovery.k8s.io/v1
kind: EndpointSlice
metadata:
  name: galera-ep
  labels:
    kubernetes.io/service-name: galera
addressType: IPv4
ports:
  - name: mysql
    protocol: TCP
    port: 3306
endpoints:
  - addresses:
      - "192.168.0.11"
    conditions:
      ready: true
    zone: zone1
    hints:
      forZones:
       - name: "zone1"
  - addresses:
      - "192.168.0.12"
    conditions:
      ready: true
      serving: true
    zone: zone2
    hints:
      forZones:
        - name: "zone2"
  - addresses:
      - "192.168.0.13"
    conditions:
      ready: true
      serving: true
    zone: zone3
    hints:
      forZones:
        - name: "zone3"

Deploy:
apiVersion: apps/v1
kind: Deployment
metadata:
  labels:
    app: ubuntu
  name: ubuntu
spec:
  replicas: 3
  selector:
    matchLabels:
      app: ubuntu
  strategy:
    rollingUpdate:
      maxSurge: 1
      maxUnavailable: 0
    type: RollingUpdate
  template:
    metadata:
      labels:
        app: ubuntu
    spec:
      topologySpreadConstraints:
      - maxSkew: 1
        topologyKey: topology.kubernetes.io/zone
        whenUnsatisfiable: DoNotSchedule
        labelSelector:
          matchLabels:
            app: ubuntu
      containers:
      - name: ubuntu
        args:
        - while true; do sleep 1000; done;
        command:
        - /bin/bash
        - -c
        - --
        image: ubuntu:latest
        imagePullPolicy: Always
      dnsPolicy: ClusterFirst
      restartPolicy: Always

Inside pod:

If in one namespace

mysql -p -h galera.svc -P 3306

If in different namespaces

mysql -p -h galera.svc.default.cluster.local -P 3306


text:
Q: GridLayoutManager spanSizeLookup bug I am having an issue with GridLayoutManger setSpanSizeLookup, when an orientation of activity changes, I am changing the span count while checking if the specific position is some sort of type, this works perfectly on orientation change, my only problem is, I'm using zxing library to do barcode scanning, whenever a button is clicked I'm opening the zxing default intent and retrieve date from it, however when zxing is opening it goes to landscape and my current activity orientation is portrait this gives me the IllegalArgumentException that the layout manage throws when only opening the Xzing intent, the crash log is as this
java.lang.IllegalArgumentException: Item at position 0 requires 2 spans but GridLayoutManager has only 1 spans.
this problem doesn't occur if i rotate the phone, only happens when I launch the Xzing intent, i couldn't really figure out how how I solve this issue as its bugging me. here is my spanSizeLookup -
manager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
     @Override
     public int getSpanSize(int position) {
        return adapter.getHolders().get(position).getLabelHolder() != null ? getResources().getInteger(R.integer.span) : 1;
     }
});

the span is base on screen size so it can be 1-2, 2-3 and 3-4. i repeat this doesn't give me any error on orientation change, only the error occur when I open the zxing
P.S if i open zxing intent while my activity is on landspace the crash wont occur.
Edit
it seems like only launching the zxing default intent causing this issue, I'm having an activity where it goes landscape after it launches and the exception didn't occur, as a workaround i did, was that i created an activity that handles the barcode scanning with a delay of 1 second to launch the intent as if i didn't do that, it will throw the same exception.
Edit 2
I just found that, even without setSpanSpizeLookup the crash still occurs.  by just calling manager.setSpanCount(getResources().getInteger(R.integer.span))

A: Here's the source code that throws the exception in GridLayoutManager.layoutChunk()
final int spanSize = getSpanSize(recycler, state, pos);
if (spanSize > mSpanCount) {
    throw new IllegalArgumentException("Item at position " + pos + " requires " +
           spanSize + " spans but GridLayoutManager has only " + mSpanCount
           + " spans.");
}

Is your spanSize greater than your spanCount? Try to debug and probably change your spanCount and see how it works.
---- Updated ----
There're couple ways to switch between list and grid.

*

*Only changing the spanCount.
You have to call LayoutManager.requestLayout() after you change your spanCount. Otherwise your app may crash.

*Only changing the SpanSizeLookUp.
private class CustomSpanSize extends GridLayoutManager.SpanSizeLookup {

  private static final int LIST_SPAN_SIZE = 1;
  private static final int GRID_SPAN_SIZE = 2;

  private int mSpanSize = LIST_SPAN_SIZE;

  public void asList() {
    mSpanSize = LIST_SPAN_SIZE;
  }

  public void asGrid() {
    mSpanSize = GRID_SPAN_SIZE;
  }

  @Override
  public int getSpanSize(int position) {
    return mSpanSize;
  }
}

and use it like that
@Override
protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);

  mLayoutManager = new GridLayoutManager(this, 2);

  mCustomSpanSize = new CustomSpanSize();
  mLayoutManager.setSpanSizeLookup(mCustomSpanSize);
  RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recycler);
  recyclerView.setHasFixedSize(true);
  recyclerView.setLayoutManager(mLayoutManager);

  ...
}

public void someFunction() {
  if (changed) {
    mCustomSpanSize.asList();
  } else {
    mCustomSpanSize.asGrid();
  }
  // use this to update the layout
  mAdapter.notifyDataSetChanged();
  // or you can use this to update the layout
  mLayoutManager.requestLayout();
}

this way won't crash even you forget to call notifyDataSetChanged or requestLayout

A: Edit: call setSpanCount() and make it a bigger number than that span no?
Perhaps more code would be in order.
That sounds like it could have been a concurrent modification error. Try not using a delay per sé, but running modifications on the UI thread. This will block the UI from trying to access the list.
if(adapter.getHolders().get(position).getLabelHolder() != null)
    return getResources().getInteger(R.integer.column);
else
    return 1;

so what is getResources().getInteger(R.integer.column)?
Isn't that going to be the same number every time?

A: Amazingly, I had the same issue and just found the solution. After initializing the GridLayoutManager with the spanCount passed in the constructor, our app would crash. BUT, if I setSpanCount() after constructing the object, IT WORKS! :O
We're using RecyclerView 23.0.1. hope this helps someone.

A: Too late to answer this question, however in a latest project that i worked on, i faced the same issue & after some really debugging, i found out what was the cause to the issue but no clue why would it cause it.
zxing Library intent it actually calls CLEAR_TOP before calling the startActivityForResult & that was the problem, after modifying the source code of zxing Intent to remove that particular line, the crash is gone.


text:
Q: Racket checkerboard program that takes the size (row x column) and size of squares as args and builds a red and black checkerboard with DrRacket Hi I'm struggling with this problem, I don't know how to add the number of square tiles and incorporate that as a user input value, I only know how to increase the size of the tiles. So I can make the squares bigger but I can't increase the number of them. The main issue is alternating the square colors red and black and having user input of the board size. If you can show me with circles or anything else how to take user input to add more I'd appreciate any help, this is due in three days and I've been working on it for a while.
Edit: In my class we haven't learned for-loops in racket so if there's an iterative/recursive way that would help me out.

Here's my code with multiple attempts:
#lang slideshow

(define (square n) (filled-rectangle n n))
(define (redblock n) (colorize(square) "red"))
(define (blackblock n) (colorize(square) "black"))

;slideshow
(define (series n)
  [hc-append (* square n)]) ; contract violation, expected: number?, given: #<procedure:square>

;slideshow
(define (rb-series mk)
  (vc-append
   (series [lambda (sz) (colorize (mk sz) "red")])
   (series [lambda (sz) (colorize (mk sz) "black")])))

(define (checker p1 p2) ;makes 2x2
  (let ([p12 (hc-append p1 p2)]
        [p21 (hc-append p2 p1)])
    (vc-append p12 p21)))

(define (four p) ;can we get the parameter of this as any number instead of the shape?
  (define two-p (hc-append p p))
  (vc-append two-p two-p))

(define (checkerboard n sz)
  (let* ([redblock (colorize(square sz)"red")]
         [blackblock (colorize(square sz)"black")])
    (define (blackred-list n)
      ;(define (string lst)) ;is there a way to construct an empty string to add to?
      (for ([i n])
        (if (even? i)
            (hc-append blackblock)
            (else
             (hc-append (redblock)))))) ; this else part throws an error saying no hc-append
     (define (redblack-list n)
      (for ([i n])
        (if (even? i)
            (hc-append redblock)
            (else (hc-append blackblock))))) ;another else with the same issue
     (define (row-list n)
       (for ([i n])
         (if (even? i)
             (vc-append blackred-list)
             (else
              (vc-append redblack-list)))))
    (checkerboard 5 20))) ;this is just to test it, but how would I get user input?```

A: Let's break it down step by step:

*

*Define function named checkerboard:

(define (checkerboard n sz) ...

*

*With local definitions of redblock and blackblock...

(let ([redblock (colorize (filled-rectangle sz sz) "red")]
      [blackblock (colorize (filled-rectangle sz sz) "black")])

*

*With function blackred-list (I used letrec for recursive local definitions)...

(letrec ([blackred-list
              (lambda (m) (cond ((zero? m) '())
                                ((even? m) (cons blackblock (blackred-list (sub1 m))))
                                (else (cons redblock (blackred-list (sub1 m))))))]

*

*With function redblack-list, which is very similar to blackred-list, so I am leaving that as work for you.

*With function row-list:

[row-list (lambda (m) (map (lambda (i) (apply hc-append (reverse
                                                       (if (even? i)
                                                           (blackred-list m)
                                                           (redblack-list m)))))
                                    (range m)))]

Then write (apply vc-append (row-list n)) inside letrec.
User input isn't mentioned in task, because you will just call (checkerboard 6 15) (or any other test) in REPL, but you surely can do this:
> (checkerboard (read) (read))

A: If one can confidently write and assemble small functions then the suggestions in
the exercise may be all one needs to produce a solution. But if this is a skill
that one is learning, then following a systematic design method may
help that learning process.
The design method here is HtDF (How to Design Functions): write down stub with signature and purpose, examples, and template, then edit the template to produce the required function.
(This answer uses characters to stand for blocks -- substitute eg hc-append for list->string for images)
(define redblock #\r)
(define blackblock #\b)
#;
(define (blackred-list m) ;; Natural -> ListOfBlock       ; *stub* ;; *signature*
  ;; produce list of m alternating blocks (last one red)  ; *purpose statement*
  empty)                                                  ; *stub body* (valid result)

(check-expect (blackred-list 0) empty )                   ; *minimal example*
#;
(define (fn n)                                            ; *template*
  (cond                                                   ;
    [(zero? n) ... ]                                      ;
    [else (.... n (fn (- n 1))) ]))                       ;

(check-expect (blackred-list 1) (list redblock) )         ; *examples* to guide .... edit
(check-expect (blackred-list 2) (list blackblock redblock) )

(define (blackred-list m) ;; Natural -> ListOfBlock       ; (edit template)
  ;; produce list of m alternating blocks (last one red)
  (cond
    [(zero? m) empty ]
    [else (cons
           (if (even? m)
               blackblock
               redblock)
           (blackred-list (- m 1))) ]))

(check-expect (blackred-list 3) (list redblock blackblock redblock) )

(define (redblack-list m) ;; Natural -> ListOfBlock
  ;; produce list of m alternating blocks (last one black)
  (cond
    [(zero? m) empty ]
    [else (cons
           (if (even? m)
               redblock
               blackblock)
           (redblack-list (- m 1))) ]))

(check-expect (redblack-list 3) (list blackblock redblock blackblock) )
#;
(define (row-list m) ;; Natural -> ListOfString           ; *stub*
  ;; produce list of m alternating strings of blocks (last one ends in red)
  empty)

(check-expect (row-list 0) empty)                         ; *examples* (same template)
(check-expect (row-list 1) (list "r") )
(check-expect (row-list 2) (list "rb" "br") )

(define (n-strings-of-length m n) ;; Natural Natural -> ListOfString
  ;; produce list of n alternating length m strings of blocks (last one ends in red)
  (cond
    [(zero? n) empty ]
    [else (cons
           (if (even? n)
               (list->string (redblack-list m))
               (list->string (blackred-list m)))
           (n-strings-of-length m (- n 1))) ]))

(define (row-list m) ;; Natural -> ListOfString
  ;; produce list of m alternating length m strings of blocks (last one ends in red)
  (n-strings-of-length m m))

(define (display-rows los) ;; ListOfString ->             ; (from natural list recursion template)
  ;; display los, one element per line
  (cond
    [(empty? los) (void) ]
    [else (begin
            (display (car los))
            (newline)
            (display-rows (cdr los))) ]))

(define (checkerboard m) ;; Natural ->
  ;; display checkerboard with side m
  (display-rows (row-list m)))

Welcome to DrRacket, version 8.4 [cs].
Language: Advanced Student.
All 8 tests passed!
>

The functions can now be reordered to produce the solution in specified local form:
(define redblock #\r)
(define blackblock #\b)

(define (checkerboard m) ;; Natural ->
  ;; display checkerboard with side m
  (local [
    (define (blackred-list m) ;; Natural -> ListOfBlock
      ;; produce list of m alternating blocks (last one red)
      (cond
        [(zero? m) empty ]
        [else (cons
               (if (even? m)
                   blackblock
                   redblock)
               (blackred-list (- m 1))) ]))
    (define (redblack-list m) ;; Natural -> ListOfBlock
      ;; produce list of m alternating blocks (last one black)
      (cond
        [(zero? m) empty ]
        [else (cons
               (if (even? m)
                   redblock
                   blackblock)
               (redblack-list (- m 1))) ]))
    (define (n-strings-of-length m n) ;; Natural Natural -> ListOfString
      ;; produce list of n alternating length m strings of blocks (last one ends in red)
      (cond
        [(zero? n) empty ]
        [else (cons
               (if (even? n)
                   (list->string (redblack-list m))
                   (list->string (blackred-list m)))
               (n-strings-of-length m (- n 1))) ]))
    (define (row-list m) ;; Natural -> ListOfString
      ;; produce list of m alternating length m strings of blocks (last one ends in red)
      (n-strings-of-length m m))
    (define (display-rows los) ;; ListOfString ->
      ;; display los, one element per line
      (cond
        [(empty? los) (void) ]
        [else (begin
                (display (car los))
                (newline)
                (display-rows (cdr los))) ]))  ])
  (display-rows (row-list m)))

Welcome to DrRacket, version 8.4 [cs].
Language: Advanced Student.
> (checkerboard 5)
rbrbr
brbrb
rbrbr
brbrb
rbrbr
>


text:
Q: dhtmlx grid smartrender not work normally after sorting with splitAt mode I use split mode and smartrender in dhtmlx grid. After I sort rows, rendered rows disappear and never come out on the right side, like the following picture.
after sorting, rows on right side could not be rendered anymore(click here to view the picture)
It's strange, rows on the left could be rendered when I scrolling on both sides.But rows on right side could not be rendered.
Anyone helps?
Thanks!
code structure:
var grid = new dhtmlXGridObject('#container');
grid.setImagePath("./bower_components/dhtmlxSuitePro/4.1.1/codebase/imgs/");
grid.enableTreeCellEdit(false);
grid.setHeader('...');
grid.attachHeader('...');
grid.setInitWidths('...');
grid.setColAlign('...');
grid.setColTypes('...');
grid.setColSorting('...');

grid.splitAt(2);
grid.enableSmartRendering(true);

grid.init();
grid.parse(data,'json'); // data is defined

A: Finally, after reading the docs again, I found grid.enableSmartRendering(true); should be after grid.init();
code following works:
var grid = new dhtmlXGridObject('#container');
grid.setImagePath("./bower_components/dhtmlxSuitePro/4.1.1/codebase/imgs/");
grid.enableTreeCellEdit(false);
grid.setHeader('...');
grid.attachHeader('...');
grid.setInitWidths('...');
grid.setColAlign('...');
grid.setColTypes('...');
grid.setColSorting('...');
grid.init();

grid.splitAt(2);
grid.enableSmartRendering(true);

grid.parse(data,'json'); // data is defined


text:
Q: c# Ternary operator I am working on a an application that has no documentation (although the code is quite clear and well-written) and I am trying to write some useful technical documentation for the next guy who comes along after I am in a mental hospital.
In the web-service method, if the call to the web-service returns an error, then the Catch code runs to increment the number of retries for the message and set the MessageStatus to "New" (so that it is retried if less than 5) or "Error" (for unknown errors), but there is one line I am not completely sure of and I need to document this process properly:
catch (Exception ex)
{
int NoRetries = (int)dRow[(int)Common.OutboundSQLFields.Message_Retries];
string messageStatus = (NoRetries < 5) ? Common.MessageStatus(ex) : "Expired";
    ...

Does this mean that if the NoRetries is greater than 4, then the MessageStatus will be set to Expired, else the method Common.MessageStatus will be called to reset the string MessageStatus based on the value of (ex) ?
So to make it more self-describing, could I rewrite that Ternary operator code as:
string MessageStatus="";
If (NoRetries > 4)
    {
    MessageStatus = "Expired";
    }
else
    {
    MessageStatus = Common.MessageStatus(ex);
    }

A: (Statement) ? TRUE : FALSE
So if NoRetries < 5 then Common.MessageStatus(ex)
if NoRetries >= 5 then "Expired"
Hope this clarifies it :)

A: As the statement is:
string messageStatus = (NoRetries < 5) ? Common.MessageStatus(ex) : "Expired";

It should be like:
string MessageStatus="";
if (NoRetries < 5)
    MessageStatus = Common.MessageStatus(ex);
else
    MessageStatus = "Expired";

You reversed it actually. But your's is correct too.


text:
Q: "loadHTMLString" height width issue with WKWebView I am trying to load HTML content to WKWebView, It does not load properly the same as screen height/width, same code is working fine with UIWebView, See the following code
webView.loadHTMLString(htmlString!, baseURL: nil)

HTML string content  667px is screen height and 375px is screen width.
<!DOCTYPE HTML>

        <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
            <title>Highcharts Example</title>

What can I do to solve this issue?

A: Add headerString before your html code and try it Like below
let description = "
 HTML content
"
var headerString = "<meta name='viewport' content='width=device-width,
initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0'>"
headerString.append(description)
self.webView.loadHTMLString("\(headerString)", baseURL: nil)


text:
Q: What is difference between DaemonStage and ElementProblemAnalyzer? I'm developing Resharper plugin and I don't realize between Deamon Stages and Element Problem Analyzers?
When I need use one or another? If they both provide code analysis.

A: An ElementProblemAnalyzer<T> will only be called for specific nodes in the abstract syntax tree, while a daemon stage gets to process the whole file. The nodes you're interested in are registered in the ElementProblemAnalyzerAttribute constructor, and the T parameter of the base class is the common node interface. If you're interested in just one node type, it's the interface for that node, if you're interested in several, it would be the most common base type, perhaps ITreeNode or ICSharpTreeNode.
[ElementProblemAnalyzer(typeof(ICSharpArgument),…)]
public class MyAnalyzer : ElementProblemAnalyzer<ICSharpArgument>
{
  // ...
}

You'd use an element problem analyser if you only need to check a particular node, without looking at the rest of the file. You can still navigate from the node you're at (for example, given a method call, you could have an analyser for the argument, in which you navigate from the argument node up to the method call node, and look to see if the argument is the same as the default value, meaning it's redundant code).
You would use a daemon stage if you need more context within the file, for example, a list of all of the methods in a class, or more control of how the abstract syntax tree is walked - you can skip child nodes of a method declaration if you're not interested in the statements or expressions within.
If it helps, element problem analysers are actually implemented as daemon stages. They're only supported by C#, VB, JS and XML. Each language has a daemon stage that walks the AST for error checking, and as it does so, calls Run for each analyser that's interested in each node type of the tree.


text:
Q: Why is it OK to model demographics as random effects in bayesian multilevel models? In Bayesian multilevel models (with, say, people nested within congressional districts) I sometimes see individual level demographic variables like race modeled as random effects.
So here's a slightly simplifed example from this paper:
$$
Pr(y_i=1)=\text{logit}^{-1}(\gamma_0 + \alpha^{race}_{r[i]} +\alpha^{gender}_{g[i]}+\alpha^{edu}_{e[i]}+\alpha^{district}_{d[i]}...)$$
$$\alpha^{race}_{r[i]} \sim N(0,\sigma^2_{race}), for~r = 1,....4 $$
$$\alpha^{gender}_{g[i]} \sim N(0,\sigma^2_{gender}) $$
$$\alpha^{edu}_{e[i]} \sim N(0,\sigma^2_{edu}), for ~e=1,...,5
$$
As I understand it this model is treating all the individual level demographic variables as "random effects" just like district. So for race it is assuming that the 4 racial categories that exist in the data (black, white, hispanic, other) are actually just 4 random draws from a larger population of all possible races. To me this seems strange and wrong, since the racial categories we have in the data are meant to be exhaustive and there doesn't seem to be any reason to think that racial differences will be normally distributed.
So my question is: Is my interpretation of this model correct, and if so why is it justified?
I know that someone actually asked this question before but the answer they were given was that it is probably NOT appropriate to treat race etc as random effects. But that's precisely what is done in  many papers on Bayesian multilevel models.

A: "Fixed" and "random" effects is terminology from frequentist models. In fact, it is not the best and not consistently used terminology. In frequentist statistics you are trying to find point estimates for the parameters, with the exception of random variables, where you want to learn about the distribution of those effects. In Bayesian statistics every parameter is treated as random variable and we want to learn about it's distribution, so there's no such distinction.

A: Categories of social position and social identity—including common demographic variables—are important demarcations of population. In the population sciences, there is a good deal of emphasis on differentiating the mean or median (central) experiences of populations, however, the variability of experiences distributed within populations is also substantively important.
Take systolic blood pressure (SBP) as an example: it is approximately normally distributed, and one could imagine two populations with nearly the same, or even identical mean SBP. Does this mean that the health of the two populations with respect to blood pressure is the same? No! If one population is considerably more variable, then its SBP-related health is actually quite a bit worse. First, knowing nothing else but which population an individual is from, we are less certain of their SBP. Second, if there are extremes of SBP (values of it at which risk for bad things happening rises sharply; SBP>130 sharp increase in stroke risk, SBP <90 sharp increase in waking up dead from hypotension) then the population with greater variability has more, possibly far more people "falling through the cracks" at the extremes. The cyan shaded region in the below graph (a cartoon I made, not actual data) is how much more likely people in the blue population are to be at high risk due to hypertension or hypotension than people in the red population. The more variable population is more vulnerable.

Back to your question, the current US (and global!) social moment of unrest against centuries of institutionalized anti-black racism and against half a millennium of colonization of American Indians, Hawaiians and Pacific Islanders, and Alaska Natives points out that the vulnerability—the increased uncertainty in outcomes, and the increased numbers in the extremes—of the populations defined by racial demographic groups (among others) is a good reason to look to methods, such as using mixed models/random effects models/hierarchical linear models/multilevel models/etc. (as @Tim rightly points out the language is a smidge muddled) to provide estimates of population variability.
NB: I do not see this as an issue of Bayesian vs Frequentist, but as a question of substantive modeling of the world around us.

A: I'd recommend looking at this answer from @Paul for guidance on so-called "random effects" and hierarchical models. In particular, this quote is on point:

Random effects are estimated with partial pooling, while fixed effects are not.
Partial pooling means that, if you have few data points in a group,
the group's effect estimate will be based partially on the more
abundant data from other groups. This can be a nice compromise between
estimating an effect by completely pooling all groups, which masks
group-level variation, and estimating an effect for all groups
completely separately, which could give poor estimates for low-sample
groups.

The answer goes on with an example, and discussion of the relationship of this approach to hierarchical Bayesian modeling.
Such pooling is exactly what the authors of the paper you cite were setting out to do with their multi-level approach:*

... a multilevel model pools group-level parameters towards their mean, with greater pooling when group-level variance is small and more smoothing for less populated groups. The degree of pooling emerges from the data endogenously ...

So although it's often argued that categories with few levels (sex, race) should be treated as fixed effects in regressions, they need to be treated as random effects to accomplish this partial pooling.

*The authors used GLMER in R for this, so I suppose this particular example isn't strictly a Bayesian approach.

A: One interpretation would be that it would not be helpful to call the $\alpha^{race}$ 'random effects'.
Practically, it looks like the race effects $\alpha^{race}\sim N(0,\sigma^2_{race})$ (for instance) have a hierarchical PRIOR, that is, conditioned on the race effect variance we have a normal prior.  In turn, $\sigma^2_{race}$ should have a prior, effectively making the $\alpha^{race}$ have a prior that is a mixture distribution.  As mentioned, it isn't really helpful to think of this as a random effect, hyper parameter $\sigma^2_{race}$ does not really have a useful definition (since, as you said, the races were not sampled from a population of races).  Possibly you could make a post hoc interpretation of $\sigma^2_{race}$ as a guide to how different the race effects are, but for that purpose you could instead make direct comparisons between the $\alpha^{race}$ values.
The $\sigma^2_{race}$ is just part of the definition of the prior of $\alpha^{race}$.  It might have been just as good to place a huge constant value on $\sigma^2_{race}$ and thus leave the $\alpha^{race}$ with a vague prior.


text:
Q: Quiero poner mapa de Google Maps en Android y obtengo el error: "could not find dependency com.google.android" He leído y he visto algunos vídeos sobre como hacerlo pero el problema aparece cuando empiezo a meter código, me salen muchos errores.
Ya he instalado el Google Play Services y el Google USB Driver pero al intentar solucionar los errores e instalar lo que me pide me salta este error:

"could not find dependency com.google.android".

Alguien puede ayudarme?
Muchas gracias.

He borrado la clase, xml y todo lo que tenía que ver con Google Maps y ahora tampoco me funciona el proyecto que anteriormente si me funcionaba.
También me da este error al intentar compilarlo.
Error:Could not resolve all files for configuration ':app:debugCompileClasspath'.

Could not find com.google.android.gms:play-services-maps:11.6.2.
    Searched in the following locations:
        file:/C:/Users/adminportatil/AppData/Local/Android/sdk/extras/m2repository/com/google/android/gms/play-services-maps/11.6.2/play-services-maps-11.6.2.pom
        file:/C:/Users/adminportatil/AppData/Local/Android/sdk/extras/m2repository/com/google/android/gms/play-services-maps/11.6.2/play-services-maps-11.6.2.jar
        file:/C:/Users/adminportatil/AppData/Local/Android/sdk/extras/google/m2repository/com/google/android/gms/play-services-maps/11.6.2/play-services-maps-11.6.2.pom
        file:/C:/Users/adminportatil/AppData/Local/Android/sdk/extras/google/m2repository/com/google/android/gms/play-services-maps/11.6.2/play-services-maps-11.6.2.jar
        file:/C:/Users/adminportatil/AppData/Local/Android/sdk/extras/android/m2repository/com/google/android/gms/play-services-maps/11.6.2/play-services-maps-11.6.2.pom
        file:/C:/Users/adminportatil/AppData/Local/Android/sdk/extras/android/m2repository/com/google/android/gms/play-services-maps/11.6.2/play-services-maps-11.6.2.jar
        file:/C:/Program Files/Android/Android Studio/gradle/m2repository/com/google/android/gms/play-services-maps/11.6.2/play-services-maps-11.6.2.pom
        file:/C:/Program Files/Android/Android Studio/gradle/m2repository/com/google/android/gms/play-services-maps/11.6.2/play-services-maps-11.6.2.jar
        https://jcenter.bintray.com/com/google/android/gms/play-services-maps/11.6.2/play-services-maps-11.6.2.pom
https://jcenter.bintray.com/com/google/android/gms/play-services-maps/11.6.2/play-services-maps-11.6.2.jar
    Required by:
        project :app

A: En realidad el problema es configuación de Android Studio, en este caso necesitas actualizar el Android Support Repository desde el SDK Manager.

Al actualizar probablemente necesites actualizar otros componentes, pero en la terminal te agregara el enlace para realizar las actualizaciones pendientes.


text:
Q: Does not load component until a variable has also been set in useEffect I have a Problem: When the user arrives at the /chat path, it should first be checked whether he has fulfilled all the criteria. If not, he will be redirected. If he does, then all his data should be saved from the backend to the localStorage.
The problem is that the ChatComponent is loaded before the localStorage is set. I have a localStorage .getItem(...) in the ChatComponent which is null, but as soon as I reload the page the expected value is in it.
Is there a way to load the ChatComponent only when the localStorage is set, so that I don't have a null value in the ChatComponent and don't have to reload the page?
import React, { useEffect, useState } from "react";
import { useHistory } from "react-router-dom";
import { Ellipsis } from 'react-spinners-css';
import axios from "axios";
import Chatcomponent from "../components/chat/Chatcomponent";

function Chat() {

  const history = useHistory();
  const [isloading, setIsloading ] = useState(true);

  useEffect(() => {
    filledInterests()
  }, []);

  const filledInterests = () => {
    document.body.style.cursor = "wait";
    axios
       .post("https://localhost:4000/profile/get", {})
      .then((response) => {
        if (response.data.givenname === "FILLER") {
          callFirststeps();
          setIsloading(false);
        }
        else {

          if( localStorage.getItem('getName') === null ) {
            loadUserData();
            setIsloading(false);
          }

        }
      })
      .catch((error) => {
        console.log(error);
        //console.log(error.response.status);
      });
      document.body.style.cursor = "default";
  };

  const loadUserData = () => {
    fillName();
    fillIntersts();

    // Only after the variable has been set here,
    // the chat component may be loaded, so that the variables are also set.
    // What I tried:
    // window.location.reload();
  }

  const fillName = () => {
    axios
        .post("http://localhost:4000/profile/get",
        {
          "field1": "id",
          "field2": "givenname",

        }
        )
        .then((res) => {
            if (res.status === 200) {
              localStorage.setItem('userName', res.data.givenname);
              localStorage.setItem('userEmail', res.data.email);
            }
        })
        .catch((error) => {
            console.log(error);
        });
  }

  // eslint-disable-next-line
  const callFirststeps = () => {
    history.push({
      pathname: "/first-steps",
      state: {

      },
    });
  };

  return (
    <body>
        {
            isloading === true &&
                <Ellipsis color="#5869FF" style={{left:"50", right:"50", top:"50", bottom:"50",}}/>
        }
        {
            isloading === false &&
            <Chatcomponent></Chatcomponent>
        }
    </body>
  );
}

export default Chat;

A: Nope, there is no other way to do that, you are handling that as needed. You can changed the implementation details but in the end it will be the same check and if statement for rendering logic.


text:
Q: After upgrade, get blank purple screen. No gdm and can't switch to tty I upgraded to 11.04 using update-manager -d. When I try to boot, I just get a purple blank screen, with no ubuntu logo/dots showing. It never gets to the gdm login screen (I left it for 20min) and I can't get to a tty by pressing Ctrl+Alt+F1. I don't see a grub menu/count down screen either.
My computer is a Dell Vostro 1500 with a Nvidia Geforce. I had the proprietary nvidia driver installed before upgrading.
I've boot with a live cd, from where I am writing this, and I can mount the disk, but I don't know where to start looking for the issue.

A: What I did from the command line is to find the packages for nvidia (dpkg -l | grep nvidia) and then apt-get remove nvidia-173 (or whatever package you get from the previous command).
The problem is that you will still have the nvidia modues listed in xorg.conf. So, I also mv /etc/X11/xorg.conf /etc/X11/xorg.conf_backup and rebooted.
I landed in a graphical mode as usual, without the nvidia GL stuff, but then there are graphical tools to set it up.
At this state, it's safe to delete the xorg.conf backup you just created.

A: I tried booting again, and was able to get into the grub menu. Not sure why I could not get to the menu before. Maybe I just was not pressing the down arrow soon enough. (The grub menu is now also purple.)
I can boot with an old kernel 2.6.35-28-generic, but not with the new kernel 2.6.38.7. This corresponds  with the note about nvidia drivers it the release notes.

A: I had this issue too and I've solved it installing the appropriate version of nvidia drivers (for me 173.xx)
Simply log in with a ubuntu classic (no effects) session, go to administration -> proprietary driver and you'll find you have a recommended version of nvidia drivers installed and another one. Just activate the other one and reboot.

A: You can try the Noveau drivers for NVIDIA or try this:
sudo gedit /etc/default/grub
Look for the quiet nosplash section and add this next to it: nohz=off
Then:
sudo update-grub
I had a similar problem with an ATI/AMD card and didn't want to use the pci=noacpi since it disables key features.


text:
Q: git branch switching and submodules I have 2 branch, master & secondary and they're kept in sync periodically by merging master => secondary.
At one point, master had a several submodules that were deleted and the same submodules were re-added.
I'm now trying to merge master into secondary but whenever I try to switch from master to secondary, I get these error messages on the submodules that were overwritten:
warning: unable to rmdir libs/AFNetworking: Directory not empty
warning: unable to rmdir libs/MBProgressHUD: Directory not empty
Branch secondary set up to track remote branch secondary from origin.
Switched to a new branch 'secondary'

'master' branch starts like this:
git clone repourl:master.git
cd project_directory
git submodule update --init <= in master at the moment
git checkout secondary


text:
Q: Cloud Function for Firebase Type Error - Cannot Read Property I'm trying to write a Cloud Function that creates a record whenever someone uses our legacy app to create a record (we have changed the Firebase backend architecture and want to slowly migrate users). However, I'm getting the following error in my logs:
TypeError: Cannot read property 'update' of undefined
    at exports.makeNewComment.functions.database.ref.onWrite.event (/user_code/index.js:14:92)
    at /user_code/node_modules/firebase-functions/lib/cloud-functions.js:35:20
    at process._tickDomainCallback (internal/process/next_tick.js:129:7)

Here is the script in question:
//required modules
var functions = require('firebase-functions');
const admin = require('firebase-admin');

// Listens for new comments added to /comments/ and adds it to /post-comments/

exports.makeNewComment = functions.database.ref('comments/{commentId}').onWrite(event => {
  // Grab the current value of what was written to the Realtime Database.
  const commentId = event.params.commentId;
  const comment = event.data.val();
  // You must return a Promise when performing asynchronous tasks inside a Functions such as
  // writing to the Firebase Realtime Database.
  //return event.data.ref.parent.child('post-comments').set(comment);
  return functions.database.ref('post-comments/' + comment['postID'] + '/' + commentId).update(comment).then(url => {
    return functions.database.ref('user-comments/' + comment['postedBy'] + '/' + commentId).update(comment);
  });
});

//initialize
admin.initializeApp(functions.config().firebase);

Thanks!

A: You can't use functions.database.ref() in the middle of a function to get a ref to somewhere in your database.  That's only for defining a new Cloud Function.
If you want a ref to somewhere in your database, you can use event.data.ref or event.data.adminRef to get a ref to the location where the event triggered.  You could then use the root property of that to rebuild a new ref to somewhere else in the database.  Or you can use your admin object to build a new ref.
It might be helpful to look at some sample code to get a sense of how things work.

A: Based on Doug's answer, you can replace functions.database.ref with event.data.ref.root.
var functions = require('firebase-functions');
const admin = require('firebase-admin');

exports.makeNewComment = functions.database.ref('comments/{commentId}').onWrite(event => {

  const commentId = event.params.commentId;
  const comment = event.data.val();

  return event.data.ref.root.child('post-comments/' + comment['postID'] + '/' + commentId).update(comment).then(url => {
    return event.data.ref.root.child('user-comments/' + comment['postedBy'] + '/' + commentId).update(comment);
  });
});

admin.initializeApp(functions.config().firebase);


text:
Q: VB.net Sort File Listed Gridview I am trying to sort a gridview that list a directory's files.
I have tried to sort in various different ways from resources like so:
http://forums.asp.net/t/963636.aspx?Default+sort+order+in+GridView
sorting and paging with gridview asp.net
http://forums.asp.net/t/1076872.aspx?Gridview+how+to+find+a+column+by+it+s+column+name+rather+than+it+s+Cell+index+
http://forums.asp.net/t/963636.aspx?Default+sort+order+in+GridView
However, every time I reload the page the files are not ordered in Ascending order.
I would like to be able to order by the file's "Value" [Column: File Name] since that would give me the results that I want but nothing is working.
I have also tried VB.NET Sort files in directory by alphanumeric like so:
For Each filePath As String In filePaths.OrderBy(files)

 files.Add(New ListItem(Path.GetFileName(filePath), filePath))
 'files.Add(New ListItem(Path.GetFileName(filePath)

Next

but get erros from the line filePaths.OrderBy(files)
 since the information inside the parenthesis is wrong.
Any suggestions?
FYI: path for Directory.GetFiles is fake for security purposes
Dim filePaths() As String = Directory.GetFiles("\\...\...\uploads\attachments\")

Dim files As List(Of ListItem) = New List(Of ListItem)

  For Each filePath As String In filePaths

    files.Add(New ListItem(Path.GetFileName(filePath), filePath))

  Next

   DisplaySup.DataSource = files
   DisplaySup.DataBind()
   DisplaySup.Sort("File Name", System.Web.UI.WebControls.SortDirection.Ascending)

   'If [String].IsNullOrEmpty(DisplaySup.SortExpression) Then
      'DisplaySup.Sort("SortExpression", SortDirection.Ascending)
      'DisplaySup.DataBind()
   'End If

HTML
<asp:GridView ID="DisplaySup" runat="server" align="center" AutoGenerateColumns="False" BorderColor="Black" BorderStyle="Solid" Font-Size="Small">
<Columns>

<asp:TemplateField HeaderText = "Delete File" SortExpression="Value">
   <ItemTemplate>
      <asp:button ID = "btnDelete" cssClass = "submit-btn small" Text = "Delete" CommandArgument = '<%# Eval("Value") %>' runat = "server" OnClick = "DeleteFile" />
   </ItemTemplate>
</asp:TemplateField>

 <asp:TemplateField HeaderText = "File Name" SortExpression="Value">
   <ItemTemplate >
           <asp:LinkButton ID="lnkDownload" Text = '<%# Eval("Value").ToString().Substring(39) %>' CommandArgument = '<%# Eval("Value") %>' runat="server" OnClick = "DownloadFile"></asp:LinkButton>
      </ItemTemplate>
 </asp:TemplateField>
 </Columns>

 <HeaderStyle BackColor="#BDBDAE" Font-Underline="False"
  CssClass="linkNoUnderline" HorizontalAlign="Left" />
</asp:GridView>

UPDATE: I also tried the following example GridView Sorting Question and once again the gridview doesn't sort

A: Found a way to fix my issue.
I referenced: Sorting Directory.GetFiles()
and did the following to pre-sort the directory and then list the files in my gridview:
Dim filePaths() As String = Directory.GetFiles("\\...\uploads\attachments\")

'Sort the directory
Dim FilesStr() As String
FilesStr = filePaths
Array.Sort(FilesStr)

'Get each file
Dim files As List(Of ListItem) = New List(Of ListItem)

For Each filePath As String In filePaths

  files.Add(New ListItem(Path.GetFileName(filePath), filePath))
Next

DisplaySup.DataSource = files
DisplaySup.DataBind()


text:
Q: When is $scope.$apply necessary for dealing with objects/arrays with Angular? I'm working with the Soundcloud JS SDK to bring my Soundcloud favorites into a simple Angular app.
I wasn't able to get the user favorites to import in correctly until I used $scope.$apply.
function TopListCtrl($scope, $http, $modal) {
  $scope.getData = function(sc_user) {
     SC.get('/users/'+ sc_user +'/favorites', {limit: 200}, function(tracks){
     $scope.$apply(function() {
  if (Object.getOwnPropertyNames(tracks).length > 1) {
      $scope.likes = tracks;
      $scope.sortField = 'like.favoritings_count';
      $scope.reverse = true;
      $scope.sc_user = sc_user;
     }
  else {
      alert("That user has 0 Soundcloud likes. So sad...")
     }
  }).error(function (data, status, headers, config) {
             alert("Something went awry with that request. Double check that's a real Soundcloud username");

        })
        });
  }

If you don't use $scope.apply, it doesn't work (and says SC.get not defined).
I'd like to understand a bit better why $scope.$apply is necessary.  I ask this because when I was just using the http api, I didn't need it.
function TopListCtrl($scope, $http, $modal) {
  $scope.getData = function(sc_user) {
     var url = 'http://api.soundcloud.com/users/'+ sc_user +'/favorites.json?client_id=0553ef1b721e4783feda4f4fe6611d04&limit=200&linked_partitioning=1&callback=JSON_CALLBACK';
    $http.jsonp(url).success(function(data) {
     if (Object.keys(data.collection).length > 0) {
      $scope.likes = data;
      $scope.sortField = 'like.favoritings_count';
      $scope.reverse = true;
      $scope.sc_user = sc_user;
     }
    else {
      alert("That user has 0 Soundcloud likes. So sad...")
     }
  }).error(function (data, status, headers, config) {
             alert("Something went awry with that request. Double check that's a real Soundcloud username");
        });
  }

A: Usually angular knows about the code that's executing because you're the one providing the function callbacks but it's angular that's actually calling them. After angular calls a function, it will call $apply sometime later to trigger a $digest cycle.
If you don't know what a $digest cycle is, the concept is simple. During the $digest phase, angular will do a dirty check on every scope variable that's been set up with a $watch handler and check if it's changed; if it has angular will call its the corresponding $watch handler to update the view.
Getting back to the original question - when angular knows about your code, it will trigger a $digest cycle for you - so there is no need to call $apply explicitly. If you handle a jquery event, that's a different story. Angular has no idea that a $digest might be needed - how can it? So $apply is needed to trigger the $digest manually.

A: I know that you've already received the correct response to your question.  I thought I'd also mention that it's not terribly difficult to use $http to make requests to the Soundcloud API, so that you won't need to use $scope.$apply.  Here are mine:
  var request = function(method, path, params, callback) {
    params.client_id = sc.soundcloud.client_id;
    params.oauth_token = sc.soundcloud.access_token;

    $http({
      method: method,
      url: sc.soundcloud.api.host + path,
      params: params
    })
    .success(callback);
  };

    get: function(path, params, callback) {
      request('GET', path, params, callback);
    },

    put: function(path, params, callback) {
      request('PUT', path, params, callback);
    },

    post: function(path, params, callback) {
      request('POST', path, params, callback);
    },

    delete: function(path, params, callback) {
      request('DELETE', path, params, callback);
    }

A: Pixelbits' answer and an article by Jim Hoskins on $scope.$apply helped me understand this a little better.  Here's the crucial point per my original question:

So, when do you need to call $apply()? Very rarely, actually.
  AngularJS actually calls almost all of your code within an $apply
  call. Events like ng-click, controller initialization, $http callbacks
  are all wrapped in $scope.$apply(). So you don't need to call it
  yourself, in fact you can't. Calling $apply inside $apply will throw
  an error.
You do need to use it if you are going to run code in a new turn. And
  only if that turn isn't being created from a method in the AngularJS
  library. Inside that new turn, you should wrap your code in
  $scope.$apply()
  (emphasis mine)

I'm still hazy on turns but I get the crucial point is that the method (SC.get in my case) isn't part of the AngularJS library so I, therefore, need to use $apply.
(At least I think I get it)


text:
Q: Как получить завтрашнюю дату python Как получить завтрашнюю дату в формате dd.mm ?
from datetime import datetime, timedelta

tomorrow_date = datetime.now() + timedelta(days=1).strftime("%d.%m")

Пробовал так, но ловлю ошибку:
AttributeError: 'datetime.timedelta' object has no attribute 'strftime'

Как исправить?

A: import datetime

today = datetime.date.today()
tomorrow = today + datetime.timedelta(days=1)

print(tomorrow.strftime('%d.%m'))

A: Ответ не совсем по теме, но лично я использую для работы со временем не встроенный datetime, а сторонний pendulum, где все более понятно (я бы сказал, на интуитивном уровне).
import pendulum

tomorrow = pendulum.tomorrow('Europe/Moscow').format('DD.MM')

Поэтому, если нет каких-либо ограничений, можно смело использовать и эту библиотеку


text:
Q: ASP MVC Enforcing Certain Criteria Before Pages are Available I'd like some ideas or advice on the best way to tackle this particular problem and I'm wondering if there is an established pattern for dealing with this problem.
I have an MVC application in the process of being built that requires the users to perform certain tasks before some pages are available for navigating too.  There are a few ways I can do this from a presentation perspective such as having menu items disabled etc and only enabled once the criteria are met.
The issue is that I have two separate databases, one with all the security data and one for all the application data.  I could simply have an additional table with a set of booleans to show when a particular step has been completed and then retrieve that on login and act accordingly.
Any idea on this would be really appreciated.

A: One way is to create roles that are area/pages specific.  After a user has completed whatever it is they need to complete, then add them to the role.
This allows you to use the AuthorizeAttribute.
[Authorize(roles = "CompletedSurvey")]
public class MyClassController ...

or
[Authorize(roles = "CompletedSurvey")]
public ActionResult SomeAction()...


text:
Q: net core odata put and patch nested data structures I have been using odata in a .net core 2.x web api, and so fare it has worked great, but now I am starting to implement the PUT/PATCH endpoints and I start running into issues with nested structures. In a simple order/item setup as illustrated below I need to manually handle the removal and addition of items to an order if they have changed. I cannot get odata to track nested changes as well.
public class Item
{
    [Key]
    public int Id { get; set; }
    public int OrderId { get; set; }
    public Order Order { get; set; }
}

public class Order
{
    [Key]
    public int Id { get; set; }
    public virtual ICollection<Item> Items { get; set; }
}

And my service that updates the order:
public void Update(Order order)
{
    using (var trans = DbContext.Database.BeginTransaction())
    {
        try
        {
            var existingItems = DbContext.Items.Where(t => t.OrderId == order.Id);
            var deleteItems = existingItems.Where(t => order.Items.Count() == 0 || !order.Items.Any(c => c.OrderId == t.OrderId));
            var addItems = order.Items.Where(t => !existingItems.Any(c => c.OrderId == t.OrderId));
            addItems.ToList().ForEach(a => a.OrderId = order.Id);

            DbContext.RemoveRange(deleteItems);
            DbContext.AddRange(addItems);

            DbContext.SaveChanges();

            DbContext.Entry(order).State = EntityState.Modified;
            DbContext.SaveChanges();

            trans.Commit();
        }
        catch (Exception ex)
        {
            trans.Rollback();
            throw ex;
        }
    }
}

Compared to how everything else in Odata works this is a lot of work, and only gets much more complex with deeper nested objects.
Am I doing something wrong, I cannot find much resources on this issue?

A: It seems like this is currently not supported. I´ve spent some time on investigating this but the only helpful resource is this: http://odata.github.io/WebApi/#03-02-built-in-routing-conventions
That means to me, that we need to write multiple patch-operations in the prinicipal controller for related entities. There are many github-issues on that - but I don´t find any helpful information there.
I´ve asked a question regarding this issue here and one of the contributors confirmed that..