text:
Q: How To Scrape Shopee User Review With BS4 I'm learn python 3 and try to scrape user reviews at shopee product page, but find some error
from bs4 import BeautifulSoup as bs
import requests
import time

link = input()

page = requests.get(link)

soup = bs(page.content, 'html.parser')

name = soup.find_all('a', class_='shopee-product-rating__author-name')

print(name)

but no result
[]

Process finished with exit code 0

How to show some reviewers name?
Thanks for your help, sorry for my english :)

A: The page uses JavaScript to load ratings. But you can use requests module to simulate it.
For example:
import re
import json
import requests

url = 'https://shopee.co.id/Premium-Brill-Eighty-eight-Flannel-Shirt-077-i.32031549.1991571675'

r = re.search(r'i\.(\d+)\.(\d+)', url)
shop_id, item_id = r[1], r[2]
ratings_url = 'https://shopee.co.id/api/v2/item/get_ratings?filter=0&flag=1&itemid={item_id}&limit=20&offset={offset}&shopid={shop_id}&type=0'

offset = 0
while True:

    data = requests.get(ratings_url.format(shop_id=shop_id, item_id=item_id, offset=offset)).json()

    # uncomment this to print all data:
    # print(json.dumps(data, indent=4))

    i = 1
    for i, rating in enumerate(data['data']['ratings'], 1):
        print(rating['author_username'])
        print(rating['comment'])
        print('-' * 80)

    if i % 20:
        break

    offset += 20

Prints:
sherly_riestyana
Barang datang sesuai pesanan...
Terima kasih ya..........
--------------------------------------------------------------------------------
s*****y

--------------------------------------------------------------------------------
deviltfnt
Barang cepat sampai, bahannya bagus catoon. Itu difoto pake flash sama yang engga kelihatan lebih terang. Real pict sih menurut gue. Kaget liat harga aslinya dan gue dapet murah bngt. Wahhh kalo bisa sampe bintang 10 gue kasih deh!!
--------------------------------------------------------------------------------
machito83
Bahan bagus....tpi kok warna agak beda say, sama gambarnya....,kamera nya terlalu keterangan mungkin yak
--------------------------------------------------------------------------------
4andis
Kualitas Premium, Terimakasih Sudah amanah... Harga tidak membohongi kualitas
--------------------------------------------------------------------------------
nila130893
Saya sukaaaaaaaa sekaleeeeeeee
Trimakasi sis semoga barang nya laris manis yah
--------------------------------------------------------------------------------

...and so on.

A: import requests

params = {
    "filter": "0",
    "flag": "1",
    "itemid": "1991571675",
    "limit": "59",
    "offset": "0",
    "shopid": "32031549",
    "type": "0"
}

def main(url):
    r = requests.get(url, params=params).json()
    for item in r['data']['ratings']:
        print(item['author_username'])

main("https://shopee.co.id/api/v2/item/get_ratings")

Output:
s*****y
deviltfnt
machito83
4andis
nila130893
herryhaz
muhaeminahmad
egarifarr
ris0802
gilangpangestu97
daffarb
andri270702
muhammadrestus
86499hb8xa
nanangazari
agusgunawan530
okhai
agganggitarahmawati
prillyoctavia
agustinadamayanti26
budianugrh
guse8693
rizkyawali
abeng_palu
defrized
maul0712
akaieria
didikprayugo1616
d*****9
susi557
muntafiah.
faizaharinii
lisnawww
abdulrozak57910
0*****.
asmaul435
d*****i
gerryalaneee
r*****n
miftahud08
aristna354
ummy_naqia
hildasaf
asfiatulistianah
dhinginanjar
abdul825
irfan_yusup123
evahelen
riskanurhidayani
rikkifirnanda01
riyan.shop
aldinugraha107
cicimulyani19
harisprabowo100
reza.bge
mhzulhamdi
asepnurjaman96
riskaarami
dheaamandapute

With comments:
import requests
from prettytable import PrettyTable

params = {
    "filter": "0",
    "flag": "1",
    "itemid": "1991571675",
    "limit": "59",
    "offset": "0",
    "shopid": "32031549",
    "type": "0"
}

def main(url):
    r = requests.get(url, params=params).json()
    x = PrettyTable()
    x.field_names = ["UserName", "Comment"]
    for item in r['data']['ratings']:
        x.add_row([item['author_username'], item['comment']])
    print(x)

main("https://shopee.co.id/api/v2/item/get_ratings")

Output:
+---------------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
|       UserName      |                                                                                Comment                                                                                |
+---------------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
|   sherly_riestyana  |                                                                                Barang datang sesuai pesanan...                                                                                |
|                     |                                                                                Terima kasih ya..........                                                                                |
|       s*****y       |                                                                                |
|      deviltfnt      | Barang cepat sampai, bahannya bagus catoon. Itu difoto pake flash sama yang engga kelihatan lebih terang. Real pict sih menurut gue. Kaget liat harga aslinya dan gue dapet murah bngt. Wahhh kalo bisa sampe bintang 10 gue kasih deh!!   |
|      machito83      |                                                                     Bahan bagus....tpi kok warna agak beda say, sama gambarnya....,kamera nya terlalu keterangan mungkin yak                                                                      |
|        4andis       |                                                                                Kualitas Premium, Terimakasih Sudah amanah... Harga tidak membohongi kualitas                                                                                |
|      nila130893     |                                                                                Saya sukaaaaaaaa sekaleeeeeeee                                                                                |
|                     |                                                                                Trimakasi sis semoga barang nya laris manis yah                                                                                |
|       herryhaz      |                                                                        Kualitas sangat baik, produk original, harga mantul,  pengiriman mantul,  recommended seller banget                                                                        |
|                     |                                                                                Langganan gan                                                                                |
|    muhaeminahmad    |                                                                                Barang sudah nyampe,,, kualitas ok. Bahan nya jg adem. Pokok nya ok.                                                                                |
|      egarifarr      |                                              Joss gandoss pengirimann cepat pengemasan cepatt responn jugaa baik meskipun order nya cod, kemejanya jugaa okee sesuaii gambarr mantulll pokok ee                                             |
|       ris0802       |                                                                                Puas deh pokoknya pelayanan ditoko ini                                                                                |
|   gilangpangestu97  |                                                                        Maaf saya kasih bintang 3, karena ada kesalahan pengiriman saya pesen  ukuran m yg dikirim malah xl                                                                        |
|       daffarb       |                                                                                Mantap lur,next order disini lagi lah                                                                                |
|     andri270702     |                                                                                Jahitan kurang rapi bahannya kasar banget                                                                                |
|    muhammadrestus   |                                                                                |
|      86499hb8xa     |                                                                                Memuaskan sekali....                                                                                |
|     nanangazari     |                                                                              Ikutaan xlnya ngpas banget Ama badan saya ukuraan xlnya bisa dilebihin besar lagi maksih                                                                             |
|    agusgunawan530   |                                                                                Alhamdulillah barang sudah sampe sesuai sama yang di gambar top markotop                                                                                |
|        okhai        |                                                                                Puas                                                                                |
| agganggitarahmawati |                                                                                Paket sampai dengan cepat, bahan bagus, terbungkus rapi, nice , pertahankan                                                                                |
|    prillyoctavia    |                                                                                TOP! Bahan, motif, dan warna bagusss                                                                                |
| agustinadamayanti26 |                                                                                |
|      budianugrh     |                                                                                bahan bagus tebel lembut juga bahan nya tenks                                                                                |
|       guse8693      |                                                                 Sudah 2 kali saya belanja di toko ini selalu puas,respon cepat barang yg dikirim sesuai,sukses terus buat toko ini                                                                |
|      rizkyawali     |                                                                                Cepet bray sehari sampai                                                                                |
|      abeng_palu     |                                                                    Sesuai lah meski,cuma pengiriman dari jnt nya lambat sangat.kalo untuk produknya di jamin gak bakalan nyesel                                                                   |
|       defrized      |                                                                                |
|       maul0712      |                                                                                Mantappp deh                                                                                |
|       akaieria      |                                                                        Udh yg kesekian kali beli disini, selalu puas, barang oke, pengiriman oke bgt. Langganan pokoknya                                                                         |
|   didikprayugo1616  |                                                                                mantaaapp.. sesuai gambar.. terimakasih                                                                                |
|       d*****9       |                                                                                Kualitas produk sangat baik bahannya lainnya adem halus juga                                                                                |
|       susi557       |                                                                                Selalu langganan. Karena barang bagus                                                                                |
|      muntafiah.     |                                                                                Bahan bagus tapi mungkin warna nya aja kurang terang                                                                                |
|     faizaharinii    |                                                                                Ajsgsbsywbshshsbdhusjssbsjsjjsjssjwjwjwjwjsjsjwjsjsj                                                                                |
|       lisnawww      |                                                                                Bbbbbbbbbgss bbbbbbggggsssssss bbbbbbggggssssssssssss                                                                                |
|   abdulrozak57910   |                                                                                mantaap                                                                                |
|       0*****.       |                                                                                Mantappp                                                                                |
|      asmaul435      |                                                                                Pesanan nya sudah saya terima dengan selamat. Makasih....                                                                                |
|       d*****i       |                                                                          Terima kasih barang sudah sampai dengan baik, bahan kemeja nya bagus lembut enak di pakainya..                                                                           |
|     gerryalaneee    |                                                                                Nyampe nya agak kusut... Tapibwajarlah....                                                                                |
|                     |                                                                                Barang nya bagus ini, bkn yg model berbulu....                                                                                |
|                     |                                                                                Untuk harga segitu... Kualitas aku anggap OKE bnget                                                                                |
|       r*****n       |                                                                                Bagus                                                                                |
|      miftahud08     |                                                                                Kedua kali nya the best banget                                                                                |
|      aristna354     |                                                                                Pengirimannya cepat mantab barang oke                                                                                |
|      ummy_naqia     |                                                                                It's very good                                                                                |
|       hildasaf      |                                                              Motif, warna, dan ukuran sesuai pesanan dan foto produk. Bahannya alus banget, mantaplah. Ps : XLnya ngga terlalu gede.                                                              |
|   asfiatulistianah  |                                                                                Kualitas produk baik, produk original, harga produk sangat baik. Bahan lembut                                                                                |
|     dhinginanjar    |                                                                                Mantep                                                                                |
|       abdul825      |                                                                                None                                                                                |
|    irfan_yusup123   |                                                                                Barang nya udah sampe cepet sih lumayan, barangnya bagus ko adem                                                                                |
|       evahelen      |                                                                                Bahan nya tebal,,,adem, sesuai gambar puas belanja disini next order disini lagi                                                                                |
|   riskanurhidayani  |                                                                                Ngga tau mau komen gimana lagi.                                                                                |
|                     |                                                                                Sangat puas.                                                                                |
|                     |                                                                                Sampai di sulawesi cuman sehariii saking cepatnya dalam pengemasan dan pengiriman.                                                                                |
|                     |                                                                                Baru nyampe 6 baju langsung belanja lagi 3 baju.                                                                                |
|                     |                                                                                Padahal bulan lalu jga beli  7 baju                                                                                |
|                     |                                                                                Mulai dari Adek, sepupu, om dan doi semua suka bahannya.                                                                                |
|                     |                                                                                Bkn bahan baju murahan.                                                                                |
|   rikkifirnanda01   |                                                                                Barang original, ternyata kain nya halus ku kira agak kaku                                                                                |
|      riyan.shop     |                                                    Pesanannya udh nyampe kak. Kualitas produk sangat bagus. Tebal dan tidak murahan. Harga terjangkau. Warna sesuai pesanan. Terimakasih kak.                                                     |
|                     |                                                                                Recomended pokoknya.                                                                                |
|    aldinugraha107   |                                                                                Saya suka                                                                                |
|    cicimulyani19    |                                                                                |
|   harisprabowo100   |                                                                                Naice                                                                                |
|       reza.bge      |                                                                                Packing nya mantap , baru kali ini order bahan nya mantep next order pasti                                                                                |
|      mhzulhamdi     |                                                                                Barang mantap tapi utk ukurannya ngepas kyk L padahal udh ambil ukuran xl                                                                                |
|    asepnurjaman96   |                                                                                Cukuplah  untk harga segini                                                                                |
|                     |                                                                                Estimasi pengiriman topmarkotop                                                                                |
|                     |                                                                                Saran aja diskusi chat di perbaiki lagii                                                                                |
|      riskaarami     |                                                 makasi gan barang sampai dengan aman, dan kurir ramah. dan barang sesuai dengan yang ada di picture dan respon penjual sangat cepat. terimakasih.                                                 |
+---------------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+


text:
Q: Mouse driver needs update in Mac I have a Microsoft optical wheel mouse (several actually) which work perfect in MS Windows.
However in Mac (lastest OS Monterrey), the scroll wheel sometimes behaves eradically, by scrolling the screen up a bit while I am using mouse wheel repeatedly to scroll it down.
I connected my friend's newer Dell mouse which does not behave that way.
It's definitely a problem with the mouse driver included in OSX.
Is there a fix for this?

redpajama_set_name: RedPajamaStackExchange


text:
Q: How do I only print a statement when the end of file is reached in Bison? For simplification of the original problem, supposed I wanted to parse a string of left and right parentheses. The flex file would have the tokens
"(" return LPAREN
")" return RPAREN

and the bison file would have the productions
completedparse: pair {printf("Success!\n");}
;
pair: LPAREN pair RPAREN
    | LPAREN RPAREN pair
    | LPAREN RPAREN
;

IF given the string "(()()(()))" or "()()(())" It would succeed.
The problem I have is that "(()()))" would print the success statement, immediately before failure. I know that bison creates the production
$accept: completedparse $end

which is how bison accepts or rejects the string. All my problems would go away if I could write my own $accept production and include any print statements in that production. But according to the 3.0.2 manual $accept cannot be used in the grammar.
My problems would also go away if I could modify the return value of yyparse() (assume that I need more information than just 0 => success, 1 => failure). I don't think this is possible though.
If you have any insight please respond, and thanks for any help!

A: One simple solution:
completedparse: pair {printf("Success!\n");}
              | pair error
              ;

The error pseudo-terminal won't match all errors, but it will match the one where an EOF is expected and something else is found. If the error is encountered in some other context, the error production won't apply. In general, you should use yyerror to perform an action on a syntax error; the above rule is simply a way to avoid invoking the completedparse action in the case that there is garbage at the end of the input.
By the way, your grammar does not match (())(). You might want to use:
pair:         /* EMPTY */
    |         '(' pair ')' pair
    ;

Additionally:
In response to the addendum in the comments:

*

*You can use the action { YYABORT } in the error production in order to immediately return (with a return value of 1, indicating a syntax error). If you want to print a generic error message, you are probably better off doing so in your yyerror implementation, since that will be called on any syntax error, while the error production will only be reduced on certain errors. You can use error productions to generate more specific error messages, but that's a lot more work.

*You cannot customize the $accept pseudo-production. However, the above technique is more or less equivalent.

*You cannot change the return type or values of yyparse (0 success, 1 syntax error, 2 allocation error). However, it is often useful to return more data from a parse (for example, an AST). The "traditional" solution is to just use a global variable, but for those of us with a distaste for global variables, another solution is to use the [%parse-param][1] declaration to add one or more additional arguments; normally, your start production will set the value of the objects to which these arguments point. If you do this, you should always check the return value of yyparse before relying on the additional return information, exactly because the start production may be evaluated even in the case of an error.


text:
Q: Convert Delphi Enumerated type to Similar thing in C# I am new at c# and have been programming for many years in Delphi. I am stuck on the following problem and I hope someone can help me.
In Delphi you could declare a type:
type
  TBtn = (btYes, btNo, btOK);

then create a procedure
procedure TfrmMain.Button(ABtn: TBtn);
begin
  //Do something;
end;

and call the procedure like this
Button(btYes);

or
Button(btNo);

I want to do the same thing in C#
public Button (ABtn TBtn, string AString){
//Do Someting;
}

and call it
Button(btYes,"Hallo World");

How can I accomplish this?

A: In Delphi that is an enumerated type. The C# equivalent is an enum.
Declare the type like this:
enum Btn {Yes, No, OK};

Declare the function like this:
public void Button(Btn btn, string str)
{
    // Do Something;
}

And call the function like so:
Button(Btn.Yes, "Hallo World");

While you are still learning C#, I would recommend that you keep an introductory text close to hand.


text:
Q: How to make key and array change together? <?php
    $test = array("a" => "horse","b" => "fish");
    $k = array_keys($test);
    print_r($k);
    unset($test["a"]);
    print_r($test);
    print_r($k);
?>

I have changed array("a" => "horse","b" => "fish") into array("b" => "fish") with unset function ; the $k unchanged.
How make the key in the array and array itself change together?
To change the $k into:
Array
(
    [0] => b
)

Not:
Array
(
    [0] => a
    [1] => b
)

A: What I've understand from your question then you can simply use array_intersect as
$test = array("a" => "horse", "b" => "fish");
$k = array_keys($test);
unset($test["a"]);
$k = array_intersect(array_keys($test), $k);
print_r($k);


text:
Q: Ошибка сохранения файла в Geany (Linux Ubuntu) Установил на Ubuntu 15.04 Geany версии 1.25.
При попытке сохранения файла выскакивает ошибка, как на скриншоте ниже. Подскажите, как можно пофиксить это.
Заранее благодарю.

A: вероятно, каталог и файлы, в которые вы пытаетесь внести изменения, принадлежат другому пользователю.
один из возможных вариантов «решения» — изменить принадлежность этих файлов/каталогов:
$ sudo chown $USER /путь/к/файлу/и/или/каталогу ...

или рекурсивно для всего содержимого каталога:
$ sudo chown -R $USER /путь/к/каталогу ...


text:
Q: OpenID + Google returning different unique ids for same user I am working on a project using openid as a login. So far its been working fine. Today however I noticed a user using gmail provider could not log in with their existing account.
I looked over the code and could find no issue. In the end I made a copy of their existing unique id key and made them create a new account. When the new account was created I compared the two openid unique keys and they were different for the same account.
As far as I know this would break the whole premise of openid.
I would like to know if others have had a similar experience and so I can identify if the issue is related to openid / gmail or is something on my end.
Project Specs.
- Java 6.0
- Tomcat 7.0
- MySQL 5.5
- JOpenID 2.0

A: Google will create a different OpenID for each URL as better described by Andrew Arnott here.
Do notice that Google ID, Facebook ID, Flickr ID for a same user coming from any one of those different sites... will be unique!


text:
Q: Is it possible to further generalise Brahmagupta's identity? Is it possible to generalise Brahmagupta's identity
further, by which I mean, for different n, for example take the equations:
$$1357 = 37^2 - 3\times2^2$$
$$1357 = 38^2 - 87\times1^2$$
$$1357^2 = 1841449 = 3445^2 - 261\times196^2$$
Is there an algebraic route between the first two and the third?

A: No, I wouldn't think so. It would be easy enough if $3 \cdot 87$  were a square, this is called composition in different orders in Buell's book.
As $261$  is not a square: if there were some nice way to  combine things, we could expect to take
$$ 2^2 - 3 \cdot 1^2 = 1 \; , \; \; \;  28^2 - 87 \cdot 3^2 = 1 $$
and quickly solve $x^2 - 261 y^2 = 1^2 = 1$  in fairly small numbers. However, the smallest such is
$$ 192119201^2 - 261 \cdot 11891880^2 = 1 $$


text:
Q: How do I access an ASP.NET variable to pass as JSON string to WCF Ajax Enabled Service I have a WCF AJAX enabled web service, and I am trying to pass a value of a field in an ASP.NET page into it with JSON but I always get nothing f. I want to do something like what we did in ASP.NET web services:
request.form("SbID").toString();
My Web Service is getting in a parameter that is NULL and I think its because of what I pass in the form. The Web Service is:
[OperationContract]
        [WebGet]
        public ResultData GetContactsDataAndCountbyGUID(string requestGUID)
        {
            ResultData result = new ResultData();
            common c = new common();

            string request = String.Empty;
            try
            {
                request = OperationContext.Current.RequestContext.RequestMessage.ToString();

            }
            catch (Exception ex)
            {

            }

            try
            {
                List<CONTACT> listContacts = new List<CONTACT>();

                DataSet ds = new DataSet();
                ds = c.GetDataSet(requestGUID);
                DataTable dt = new DataTable();
                dt = ds.Tables[0];

                // listContacts = CollectionHelper.ConvertTo<CONTACT>(dt);

                listContacts = c.ConvertTo<CONTACT>(dt);

                result.Data = listContacts;
                result.Count = listContacts.Count;

           }

This is the JavaScript/jQuery:
  <script type="text/javascript">
            //function DoUpdate(sbiId) {
            //    var input = '{"SbiId":"' + sbiId + '"}';
            //    var dataSource;
        $(document).ready(function() {
            **var input ='{"SbiId":"<%=guid %>"}';**
            $.ajax({
                url: "http://www.blah.com/services/testsService.svc/GetContactsDataAndCountbyGUID",
                type: "GET",
                contentType: "application/json; charset=utf-8",
                data: input,
                dataType: "json",
                success: function(data) {
                    var mtv = $find("<%= RadGrid1.ClientID %>").get_masterTableView();
                    console.log(data);
                    mtv.set_dataSource(data.d.Data);
                    mtv.dataBind();
                }
            });
            // }

        });
        </script>

I am trying to pass the value of GUID, which is in the form by:
public string guid = null;
        common c = new common();
        protected void Page_Load(object sender, EventArgs e)
        {
             try
            {

                IHubContext hubContext = GlobalHost.ConnectionManager.GetHubContext<AlphaHub>();
                // common c = new common();
                var userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext()));
                ApplicationUser user = userManager.FindByNameAsync(User.Identity.Name).Result;
                string connectionId =  c.GetCurrentConnection(user.RegistrationCode);

                string request = "Contact" + " - " + connectionId + " - " + user.RegistrationCode;
                string guid = c.recordDataRequest(user.RegistrationCode, request, connectionId, "out", "");
                request = request + " - " + guid;
                hubContext.Clients.Client(connectionId).CallForReport(request);
           //   hub
                Thread.Sleep(1000);
            }

How do I get this value passed in and retrieved?

A: ASP.Net is stateless, you're not going to be able to access a variable from the code behind.
Store it in a hidden variable which you can access from jQuery.
<input type="hidden" id="hdnGuid" runat="server">

Set it in your code behind:
string guid = c.recordDataRequest(user.RegistrationCode, request, connectionId, "out", "");
hdnGuid.Value = guid;

In your jQuery accesses it:
var hdnGuid = $("#<%= hdnGuid.ClientID %>").val();
var input ='{"SbiId":"' + hdnGuid + '"}';


text:
Q: Mahout: converting one large text file to SequenceFile format I have done a lot of searching on the web for this, but I've found nothing, even though I feel like it has to be somewhat common.  I have used Mahout's seqdirectory command to convert a folder containing text files (each file is a separate document) in the past.  But in this case there are so many documents (in the 100,000s) that I have one very large text file in which each line is a document.  How can I convert this large file to SequenceFile format so that Mahout understands that each line should be considered a separate document?  Thank you very much for any help.

A: Yeah, it is not quite apparent or very intuitive how to do this, although (lucky for you :P) I have answered that exact question several times here in stack, for instance here. Have a look ;)


text:
Q: Gradle Script to generate/clean Multiple Product Flavors I know how to create product flavors with gradle.I did successfully created the product flavors and apks as per product flavors.
In my project I have 8 different product flavors.
I want a gradle script by running this script I can generate/clean multiple apks for all the product flavors.
Can anyone please help me?
Additional Information :: I am using android studio 0.8.3

A: gradlew build will generate an APK for each variant (flavor + build type).
You can also run gradlew tasks to list all of the tasks available, if you want to generate a few specific variants.


text:
Q: DELETE request on row with nested foreign keys I have a Table A that is referenced to by Table B, and Table C has references to Table B.
Such that:

*

*Table A (pk: id)

*Table B (pk: id, fk: A_id)

*Table C (fk: B_id)

Every foreign key has a constraint ON_DELETE:CASCADE, however if I attempted to delete Table A - it refuses to. This is happening because rows in Table B have foreign keys pointing to Table A, and Table C has rows pointing to Table B.
I'm confident that I can resolve this issue by deleting Table B first, and then deleting Table A. However, would someone explain why this DELETE isn't possible? Surely, it should be able to perform a function of going down a 'hierarchy' of foreign keys and  deleting everything in order?
Thanks

A: In ON DELETE CASCADE operation, if a parent row is deleted, it will first delete the child row and then the parent row so as to ensure that no references are left as foreign key
As for your question, since Table B is referring to Table A 's primary key and Table C is referring to Table B's primary key, the relationship for which on delete cascade should work is just a parent child and not beyond.


text:
Q: Move quantity field to top of product options? I'm looking to move my quantity field to the top of my product options. I'd like to have it under the short description if possible. Just having a hard time locating where you change the layout for this stuff.
Thanks.

A: The quantity box is located in the file .../frontend/base/default/template/catalog/product/view/addtocart.phtml.
As long as you keep the field in the form located in .../frontend/base/default/template/catalog/product/view.phtml it should work. So either remove it from the addtocart.phtml or move the whole <?php echo $this->getChildHtml('addtocart') ?> in the view.phtml.


text:
Q: why this setState is unexpectedly passing the old value? I've this parent component(Parent) which holds an inner component(InnerComp) (for organizing code). The inner component has another nested component(Comp) which I'm importing from another file. to update Parent's state from Comp, I'm passing the setParentCount function via prop in Comp

function Parent() {
  const [parentCount, setParentCount] = useState(0);

  const InnerComp = () => (
    <>

necessary inner comp

      <Comp setParentCount={setParentCount} />
    </>
  );

  return (
    <>

Parent

      <InnerComp />

parent comp count = {parentCount}

    </>
  );
}

Comp has its own state as well. the "Click" button in Comp calls the handleClick function on click. the handleClick function is trying to update both the Comp and Parent's state. but it seems that compCount is not getting updated.

function Comp({ setParentCount }) {
  const [compCount, setCompCount] = useState(0);

  useEffect(() => {
    console.log(compCount);
  }, [compCount]);

  function handleClick() {
    setCompCount((prev) => prev + 1);

    setParentCount((prev) => prev + 1);
  }

  return (
    <>

child comp

      <button onClick={handleClick}>Click</button>

child comp count = {compCount}

    </>
  );
}

I've added the useEffect as well for compCount in Comp. it's logging every time I click the button. but the same initial value. means the setCompCount function is setting the old value every time. I wonder why it is happening.
When I add the InnerComp's JSX directly inside Parent instead of making a new inner component, it works fine. But I kinda need the InnerComp to keep my code organized.
I know I can make it work with useContext, but I think having context here will make this tiny component really heavy.
Here's a codesandbox

A: Your issue is that you are defining InnerComp within the Parent component. This means that every time your Parent component rerenders, it redefines the InnerComp function, creating a new component type each time. In other words, on every rerender of Parent, InnerComp represents a completely new component, and using it will replace the previous version of InnerComp and start with the default state.
To fix this, you should move the definition of InnerComp outside the Parent component, and make any dependencies of Parent passed in as props to InnerComp like so:
const InnerComp = ({ setParentCount }) => (
  <>

necessary inner comp

    <Comp setParentCount={setParentCount} />
  </>
);

function Parent() {
  const [parentCount, setParentCount] = useState(0);
  return (
    <>

Parent

      <InnerComp setParentCount={setParentCount} />

parent comp count = {parentCount}

    </>
  );
}

This way, InnerComp doesn't keep getting redefined and represents the same component type each rerender, thus preserving its internal state.
Here's a CodeSanbox with a working example.

A: The problem is the InnerComp is getting renewed everytime the parent state updates. Updating the parent state triggers rerender of the parent component in which InnerComp is declared and rendered. That causes InnerComp and also Comp which is in InnerComp to be initialized everytime the parent state change. It is not a good way to declare a component inside a compoent.
React Docs suggestion on nested component defination.
To resolve this, you can move InnerComp component declaration outside of the Parent and pass the necessary props. If you don't like passing the setParentCount props multiple times to child component you can consider using react context or state management libraries such as Redux, Recoil, etc.
const InnerComp = ({setParentCount}) => (
    <>

necessary inner comp

      <Comp setParentCount={setParentCount} />
    </>
 );

function Parent() {
  const [parentCount, setParentCount] = useState(0);

  return (
    <>

Parent

      <InnerComp setParentCount={setParentCount} />

parent comp count = {parentCount}

    </>
  );
}


text:
Q: Is it safe to use variable session data? I have a (hopefully) quick question regarding sessions. Whilst I have used sessions extensively, I have not used them in a situation whereby the values change depending on a users actions.
After logging in to my application, a user can select a company area, which has many levels of pages and folders. All of these pages will need this 'company_id'. At the moment I send the company_id via GET, but as I get deeper into the application this is becoming increasingly hard to maintain, with various other data being stored in the URL.
Therefore, when a user selects their company, I could set their company_id in $_SESSION array. However, when a user changes company, I would then need to change $_SESSION['company_id'] to the new value.
Is this a good use of sessions? I could potentially clean up my urls by using session data rather than always using GET, but I am unsure if this is a recommended way of using sessions.
Thanks in advance

A: This is a bad implementation of the HTTP design philosophy. All HTTP requests should be self contained, RESTful. All information needed to get a specific page should be present in the request itself (URL, headers and body), not dependent on hidden state.
Super trivial example: you can't copy a URL to someplace or someone else and have them see the same page. The content of the page is dependent on session state, which has been laboriously set through the visit history of several previous pages. To return to this same page, you need to retrace the same steps, recreating some hidden server-side state to arrive at the same page.
This gets even more complex and messier if you take into account that a visitor may want to open pages requiring different states in two or more simultaneous tabs/windows.
All this isn't to say that it can't work, only that it's hideously complex and will break the usual expected behaviour of browsers, unless you really bend over backwards to somehow prevent that.

A: If the many levels of pages and levels are per-company, you can put the company_id in a specific include file - this part of the site being dedicated to a given company.
However if they're shared by multiple companies, and this is probably what you want, this is potentially misleading, or even dangerous depending on the user actions, since the user may jump to a given page (link...) and access a page with unexpected data linked to a company which ID is provided by the session or cookie.
You could dynamically build the links on a page, based on IDs, to ensure consistency during the navigation from that page. Any direct "jump" to another part of the site will not carry the ID with it (and the page may offer to select a company).
Depending on your web server and if you have control over it you could build the URL having "company ID" as an element of the URL path, not the GET parameters
Eg
http://example.com/invoicing/company382/listprices.php

using a rewrite (web server configuration) to change the URL to be actually used to
http://example.com/invoicing/listprices.php?compid=company382

(URL not visible to the user) that informs of the company ID via the GET parameters.


text:
Q: WPF UserControl : Keep multiple linked dependency properties in sync without recursive loop causing Stack Overflow I am trying to create a simple user control for an immutable object with multiple properties.
The immutable object and a its properties should be exposed trough dependency properties of the user control.
When one dependency property changes, others need to change as well.
I think the best way to explain my problem is with a small example:
Let's say I have an immutable class Person.
The Person class has two properties: FirstName and LastName.
Person class:
    public class Person
    {
        private readonly string _firstName;
        private readonly string _lastName;
        public string FirstName => _firstName;
        public string LastName => _lastName;

        public Person(string firstName, string lastName)
        {
            _firstName = firstName;
            _lastName = lastName;
        }
    }

I want to make a view that has 2 text boxes: one for the First name and one for the last. I also want this view to have a dependency property that allows binding to the Person object created by the input of these two text boxes.
When I change the FirstName, this should result in a new Person.
When I change the LastName, this should result in a new Person.
When I change the Person, also FirstName and LastName need to be changed.
Usage example:
        <StackPanel Orientation="Vertical">
            <local:PersonView Person="{Binding PersonA, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"></local:PersonView>
            <local:PersonView Person="{Binding PersonB, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"></local:PersonView>
            <local:PersonView Person="{Binding PersonC, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"></local:PersonView>
        </StackPanel>

User control:
<UserControl x:Class="AutoMuse.GlobalSettings.PersonView"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
             xmlns:local="clr-namespace:AutoMuse.GlobalSettings"
             mc:Ignorable="d"
             d:DataContext="{d:DesignInstance Type=local:PersonView, IsDesignTimeCreatable=True}"
             d:DesignWidth="300">
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="*" />
            <ColumnDefinition Width="*" />
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
            <RowDefinition Height="*" />
            <RowDefinition Height="*" />
        </Grid.RowDefinitions>
        <StackPanel Orientation="Vertical"
                    Grid.Column="0"
                    Grid.Row="0">
            First Name
            <TextBox Text="{Binding FirstName, Mode=TwoWay, UpdateSourceTrigger=LostFocus, RelativeSource={RelativeSource AncestorType=UserControl}}"></TextBox>
        </StackPanel>
        <StackPanel Orientation="Vertical"
                    Grid.Column="1"
                    Grid.Row="0">
            Last Name
            <TextBox Text="{Binding LastName, Mode=TwoWay, UpdateSourceTrigger=LostFocus, RelativeSource={RelativeSource AncestorType=UserControl}}"></TextBox>
        </StackPanel>
        <StackPanel Orientation="Horizontal"
                    Grid.Column="0"
                    Grid.ColumnSpan="2"
                    Grid.Row="1">
            <TextBlock>Welcome: </TextBlock>
            <TextBlock Text="{Binding Person, Mode=OneWay, UpdateSourceTrigger=PropertyChanged, TargetNullValue=-, FallbackValue=-, RelativeSource={RelativeSource AncestorType=UserControl}}"></TextBlock>
        </StackPanel>
    </Grid>
</UserControl>

Code behind of user control:
    ///
    /// Interaction logic for PersonView.xaml
    ///
    public partial class PersonView : UserControl
    {
        public string FirstName
        {
            get { return (string)GetValue(FirstNameProperty); }
            set { SetValue(FirstNameProperty, value); }
        }

        // Using a DependencyProperty as the backing store for FirstName.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty FirstNameProperty =
            DependencyProperty.Register("FirstName", typeof(string), typeof(PersonView), new PropertyMetadata(OnFirstNameChanged));

        public string LastName
        {
            get { return (string)GetValue(LastNameProperty); }
            set { SetValue(LastNameProperty, value); }
        }

        // Using a DependencyProperty as the backing store for LastName.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty LastNameProperty =
            DependencyProperty.Register("LastName", typeof(string), typeof(PersonView), new PropertyMetadata(OnLastNameChanged));

        public Person Person
        {
            get { return (Person)GetValue(PersonProperty); }
            set { SetValue(PersonProperty, value); }
        }

        // Using a DependencyProperty as the backing store for FullName.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty PersonProperty =
            DependencyProperty.Register("Person", typeof(string), typeof(PersonView), new PropertyMetadata(OnPersonChanged));

        private static void OnLastNameChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            if (d is PersonView personView)
                personView.OnLastNameChanged((string)e.OldValue, (string)e.NewValue);
        }
        private static void OnFirstNameChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            if (d is PersonView personView)
                personView.OnFirstNameChanged((string)e.OldValue, (string)e.NewValue);
        }
        private static void OnPersonChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            if (d is PersonView personView)
                personView.OnPersonChanged((Person)e.OldValue, (Person)e.NewValue);
        }

        private void OnFirstNameChanged(string oldValue, string newValue)
        {
            Person = new Person(newValue, Person?.LastName);
        }
        private void OnLastNameChanged(string oldValue, string newValue)
        {
            Person = new Person(Person?.FirstName, newValue);
        }

        private void OnPersonChanged(Person oldValue, Person newValue)
        {
            FirstName = newValue?.FirstName;
            LastName = newValue?.LastName;
        }

        public PersonView()
        {
            InitializeComponent();
        }
    }

The main focus is on these methods:
        private void OnFirstNameChanged(string oldValue, string newValue)
        {
            Person = new Person(newValue, Person?.LastName);
        }
        private void OnLastNameChanged(string oldValue, string newValue)
        {
            Person = new Person(Person?.FirstName, newValue);
        }

        private void OnPersonChanged(Person oldValue, Person newValue)
        {
            FirstName = newValue?.FirstName;
            LastName = newValue?.LastName;
        }

Unfortunately, when setting the Person, this will set the FirstName, this will set the Person, this will set the FirstName, and so on ...
You can see that this leads to a loop and thus a stack overflow.
I can think of a few work arounds:

*

*adding a boolean field to prevent the recursive calling (e.g: _handlingOnPersonChanged) and then checking this.

*using the Equals function to only set a new value on inequality.

However I don't think these are the right solution to this problem.
What would be a good way to keep multiple Dependency Properties in sync without having this kind of recursive loop?
Thanks in advance!
EDIT 1
It seems the example did work correctly. Probably because under the hood the values are compared and the value changed callback is only called when the value actually changes. In my real application, the dependency properties like FirstName and LastName are not strings, but non-primitive custom types. These have both an Equals method and Equality operator overloads, but it seems that nor the Equals method, nor the '=='/'!=' are called. This makes that the value changed callback is called everytime, regardless of equality of old and new value. And this again results in the recursive loop: PersonChanged > FirstNameChanged > PersonChanged > FirstNameChanged > ...
As ASh has pointed out: calling OnPropertyChanged(...) myself was not needed, since this is handled under the hood, so these are removed. Removing them did not solve the problem however.

A: don't call OnPropertyChanged for any property. if there is any value change, it will be handled by property change callback.
private void OnPersonChanged(Person oldValue, Person newValue)
{
    if (FirstName != newValue?.FirstName)
        FirstName = newValue?.FirstName;
    if (LastName != newValue?.LastName)
        LastName = newValue?.LastName;
}

A: This is one possible solution as mentioned in the original question (using the Equals function to only set a new value on inequality). I do wonder however if there is a simple solution that does not require an Equality method?. Implementing equality methods is not that hard, but still wondering out of curiousity.

I made a wrapper for the string to see what would happen if the property type for FirstName/LastName is not a primitive type to simulate my real-world application. In this case it is a simple StringWrapper:
    public class StringWrapper : IEquatable<StringWrapper>
    {
        public string Value { get; set; }
        public override string ToString() => Value;
        public override bool Equals(object obj) => Equals(obj as StringWrapper);
        public bool Equals(StringWrapper other) => other != null && Value == other.Value;
        public override int GetHashCode() => -1937169414 + EqualityComparer<string>.Default.GetHashCode(Value);

        public StringWrapper(string str)
        {
            Value = str;
        }

        public static bool operator ==(StringWrapper left, StringWrapper right)
        {
            return EqualityComparer<StringWrapper>.Default.Equals(left, right);
        }

        public static bool operator !=(StringWrapper left, StringWrapper right)
        {
            return !(left == right);
        }
    }

For what I could see, the Equals method, not the == or != operator is not called automatically (I could be wrong in this). But adding it manually and checking for equality before setting resolves the issue, as shown below.

        private void OnFirstNameChanged(StringWrapper oldValue, StringWrapper newValue)
        {
            if (newValue != oldValue)
                Person = new Person(newValue?.Value, Person?.LastName?.Value);
        }
        private void OnLastNameChanged(StringWrapper oldValue, StringWrapper newValue)
        {
            if (newValue != oldValue)
                Person = new Person(Person?.FirstName?.Value, newValue?.Value);
        }

        private void OnPersonChanged(Person oldValue, Person newValue)
        {
            if (newValue != oldValue)
            {
                FirstName = newValue?.FirstName;
                LastName = newValue?.LastName;
            }
        }


text:
Q: Trying to get my controller and action name in a javascript file I'm looking at the SO link here and the anser that is given is
var controllerName = '@ViewContext.RouteData.Values["Controller"].ToString()';

but this doesn't seem to return anything in my javascript file. It just shows the value as the string '@ViewContext.RouteData.Values["Controller"].ToString()' it doesn't compute the name.

A: I had to put this in my view
<script type="text/javascript">
    var controllerName = '@ViewContext.RouteData.Values["Controller"].ToString()';
    var actionName = '@ViewContext.RouteData.Values["Action"].ToString()';
</script>

I couldn't just read it in my javascript file. Now the two variables are accessable in my JS file


text:
Q: Disabling TLS 1.0 affecting secure communication We have a .NET 4.7.1 ASP.NET MVC application running on Windows Server 2012 R2.
In the Registry, we set the "Enabled" properties to zero (FALSE) for the following keys:

HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS
1.0\Client
HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS
1.0\Server

However, after rebooting, we found that whilst our application could pull data securely from a 3rd party "Service Reference", it was unable to pull data securely from another 3rd party "Web Reference".
Reverting the "Client" Enabled property to 4294967295 (true) (and rebooting) solved the issue.
We're informed that the web-reference concerned supports TLS 1.0, 1.1, and 1.2, and that other clients are able to consume data using TLS 1.1/1.2.
The MVC application is set to use the server settings (protocols are not hard-coded).


text:
Q: How to send a array of object to restful WCF with POST and JSON when i'm trying to send json with POST method, i'm getting error
[{"ExtensionData":null,"Date":"12/16/2014 22:11:16","IsPlayer":false,"MagicInfo":null,"SpellInfo":null},{"ExtensionData":null,"Date":"12/16/2014 22:11:16","IsPlayer":false,"MagicInfo":null,"SpellInfo":null}]

service:
[WebInvoke(UriTemplate = "InsertCastActivities", Method = "POST",
                    RequestFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare)]
[OperationContract]
bool InsertCastActivities(List<CastActivityDto> castActivitiesDto);

The remote server returned an error: (400) Bad Request. Request Error
  The server encountered an error processing the request. See server
  logs for more details.

A: What is definition of class CastActivityDto?
You must define a DataContract and Datamember attribute.
so class must be something like this
[DataContract]
public class CastActivityDto
{
   [DataMember]
   public string SomeAttribute { get;set;}

   [DataMember]
   public string AnotherAttribute { get;set;}
}

then you can post JSON data in format
{
  castActivitiesDto :
  [
     {SomeAttribute : "1", AnotherAttribute : "1" },
     {SomeAttribute : "2", AnotherAttribute : "2" }
  ]
};

A: It was a DATETIME type error.
When it is:
[DataMember]
public virtual String Time
{
    get { return this.date.ToString(); }
    set
    {
        this.date = value != null ? DateTime.Parse(value) : DateTime.Now;
    }
}

everything works fine ! :)


text:
Q: Почему пропадает доменная сеть на одном компьютере с 20.00 до 8.00 и пишет "подлинность не проверена"? Столкнулся с такой проблемой на предприятии. Обратилась сотрудница с проблемой, что компьютер работает хорошо до 20.00, после 20.00 они, якобы, не могут попасть ни в 1С, ни в сетевые папки, да и ввести пароль и зайти на компьютер становится сложнее (ПК грузит минут 5-10).
После того, как я узнал про проблему, так сразу переустановил в АD учетку, ну соответственно повторно подключился к доменной сети и результата нет, после чего прописал статический IP со всеми настройками (IP так же установил другой) и не помогло. В чем может быть проблема?


text:
Q: IQueryable order by two or more properties I am currently ordering a list of custom objects using the IQueryable OrderBy method as follows:
mylist.AsQueryable().OrderBy("PropertyName");

Now I am looking to sort by more than one property. Is there any way to do that?
Thanks,
Yannis

A: You probably want to use the ThenBy extension method to be able to sort by multiple fields
 return myList.AsQueryable().OrderBy(m=>m.Property1).ThenBy(m => m.Property2);

If you want dynamic Linq, look at LinqKit.  I recently implemented Microsoft's dynamic Linq library from here and was able to sort by two fields using a string.
Awesome stuff!  Not sure if this will be in .NET 5 or not.

A: OrderBy(i => i.PropertyName).ThenBy(i => i.AnotherProperty)

In OrderBy and ThenBy you have to provide keySelector function, which chooses key for sorting from object. So if you know property name only at runtime then you can make such function with Reflection like:
var propertyInfo = i.GetType().GetProperty("PropertyName");
var sortedList = myList.OrderBy(i => propertyInfo.GetValue(i, null))

But it will be slower, then direct access to property. Also you can "compile" such function on the fly with Linq.Expressions and it will work faster than reflection but it is not very easy.  Or you can use CollectionViewSource and their sorting ablilities in WPF.
And don't forget that OrderBy() returns sorted enumerable and it does not sort your existed List inplace. In your example you did not save sorted list to variable.

A: You could use .ThenBy:
var result = mylist
    .AsQueryable()
    .OrderBy(x => x.PropertyName)
    .ThenBy(x => x.SomeOtherProperty);

A: As others have suggested, you can use 'ThenBy'. If you want to convert a string to a different value before using it, this is possible too, for example...
    var sortedSystemTestResultsList = systemTestResultsList.OrderBy(s =>
    {
        DateTime dt;
        if (!DateTime.TryParse(s.testPointCompletedDate, out dt)) return DateTime.MaxValue;
        return dt;
    }).ThenBy(s =>
    {
        Int32 tpID;
        if (!Int32.TryParse(s.testRunResultID, out tpID)) return Int32.MaxValue;
        return tpID;
    });


text:
Q: how to send data from array to pointer variable and back from pointer variable to array? #include "MAIN.h"
#include "xcpip_callbacks.h"
typedef unsigned _int16 uint16;
typedef unsigned _int8 uint8;

uint16 port = 18017;
void XcpApp_IpTransmit( uint16 port, Xcp_StatePtr8 pBytes, uint16 numBytes )

{
        WSADATA wsa;
        SOCKET s;
        uint8 bytes_recieved;
        uint8 send_data[1024],recv_data[1024];

        struct sockaddr_in server;  // creating a socket address structure: structure contains ip address and port number

        printf("Initializing Winsock\n");
        if(WSAStartup(MAKEWORD(2,2), &wsa)!=0)
        {
            printf("Failed Error Code: %d", WSAGetLastError());
            return 1;
        }
        printf("Initialised\n");

        //int sock, bytes_recieved;
        //char send_data[1024],recv_data[1024];
        //struct hostent *host;
        //struct sockaddr_in server_addr;

        //host = gethostbyname("127.0.0.1");

        /*if ((s = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
            perror("Socket");
            exit(1);
        }*/

        //CREATING a SOCKET

        if ((s = socket(AF_INET, SOCK_STREAM, 0)) == -1)
        {
            printf("Could not Create Socket\n");
            return 0;
        }
        printf("Socket Created\n");

        server.sin_addr.s_addr = inet_addr("192.168.0.1");
        server.sin_family = AF_INET;
        server.sin_port = htons("port");

        //Connect to a remote server
        if(connect(s, (struct sockaddr *)&server, sizeof(server))<0)
        {
        puts("Connect Error\n");
        return 1;
        }

        puts("Connected\n");

        //SENDING a data

        /* bzero(&(server_addr.sin_zero),8);

        if (connect(sock, (struct sockaddr *)&server_addr,
                    sizeof(struct sockaddr)) == -1)
        {
            perror("Connect");
            exit(1);
        }*/

        while(1)
        {
        /*
            s- socket
            recv_data - receive data buffer and size of it (1024)
        */
          bytes_recieved=recv(s,recv_data,1024,0);
          recv_data[bytes_recieved] = '\0';

          if(strcmp(recv_data , "q") == 0 || strcmp(recv_data , "Q") == 0)
          {
           close(s);
           break;
          }

          else
           printf("\nRecieved data = %s " , recv_data);

          /*
          port For TCP: the port which listened for the connection which
                        was used to transmit the data. Note that this may not be
                        the same as the port which actually transmitted the data.
          For UDP:      the port which transmitted the data.
                        numTxBytes The number of bytes which were transmitted during the
                        latest call to XcpApp_IpTransmit(). For TCP, this may
                        be less than the total number of bytes which were supplied
                        to XcpApp_IpTransmit().*/

          XcpIp_TxCallback(uint16 port, uint16 numTxBytes );

           printf("\nSEND (q or Q to quit) : ");
           gets(send_data);

          if (strcmp(send_data , "q") != 0 && strcmp(send_data , "Q") != 0)
           send(s,send_data,strlen(send_data), 0);

          else
          {
           send(s,send_data,strlen(send_data), 0);

           /*
         chunkLen :  The number of bytes at pChunkData.
         pChunkData : The payload of the received IP frame. The caller does not
                      need to interpret the payload: the entire payload should be
                      passed to XcpIp_RxCallback().
                      The caller can discard this data after the function returns.
        port For TCP:  the port which listened for the connection which
                       received the data. Note that this may not be the same as
                       the port which actually received the data.
        For UDP:       the port which received the data. */

          XcpIp_RxCallback(uint16 chunkLen, uint8* pChunkData, uint16 port);

           closesocket(s);
           WSACleanup();
           break;
          }

        }

}

I have created a TCP Layer for sending and receiving the data on the specific port and calling some specific XCP protocol to perform some activity. I have created a socket and specified the port number and ip address to send and receive data. I am receiving some data on the recv_data[1024]; I can send data from the send_data[1024];
I need some help for :
Before writing or sending that data: I should send the data from send_data[1024] to Xcp_StatePtr8 pBytes (pointer points to memory in an address space). Later I have to write data from Xcp_StatePtr8 pBytes to recv_data[1024];
Could anyone please suggest me some ideas ??

A: You can use memcpy to write the data from an array to a pointer and vice versa like this example I created below:
#include <stdio.h>
#include <cstring>

#define MAX_SIZE 20

int main()
{
    int anTest[MAX_SIZE] = {200, 200, 200, 200};
    int anTest2[MAX_SIZE];
    int* pnTest = new int[MAX_SIZE];

    // Initializing array and pointer to 0
    memset(anTest2, 0, sizeof(anTest2));
    memset(pnTest, 0, sizeof(pnTest));

    //Outputting anTest values and exiting loop when
    //an element contains 0, just because.
    puts("anTest values: ");
    for(int nIndex = 0; nIndex < MAX_SIZE; nIndex++)
    {
        if (0 == anTest[nIndex])
        {
            break;
        }

        printf("%d: %d\n", nIndex, anTest[nIndex]);
    }

    //Copying array to pointer
    memcpy(pnTest, anTest, MAX_SIZE * sizeof(int));

    //Copying pointer to array
    memcpy(anTest2, pnTest, MAX_SIZE * sizeof(int));

    //Outputting anTest2 values and exiting loop when
    //an element contains 0, just because.
    puts("\nanTest2 values: ");
    for(int nIndex = 0; nIndex < MAX_SIZE; nIndex++)
    {
        if (0 == anTest2[nIndex])
        {
            break;
        }

        printf("%d: %d\n", nIndex, anTest2[nIndex]);
    }

    //Deleting pointer since it's no longer needed.
    delete pnTest;
    pnTest = NULL;

    return 0;
}

[EDIT] I forgot to add code to prove that it works (I always check my code by walking through the code instead of outputting the values lol). I edited my code to include printing the output values.


text:
Q: link scattered ui to one controller in angular js How can I join multiple scattered UI components, other than using multiple ng-controller directives? I saw an advices of creating some kind of UI service, but I don't know how to call service methods from ng-click.
In code below i have form for adding list items, but it is in overlay, while items themself should be in

, so how do I link it all together?

html:

Add site

Title

                <input type="text" id="addSiteTitle" ng-model="newSite.title">

URL

                <input type="text" id="addSiteUrl" ng-model="newSite.url">

                <button id="addSiteSumit" ng-click="addSite()">Add</button>
                <button id="addSiteCancel" ng-click="hideOverlay()">Cancel</button>

New tab

Add site

Settings

Delete

Resize

Edit

Back

Small

Normal

Large

Icon

SitesController:
app.controller('SitesController', function($scope, SitesFactory){
    $scope.sites = SitesFactory.getSites();
    console.log($scope.sites);
    $scope.addSite = function(){
        console.log($scope.newSite);
        // code for adding site
    }
    $scope.showOverlay = function(){
        $('#overlay').addClass('shown');
    }
    $scope.hideOverlay = function(){
        $('#overlay').removeClass('shown');
    }
});

A: You could move your ng-controller="SitesController" directive to the body tag and remove it from the inner divs.  That will allow all of the inner divs to use SitesController.


text:
Q: Gradle Version for debugging React-Native on Windows using VS Code I'm trying to debug a React-Native app on Windows using VS Code and the React Native Tools extension.  I have my app running in the emulator.  I run the React Native: Check development environment configuration
and I see:
Info] Starting Environment check...

<<< Dev Environment verification result >>>

*** Common ***
 ✓ Node.JS
 ✓ NPM

*** Android ***
 ✓ ADB
 ✓ Android Emulator
 ✓ Android Env
 ✓ Java
 ✖ Gradle - Requried for building android apps
  Command not found. Make sure Gradle is installed

When I go to Android Studio File > Project Structure I see:

I've tried the following in my C:\Users\user\source\TargetSum\android\gradle\wrapper\gradle-wrapper.properties file:
# distributionUrl=https\://services.gradle.org/distributions/gradle-7.5.1-all.zip
#distributionUrl=https\://services.gradle.org/distributions/gradle-7.3.1-all.zip
distributionUrl=https\://services.gradle.org/distributions/gradle-7.4-all.zip

7.5.1 was the version automatically put in the gradle-wrapper.properties file.  I've restarted VS Code after each change, but I see the:
✖ Gradle - Requried for building android apps
      Command not found. Make sure Gradle is installed

with all 3 versions


text:
Q: Select IN with an array with duplicate value on it I am trying to make a request where I select from an array of value using the IN, but inside this array, if I have the same value twice, I'd like the request to return the result twice.
To clarify, here is an example:
select id_exo, count(id_exo) FROM BLOC WHERE id_seance IN (10,10) group by id_exo

So inside the IN, I put 2 times the value 10.
Here is the result:

id_exo
count(id_exo)

60
1

82
1

But in count, I'd like to have the number 2 since I have put twice 10 inside my IN.
How can I achieve that?

A: SELECT id_exo, COUNT(id_exo)
FROM bloc
JOIN (SELECT 10 id_seance
      UNION ALL
      SELECT 10) val USING (id_seance)
GROUP BY id_exo

A: Prior to MySQL 8.0 you can join with a sub select:
select * from BLOC as b
inner join (
  select 1 as 'id', 10 as 'value'
  union
  select 2,10
  union
  select 3,10) as myValues on myValues.value = b.id_seance

You need the id column as the UNION statement removes duplicate rows
If you are lucky enough to have MySQL 8.0 look at the VALUES statement
https://dev.mysql.com/doc/refman/8.0/en/values.html
Here you should instead be able to join with something like
VALUES ROW(10), ROW(10), ROW(10)


text:
Q: Google placepicker not running on main thread warning I noticed that with an update to xcode 9, a run-time warning message pops up when presenting Google Place Picker:

UI API called from background thread

present(GooglePlacePicker, animated: true, completion: nil)

I am pretty certain that I am calling that from the main thread, but in case I wasn't I tried fetching main thread first:
DispatchQueue.main.async(execute: {
    self.present(self.GooglePlacePicker, animated: true, completion: nil)
})

I noticed that this is only an issue for Google Place Picker, as I've tried the same thing with Google Autocomplete and I receive no such warning. I'd imagine that this may have something to do with additional UI components in Place Picker built in to the iOS SDK but was wondering if anybody was able to prevent this warning. Otherwise, I would assume that Google would address this in the next SDK release.

A: The issue lies in Google PlacePicker SDK code, not yours. Its up to them to fix this issue. Track the SDK for latest version. They must've patched it by now as they have already done for Firebase SDK recently. If there is no update on this, you'll have to wait until they fix it.
My answer here explains more about this runtime issue if you want to check it out.


text:
Q: Points of differentiability of squared distance from a point in metric spaces I posted this same question on MSE with no answer.
Let $I:=(0, + \infty)$ and let $(X,d)$ be a complete and separable metric space. In this setting we say that $u : I \to X$ is absolutely continuous if there exists $g \in L^1(I)$, $g \ge0$ s.t.
$$ \tag{1}\label{1} d(u_s,u_t) \le \int_s^t g(r)dr \quad \forall \, s,t \in I, \quad s \le t.$$
It is well known (see Duda - Absolutely Continuous Functions with Values in a Metric Space (DOI)) that such a $u$ is metrically differentiable.
Now for an absolutely continuous $u : I \to X$ and $v \in X$, consider the real-valued function $f_{u,v} : I \to [0, + \infty)$ defined by
$$f_{u,v}(t):=d^2(u_t,v) \quad t \in I.$$
Then $f$ is also absolutely continuous, so it is differentiable for almost all $t \in I$. Let $A_{u,v}$ be the full-measure domain of differentiability for $f_{u,v}$.
Can we show that $A_{u,v}$ depends only on $u$?
For example, this is true if $X$ is a real separable Hilbert space, and even in Wasserstein spaces. Is this true in general?

A: Consider the separable metric space $X=[0,1]\times\{0,1\}$ endowed with the $\ell_1$-metric $d:X\times X\to\mathbb R$ defined by
$$d\big((x,i),(y,j)\big)=|x-y|+|i-j|.
$$
It seems that this metric space yields a counterexample to your question.


text:
Q: How to get a button to work with view in android I have been trying to add a erase function to this drawing app. I was planning on it just simpily drawing white over where you move your finger. For some reason  i cannot get the button to work. If i can get this button to work I will be able to add more colors ect.
(i have not done anything with Mainactivity)
package com.example.draw;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.os.Bundle;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class MainDrawingView extends View
{
private Paint paint = new Paint();
private boolean erase;
private Path path = new Path();
Button aButton;

public MainDrawingView(Context context, AttributeSet attrs)
{
    super(context, attrs);
    paint.setAntiAlias(true);
    paint.setStrokeWidth(5f);
    paint.setStyle(Paint.Style.STROKE);
    paint.setStrokeJoin(Paint.Join.ROUND);

    aButton = (Button) this.findViewById(R.id.button1);
    aButton.setOnClickListener(new OnClickListener()
    {
        public void onClick(View v)
        {
            erase = !erase;
        }
    });
}

@Override
protected void onDraw(Canvas canvas)
{
    canvas.drawPath(path, paint);
}

public boolean onTouchEvent(MotionEvent event)
{
    if(erase) paint.setColor(Color.WHITE);
    else paint.setColor(Color.BLACK);

    // Get the coordinates of the touch event.
    float eventX = event.getX();
    float eventY = event.getY();
    switch (event.getAction()) {
        case MotionEvent.ACTION_DOWN:
            // Set a new starting point
            path.moveTo(eventX, eventY);
            return true;
        case MotionEvent.ACTION_MOVE:
            // Connect the points
            path.lineTo(eventX, eventY);
            break;
        default:
            return false;
    }

    // Makes our view repaint and call onDraw

    invalidate();

    return true;
}
}
Activity_main<

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"

xmlns:tools="http://schemas.android.com/tools"

android:layout_width="match_parent"

android:layout_height="match_parent"

android:background="#ffffff"

tools:context="com.example.draw.FullscreenActivity">

<!-- This is the view on which we will draw. -->

<view

    android:layout_width="match_parent"

    android:layout_height="match_parent"

    class="com.example.draw.MainDrawingView"
    android:id="@+id/single_touch_view"

    android:layout_gravity="left|top"
    android:background="#ffffff" />

<Button
    android:id="@+id/button1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Button" />

</FrameLayout>

A: It seems like your problem is that you're using the wrong types. Your erase variable is of type Paint:
private Paint erase = new Paint();

But in your code you're treating it like an int that represents a boolean.
if(erase != 0) { paint.setColor(Color.BLACK); }
if(erase == 0) { paint.setColor(Color.WHITE); }
...
erase = 1;

Secondly, you're never actually setting the onClickListener for your button.  Also, the logic to set the color should all be moved into either your onTouch or the onClick method.  You really should have:
public class MainDrawingView extends View
{
    private Paint paint = new Paint();
    private boolean erase;
    private Path path = new Path();
    Button aButton;

    public MainDrawingView(Context context, AttributeSet attrs)
    {
        super(context, attrs);
        paint.setAntiAlias(true);
        paint.setStrokeWidth(5f);
        paint.setStyle(Paint.Style.STROKE);
        paint.setStrokeJoin(Paint.Join.ROUND);

        aButton = (Button) this.findViewById(R.id.button1);
        aButton.setOnClickListener(new OnClickListener()
        {
            public void onClick(View v)
            {
                erase = !erase;
            }
        });
    }

    @Override
    protected void onDraw(Canvas canvas)
    {
        canvas.drawPath(path, paint);
    }

    public boolean onTouchEvent(MotionEvent event)
    {
        if(erase) paint.setColor(Color.WHITE);
        else paint.setColor(Color.BLACK);

        // Get the coordinates of the touch event.
        float eventX = event.getX();
        float eventY = event.getY();
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                // Set a new starting point
                path.moveTo(eventX, eventY);
                return true;
            case MotionEvent.ACTION_MOVE:
                // Connect the points
                path.lineTo(eventX, eventY);
                break;
            default:
                return false;
        }

        // Makes our view repaint and call onDraw

        invalidate();

        return true;
    }
}

A: It is possible that your view is not being created with the following constructor
Context context, AttributeSet attrs

It might be using a different default constructor that you have not overridden.  Then nothing would get setup and you would not get any click behavior that your expecting from your listener.

A: It looks like you do not have your onCreate(Bundle savedInstances) method setup to to add the listener correctly.


text:
Q: Showing that $\sum_{i=1}^{n}\sum_{j=1}^{n}(a_{i} - a_{j})^2 = 2n \sum_{i=1}^{n}(a_{i} - \bar{a})^2$ I wish to show $\sum_{i=1}^{n}\sum_{j=1}^{n}(a_{i} - a_{j})^2 = 2n \sum_{i=1}^{n}(a_{i} - \bar{a})^2$ for any numbers $a_1, a_2, ..., a_n$.
I assume the first step $+\bar{a}$ and $-\bar{a}$ in the first equation, to get $(a_{i} - \bar{a})^2$ in the end. But, I can't get it to the second equation.

A: Here is a hint, for any numbers the sum of the mean deviations is zero, i.e.
$$\sum_{i=1}^n \left(a_i - \bar{a} \right) = 0 $$
Recall also that
$$ \sum_{i=1}^n \left(a_i - \bar{a} \right)^2 =  \sum_{j=1}^n \left(a_j - \bar{a} \right)^2 $$
With these in mind, you should be able to reach the sum on the RHS.


text:
Q: Declaring an object with a parameterized constructor inside another class C++ I wish to have an object of one class contained inside a different class.
class A contained inside class B as in the simple example below.
The problem is that class A only has a parametrized constructor.
Is there another way to do declare the class A object in class B without having to use a pointer to class A ?
class A
{
    public:
        A(int var1, int var2);
    private:
        //...
};

class B
{
    public:
        B();
    private:
        A  a;      // Compiler error
        A* a_ptr; // This will of course work fine. We can create a new A object with parameters any time using the a_ptr
};

A:
A  a;      // Compiler error

except if the constructor of B explicitly calls the constructor of A with required arguments (e.g. B() : a(an_int, an_int) {...}), that requests a constructor without parameter or where all parameters have default value, but you do not have that constructor, only a constructor requiring 2 int

Is there another way to do declare the class A object in class B without having to use a pointer to class A ?

you do not declare but define / instantiate a new instance of A each time you instantiate a new instance of B
Note you can create later the instance of A without using a pointer as with a_ptr having for instance
std::vector<A> a;

and when you know the instance of A you need doing for instance
a.push_back(A(an-int, an-int));

but the fact you want only one instance is not visible in the definition of a (out of a welcome comment)


text:
Q: Intent.EXTRA_CC not populating cc field in android app I'm pre-filling an email which should launch in the users default email app but for some reason the CC line isn't populating with it's intended string. Any Idea what's going on?
Intent toSupportIntent = new Intent(Intent.ACTION_SENDTO, Uri.parse("mailto:" +  getString(R.string.support_email)));
toSupportIntent.putExtra(Intent.EXTRA_CC, getString(R.string.cc_support_email));
toSupportIntent.putExtra(Intent.EXTRA_SUBJECT, getString(R.string.support_email_subject));
toSupportIntent.putExtra(Intent.EXTRA_TEXT, getString(R.string.support_email_message));
startActivity(toSupportIntent);

A: ACTION_SENDTO is not documented to support EXTRA_CC. Hence, you should not be surprised when it does not work with all apps.


text:
Q: "to the north of London", "north of London", or "in the north of London" Consider these sentences:

*

*The company's office is to the north of London.

*The company's office is in the north of London.

*The company's office is north of London.

As far as Grammar is concerned, I think all of them are valid. To show this, I just quote from the dictionaries:

*

*"The Yorkshire Dales are twenty miles to the north of the city."

*"there will be heavy wintry showers, particularly in the north."

*"the town is twenty-five miles north of Newport."
Would you please tell me what is the difference between these sentences?

A: To the north of X and north of X means that it lies beyond X on its northern side (or "above" X on a map oriented with North up).  Some would infer that something which is "to the north of X" is not very distant from or relatively close to X, whereas a place "north of X" could be quite far from X.
In the north of X means that it lies in the northern part of X.
Edinburgh is north of  Manchester.
Dundee is to the north of Edinburgh.
Durham is in the north of England.


text:
Q: Terminology question regarding a certain "partial maximum likelihood" which approximates the marginal likelihood Suppose that we have a model with many parameters, which we'll partition into two subvectors called $\theta$ and $\lambda$. In this situation, $\lambda$ corresponds to those parameters that are really of interest, and $\theta$ are nuisance parameters. In particular, we would really like to look at quantities like $P(x|\lambda)$, $P(x)$ and $P(\lambda|x)$, meaning we marginalize on the $\theta$. However, performing the integral over all $\theta$ may be hard.
However, for each $\lambda$, we may not even care about every possible value of $\theta$ for each lambda. We may only care about the best possible value of $\theta$ for that $\lambda$. This would suggest we look at something like this "partial maximum likelihood"
$$
Q(x|\lambda) = \max_\theta P(x|\theta,\lambda) P(\theta|\lambda) = \max_\theta P(x, \theta|\lambda)
$$
This is a interesting function in its own right. If we treat it as a likelihood function we can easily derive the related quantities $Q(x) = \sum_\lambda Q(x|\lambda) P(\lambda)$, and $Q(\lambda|x) = Q(x|\lambda) P(\lambda)/Q(x)$. It isn't a true likelihood as the sum on all possible $x$ for $Q(x|\lambda)$ need not be 1, but some quantity which may be very close to $1$. We could try to normalize or just not care, as even if it isn't, the function $Q(\lambda|x)$ is a true probability distribution as these normalizing terms cancel.
Question: what is this called? It doesn't seem to be quite the partial likelihood. I guess one could say it is a quasi-likelihood? It would make sense to call it a "partial maximum likelihood," I guess, except I am not quite sure if it is the same as this thing. Or can we perhaps treat the posterior as a true posterior on some other related quantity?

A: This is called the profile likelihood function.  Taking $\hat{\theta} \equiv \hat{\theta}(x,\lambda) \equiv \text{arg max}_\theta P(x,\theta|\lambda)$ gives $Q(x|\lambda) = P(x,\hat{\theta}|\lambda)$, yielding $Q$ as a profile likelihood.


text:
Q: For tensorflow, What's the differences between ResourceApplyAdam and ApplyAdam? Is there any differences on features or performance between them, or it's just an alias for different version.

A: return types are different. see reference
tensorflow::ops::ResourceApplyAdam
Returns: the created Operation

tensorflow::ops::ApplyAdam
Output: Same as "var".

reference
ResourceApplyAdam
ApplyAdam

A: Read the Documentation carefully, along with return type, public attributes, public functions are also different
Resource apply adam
Apply Adam


text:
Q: SQL Server query group dates and amounts I have this table:
ID, PayDate  , ActualPayDate , Cost , Price
1 , 18-11-18 , 30-11-18      , 100  , 120
2 , 28-3-19  , 1-4-19        , 150  , 230
3 , 5-4-19   , null          , 170  , 290
4 , 5-3-19   , null          , 100  , 200

I want to group the PayDate by year and month for the Cost column and group by the ActualPayDate for the Price, the results should by somthing like this:
Year , Month , Cost , Price
2018 , 11    , 100  , 120
2018 , 12    , 0    , 0
2019 , 1     , 0    , 0
2019 , 2     , 0    , 0
2019 , 3     , 250  , 0
2019 , 4     , 170  , 230

Please help.

A: Use apply:
select year(v.dte), month(v.dte), coalesce(sum(v.cost), 0) as cost,
      coalesce(sum(v.price)) as price
from t cross apply
     (values (t.paydate, t.cost, 0),
             (t.actualpaydate, 0, t.price)
     ) v(dte, cost, price)
group by year(v.dte), month(v.dte)
order by year(v.dte), month(v.dte);

A: Please try this sub sql then join with the time diminsion.
with CTE as
(
select Year(PayDate) as [Year]
    , Month(PayDate) as [Month]
    , Sum(Cost) as [cost]
    , Sum(Price) as Price
from table
Group by Year(PayDate), Month(PayDate)
)
Select Cte.*,  tblDimTime * from CTE
Outer join tblDimTime
 on cte.[Year] = cte.[Year]
 and cte.[Month] = cte.[Month]

here is link to "Creating a date dimension or calendar table in SQL Server"
https://www.mssqltips.com/sqlservertip/4054/creating-a-date-dimension-or-calendar-table-in-sql-server/


text:
Q: How should I deal in correct way with recuring events and possible events' details? (Mongo,Vue) I am struggling with the way how I should design scheme for my data.
I saw a lot of threads with recuring calendar events but I can't translate it into my case as it is slightly different and this small difference making it tough.
Basically I have two models which don't let me sleep. EVENT and EVENT_DETAILS
First of all, I am using MongoDB but this is mostly more high level abstraction than going down to DB level, but I can be wrong.
Backend is SailsJS.
On the frontend I have VueJS SPA.
I have events. Most of them are recuring forever (permanent), but some of them are either one off, so have exact date when they happen,
some of them are recuring on one day of week in given period and some of permanent are suspended for given period.
EVENT can exist without EVENT_DETAILS, but not the other way of course.
I need to let user go through WEEKS periods and be able to see list of EVENTS in given period and related EVENT_DETAILS and if there is no EVENT_DETAILS,
let him create it.
For handling permanent, suspension and temporary, I have following attributes in
my EVENT (I show only relevant atts):
TYPE: [0,1,2]; 0 - permanent, 1 - temp, 2 - one off
SUSPENDED: true/false
SUSPENSION_DATES (from,to)
PERIOD (from,to) - for temporary
DAY: [0-6] - day of the week (choosen for 0 and 1, autmatically for 2 - one off

and of course association to EVENT_DETAILS.
Is it ok or should I amend it to make it correct/better/easier to deal with ?
How should I handle criteria to give user complete list of events for particular period?
I am of course not asking for code as it is not an issue for me.
I am asking for help with logic/criteria as I am really stuck with that for few days.

A: A few improvements you may consider:

*

*since your events are specified by the unit of day, events happening on one day and those last for a period can be normalized into one, by setting start and end dates to the same for one-off events.

*As for a field in a schema in mongodb, not only primitive types are allowed, objects/arrays can also be used to form complicated structures. So you can just store an event's details in the event schema, with a field of array of strings, like {type: [String], default: []} in mongoose syntax, or even {type: [{label: String, description: String}], default: []}.

For the second bullet, embedding documents in mongodb is good for forming a model-like database structure, but mongodb doesn't do really well in aggregation, so only embed those "belonging" to a schema (or, those with a one-one or multi-one relation mapping to another, not multi-multi), in our case here, it should be safe to do so since details belong to single events.
So now there's just events in periods and weekly events, which can't be normalized into one since one is continous and the other is not. Having a type flag to identify them seems all right to me. You can make some comments/documents and add some configs like const EVENT_TYPES = {PERMANENT: 0, TEMP: 1} and use these readable type configs instead of 0 1s to make sure your colleages and yourself won't hate you in the future ;)


text:
Q: SwiftUI How to vertically center a view inside a VStack I would like to have one view in the vertical center of the screen, one view at the top of the screen and one view vertically centered between these two views like so:

This took me 5min to do on a storyboard but I don't seem to find a way to do it in SwiftUI .
I already tried with multiple zstacks, vstacks, multiple custom alignments but this is the closest I got:
struct SelectionView: View {
    var body: some View {
        ZStack(alignment: .myAlignment) {
            Color.green
                .edgesIgnoringSafeArea(.all)

            VStack {
                Image(systemName: "clock")
                    .resizable()
                    .foregroundColor(.white)
                    .aspectRatio(contentMode: .fit)
                    .frame(width: 156, height: 80)

//                Spacer()

                Text("My\nmultiline label")
                    .multilineTextAlignment(.center)
                    .font(.title)
                    .foregroundColor(.white)

//                Spacer()

                VStack(spacing: 16) {
                    RoundedRectangle(cornerRadius: 5).fill(Color.white).frame(height: 79)
                    RoundedRectangle(cornerRadius: 5).fill(Color.white).frame(height: 79)
                }
                .alignmentGuide(VerticalAlignment.myAlignment) { dimension in
                    dimension[VerticalAlignment.center]
                }
                .layoutPriority(1)
            }
            .padding([.leading, .trailing], 24)
        }
    }

}

struct SelectionView_Previews: PreviewProvider {
    static var previews: some View {
        LanguageSelectionView()
    }
}

// MARK

extension HorizontalAlignment {

    enum MyHorizontal: AlignmentID {
        static func defaultValue(in d: ViewDimensions) -> CGFloat
                 { d[HorizontalAlignment.center] }
    }

    static let myAlignment =
                 HorizontalAlignment(MyHorizontal.self)
}

extension VerticalAlignment {
    enum MyVertical: AlignmentID {
        static func defaultValue(in d: ViewDimensions) -> CGFloat
                 { d[VerticalAlignment.center] }
    }

    static let myAlignment = VerticalAlignment(MyVertical.self)
}

extension Alignment {
    static let myAlignment = Alignment(horizontal: .myAlignment,
                               vertical: .myAlignment)
}

I'm keeping the GeometryReader as a last resort as it feels like a too drastic measure for this seemingly simple layout..
I guess I'm approaching this in some wrong way (still too much UIKit/Constraints in my head)..

A: Here is possible solution. Tested with Xcode 12 / iOS 14

struct SelectionView: View {
    var body: some View {
        ZStack {
            Color.green
                .edgesIgnoringSafeArea(.all)

            VStack(spacing: 16) {
                Color.clear
                    .overlay(
                        VStack {
                            Image(systemName: "clock")
                                .resizable()
                                .foregroundColor(.white)
                                .aspectRatio(contentMode: .fit)
                                .frame(width: 156, height: 80)
                            Color.clear
                                .overlay(
                                    Text("My\nmultiline label")
                                        .multilineTextAlignment(.center)
                                        .font(.title)
                                        .foregroundColor(.white)
                            )
                        }
                    )
                RoundedRectangle(cornerRadius: 5).fill(Color.white).frame(height: 79)
                RoundedRectangle(cornerRadius: 5).fill(Color.white).frame(height: 79)
                Color.clear
            }
            .padding([.leading, .trailing], 24)
        }
    }
}


text:
Q: installing angular/cli with unhandled problem When I run the following command:
npm install -g @angular/cli

I get the following error:

C:\Users\AA>npm install -g @angular/cli
npm WARN deprecated request@2.88.2: request has been deprecated, see https://github.com/request/request/issues/3142
C:\Users\AA\AppData\Roaming\npm\ng -> C:\Users\AA\AppData\Roaming\npm\node_modules\@angular\cli\bin\ng

@angular/cli@9.1.7 postinstall C:\Users\AA\AppData\Roaming\npm\node_modules\@angular\cli
node ./bin/postinstall/script.js

+ @angular/cli@9.1.7
removed 1 package and updated 1 package in 15.551s

C:\Users\AA>
C:\Users\AA>ng --version
An unhandled exception occurred: ENOENT: no such file or directory, scandir 'C:\Users\AA\node_modules'
See "C:\Users\AA\AppData\Local\Temp\ng-MhKi22\angular-errors.log" for further details.

I have no idea, hope someone can help me out.

A: Angular is looking for a 'node_modules' subfolder in the app. You have not created any app, but Angular it's looking for one nevertheless. Type:

mkdir node_modules

And then execute again ng v
This error is a somewhat-well-document and recurrent error with angular-cli (see here). It's probably that you'll find additional errors when trying to run apps with ng serve. You'll probably have to install angular devkit with:

npm install @angular-devkit/core --save-dev


text:
Q: Marklogic MVCC :contemporaneous vs non-blocking I ma trying to understand the contemporaneous and non-blocking parameters with the help of an example. Please let me know if I am correct.
Assume we have transactions T1, T2, T3 occurring at time stamp = 10.
T1, T2, T3 commit at 30, 40, 50 respectively.
If a query transaction comes at 35:
for contemporaneous:
The query reads a version with T1 committed, and keeps T2 and T3 waiting till the read is done.
For non-blocking:
The query gets to read only after all 3 transaction T1,T2,T3 are committed at 50.

A: This is easiest to understand and matters most if you think about querying on a disaster recovery replica cluster.  In a DR setup each forest on the primary is replicating its journal frames to matching forests on the replica.  There are often multiple forests in a database, and because replication is at the forest level some forests might have slightly later data than others.
Now imagine a (read-only) query comes in to the database on the replica.  You have two choices.  One, you could run the query at the last timestamp for which you have all the data (that's nonblocking).  Two, you could run the query at the last timestamp you see any data for (in the forest furthest along) and wait for all the data to arrive (for the other forests) so you can get a transactionally consistent view for that later time (that's contemporaneous).
Notice that both options are transactionally consistent.  It's just about how the database chooses the timestamp at which you want the query to run.
Read-only queries always run lock-free.