text:
Q: can't scrape images from a webpage using the requests module When I check on this site, I see a lot of images. I wish to scrape images from that site using the requests module.
This is my failed attempt:
import requests
from bs4 import BeautifulSoup

start_url = 'https://lexica.art/'
link = 'https://lexica.art/api/trpc/prompts.infinitePrompts'

headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/105.0.0.0 Safari/537.36',
    'Accept': '*/*',
    'referer': 'https://lexica.art/',
    'accept-encoding': 'gzip, deflate, br',
    'accept-language': 'en-US,en;q=0.9,bn;q=0.8',
    'X-Requested-With': 'XMLHttpRequest',
}

params = {
    'batch': '1',
    'input': '{"0":{"json":{"text":"","searchMode":"images","showLikes":"false","cursor":"50"}}}'
}

with requests.Session() as s:
    s.headers.update(headers)
    res = s.get(link,params=params)
    print(res.status_code)
    print(res.json())

Output I'm getting:
403

raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

A: They actually offer an API:
import requests
import pandas as pd

s = requests.Session()
r = s.get( 'https://lexica.art/api/v1/search?q=apples')
df = pd.json_normalize(r.json()['images'])
print(df)

Result:
id  gallery src srcSmall    prompt  width   height  seed    grid    model   promptid    nsfw
0   0482ee68-0368-4eca-8846-5930db866b33    https://lexica.art?q=0482ee68-0368-4eca-8846-5930db866b33   https://lexica-serve-encoded-images.sharif.workers.dev/md/0482ee68-0368-4eca-8846-5930db866b33  https://lexica-serve-encoded-images.sharif.workers.dev/sm/0482ee68-0368-4eca-8846-5930db866b33  cute chubby blue fruits icons for mobile game ui    512 512 1413536227  False   stable-diffusion    d9868972-dad8-477d-8e5a-4a0ae1e9b72b    False
1   0f19f591-1717-4fa8-b4a0-25958d163f66    https://lexica.art?q=0f19f591-1717-4fa8-b4a0-25958d163f66   https://lexica-serve-encoded-images.sharif.workers.dev/md/0f19f591-1717-4fa8-b4a0-25958d163f66  https://lexica-serve-encoded-images.sharif.workers.dev/sm/0f19f591-1717-4fa8-b4a0-25958d163f66  !!bomb!!, nuke, bomb design, cherry, made of cherries   512 512 2887885166  False   stable-diffusion    d043266e-132b-4b18-be7a-099215310453    False
2   1085f1db-df23-4962-a459-730dd1e2a658    https://lexica.art?q=1085f1db-df23-4962-a459-730dd1e2a658   https://lexica-serve-encoded-images.sharif.workers.dev/md/1085f1db-df23-4962-a459-730dd1e2a658  https://lexica-serve-encoded-images.sharif.workers.dev/sm/1085f1db-df23-4962-a459-730dd1e2a658  not an apple    1024    1024    741458261   False   stable-diffusion    47e06771-2585-4b9c-8abd-c2cbd5728a29    False
3   11f2a286-9ef4-4884-b442-a495c0b31432    https://lexica.art?q=11f2a286-9ef4-4884-b442-a495c0b31432   https://lexica-serve-encoded-images.sharif.workers.dev/md/11f2a286-9ef4-4884-b442-a495c0b31432  https://lexica-serve-encoded-images.sharif.workers.dev/sm/11f2a286-9ef4-4884-b442-a495c0b31432  7 apples inside a brown braided basket  512 512 309592135   False   stable-diffusion    53a41b62-c8fb-4098-9dab-c58a68d57302    False
4   16cf1767-4fe3-4ab1-ab9d-24c193a09ccf    https://lexica.art?q=16cf1767-4fe3-4ab1-ab9d-24c193a09ccf   https://lexica-serve-encoded-images.sharif.workers.dev/md/16cf1767-4fe3-4ab1-ab9d-24c193a09ccf  https://lexica-serve-encoded-images.sharif.workers.dev/sm/16cf1767-4fe3-4ab1-ab9d-24c193a09ccf  not an apple    1024    1024    741458261   False   stable-diffusion    47e06771-2585-4b9c-8abd-c2cbd5728a29    False
5   18bb20b7-f1dd-4014-a4e4-c698499d01cd    https://lexica.art?q=18bb20b7-f1dd-4014-a4e4-c698499d01cd   https://lexica-serve-encoded-images.sharif.workers.dev/md/18bb20b7-f1dd-4014-a4e4-c698499d01cd  https://lexica-serve-encoded-images.sharif.workers.dev/sm/18bb20b7-f1dd-4014-a4e4-c698499d01cd  semi reallistic gouache gesture painting, by yoshitaka amano, by ruan jia, by Conrad roset, by dofus online artists, detailed anime 3d render watermelon monster, watermelon terrible monster, antrophomorfic watermelon, portrait, cgsociety, artstation, rococo mechanical, Digital reality, sf5 ink style, dieselpunk atmosphere, gesture drawn  512 704 2551230084  False   stable-diffusion    22712be3-7fa9-4d95-aec2-dd36323025a5    False
6   1a646e6f-5c33-4794-9d07-9dc2c45cc42c    https://lexica.art?q=1a646e6f-5c33-4794-9d07-9dc2c45cc42c   https://lexica-serve-encoded-images.sharif.workers.dev/md/1a646e6f-5c33-4794-9d07-9dc2c45cc42c  https://lexica-serve-encoded-images.sharif.workers.dev/sm/1a646e6f-5c33-4794-9d07-9dc2c45cc42c  insanely fine detail, still life classical academical oil paintintg, a fragment with a close - up apple. flemish baroque, dutch, netherlands.   1536    1536    1297713546  True    stable-diffusion    13e89043-0756-4082-9eee-ad04abb89747    False
7   20270ecc-3f9d-4561-a97d-e29118c574e0    https://lexica.art?q=20270ecc-3f9d-4561-a97d-e29118c574e0   https://lexica-serve-encoded-images.sharif.workers.dev/md/20270ecc-3f9d-4561-a97d-e29118c574e0  https://lexica-serve-encoded-images.sharif.workers.dev/sm/20270ecc-3f9d-4561-a97d-e29118c574e0  apple   576 1024    895444468   False   stable-diffusion    3a669200-a02d-4432-a12d-07309e9b9a3e    False
8   2858f7bb-6931-4a37-b818-6d4a743c958f    https://lexica.art?q=2858f7bb-6931-4a37-b818-6d4a743c958f   https://lexica-serve-encoded-images.sharif.workers.dev/md/2858f7bb-6931-4a37-b818-6d4a743c958f  https://lexica-serve-encoded-images.sharif.workers.dev/sm/2858f7bb-6931-4a37-b818-6d4a743c958f  artwork of a guava in the style of vladimir kush    1536    1536    2624678908  True    stable-diffusion    261f4447-ddd8-4c0b-ae8b-83df8a538957    False
9   369b2c1b-386d-4813-b646-280ae9d9e51a    https://lexica.art?q=369b2c1b-386d-4813-b646-280ae9d9e51a   https://lexica-serve-encoded-images.sharif.workers.dev/md/369b2c1b-386d-4813-b646-280ae9d9e51a  https://lexica-serve-encoded-images.sharif.workers.dev/sm/369b2c1b-386d-4813-b646-280ae9d9e51a  Beautiful naturist women stand on the side of a lonely apple tree facing the camera holds apple in hand, classical painting, symmetrical, realism, golden hour  1024    832 210477432   False   stable-diffusion    283a7548-d47c-48ef-b703-0297819f9a6b    False
10  3773045f-d32e-4d55-82a1-290db19f6058    https://lexica.art?q=3773045f-d32e-4d55-82a1-290db19f6058   https://lexica-serve-encoded-images.sharif.workers.dev/md/3773045f-d32e-4d55-82a1-290db19f6058  https://lexica-serve-encoded-images.sharif.workers.dev/sm/3773045f-d32e-4d55-82a1-290db19f6058  beautiful aesthetic inspirational digital painting of a close - up cherry, by greg rutkowski, trending on artstation, volumetric light. 1536    1536    2997455144  True    stable-diffusion    9fe37972-91a1-4e43-a52d-dfb40f5e0d55    False
11  4555888b-637d-4475-b1f4-93467acf2955    https://lexica.art?q=4555888b-637d-4475-b1f4-93467acf2955   https://lexica-serve-encoded-images.sharif.workers.dev/md/4555888b-637d-4475-b1f4-93467acf2955  https://lexica-serve-encoded-images.sharif.workers.dev/sm/4555888b-637d-4475-b1f4-93467acf2955  heaven fantasy painting, big pearly gate in heaven, apples, fruit, 8 k, trending on art station, digital art, puffy clouds, godly, godrays  1024    512 556361121   False   stable-diffusion    00bf7214-9e87-4294-bb02-0d376e8acda0    False
12  456731a2-1459-46b5-8537-8deb273ecaba    https://lexica.art?q=456731a2-1459-46b5-8537-8deb273ecaba   https://lexica-serve-encoded-images.sharif.workers.dev/md/456731a2-1459-46b5-8537-8deb273ecaba  https://lexica-serve-encoded-images.sharif.workers.dev/sm/456731a2-1459-46b5-8537-8deb273ecaba  apple cores in different art styles 512 512 616795706   False   stable-diffusion    44f9707d-f68e-4ead-a1d1-0e71dc239011    False
13  47ba538e-767e-420c-bc11-08561b986323    https://lexica.art?q=47ba538e-767e-420c-bc11-08561b986323   https://lexica-serve-encoded-images.sharif.workers.dev/md/47ba538e-767e-420c-bc11-08561b986323  https://lexica-serve-encoded-images.sharif.workers.dev/sm/47ba538e-767e-420c-bc11-08561b986323  A beautiful naturist woman stands on the side of a lonely apple tree facing the camera holds apple in hand, classical painting, symmetrical, realism, golden hour   1024    832 2183080406  False   stable-diffusion    b59d5525-d0db-4881-bf54-3b1fbaf776a1    False
14  484e49c6-1259-40fd-8c64-a1a8a0a46b6f    https://lexica.art?q=484e49c6-1259-40fd-8c64-a1a8a0a46b6f   https://lexica-serve-encoded-images.sharif.workers.dev/md/484e49c6-1259-40fd-8c64-a1a8a0a46b6f  https://lexica-serve-encoded-images.sharif.workers.dev/sm/484e49c6-1259-40fd-8c64-a1a8a0a46b6f  a photo of an apple 512 512 2529659975  False   stable-diffusion    f5c96cff-5b29-4bc4-a1dc-996c47e91a7c    False
15  49c82f05-c4de-4ea5-a6ec-afc32d7dacaf    https://lexica.art?q=49c82f05-c4de-4ea5-a6ec-afc32d7dacaf   https://lexica-serve-encoded-images.sharif.workers.dev/md/49c82f05-c4de-4ea5-a6ec-afc32d7dacaf  https://lexica-serve-encoded-images.sharif.workers.dev/sm/49c82f05-c4de-4ea5-a6ec-afc32d7dacaf  a closeup portrait of a woman wearing a dress made of tangled twisted knotted iridescent ribbon, picking pomegranates from a tree in an orchard, foggy, moody, photograph, by vincent desiderio, canon eos c 3 0 0, ƒ 1. 8, 3 5 mm, 8 k, medium - format print  704 704 2563006189  False   stable-diffusion    3606134c-e832-4090-8306-25c5738d33b3    False
16  5164671f-8a50-4c2f-9ba3-1c5b8862efc3    https://lexica.art?q=5164671f-8a50-4c2f-9ba3-1c5b8862efc3   https://lexica-serve-encoded-images.sharif.workers.dev/md/5164671f-8a50-4c2f-9ba3-1c5b8862efc3  https://lexica-serve-encoded-images.sharif.workers.dev/sm/5164671f-8a50-4c2f-9ba3-1c5b8862efc3  Psychedelic portrait of a Granny Smith apple with google eyes floating in space wearing a top hat , volumetric lighting, artstation, digital painting, very high detail, hyperrealistic, vivid color    1024    768 737376707   False   stable-diffusion    de4d1b46-1b05-43ac-9e06-9f0e0e8c4e8d    False
17  5661f867-cd24-4101-b0c6-6a2e55cd8be4    https://lexica.art?q=5661f867-cd24-4101-b0c6-6a2e55cd8be4   https://lexica-serve-encoded-images.sharif.workers.dev/md/5661f867-cd24-4101-b0c6-6a2e55cd8be4  https://lexica-serve-encoded-images.sharif.workers.dev/sm/5661f867-cd24-4101-b0c6-6a2e55cd8be4  a closeup portrait of a woman wearing a copper bodysuit, picking apples from a tree, foggy, moody, photograph, by vincent desiderio, canon eos c 3 0 0, ƒ 1. 8, 3 5 mm, 8 k, medium - format print  704 704 972944262   False   stable-diffusion    a49316da-bd58-4cf1-af64-3530ed3a590c    True
18  5a88b216-8e06-480d-8778-820d8d9a3fb8    https://lexica.art?q=5a88b216-8e06-480d-8778-820d8d9a3fb8   https://lexica-serve-encoded-images.sharif.workers.dev/md/5a88b216-8e06-480d-8778-820d8d9a3fb8  https://lexica-serve-encoded-images.sharif.workers.dev/sm/5a88b216-8e06-480d-8778-820d8d9a3fb8  a green apple on a red cube, photoreal, detailed, unreal engine 5, 8 k  512 512 2572329254  False   stable-diffusion    f8067a9c-330d-4641-974e-610cbc7b96c8    False
19  5b78d3b9-2e3a-48ec-978d-fc8055123f41    https://lexica.art?q=5b78d3b9-2e3a-48ec-978d-fc8055123f41   https://lexica-serve-encoded-images.sharif.workers.dev/md/5b78d3b9-2e3a-48ec-978d-fc8055123f41  https://lexica-serve-encoded-images.sharif.workers.dev/sm/5b78d3b9-2e3a-48ec-978d-fc8055123f41  an apple doing CrossFit, super detailed, hd image   512 512 3427155591  False   stable-diffusion    ac80fdbd-1e32-4815-9cab-7bd4823999fc    False
20  60faddc6-1b6d-47a7-85bd-8c2347ae2c39    https://lexica.art?q=60faddc6-1b6d-47a7-85bd-8c2347ae2c39   https://lexica-serve-encoded-images.sharif.workers.dev/md/60faddc6-1b6d-47a7-85bd-8c2347ae2c39  https://lexica-serve-encoded-images.sharif.workers.dev/sm/60faddc6-1b6d-47a7-85bd-8c2347ae2c39  photogenic apple fruit, dark lights, cinematic, sharp focus, realistic, in sunset   512 512 13646997    False   stable-diffusion    8dc21b03-327a-447c-b119-76bf980329d2    False
21  67cff8c3-a846-4c17-9378-0356cb76fa16    https://lexica.art?q=67cff8c3-a846-4c17-9378-0356cb76fa16   https://lexica-serve-encoded-images.sharif.workers.dev/md/67cff8c3-a846-4c17-9378-0356cb76fa16  https://lexica-serve-encoded-images.sharif.workers.dev/sm/67cff8c3-a846-4c17-9378-0356cb76fa16  galaxy apple    512 512 2623129452  False   stable-diffusion    77ecab61-3eff-4c38-bd19-55c3a030055a    False
22  6ca4908d-7a6c-468d-aa22-dbcf6e7c20b1    https://lexica.art?q=6ca4908d-7a6c-468d-aa22-dbcf6e7c20b1   https://lexica-serve-encoded-images.sharif.workers.dev/md/6ca4908d-7a6c-468d-aa22-dbcf6e7c20b1  https://lexica-serve-encoded-images.sharif.workers.dev/sm/6ca4908d-7a6c-468d-aa22-dbcf6e7c20b1  portrait smiling hot chloe moretz as gardener in apple orchard, full length shot, shining, 8k highly detailed, sharp focus, illustration, art by artgerm, mucha, bouguereau 1536    2112    1606479462  True    stable-diffusion    0494f4f9-f459-405a-ac32-3815bc2cbc4c    False
23  6ce9e21a-962d-47be-aa9f-dc5c259c486b    https://lexica.art?q=6ce9e21a-962d-47be-aa9f-dc5c259c486b   https://lexica-serve-encoded-images.sharif.workers.dev/md/6ce9e21a-962d-47be-aa9f-dc5c259c486b  https://lexica-serve-encoded-images.sharif.workers.dev/sm/6ce9e21a-962d-47be-aa9f-dc5c259c486b  pacman on speed eating a cherry 512 512 3759614023  False   stable-diffusion    2919a07b-43c3-4282-819b-4b05a114580b    False
24  6d09affc-1410-4761-8701-ec781ad6b8c3    https://lexica.art?q=6d09affc-1410-4761-8701-ec781ad6b8c3   https://lexica-serve-encoded-images.sharif.workers.dev/md/6d09affc-1410-4761-8701-ec781ad6b8c3  https://lexica-serve-encoded-images.sharif.workers.dev/sm/6d09affc-1410-4761-8701-ec781ad6b8c3  painting portrait of a beautiful girl with an apple in her hand, intricate, elegant, digital painting, smooth, sharp focus, shiny gold, realistic gold, realistic metal, by William-Adolphe Bouguereau and Gustav Klimt,    576 1024    3507747382  False   stable-diffusion    7687c392-05bd-44bc-a4ae-ddbf33dec90e    False
25  707af560-5ea0-49f4-ae7c-b4dd022a3fa0    https://lexica.art?q=707af560-5ea0-49f4-ae7c-b4dd022a3fa0   https://lexica-serve-encoded-images.sharif.workers.dev/md/707af560-5ea0-49f4-ae7c-b4dd022a3fa0  https://lexica-serve-encoded-images.sharif.workers.dev/sm/707af560-5ea0-49f4-ae7c-b4dd022a3fa0  attack of the killer's tomatoes. cyberpunk style    512 512 2055904510  False   stable-diffusion    926d4e45-e3ce-48a8-bdf1-4adfeaf16d91    True
26  79a4d97b-904e-4477-97c2-bf1427eff6f5    https://lexica.art?q=79a4d97b-904e-4477-97c2-bf1427eff6f5   https://lexica-serve-encoded-images.sharif.workers.dev/md/79a4d97b-904e-4477-97c2-bf1427eff6f5  https://lexica-serve-encoded-images.sharif.workers.dev/sm/79a4d97b-904e-4477-97c2-bf1427eff6f5  an evil apple, menacing piece of fruit  1536    1536    2173688452  True    stable-diffusion    aa50a2e9-d4c6-4aba-82cb-117be680843f    False
27  7d351afb-d7b1-41ee-948d-0b65c2e12470    https://lexica.art?q=7d351afb-d7b1-41ee-948d-0b65c2e12470   https://lexica-serve-encoded-images.sharif.workers.dev/md/7d351afb-d7b1-41ee-948d-0b65c2e12470  https://lexica-serve-encoded-images.sharif.workers.dev/sm/7d351afb-d7b1-41ee-948d-0b65c2e12470  exactly three apples    1536    1536    1834310726  True    stable-diffusion    d9f5d8d5-8dcd-4979-88c4-3f10fb9e09be    False
28  8d38955c-13ce-405b-b815-fda5a1326f12    https://lexica.art?q=8d38955c-13ce-405b-b815-fda5a1326f12   https://lexica-serve-encoded-images.sharif.workers.dev/md/8d38955c-13ce-405b-b815-fda5a1326f12  https://lexica-serve-encoded-images.sharif.workers.dev/sm/8d38955c-13ce-405b-b815-fda5a1326f12  insanely fine detail, still life classical academical oil paintintg, a fragment with a close - up apple. flemish baroque, dutch, netherlands.   1536    1536    789958954   True    stable-diffusion    62b312c4-b752-40a7-abe5-79e9611683e0    False
29  91fa7c4c-0f1b-4e2e-93a7-fcf251ad2a17    https://lexica.art?q=91fa7c4c-0f1b-4e2e-93a7-fcf251ad2a17   https://lexica-serve-encoded-images.sharif.workers.dev/md/91fa7c4c-0f1b-4e2e-93a7-fcf251ad2a17  https://lexica-serve-encoded-images.sharif.workers.dev/sm/91fa7c4c-0f1b-4e2e-93a7-fcf251ad2a17  apple cores in different art styles 512 512 616795706   False   stable-diffusion    44f9707d-f68e-4ead-a1d1-0e71dc239011    False
30  937274e9-1a90-4ddd-9cc4-49f92b9d1e87    https://lexica.art?q=937274e9-1a90-4ddd-9cc4-49f92b9d1e87   https://lexica-serve-encoded-images.sharif.workers.dev/md/937274e9-1a90-4ddd-9cc4-49f92b9d1e87  https://lexica-serve-encoded-images.sharif.workers.dev/sm/937274e9-1a90-4ddd-9cc4-49f92b9d1e87  an apple on a table 2048    2048    1444513431  True    stable-diffusion    f1cc3eae-9824-4fba-8df6-296adbf6e074    False
31  955c315b-2b7a-4847-8a3e-f0e13b41864b    https://lexica.art?q=955c315b-2b7a-4847-8a3e-f0e13b41864b   https://lexica-serve-encoded-images.sharif.workers.dev/md/955c315b-2b7a-4847-8a3e-f0e13b41864b  https://lexica-serve-encoded-images.sharif.workers.dev/sm/955c315b-2b7a-4847-8a3e-f0e13b41864b  apple   512 512 458991934   False   stable-diffusion    a64f1097-d9dd-4b63-8c5c-58b6cd5ab818    False
32  96d1d06b-92a9-42ac-9afb-786f36b2366b    https://lexica.art?q=96d1d06b-92a9-42ac-9afb-786f36b2366b   https://lexica-serve-encoded-images.sharif.workers.dev/md/96d1d06b-92a9-42ac-9afb-786f36b2366b  https://lexica-serve-encoded-images.sharif.workers.dev/sm/96d1d06b-92a9-42ac-9afb-786f36b2366b  a post - picture of a new delicious fruit vibrant color scheme, highly detailed, in the style of romanticism, cinematic, artstation, moebius, greg rutkowski    512 704 3662723596  False   stable-diffusion    e51731a6-49c1-44ec-9a13-dbd0fa4e7044    False
33  97720e5e-eba2-48d1-b1d5-1df3e12e2044    https://lexica.art?q=97720e5e-eba2-48d1-b1d5-1df3e12e2044   https://lexica-serve-encoded-images.sharif.workers.dev/md/97720e5e-eba2-48d1-b1d5-1df3e12e2044  https://lexica-serve-encoded-images.sharif.workers.dev/sm/97720e5e-eba2-48d1-b1d5-1df3e12e2044  a painting of an apple marc simonetti, yoshitaka amano, ruan jia, rossdraws,    1536    1536    2148704357  True    stable-diffusion    4cef8bc6-7c86-4c92-8060-8a469c75b9ef    False
34  9b98b285-97a1-43e9-9e81-fd994c3a59e2    https://lexica.art?q=9b98b285-97a1-43e9-9e81-fd994c3a59e2   https://lexica-serve-encoded-images.sharif.workers.dev/md/9b98b285-97a1-43e9-9e81-fd994c3a59e2  https://lexica-serve-encoded-images.sharif.workers.dev/sm/9b98b285-97a1-43e9-9e81-fd994c3a59e2  real small apples arranged into bitcoin logo, real photo, top down view 1536    1536    1804574273  True    stable-diffusion    f59ff2b8-7311-4f01-9f55-2c45e6560ec4    False
35  a3c92eb6-b394-400f-9757-42dff9b6d139    https://lexica.art?q=a3c92eb6-b394-400f-9757-42dff9b6d139   https://lexica-serve-encoded-images.sharif.workers.dev/md/a3c92eb6-b394-400f-9757-42dff9b6d139  https://lexica-serve-encoded-images.sharif.workers.dev/sm/a3c92eb6-b394-400f-9757-42dff9b6d139  portrait chloe moretz as gardener eating apple in apple orchard, full length shot, shining, 8k highly detailed, sharp focus, illustration, art by artgerm, mucha, bouguereau    1536    2112    2853497311  True    stable-diffusion    c3e077a0-9e48-4d34-bc53-3256e2365ed7    False
36  a47b1834-e06d-4631-b0a9-c59f786e03ef    https://lexica.art?q=a47b1834-e06d-4631-b0a9-c59f786e03ef   https://lexica-serve-encoded-images.sharif.workers.dev/md/a47b1834-e06d-4631-b0a9-c59f786e03ef  https://lexica-serve-encoded-images.sharif.workers.dev/sm/a47b1834-e06d-4631-b0a9-c59f786e03ef  Psychedelic portrait of a Granny Smith apple with google eyes floating in space, volumetric lighting, artstation, digital painting, very high detail, hyperrealistic, vivid color   1024    768 1206984812  False   stable-diffusion    b691fea9-a1a0-4295-82e2-dcb3c680c9cc    False
37  a5aee1b3-154f-4ea9-857d-749ee80dec62    https://lexica.art?q=a5aee1b3-154f-4ea9-857d-749ee80dec62   https://lexica-serve-encoded-images.sharif.workers.dev/md/a5aee1b3-154f-4ea9-857d-749ee80dec62  https://lexica-serve-encoded-images.sharif.workers.dev/sm/a5aee1b3-154f-4ea9-857d-749ee80dec62  beautiful aesthetic inspirational digital oil painting of a close - up apple, by greg rutkowski, ultra detailed, fine details, trending on artstation, volumetric light.    1536    1536    735893445   True    stable-diffusion    08b31a52-7ef4-4dff-b597-6f93c642ec0e    False
38  aaefeb5f-b21e-4d0b-a0f7-c3becdedaefc    https://lexica.art?q=aaefeb5f-b21e-4d0b-a0f7-c3becdedaefc   https://lexica-serve-encoded-images.sharif.workers.dev/md/aaefeb5f-b21e-4d0b-a0f7-c3becdedaefc  https://lexica-serve-encoded-images.sharif.workers.dev/sm/aaefeb5f-b21e-4d0b-a0f7-c3becdedaefc  delicate fishscale shimmering apple fruit pomegranate   512 512 2618437157  False   stable-diffusion    ed55d762-2b05-400a-9a38-fe43febbc8f4    False
39  ab5ef0cb-6a88-4f5a-88d7-452e42526c06    https://lexica.art?q=ab5ef0cb-6a88-4f5a-88d7-452e42526c06   https://lexica-serve-encoded-images.sharif.workers.dev/md/ab5ef0cb-6a88-4f5a-88d7-452e42526c06  https://lexica-serve-encoded-images.sharif.workers.dev/sm/ab5ef0cb-6a88-4f5a-88d7-452e42526c06  rotten tentacles coming out of a rotten apple inside a glass jar on a kitchen table hyperrealistic photography detailed 1536    1536    2594159325  True    stable-diffusion    fb0a6c61-d95c-4bd0-a340-9cc32a554b1e    False
40  b2148da3-739f-4c6c-b42d-156e12749f16    https://lexica.art?q=b2148da3-739f-4c6c-b42d-156e12749f16   https://lexica-serve-encoded-images.sharif.workers.dev/md/b2148da3-739f-4c6c-b42d-156e12749f16  https://lexica-serve-encoded-images.sharif.workers.dev/sm/b2148da3-739f-4c6c-b42d-156e12749f16  square apple    512 512 1337697659  False   stable-diffusion    db6d85d8-6ed5-4367-8075-0fcba7e0971c    False
41  c37b889f-5bef-4365-9d1d-452852356286    https://lexica.art?q=c37b889f-5bef-4365-9d1d-452852356286   https://lexica-serve-encoded-images.sharif.workers.dev/md/c37b889f-5bef-4365-9d1d-452852356286  https://lexica-serve-encoded-images.sharif.workers.dev/sm/c37b889f-5bef-4365-9d1d-452852356286  a girl with a red cloak holding a basket full of apples, by Jordan Grimmer and greg rutkowski, crisp lines and color,   512 512 3701828881  False   stable-diffusion    418452df-cdad-434d-9d4d-56a82eac104b    False
42  d42096de-94e2-4745-8c72-5df8a25e09c6    https://lexica.art?q=d42096de-94e2-4745-8c72-5df8a25e09c6   https://lexica-serve-encoded-images.sharif.workers.dev/md/d42096de-94e2-4745-8c72-5df8a25e09c6  https://lexica-serve-encoded-images.sharif.workers.dev/sm/d42096de-94e2-4745-8c72-5df8a25e09c6  an illustration of an apple in american dad style   512 512 1620054386  False   stable-diffusion    edde6394-9bd6-44a4-8519-5b68ad27f567    False
43  d81ccfea-4859-4ac3-ba96-439b2c8b0d2b    https://lexica.art?q=d81ccfea-4859-4ac3-ba96-439b2c8b0d2b   https://lexica-serve-encoded-images.sharif.workers.dev/md/d81ccfea-4859-4ac3-ba96-439b2c8b0d2b  https://lexica-serve-encoded-images.sharif.workers.dev/sm/d81ccfea-4859-4ac3-ba96-439b2c8b0d2b  an apple by René Magritte   2304    1536    404303797   True    stable-diffusion    dd807e9f-3c89-40fc-ad8b-7be6f77f68d2    False
44  dc3ec4e5-1d16-4615-adde-54152bfe35fd    https://lexica.art?q=dc3ec4e5-1d16-4615-adde-54152bfe35fd   https://lexica-serve-encoded-images.sharif.workers.dev/md/dc3ec4e5-1d16-4615-adde-54152bfe35fd  https://lexica-serve-encoded-images.sharif.workers.dev/sm/dc3ec4e5-1d16-4615-adde-54152bfe35fd  a photo of an apple 512 512 2529659975  False   stable-diffusion    e6b15326-39ce-4ee9-b8c9-152393a13c54    False
45  e05d6d83-385b-4031-9beb-b0a156b68f4d    https://lexica.art?q=e05d6d83-385b-4031-9beb-b0a156b68f4d   https://lexica-serve-encoded-images.sharif.workers.dev/md/e05d6d83-385b-4031-9beb-b0a156b68f4d  https://lexica-serve-encoded-images.sharif.workers.dev/sm/e05d6d83-385b-4031-9beb-b0a156b68f4d  bonsai apple! tree but minimalistic concept art by frank stella gilleard james whalen tom, colorful, soft light, trending on artstation, minimalism 512 512 2286171972  False   stable-diffusion    610520a3-7123-4cd0-b8b6-428f12cfa952    False
46  e587bb8f-4fc5-4854-88e3-b87b6c8d3bd2    https://lexica.art?q=e587bb8f-4fc5-4854-88e3-b87b6c8d3bd2   https://lexica-serve-encoded-images.sharif.workers.dev/md/e587bb8f-4fc5-4854-88e3-b87b6c8d3bd2  https://lexica-serve-encoded-images.sharif.workers.dev/sm/e587bb8f-4fc5-4854-88e3-b87b6c8d3bd2  impressionist oil painting of a hybrid kangaroo apple   1536    1536    2667333849  True    stable-diffusion    853a71a5-c4b6-43dd-baa4-e50ab8401130    False
47  ec123cde-635d-437c-bcc8-b8f4a79f9390    https://lexica.art?q=ec123cde-635d-437c-bcc8-b8f4a79f9390   https://lexica-serve-encoded-images.sharif.workers.dev/md/ec123cde-635d-437c-bcc8-b8f4a79f9390  https://lexica-serve-encoded-images.sharif.workers.dev/sm/ec123cde-635d-437c-bcc8-b8f4a79f9390  apple cores in different art styles 512 512 616795706   False   stable-diffusion    44f9707d-f68e-4ead-a1d1-0e71dc239011    False
48  efa8bdc0-f8ea-481f-886a-4609a635b38c    https://lexica.art?q=efa8bdc0-f8ea-481f-886a-4609a635b38c   https://lexica-serve-encoded-images.sharif.workers.dev/md/efa8bdc0-f8ea-481f-886a-4609a635b38c  https://lexica-serve-encoded-images.sharif.workers.dev/sm/efa8bdc0-f8ea-481f-886a-4609a635b38c  painting portrait of a beautiful girl with an apple in her hand, intricate, elegant, digital painting, smooth, sharp focus, shiny gold, realistic gold, realistic metal, by William-Adolphe Bouguereau and Gustav Klimt,    576 1024    68677281    False   stable-diffusion    3063bb65-a859-420f-8ebe-efd0a83e7937    False
49  fe942971-1896-4389-8134-022618bb876a    https://lexica.art?q=fe942971-1896-4389-8134-022618bb876a   https://lexica-serve-encoded-images.sharif.workers.dev/md/fe942971-1896-4389-8134-022618bb876a  https://lexica-serve-encoded-images.sharif.workers.dev/sm/fe942971-1896-4389-8134-022618bb876a  highly detailed apple   512 512 2472327392  False   stable-diffusion    2f159d63-ea1e-4648-afc7-5278c8ce16f7    False


text:
Q: Dynamically attach directive name to html tag using angularjs Is it possible to attach directive name to HTML tag by using user defined function which is defined in controller.
Assume directive name is test-val

In controller
    $scope.test = function() {
     do something // attach directive name to html div [id=attch]
    }
On trigger of a function test() div should attach directive name. Is this is possible?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Facebook Authentication, IFrame and Variable Passing Help I am currently using this recently written tutorial on authorizing an application with facebook using auth 2.0 and it works. the application authorizes correctly and uses the GraphAPI.
http://kartiklad.com/oauth-2-0-and-graph-api-for-facebook-canvas-applications/
But the problem is using the IFrame with a multi page website and this method of authentication, each time a different page is called, it has to go back to authentication page which will redirect the user page to the application, which makes it impossible to pass variables using $_GET.
So how would anyone else here suggest passing variables from one page to the next in an iframe?
This is probably not needed by the application I am working on is at : http://apps.facebook.com/prtrackevents/

A: The problem is that your urls are only navigating within the frame. The authentication of facebook is including your session variables inside a ?session=... query tag on your frame so that when you navigate to a url in your iframe you loose the ?session querystring value so then your app has to re authenticate. The fix is that your links must include target="_top" so that they cause the entire page to change positions. For example, your details link should be like this:
Details


text:
Q: Where do I find my bookmarks in my old homefolder and where do I put them in 12.04? I would have just upgraded but everything fell apart during the process.  I think I saved everything off the drive.  Now I'm trying to put it back together with 12.  Where can I find my bookmarks in 10.04, and where do I put them in 12.04?
Thanks

A: They should be here: .mozilla/firefox/xxxxxxxx.default/.
This xxxxx stuff is a random string of 8 characters.
If you don't see ".mozilla" folder in your old home folder you have to make nautilus to show you also hidden folders:
http://www.techheadz.co.uk/253.html

A: When this happen , i generally look for the config directory of firefox in the old home folder and copy it to the new , it usually is .mozilla/firefox.
1)backup your current .mozilla/firefox directory
2) erase you current .mozilla/firefox
3) copy the old one to the current one
4) test it via firefox
They're are other ways to do it but i found it the most easy one

A: Small guide for your situation by Mozilla:
http://support.mozilla.org/en-US/kb/back-and-restore-information-firefox-profiles
Which files have what data:
http://support.mozilla.org/en-US/kb/Recovering%20important%20data%20from%20an%20old%20profile#w_bookmarks-and-browsing-history


text:
Q: Rails has_many with an integer primary key and a string foreign key I have three rails objects: User, DemoUser and Stats. Both the User and the DemoUser have many stats associated with them. The User and Stats tables are stored on Postgresql (using ActiveRecord). The DemoUser is stored in redis. The id for the DemoUser is a (random) string. The id for the User is a (standard-rails) incrementing integer.
The stats table has a user_id column that can contain either the User id or the DemoUser id. For that reason, the user_id column is a string, rather than an integer.
There isn't an easy way to translate from the random string to an integer, but there's a very easy way to translate the integer id to a string (42 -> "42"). The ids are guaranteed not to overlap (there won't be a User instance with the same id as a DemoUser, ever).
I have some code that manages those stats. I'd like to be able to pass over a some_user instance (which can either be a DemoUser or a User) and then be able to use the id to fetch Stats, update them etc. Also would be nice to be able to define a has_many for the User model, so I can do things like user.stats
However, operations like user.stats would create a query like
SELECT "stats".* FROM "stats" WHERE "stats"."user_id" = 42
which then breaks with PG::UndefinedFunction: ERROR:  operator does not exist: character varying = integer
Is there a way to either let the database (Postgresql), or Rails do auto-translation of the ids on JOIN? (the translation from integer to string should be simple, e.g. 42 -> "42")
EDIT: updated the question to try to make things as clear as possible. Happy to accept edits or answer questions to clarify anything.

A: You can't define a foreign key between two types that don't have built-in equality operators.
The correct solution is to change the string column to be an integer.

In your case you could create a user-defined = operator for varchar = string, but that would have messy side effects elsewhere in the database; for example, it would allow bogus code like:
SELECT 2014-01-02 = '2014-01-02'

to run without an error. So I'm not going to give you the code to do that. If you truly feel it's the only solution (which I don't think is likely to be correct) then see CREATE OPERATOR and CREATE FUNCTION.

A: One option would be to have separate user_id and demo_user_id columns in your stats table. The user_id would be an integer that you could use as a foreign key to the users table in PostgreSQL and the demo_user_id would be a string that would link to your Redis database. If you wanted to treat the database properly, you'd use a real FK to link stats.user_id to users.id to ensure referential integrity and you'd include a CHECK constraint to ensure that exactly one of stats.user_id and stats.demo_user_id was NULL:
check (user_id is null <> demo_user_id is null)

You'll have to fight ActiveRecord a bit to properly constrain your database of course, AR doesn't believe in fancy things like FKs and CHECKs even though they are necessary for data integrity. You'd have to keep demo_user_id under control by hand though, some sort of periodic scan to make sure they link up with values in Redis would be a good idea.
Now your User can look up stats using a standard association to the stats.user_id column and your DemoUser can use stats.demo_user_id.

A: For the time being, my 'solution' is not to use a has_many in Rails, but I can define some helper functions in the models if necessary. e.g.
class User < ActiveRecord::Base
  # ...
  def stats
    Stats.where(user_id: self.id.to_s)
  end
  # ...
end

also, I would define some helper scopes to help enforce the to_s translation
class Stats < ActiveRecord::Base
  scope :for_user_id, -> (id) { where(user_id: id.to_s) }
  # ...
end

This should allow calls like
user.stats and Stats.for_user_id(user.id)

A: I think I misunderstood a detail of your issue before because it was buried in the comments.
(I strongly suggest editing your question to clarify points when comments show that there's something confusing/incomplete in the question).
You seem to want a foreign key from an integer column to a string column because the string column might be an integer, or might be some unrelated string. That's why you can't make it an integer column - it's not necessarily a valid number value, it might be a textual key from a different system.
The typical solution in this case would be to have a synthetic primary key and two UNIQUE constraints instead, one for keys from each system, plus a CHECK constraint preventing both from being set. E.g.
CREATE TABLE my_referenced_table (
   id serial,
   system1_key integer,
   system2_key varchar,
   CONSTRAINT exactly_one_key_must_be_set
     CHECK (system1_key IS NULL != system2_key IS NULL),
   UNIQUE(system1_key),
   UNIQUE(system2_key),
   PRIMARY KEY (id),
   ... other values ...
);

You can then have a foreign key referencing system1_key from your integer-keyed table.
It's not perfect, as it doesn't prevent the same value appearing in two different rows, one for system1_key and one for system2_key.
So an alternative might be:
CREATE TABLE my_referenced_table (
   the_key varchar primary key,
   the_key_ifinteger integer,
   CONSTRAINT integerkey_must_equal_key_if_set
     CHECK (the_key_ifinteger IS NULL OR (the_key_ifinteger::varchar = the_key)),
   UNIQUE(the_key_ifinteger),
   ... other values ...
);

CREATE OR REPLACE FUNCTION my_referenced_table_copy_int_key()
RETURNS trigger LANGUAGE plpgsql STRICT
AS $$
BEGIN
  IF NEW.the_key ~ '^[\d]+$' THEN
     NEW.the_key_ifinteger := CAST(NEW.the_key AS integer);
  END IF;
  RETURN NEW;
END;
$$;

CREATE TRIGGER copy_int_key
BEFORE INSERT OR UPDATE ON my_referenced_table
FOR EACH ROW EXECUTE PROCEDURE my_referenced_table_copy_int_key();

which copies the integer value if it's an integer, so you can reference it.
All in all though I think the whole idea is a bit iffy.

A: I think I may have a solution for your problem, but maybe not a massively better one:
class User < ActiveRecord::Base

  has_many :stats, primary_key: "id_s"

  def id_s
    read_attribute(:id).to_s
  end

end

Still uses a second virtual column, but maybe more handy to use with Rails associations and is database agnostic.


text:
Q: Server returns 404 for a web page, but page is showing fine in browser - why? A strange web page crossed my way. (And being a developer I have to solve the mystery.)
When accessing the web page in any browser, all seems normal. The web page is displayed as expected.
But when looking in the console the server acually returns a 404 status code:

So why is the browser rendering a page?
Looking at the Body shows valid HTML is returned:

Hold on. Responding 404 and sending the HTML along the way? And the browser renders it??
Why is this happening? Is this some server misconfiguration? Or is something clever going on here that I don't understand? Is there a practical reason for configuring a server on purpose to behave like this?

A: Another answer on Stack Overflow  contains some interesting information: A HTTP status code of 404 plus HTML response body is actually recommended by the spec.

The 4xx class of status code is intended for cases in which the
client seems to have erred.  Except when responding to a HEAD
request, the server SHOULD include a representation containing an
explanation of the error situation, and whether it is a temporary or
permanent condition.  These status codes are applicable to any
request method.  User agents SHOULD display any included
representation to the user.

This leaves me with two possible explanations:
Explanation 1: it's a server error.

*

*the server wrongly returns a 404 status code

*the browser thinks the response body contains details about the error and displays it - for the end user this is the actual page

Explanation 2: it's done on purpose to defeat crawlers and page watchers.

*

*the server returns 404 on purpose - non-browser user agents won't process the result as they interpret it as error

*browsers are unaffected, the end user doesn't care as long as the page is being displayed

The second one would indeed be kind of clever if you don't want your page to be indexed.

A: I faced with the same situation. My portal was hosted in a tomcat server. The portal was loaded when the host name along with the tomcat directory path was hit. But on loading the the webpage redirected to a deep-link URL and rendered the page. But if you hit the deep link URL directly in the browser it would give you 404 error in the network tab in Dev tools although the webpage would be rendered fine.
This happens because there is no resource as your deep-link URL anywhere in your server config files, so when it searches for the resource it doesn't find one and returns 404 in the network tab in Dev tools.
But browser behaves differently with the resource URL. It first loads and connects to the host name of the resource, when returned with success gets redirected as per the config files settings and renders the deep-link URL resource HTML, styling contents properly.

A: Note: I don't know whether this issue comes from me not being strict enough in the .htaccess or my CMS.
In my contrived .htaccess example I had the following rules to ignore these directories from being handled by the CMS.
RewriteCond $1 !^(branch|css|js|html|images) [NC]
I also had a branches directory inside my CMS' templates (created within CMS).  I guess my .htaccess rule wasn't strict enough here.  I had to change branch to branch\/, like so:
RewriteCond $1 !^(branch\/|css|js|html|images) [NC]
Only then would the page load without the 404 in the console.


text:
Q: Caterpillar Graphs Here is a problem I have been working on: Find a tree T containing exactly 3 vertices that are not end vertices such that T is not a caterpillar. I have been told that this is possible, but I am stuck; I am convinced that this is not possible. Here is my "proof":
Suppose there exists a tree T with three non-end vertices and T is not a caterpillar. Since T is not a caterpillar, removing the end vertices will not produce a path. So let's remove all end vertices and let the resulting graph be P. Notice that the graph P must contain only three vertices that were not end vertices. Since P is not a path, a vertex must be repeated. Notice that the graph P cannot be disconnected because trees are connected. Thus we have a connected graph of order 3 that is not a path. It cannot be a cycle because trees are a-cyclic. Such a graph P is nonsense, right?
Any help will be appreciated.

A: As pointed out by John Hughes your claim is correct. On the other hand, notice that such tree exists if the not end-vertices are MORE than 3.

The above tree has FOUR vertices that are not end-vertices, and, by removing the end-vertices (and the incident edges), we DO NOT obtain a path graph. Therefore it is not a caterpillar tree.

A: I don't, offhand, see anything wrong with your claim, but it's possible that you have mis-transcribed the original assertion --- that might be worth checking. I honestly don't know whether the assertion you think you've been asked to prove is true or not. (It appears false to me, but I haven't had a second cup of coffee yet.) But I can offer comments on what you've said.
As for your proof, there are a few rough bits. You write "Notice that the graph P must contain only three vertices that were not end vertices." I think what you mean is "Observe that, by hypothesis, $P$ contains exactly three vertices (the non-end vertices of $T$), and some number of edges."
"Since $P$ is not a path, a vertex must be repeated." That's vague. I think you might want to say "Because $P$ is not a path, ..." Actually, I think you might want to skip this sentence.
"Notice that $P$ cannot be disconnected": perhaps better to say "Observe that because $T$ is a tree, the graph $P$ is connected."
Then you can come back to the former point, and say "The only connected non-path graph on three vertices is a triangle." Now you know the structure of $P$ explicitly, and it contradicts your assumptions, so you're done.


text:
Q: Trying to install "Ubuntu Base" in Vmware but getting a kernel panic! Here is how I install Ubuntu Base in Vmware:
load the live media
sudo passwd root
su root

parted -a optimal /dev/sda

* mklabel gpt
* print
* remove remaining partitions.(if there are any).
* unit mib
* mkpart primary 1 512
* name 1 boot
* set 1 boot on
* mkpart primary 512 -1
* name 2 rootfs
* print
* quit

mkfs.fat -F 32 /dev/sda1
mkfs.ext4 /dev/sda2

mount /dev/sda2 /mnt

tar xvfz ubuntu-base-20.04.1-base-amd64.tar.gz -C /mnt

cp /etc/resolv.conf /mnt/etc/resolv.conf

mount --rbind /sys /mnt/sys
mount --rbind /proc /mnt/proc
mount --rbind /dev /mnt/dev

chroot /mnt
mount /dev/sda1 /boot

apt-get update
apt-get install --no-install-recommends grub-efi
apt-get install --no-install-recommends linux-image-5.4.0-48-generic
apt-get install --no-install-recommends initramfs-tools
apt-get install --no-install-recommends nano

nano -w /etc/default/grub
update-grub
grub-install --target=x86_64-efi --efi-directory=/boot

nano -w /etc/fstab
----
/dev/sda1            /boot      vfat    defaults,noatime 0 2
/dev/sda2            /          ext4    noatime 0 1
----

adduser l3gi0n
addgroup l3gi0n adm
addgroup l3gi0n sudo

passwd root

exit

reboot

I am getting this Kernel Panic: https://ibb.co/XFTKBtN
What did I do wrong ?


text:
Q: Hibernate ManyToOne FetchType.LAZY is not working? I am using spring 4.1.4.RELEASE + hibernate 4.3.6.Final, here is my entity code:
public class BaseEntity implements Serializable {
}

public class MarketInfo extends BaseEntity {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "id")
    private int id;

    @Column(name = "market_id", unique = true, length = 15)
    private String marketId;

    @OneToMany(fetch = FetchType.LAZY, mappedBy = "market")
    private List<MarketChannelGroup> channelGroups;

    public List<MarketChannelGroup> getChannelGroups() {
        return channelGroups;
    }

    public void setChannelGroups(List<MarketChannelGroup> channelGroups) {
        this.channelGroups = channelGroups;
    }

...
}

public class MarketChannelGroup extends BaseEntity {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "id")
    private int id;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "market_id", referencedColumnName = "market_id")
    private MarketInfo market;
...
}

From my test I can see the channelGroups in MarketInfo is working fine (if I don't call getChannelGroups(), then channelGroups is null), however if I call getChannelGroups(), the MarketInfo inside each MarketChannelGroup gets fetched, while this should not happen since market's fetch mode is FetchType.LAZY.
From console I do see the following hibernate log when I call its getter:
Hibernate: select channelgro0_.market_id as market_i5_12_1_, channelgro0_.id as id1_9_1_, channelgro0_.id as id1_9_0_, channelgro0_.channel_group_id as channel_2_9_0_, channelgro0_.channel_group_name as channel_3_9_0_, channelgro0_.channel_group_type as channel_4_9_0_, channelgro0_.market_id as market_i5_9_0_ from market_channel_group channelgro0_ where channelgro0_.market_id=?
Hibernate: select marketinfo0_.id as id1_12_0_, marketinfo0_.enable_flag as enable_f2_12_0_, marketinfo0_.enable_time as enable_t3_12_0_, marketinfo0_.market_id as market_i4_12_0_, marketinfo0_.market_name as market_n5_12_0_, marketinfo0_.stb_count as stb_coun6_12_0_ from market_info marketinfo0_ where marketinfo0_.market_id=?
Hibernate: select marketinfo0_.id as id1_12_0_, marketinfo0_.enable_flag as enable_f2_12_0_, marketinfo0_.enable_time as enable_t3_12_0_, marketinfo0_.market_id as market_i4_12_0_, marketinfo0_.market_name as market_n5_12_0_, marketinfo0_.stb_count as stb_coun6_12_0_ from market_info marketinfo0_ where marketinfo0_.market_id=?
Hibernate: select marketinfo0_.id as id1_12_0_, marketinfo0_.enable_flag as enable_f2_12_0_, marketinfo0_.enable_time as enable_t3_12_0_, marketinfo0_.market_id as market_i4_12_0_, marketinfo0_.market_name as market_n5_12_0_, marketinfo0_.stb_count as stb_coun6_12_0_ from market_info marketinfo0_ where marketinfo0_.market_id=?

could anyone help?
UPDATE
there is no optional method for ManyToOne annotation, so the solution in OneToOne doesn't work for my case.

A: Move the @OneToMany annotation from the declaration to the getter method, like this:
private List<MarketChannelGroup> channelGroups;

@OneToMany(fetch = FetchType.LAZY, mappedBy = "market")
public List<MarketChannelGroup> getChannelGroups() {
    return channelGroups;
}

A: How is your configuration archive? Look if you are using the filter OpenEntityManagerInViewFilter. If  you are using it, always that you call the method Lazy getChannelGroups() the hibernate will get fetch inside each element.

A: You have to take oneToMany annotation to getter if @id is on the getter. Lazy works but if you or some framework get the lazy property in that transction the get method fire the select.


text:
Q: filtering an array of objects that contains an array of objects confusing title let me explain.
I have an array of categories and array of products.
the array of products is an array of objects, one of the keys is categories, which itself is an array of objects and one of the keys im interested in is title.
the array of categories is an array of objects too.
I want to filter the products array to return me just the products for my chosen category (which is set in state)
I've got this, however it does not work:
filterCategories = () => {
    return this.state.products.filter((product => {
      return product.categories.map((cat) => {
        cat.title == this.state.chosenCategory
      })
    }))
  }

this method seems like it should. to my knowledge, im filtering the products array by mapping over each product and then mapping over that products categories and checking if the category title is equal to the title in state. clearly I've gone wrong somewhere. can anyone see it?
sample data:
products = [
 {
  id: '123',
  title: 'wine',
  categories: [
   {title: 'drinks'}
  ]
 }
]

categories = [
   {
  id: '123',
  title: 'drinks'
 }
]

A: It looks like you want to test whether any of the category titles match the chosenCategory: so, use the some method. Also, even better, if you're sure there's exactly one matching category, use .find instead of filter. Also make sure to return a value at the end of the internal function (which you aren't doing currently), or use an arrow function with implicit return:
filterCategories = () => (
  this.state.products.find((product) => (
    product.categories.some(({ title }) => (
      title === this.state.chosenCategory
    ))
  ))
)

A: Filter callback function is a predicate, to test each element of the array.  you are not returning anything from the inner map function too, you must instead have a filter there like
filterCategories = () => {
    return this.state.products.filter((product => {
      return product.categories.filter((cat) => {
        return cat.title == this.state.chosenCategory
      })
    }))
  }


text:
Q: first character count navigation with Oracle: count queries dont't use functional indices Oracle 9i. We have a large table (~1M rows) containing our content that carries title and author columns. We'd like to write views that offer an A-Z navigation for titles and authors to that content ( A:1300, B:45000,...)
First some preparation without any indexing:
select * from content where substr(upper(title),0,1) = 'M'

performs a little better than
select * from content where upper(title) LIKE 'M%'

ExPlan for those:
TABLE ACCESS content FULL Cost=1624

both are pretty fast even without any indices. Now the slow part:
select count(*) from CONTENT WHERE substr(upper(TITLE),0,1) = 'A';

ExPlan:
SORT AGGREGATE else like above.

Now the cumulation (this is what we want, it's really slow):
select substr(upper(title),0,1) , count(*) from content group by substr(upper(title),0,1);

ExPlan:
SORT: GROUP BY COST=8069 / TABLE ACCESS on CONTENT FULL COST=1624

So I started creating a functional index:
create index CONTENT_TITLE_LETTER_IDX on CONTENT(substr(upper(TITLE),0,1));

This speeds up the single letter count query dramatically:
select count(*) from CONTENT WHERE substr(upper(TITLE),0,1) = 'A';

ExPlan (it responds nearly in realtime):
SORT AGGREGATE COST=1 / INDEX CONTENT_TITLE_LETTER_IDX RANGE SCAN COST=1

But the cumulation query which is basically querying the same thing is not using the index (it shows the same Explain Plan as above). I tried the hint:
select /*+ index(CONTENT CONTENT_TITLE_LETTER_IDX) */ substr(upper(title),0,1) , count(*) from content group by substr(upper(title),0,1);

but it still is very slow. I assume that this might be due to the unordered index but I'd guess that even if I ran a loop around all 26 possible letters the single query ( = 'letter' ) would be faster!
Who knows how to tell Oracle to use that index (or an alternative way besides creating one-char columns or tables) ?

A: Take another look at your query:
select substr(upper(title),0,1) , count(*)
from content
group by substr(upper(title),0,1)

Note the absence of any where clause. In fact, you tell the database engine to take all rows and count how many rows there is for each initial letter. You cannot skip any row because else you can't count it. I don't think the index stores such information readily, so a full scan is the fastest you can have. If you asked for a specific letter, using a range scan on the index could make sense.
If you need this information often, create a summary table which would be updated by triggers on your main table.

A: Ok, this answers the question but doesn't really solve the problem (thanks Gerrat, we're nearly same time):
I had a look at this interesting question that told me that the CBO might reject indices containing NULL values. Taking into account that our table contains title that start with non-alpha characters and blanks (but never are null...) I tried the following:
select   substr(upper(title),0,1), count(*)
from content
 where substr(upper(title),0,1) >= 'A' AND substr(upper(title),0,1) <= 'Z'
group by substr(upper(title),0,1);

which dramatically decreases the costs:
SORT GROUP BY NOSORT COST=16 / CONTENT ACCESS BY INDEX ROWID COST=6 / CONTENT_TITLE_LETTER_IDX RANGE SCAN COST=2

from 8069 to 16
interestingly that conditioned query now even is slower (avg 2.7s) than the non-conditioned one (avg 1.5s). Adding more conditions as stated by 9000 dramatically speeds things up - even though it doesn't use the letter index at all. Thanks for that
insight!

A: I can't promise you this will be faster, but you could try:
select /*+ index(CONTENT CONTENT_TITLE_LETTER_IDX) */ substr(upper(title),0,1),
count(*) from content
where substr(upper(title),0,1) in ('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H',
'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W',
'X', 'Y', 'Z')
group by substr(upper(title),0,1);

On a similar test I did, this did use the index (nothing else I tried did), but the cost was actually higher than the full table scan).
Make sure your table and index are analyzed as well.


text:
Q: Unable to Insert Data into MySql Table using username from another $_POST function     echo "Hello : ".$_SESSION['doc_username'];

    //username sent from a different page by post method

    $username = $_POST['username'];

    echo "
Showing Health Information for : ";echo $username; "
";

    if($_POST['submit'])
    {

    $height = mysql_real_escape_string($_POST['height']);
    $weight = mysql_real_escape_string($_POST['weight']);

if($height && $weight)
{
    require "dbc.php";
    $query = mysql_query("UPDATE patient_info SET
    height='$height',weight='$weight' WHERE username='$username'");
    echo "Patient Data Saved!";
}
 else
{
    echo "All fields are required!";
}

The problem with this code is not in the mysql query. I have already checked it for syntax errors using phpcodechecker and there was none. There were more variables to be inserted into the database but height and weight will do for example. My problem is I am getting the username from a different page by POST method and I cannot save it in a way that it could be used by the "submit" value in this form to enable updating of that particular username. Because the username from the other form which $username cannot be referred to within the $_POST in this page, thus the username variable is blank when I click the submit button. How can I get a username sent from another page to this page by POST to be used in this form in the UPDATE query. The form does send the username to this page successfully which is proven when I can echo the username out. But it cannot be used by the form in this page. Please help as I am very new to PHP codes and I'm trying the best that I can.

A: On the initial page, add a hidden form element named "username" with the value you want to carry over into the form submission.
<input type="hidden" name="username" id="username" value="the.user.name">

A: You may store user name in session on request when it passed, or add to getparam of request or in hidden element of form:
<form action="procces.php?username={real_user_name}">

OR
<form>
   <input type="hidden" name="username" id="username" value="{real_user_name}"/>
   ...
</form>

A:  <input type="text" name="username" value="<?php echo $_POST['username']; ?>" />

The username in first page was transferred to another paged where you can edit it
As second page also contains a form so we also need to add username field int as when it will be posted the username will also be sent.
This had to be inserted into the 2nd form to retain the data sent from the previous in the previous page so that it can be used for the query in mysql.

A: First of all replace the line:
From:
if($_POST['submit'])

to:
if (isset($_POST['submit']))

If you are using a combobox then check that you have provided the name parameter in its markup like:
<select name="submit">
...
</select>

[EDIT]

After analyzing the code it is found that the HTML markup
  was written after form element. I think this is the issue. Rest
  appears to be Ok.

Hope this will solve the issue.

A: You may the user name in the session (supposed you have one, if not, you seriously should anyway):
Populating a form field like @tslocum suggested also needs to get the user name from somewhere. This is a quite common solution, but where does the user name come from?
There might be some time between submitting the name and rendering the current page, so as this is stateless but you need a state (State "we have a given username already") within that page during rendering and processing, take a look at $_SESSION global variable.
my approach:
Post 1:
....
$_SESSION['currentUser'] = $_POST['username'];
// you need some checks over here, don't use
// that as typed here, left out just for clearness.

... some time
Post 2:
...
$username = $_SESSION['currentUser'];
// again some checks over here!

read about $_SESSION in the php manuals.


text:
Q: how to convert multiple rows to single row? How to get sql with Query
I have three tables in the form below
Table A
ID  | Title   |Count
--- |-------- |-----
1   |Mouse    | 50
2   |pen      | 60

Table B
ID  | CompName|
--- |---------|
1   |Comp1    |
2   | Comp2   |
3   |Comp3    |

Table T
|---------------------|
|IDA    | IDB | CountT|
|-------|-----|-------|
|1      |   1 |  5    |
|2      |   1 |  6    |
|1      |   2 |  7    |
+---------------------+

I want to make such a report
| object | Copm1 | Comp2 | Comp3 |Sum|remaining |
|--------|-------|-------|-------|---|--------- |
| Mouse  | 5     | 7     | 0     | 12| 38       |
| pen    | 6     | 0     | 0     | 6 | 54       |

My answer to my question
I was able to get the final answer using the PIVOT function
DECLARE   @SQLQuery AS NVARCHAR(MAX)
DECLARE   @PivotColumns AS NVARCHAR(MAX)
SELECT   @PivotColumns= COALESCE(@PivotColumns + ',','') +
   QUOTENAME(CompName) from B

 set @SQLQuery=N'select pvt.title as object, ' +   @PivotColumns + '
 FROM
 (select title, CountT,CompName
 from T
  inner join A on T.IDA = A.ID
  inner join B  on   B.ID = T.IDA) AS src PIVOT
  (
 max(CountT)
 FOR CompName IN (' + @PivotColumns + ')
 ) AS pvt;'
 EXEC sp_executesql @SQLQuery

A: select a.title as object,
    sum(case when b.id=1 then T.countT else 0 end) as Comp1,
    sum(case when b.id=2 then T.countT else 0 end) as Comp2,
    sum(case when b.id=3 then T.countT else 0 end) as Comp3,
    sum(t.countt) as 'Sum',
    max(a.count)-sum(t.countt) as Remaining
 from TableT t
    inner join tableA A on a.id=t.IDA
    inner join TableB b on b.id=t.IDB
    group by a.Title

http://rextester.com/l/sql_server_online_compiler


text:
Q: How to run Apollo Graphql Prisma migrate deploy in Dockerfile Normally duration development I run
yarn prisma migrate dev

Now I create Docker image and run there service using docker-compose.
I have no idea where I put yarn prisma migrate deploy command in Dockerfile.
Dockerfile
FROM node:17 AS BUILD_IMAGE
WORKDIR /usr/src/app
COPY ["package.json", "yarn.lock", "tsconfig.json", "./"]
COPY ["./prisma/schema.prisma", "./prisma/"]
RUN yarn --frozen-lockfile
RUN yarn prisma generate
COPY . .
RUN yarn build
#RUN yarn install --production
RUN yarn autoclean --force

FROM node:17-alpine
ENV NODE_ENV=production
WORKDIR /usr/src/app
COPY --from=BUILD_IMAGE /usr/src/app/dist ./dist
COPY --from=BUILD_IMAGE /usr/src/app/node_modules ./node_modules
EXPOSE 4000
CMD [ "node", "dist/server.js" ]

A: I use docker for development, and I have done that using the CMD on my Dockerfile, here you go my configuration:
FROM node:16.5.0-alpine
WORKDIR /app
EXPOSE 3000
COPY . .
RUN npm i
ADD https://github.com/ufoscout/docker-compose-wait/releases/download/2.5.0/wait /wait
RUN chmod +x /wait
CMD /wait && cd selling-point-db && npm i && npx prisma migrate dev && npx prisma db seed && cd .. && npm run start:dev


text:
Q: How to load Custom Template file in Wordpress running on WAMP Server? I have used custom template file for invoices in woocommerce orders but the invoice pdf containing custom template does not load rather on clicking the button the page redirects to the bitnami home page and does not load the custom template. How can I fix this issue in localhost?

A: To change the invoice content in woocommerce you can create the same file and put in woocommerce folder in current theme File path should be  same as like that exist in woocommerce plugin folder for invoice template .
Otherwise you can also use the invoice hooks to generate the custom invoice
Thanks


text: Q: How do I copy only 20170906.1 from the text file by using batch file Hi I wanted to Copy only 20170906.1 from the demo.txt file which contain \tfs-server\TFSBUILDS\OB-MAINMVC2.0\OB-MAINMVC2.0_20170906.1\_PublishedWebsites\In.OfficeBox.Api.Task\bin and keep it in another txt file whether 20170906.1 is dynamic value it will change every day how do I get value after _ and before \


text:
Q: Background color for UIActivityIndicatorView I am using UIActivityIndicatorView to showing user that there is something going on, let them wait. But UIActivityIndicatorView looks small, do not have background color, and not very obvious to the user. While in iPhone SDK's UIImagePickerController, it uses the similar mechanism, but with the black background as well as some text besides the indicator.
I am wondering whether there is any existing component to do that task, or I have to implement my own class to perform that task.
Any suggestion are highly welcome, thanks in advance.

A: Try this simple method, Its working well for me....
UIActivityIndicatorView *activityIndicator= [[UIActivityIndicatorView alloc]initWithFrame:CGRectMake(0, 0, 50, 50)];
activityIndicator.layer.cornerRadius = 05;
activityIndicator.opaque = NO;
activityIndicator.backgroundColor = [UIColor colorWithWhite:0.0f alpha:0.6f];
activityIndicator.center = self.view.center;
activityIndicator.activityIndicatorViewStyle = UIActivityIndicatorViewStyleGray;
[activityIndicator setColor:[UIColor colorWithRed:0.6 green:0.8 blue:1.0 alpha:1.0]];
[self.view addSubview: activityIndicator];

Add following lines while load your view
//-- Add this line while processing to load your view
    [activityIndicator startAnimating];

//-- Add this line when after you view loaded
    [activityIndicator stopAnimating];

A: Seems I still have to create a separate view, because the indicator will be automatically enlarged if I enlarge the frame.
Thanks.

A: If you just want a different background color of your UIActivityIndictatorView, you could just send the setBackgroundColor message to the object, i.e.:
[activityIndicator setBackgroundColor:[UIColor blackColor]];

By the way, you can change the size of the indicator as well. just do setFrame or initWithFrame with a bigger rect. Remember UIActivityIndicatorView inherits from UIView so you get all the customization of UIView.


text:
Q: Storing values in gdb while debugging I am debugging a program and find myself doing this all the time
(gdb) p edges[i]
$9 = (std::pair<int, int> &) @0x7ffff427b790: {first = 26349, second = 25679}
(gdb) p nodes[26349].parent
$10 = 25679

what I would like to do is something like
(gdb) v = edges[i]
(gdb) p nodes[v.first].parent
$11 = 25679

The variable v is only a short hand notation/alias for edges[i]. Is something like this possible?

A: Figured it out. This is called convenience variables in gdb and has the following syntax:
(gdb) set $v = edges[i]
(gdb) p nodes[$v.first].parent
$11 = 25679

The line which reads $11 = 25679 stores also stores the last value in a convenience variable so you can do p $11. Nifty


text:
Q: how to write a relation with three parameters I want to write a relation in prolog which take three arguments.
Based on the first and second argument, the value should be assigned to the third argument.
for ex:
CctypeInt is 0..2
relation(CctypeInt,[0-{2,3,4}, 1-{2,3}, 2-{2}],Ru1)
If CctypeInt value is 0 then {2,3,4} shall be assigned to Ru1
If CctypeInt value is 1 then {2,3} shall be assigned to Ru1
If CctypeInt value is 2 then {2} shall be assigned to Ru1
second argument in the list indicates for wchich CCtypeInt value the corresponding list should be assigned.
How can we define a relation with the above behaviour.

A: relation(CctypeInt,List,Ru1) :-
    member(CctypeInt-Ru1,List).


text:
Q: Update R-tree to insert after query I would like to use the GEOS R-tree implementation to store the items of a growing structure.
However, I also need to query from the tree during the growth process to make sure that growing substructures do not overlap.
This means that I need to alternatively query from and insert to the tree.
However, qerying from GEOS R-tree triggers the build function, and inserting to a "built" tree is forbidden.
My question is therefore "is there a way around this?".
From my (limited) understanding of R-trees, this should be possible: there are supposed to support this kind of dynamic update without having to be rebuilt from scratch, so how can I do that with GEOS?
I've seen nothing in the C-API, and not much more than the cause of my problem:
// Cannot insert items into an STR packed R-tree after it has been built
assert(!built);

A: Code comments from JTS (from which GEOS is ported) summarize the R-tree implementation (and its design tradeoffs) as follows:

The STR packed R-tree is simple to implement and maximizes space
  utilization; that is, as many leaves as possible are filled to
  capacity. Overlap between nodes is far less than in a basic R-tree.
  However, once the tree has been built (explicitly or on the first call
  to #query), items may not be added or removed.

GEOS provides a Quadtree implementation that can be used when dynamic behavior is required, but it is not accessible through the GEOS C API.
Perhaps libspatialindex or boost::geometry would have an implementation that meets your needs.


text:
Q: How can I gracefully handle a Kafka outage? I am connecting to Kafka using the 0.8.2.1 kafka-clients library. I am able to successfully connect when Kafka is up, but I want to handle failure gracefully when Kafka is down. Here is my configuration:
kafkaProperties.setProperty(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, kafkaUrl);
kafkaProperties.setProperty(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringSerializer");
kafkaProperties.setProperty(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringSerializer");
kafkaProperties.setProperty(ProducerConfig.RETRIES_CONFIG, "3");
producer = new KafkaProducer(kafkaProperties);

When Kafka is down, I get the following error in my logs:
WARN: 07 Apr 2015 14:09:49.230 org.apache.kafka.common.network.Selector:276 - [] Error in I/O with localhost/127.0.0.1
java.net.ConnectException: Connection refused
at sun.nio.ch.SocketChannelImpl.checkConnect(Native Method) ~[na:1.7.0_75]
at sun.nio.ch.SocketChannelImpl.finishConnect(SocketChannelImpl.java:739) ~[na:1.7.0_75]
at org.apache.kafka.common.network.Selector.poll(Selector.java:238) ~[kafka-clients-0.8.2.1.jar:na]
at org.apache.kafka.clients.NetworkClient.poll(NetworkClient.java:192) [kafka-clients-0.8.2.1.jar:na]
at org.apache.kafka.clients.producer.internals.Sender.run(Sender.java:191) [kafka-clients-0.8.2.1.jar:na]
at org.apache.kafka.clients.producer.internals.Sender.run(Sender.java:122) [kafka-clients-0.8.2.1.jar:na]
at java.lang.Thread.run(Thread.java:745) [na:1.7.0_75]

This error repeats in an infinite loop and locks up my Java application. I have tried various configuration settings related to timeouts, retries, and acknowledgements, but I have been unable to prevent this loop from occurring.
Is there a configuration setting that can prevent this? Do I need to try a different version of the client? How can a Kafka outage be handled gracefully?

A: I figured out that this combination of settings allows the kafka client to fail quickly without holding the thread or spamming the logs:
kafkaProperties.setProperty(ProducerConfig.METADATA_FETCH_TIMEOUT_CONFIG, "300");
kafkaProperties.setProperty(ProducerConfig.TIMEOUT_CONFIG, "300");
kafkaProperties.setProperty(ProducerConfig.RETRY_BACKOFF_MS_CONFIG, "10000");
kafkaProperties.setProperty(ProducerConfig.RECONNECT_BACKOFF_MS_CONFIG, "10000");

I dislike that the kafka client holds the thread while trying to connect to the kafka server, rather than being fully async, but this at least is functional.

A: In the 0.9 client, there's also the max.block.ms property, which will limit the time the client is allowed to run.


text:
Q: Axiom of Choice, Meaning and Use of it
*

*Concerning the undecidability of an assertion ( a theorem ) in mathematics, can somebody give an example and thus prove that a theorem is undecidable ? I will then higly appreciate showing the procedure of using the axiom of choice to prove that only by using the axiom of choice the theorem in question could be proven. Can somebody also give the example of an undecidable theorem which is proven to be so but for which there is still no axiom of choice which could prove the theorem ?

*I was reading recently in a book that every undecidable question creates a bifurcation and imposes a choice. It then gives the example of P. Cohens theorem on the continuum hypotheses which, according to the book, leads to a bifurcation: we have to choose either there are no cardinals between the countable and the continuum or that there are 36 of them. The first choise is then made because of simplicity (according to the book).
What i dont understand here is: how one proceeds from the simple definition of the choice function and axiom of choice in the set-theoretical context to the assertion of such choices as mentioned above for which you would hardly see the intervention of the axiom of choice as we define it usually ?

Many thanks for your comments.

A: A theorem cannot be "undecidable" on its own; undecidability is a relationship between a theorem and a particular set of axioms. So asking for an "undecidable theorem" is like hearing about an equivalence relation and asking for an example of an "equivalent element".
Once we pick a particular set of axioms, then we can ask what theorems are undecidable from those axioms. For example,

*

*The axiom of choice is undecidable from the axioms of Zermelo-Fraenkel set theory.

*The continuum hypothesis is undecidable from the axioms of Zermelo-Franekel set theory with the axiom of choice (ZFC).

*Similarly, the existence of an inaccessible cardinal number is undecidable from the axioms of ZFC set theory (including the axiom of choice).

*The Paris-Harrington principle is undecidable from the axioms of Peano Arithmetic
There is a general result, Gödel's incompleteness theorem, which shows that all sufficiently strong systems of true axioms will have undecidable theorems. The examples above, though, are not the ones that are produced from the incompleteness theorems (not directly, at least).
The notion of "choice" in your book is not related to the sense of "choice" in the axiom of choice. The book is just saying that, if a theorem is undecidable from a set of axioms, we can decide whether we would like to add the theorem as an axiom, or whether we prefer to add its negation, and either will leave us with a consistent set of axioms.
This does not mean, though, that both the theorem and its negation are always equally acceptable. For example, many of our standard axioms are undecidable from the other axioms, but that does not suggest we should add the negations of these axioms instead (e.g. the negation of the axiom of choice is not a particularly useful axiom to add to ZF).
So the question becomes: what evidence or argument is there for accepting a new axiom, or for rejecting it?
For example, although the axiom of choice is undecidable in ZF set theory, it it standard to use it as an axiom in undergraduate mathematics. On the other hand, the continuum hypothesis is also undecidable in ZF set theory, but we don't usually take it as an axiom.  This is because the argument for taking the axiom of choice as an axiom, historically, has been broadly accepted by the mathematics community (although not universally), while the argument for taking CH as an axiom has not been accepted to nearly the same extent.


text:
Q: How can I get an sqlite3.Row-like row factory using mysql-connector-python? I want to make it clear that what I'm asking for is not just to get a dictionary, I know that can easily be done with cursor = cnx.cursor(dictionary=True). sqlite3's sqlite3.Row is special in that it can be accessed with both keys and indexes, like so:
cursor.execute("SELECT somestuff FROM sometable WHERE somecolumn = 'somevalue'")
print(cursor.fetchone()[0])
print(cursor.fetchone()['somestuff'])

Is it possible to do this with mysql-connector-python, preferably in some officially supported way, like in sqlite3?


text:
Q: Qt - Why can't I trigger mousePressEvent for my custom button in MainWindow This is my first time to ask on Stack Overflow. If any suggestion about asking question, please let me know.
I am very new to Qt, and have some problems while using event. Hope someone can provide any thoughts.
Background:
I have my custom pushButton, which is rxPushButton in rx.h and rx.cpp. I use on_rxPushButton_clicked to change the image and it works pretty well.
In MainWindow, I need to use some rx so I include the class rx and I want to detect if I press left button of the mouse, I need to know which rx has been pressed and record its id in int rxId in MainWindow.
Problem:
I tried two ways to achieve my goal, including mousePressEvent and eventFilter. I found that I can't detect the mouse pressed signal on any rx, but I can detect it outside rx in other places in Mainwindow. I wonder if the events will conflict, but when I comment on_rxPushButton_clicked in rx.cpp, MainWindow still doesn't work for the problem. So I presume that maybe the space in the screen occupied by rx will not be in control of MainWindow (I can get Debug message "test1" but not "test2" in my code, check below).
How should I do to solve this problem if I need both things (change image in rx and modify one variable in MainWindow)? Or maybe it's just something wrong with my code and how to modify?
I hope to separate them if possible because I still need to include many objects in MainWindow in the future.
Here are some of my related codes:
rx.cpp
void rx::on_rxPushButton_clicked(void)
{
    startLoading();
}

void rx::startLoading(void)
{
    state = 1;
    connect(timer, SIGNAL(timeout()), this, SLOT(loading1()));
    timer->start(LOADING_INTERVAL);
}

void rx::loading1(void)
{
    if(state == 1)
    {
        state = 2;
        ui->rxPushButton->setStyleSheet("border-image: url(:/images/Rx/Rxloading1.png);");
        disconnect(timer, SIGNAL(timeout()), this, SLOT(loading1()));
    }
}

mainwindow.cpp
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    for(int i = 0 ; i < rxSize ; i++)
    {
        rxList << new rx(this);
        int j = i/rxHorizontalCount;
        rxList[i]->setGeometry(500+(i-j*8)*110,10+j*90,100,90);
    }
    //rxList[0]->installEventFilter(this);
}

void MainWindow::mousePressEvent(QMouseEvent *event)
{
    if(event->buttons() & Qt::LeftButton)
    {
        qDebug() << "test1";
        if(rxList[0]->rect().contains(event->x(), event->y()))
            qDebug() << "test2";
    }
}

A: Event propagating prevent you to do it. When mouse is over Button, event sends to button, not to the MainWindow, thats why you never see test2 in debug output.
Since I don't know what do you need it's hard to say what you should do. You can process event in Button and send some signals or whatever, or set event filter and check if target object is your button, and so on.
Any way, read Qt event system docs for better understanding.

A: Change image in rx
Use QSignalMapper class  that bundles signals from QWidgets (class rx) and re-emits them with widget (class rx) parameters corresponding to the object that sent the signal.
We connect each button's clicked() signal to the signal mapper's map() slot, and create a mapping in the signal mapper from each button to the button itself.
Finally we connect the signal mapper's mapped() signal to the custom widget's(rx object) clicked() signal. When the user clicks a button, the custom widget(rx object) will emit a single clicked() signal whose argument is the button (rx object) the user clicked.
Handle the button clicked event in MainWindow::slotButtonsClicked(QWidget *p) function.
Modify n variable in MainWindow:
You can update variable of MainWindow in mousePressEvent function
class MainWindow : public QWidget
   {
    public :
        MainWindow (QWidget *parent);

        QSignalMapper * mapper;

    slots:
        void slotButtonsClicked(QWidget *);

    // ...
}

MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    mapper = new QSignalMapper(this);

    for(int i = 0 ; i < rxSize ; i++)
    {
        rxList << new rx(this);
        int j = i/rxHorizontalCount;
        rxList[i]->setGeometry(500+(i-j*8)*110,10+j*90,100,90);
        QObject::connect(rxList[i], SIGNAL(clicked()),mapper,SLOT(map()));

        //Adds a mapping so that when map() is signalled from the sender, the signal mapped(widget ) is emitted.
        mapper->setMapping(rxList[i], rxList[i]);
    }

    QObject::connect(mapper,SIGNAL(mapped(QWidget *)),this,SLOT(slotButtonsClicked(QWidget *)));
}

void MainWindow::mousePressEvent(QMouseEvent *event)
{
    if(event->buttons() & Qt::LeftButton)
    {
        qDebug() << "Clicked outside the button";

        //Now you can modify n variable in MainWindow
    }

    MainWindow::mousePressEvent(event);
}

void MainWindow::slotButtonsClicked(QWidget *p)
{
    rx *button = dynamic_cast<rx *>(p);
    button->on_rxPushButton_clicked();

    qDebug() << button <<" clicked on button";

    //Now you can change image in rx
}

Hope this works :)


text:
Q: Drupal: Exporting current content into editable format We need to export all of the content from a current Drupal website into an editable format (XML, XLS, etc.)  so that the content can then be translated into a different language.
Is there a clean way to do this?

A: Check out the Node Export module. It appears you can also do it with Drush.
This post https://drupal.stackexchange.com/questions/63055/how-to-export-nodes-as-xml has some detailed info on exporting nodes to XML from both command line and using the GUI. Both answers are worth reading depending on which approach you choose to take.


text:
Q: dynamic css grid | height doesn't apply to second row I want to create a dynamic grid.
this is my current css. What am i missing that the row hight is not applied to the second row?
.container{
    display: grid;
    grid-template-columns: repeat(auto-fill, 170px);
    grid-template-rows: repeat(auto-fill, 300px);
}

html:

       css

      html


text:
Q: How technically different is Parasitic Constructor Pattern from Factory Pattern Parasitic Constructor Pattern can be seen as a combination of factory and constructor pattern.
In factory pattern, we call a function which then explicitly creates an object and adds desired properties and methods to the object and finally returns the object.
function createPerson(name, age, job){
    var o = new Object();   //explicit object creation
    o.name = name;
    o.age = age;
    o.job = job;
    o.sayName = function(){
            alert(this.name);
        };
    return o;
}

var person1 = createPerson("Nicholas", 29, "Software Engineer");
var person2 = createPerson("Greg", 27, "Doctor");

Things to note:

*

*explicit object is created and returned

*method and properties are added to the explicitly created object

*method is called without new keyword

The disadvantage: it doesn't allow to identify the type of the object.
Any function can be treated as constructor by calling it with new operator. When called without new operator, inside the function, this object points to the global object (window in browser).  And when the function is called with the new operator, it first creates the new instance of object and then sets this object to a newly created object.
Constructor pattern adds methods and properties to this object and finally returns this object thus allowing to later identify the type of the object using instanceOf operator.
function Person(name, age, job){
    this.name = name;
    this.age = age;
    this.job = job;
    this.sayName = function(){
            alert(this.name);
        };
    }

    var person1 = new Person("Nicholas", 29, "Software Engineer");
    var person2 = new Person("Greg", 27, "Doctor");

Things to note:

*

*function is called with new operator (to make JavaScript engine treat it as a constructor)

*object is not created explicit instead this object is returned

Now the Parasitic  Constructor Pattern explicitly creates and returns an object similar to factory pattern and it is called with new operator like constructor pattern:
function Person(name, age, job){
    var o = new Object();
    o.name = name;
    o.age = age;
    o.job = job;
    o.sayName = function(){
            alert(this.name);
        };
    return o;
}

var friend = new Person("Nicholas", 29, "Software Engineer");
friend.sayName(); //"Nicholas"

However I can't see the use of calling the function with new operator. I mean since the function explicitly creates and returns the object we will not be able to identify the object type explicitly using instanceOf operator.
So what is great in Parasitic Constructor pattern? Is there any technical subtlety that can be exploited or suitably used for a specific object creation scenario? Or Is just another possible programmatic approach for creating object?

A: I think the part that you're skipping over with the Factory, is that in most other languages, the factory is either going to be making multiple different kinds of similar objects, whether done like:
var truck = carFactory("Truck");
var jeep  = carFactory("Jeep");

or done like:
var piano = instrumentFactory.piano("Grand");
var bass  = instrumentFactory.bass("Upright");

or any other interface you want it to have...
OR a factory's responsibility is going to be to make a very big class out of smaller classes, through dependency-injection, and potentially polymorphism:
function createTank (gunType) {
    var armour = new Armour();
    armour.hp  = 120;

    var wheels = new ChainTracks();

    var driver = new Soldier();
    driver.hp  = 15;

    var gun = gunFactory(gunType);

    var tank = new Tank(armour, wheels, gun);
    tank.driver = driver;

    return tank;
}

var ground_tank = createTank("cannon");
var aa_tank = createTank("flak_cannon");
var at_tank = createTank("depleted_uranium_lancer");

If you have a Factory which is as simple as making an object, setting its properties and returning the object, then there really is no difference.
The differences come into play when you're either talking about using a lot of specialized components to make something come together (whether they're injected, or hard-coded), or you're dealing with inheritance.
And honestly, I'd suggest learning more about those things (object composition and inheritance), before looking too much further at different ways of doing them.
Because ultimately, it doesn't make any difference to the finished code, if you used a factory, or if you used a function which modified a generic object, or if you just used a whole lot of classes in the middle of your code...  The program will run great, or will die, any way you slice it.
Where it does make a difference is in how you organize your code, and how you compose your code.
You don't really need a factory if all you're doing is making a button on the page.
If you're making a full-featured MP3 player on your page, which needs 6 buttons, a play-list, a progress-bar and a display for track name, artist name and cover art...
...NOW is a great time to start looking into factory patterns for figuring out how to put those pieces together, to ask for one thing, and have it spit out the finished product, off the assembly line.

A: I think from your perspective there isn't much of a difference, but if you go one step further and implement the abstract factory pattern, or you start to polymorph your factories, you can save a lot of work every time you write a new one.
In javascript, since you can set any value to an object because the language doesnt have private values, factories can be verry powerfull and inherit most of its logic from base-classes if you work with a framework that supports OOP standarts for objects.
EDIT
Ok, one thing, in my eyes one of the most important when it comes to JavaScript and those patterns, is prototyping.
prototyping is basicly the way you define objects in javascript so the runtime actually recognizes the object and can tell it apart from other objects.
basicly only using prototypes looks like this:
var Person = function(name){
    this.name = name
}; //constructor
Person.prototype.constructor = Person;
Person.prototype.name = 'Dave';
Person.prototype.getName = function() {
    return this.name;
}

some test code:
var dave = new Person('Dave');
console.log(dave.getName());

and finally a factory:
var PersonFactory = function(name) {
    return new Person(name);
}

Now the problem with that anotation usually is that it is poorly maintainable and it features no inheritance.
Now comes what most frameworks to:
You can create helper functions building up your prototypes and even build a prototype chain. basicly you define an object that takes in another object and it resolves the other objects members into the prototypes of the desired class object, leaving open all sorts of possibilitys for inheritance etc.
some examples can be found here:
http://www.ruzee.com/blog/2008/12/javascript-inheritance-via-prototypes-and-closures
i like the way mootools handles classes:
var MyClass = new Class({
Extends: MyOtherClass
Implements: [MyInterface, MyOtherInterface],

myPublicValue: null,
myOtherValue: null,

initialize: function() {
    //constructor
},

doStuff: function() {
    return 'stuff done';
}

});

Drawbacks of the mootools class system itself:
-Closure Compiler doesnt like trailing commas, you tend to leave them in your code
-Allmost no IDE supports autocompletion for mootools classes (because the prototypes arent
annotated in a file, could be resolved using scripts to resolve your classes into prototyped files)
Now with this there are tons of design desicions you could go for, let your factories inherit from your own prototype helper class, using the prototype helper class to create the actual factory (some recursion in here), you could resolve each object on its creation (lazy loading like) or resolve every class object on page load (be carefull, if you go into inheritance, in most implementations of it classes you derive from must be resolved first)
or go any way possible.
i hope that helped out :)
(and sorry for my bad english right now, im pretty tired tonight xD)


text:
Q: Fixing an issue with video overlapping in Chrome When animating a fullscreen video background, I found that if two <video> tags overlap, while translated with a transform, in Chrome on OSX, the one under becomes darker. It's working perfectly in other browsers and on Chrome for Windows.

video {
  width: 640px;
  height: 320px;
  display: block;
}

.top {
  position:relative;
  transform: translate(0,0);
  transition: transform 1s ease;
}

.bottom {
  position:relative;
  transform: translate(0,10px);
  transition: transform 1s ease;
}

.over:checked ~ .top {
  transform: translate(0, 10%);
}
Over <input class="over" type="checkbox">
<video class="top" src="http://techslides.com/demos/sample-videos/small.mp4" autoplay loop></video>
<video class="bottom" src="http://techslides.com/demos/sample-videos/small.mp4" autoplay loop></video>

I've recreated the issue here: https://jsfiddle.net/2angdzzy/
Is there any workaround for this problem, or has any of you seen or fixed this issue ?

A: This is a strange issue indeed. I've found out that if you change the video file format to ogg, this does not happened. Perhaps you should try other HTML supported media formats for further investigation.
Here's your updated Fiddle.
Nevertheless, the best way to include an HTML video is with multiple formats for better compatibility.
<video width="320" height="240" controls>
  <source src="movie.ogg" type="video/ogg">
  <source src="movie.mp4" type="video/mp4">
   Your browser does not support the video tag.
</video>


text:
Q: How to transfer data in the previous activity by using the back button in the action bar? I did a back button by writing in the manifest file(like there http://developer.android.com/training/implementing-navigation/ancestral.html)
<activity android:name=".Activity2"
        android:parentActivityName=".MainActivity">
        <meta-data
            android:name="android.support.PARENT_ACTIVITY"
            android:value=".MainActivity"
            />

    </activity>

How do I transfer data from Activity 2 when returning to MainActivity?Or there is a better way to make back button in action bar?

A: First, invoke Activity2 from MainActivity using Activity.startActivityForResult().
In Activity2, once the user has done the action that will set up the data you want, call Activity.setResult().  You can set a resultCode of RESULT_OK and pass an Intent here containing the Parcelable data you want to return.
Finally, you will override Activity.onActivityResult() in your MainActivity.  This will be called when Activity2 finishes.  Here you you will receive the resultCode of RESULT_OK and you can access the Intent that was set up by your Activity2.
See this link Starting Activities and Getting Results | Activity | Android Developers

A: The proper way would be to use startActivityForResult() to start the SecondActivity and use onActivityResult() to receive the data from SecondActivity to the FirstActivity.
Refer here: http://developer.android.com/training/basics/intents/result.html

A: From MainActivity you can start Activity2 using startActivityForResult() - then in the second Activity you can set the result that you want to be sent back to the MainActivity when the user clicks the Back Button. You do something like:
Intent resultIntent = new Intent();
returnIntent.putExtra("result",result);
setResult(Activity.RESULT_OK,resultIntent );

Alternatively, you could override getParentActivityIntent () (or getSupportParentActivityIntent() if using Support Library) in Activity2 like:
@Override
public Intent getParentActivityIntent () {
    Intent intent = super.getParentActivityIntent();
    //here you put the data that you want to send back - could be Serializable/Parcelable, etc
    intent.putExtra("result",result);
    return intent;
}

You can check out the selected answer here, and explore some options here


text:
Q: Making a Logback Audit Logger Wrapper I'm working on writing a class that works as a wrapper for a Logback Logger. Specifically it is to facilitate Audit logging. It should be an independent library that people should be able to import and use. The problem I've having has to do with the minimal amounts of documentation there is for declaring LogBack programatically. I am basing the general declaration on another stack overflow question (Setting Logback Appender path programmatically).
The current definition I have is below. Currently I am having trouble getting the Marker filter work to. It seems like the marker filter, as I've declared it, doesn't do anything. Ultimately I want to make sure that no other information aside from Audit logging makes it into the Audit Log files. That is why I have it Deny on mismatch. From my testing it appears that it is just ignored.
Any information or direction in regards to programmatically created Logback files would be much appreciated. Also is there anything I should worry about when a user uses my class to do audit logging then makes a Logback.xml to do their own separate logging? Thank you
import ch.qos.logback.classic.Level;
import ch.qos.logback.core.spi.FilterReply;
import org.slf4j.LoggerFactory;
import org.slf4j.Marker;
import org.slf4j.MarkerFactory;
import ch.qos.logback.classic.Logger;
import ch.qos.logback.classic.LoggerContext;
import ch.qos.logback.classic.encoder.PatternLayoutEncoder;
import ch.qos.logback.core.rolling.TimeBasedRollingPolicy;
import ch.qos.logback.core.rolling.RollingFileAppender;
import ch.qos.logback.core.filter.EvaluatorFilter;
import ch.qos.logback.classic.boolex.OnMarkerEvaluator;

public class AuditLogger {
    private static Logger logbackLogger;
    final static Marker AUDIT = MarkerFactory.getMarker("AUDIT");

    static {
       LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory();

       RollingFileAppender rfAppender = new RollingFileAppender();
       rfAppender.setContext(loggerContext);
       rfAppender.setFile("auditLogFile.currentDay.log");
       TimeBasedRollingPolicy rollingPolicy = new TimeBasedRollingPolicy();
       rollingPolicy.setContext(loggerContext);
       // rolling policies need to know their parent
       // it's one of the rare cases, where a sub-component knows about its parent
       rollingPolicy.setParent(rfAppender);
       rollingPolicy.setFileNamePattern("auditLogFile.%d{yyyy-MM-dd}.log");
       rollingPolicy.start();

       PatternLayoutEncoder encoder = new PatternLayoutEncoder();
       encoder.setContext(loggerContext);
       encoder.setPattern("[%d{ISO8601}] %5marker - %msg%n");
       encoder.start();

       rfAppender.setEncoder(encoder);
       rfAppender.setRollingPolicy(rollingPolicy);
       rfAppender.start();

       EvaluatorFilter evalFilter= new EvaluatorFilter();
       OnMarkerEvaluator markerEval= new OnMarkerEvaluator();
       markerEval.addMarker("AUDIT");

       evalFilter.setEvaluator(markerEval);
       evalFilter.setOnMatch(FilterReply.ACCEPT);
       evalFilter.setOnMismatch(FilterReply.DENY);

       rfAppender.addFilter(evalFilter);

       logbackLogger = loggerContext.getLogger("AUDIT_LOGGER");
       logbackLogger.addAppender(rfAppender);

       logbackLogger.setLevel(Level.DEBUG);

   }
   public AuditLogger(){}

   public void log(String msg){
       logbackLogger.debug(AUDIT, msg);
   }
}

A: I never found a whole lot of information on programmatically created Logback files but I'll share what I did find from my testing and fiddling around.
First of all in order to adapt Ceki's response on the linked post I used a combination of the logback.xml examples and the online API. For example in order to find out how to do a marker filter I noticed that the xml has a link to the class "ch.qos.logback.core.filter.EvaluatorFilter" and "ch.qos.logback.classic.boolex.OnMarkerEvaluator". I used the API's found here: http://logback.qos.ch/apidocs/ch/qos/logback/core/filter/EvaluatorFilter.html. Remember (as per my comment above) to run the start() method for every filter, appender, encoder, rolling policy, evaluator and anything else you create when initializing a logback instance programmatically. If you don't it will not work.
As for my testing with different combinations of programmatically created and xml created logback instances I got interesting results. It seems like the instance of logback created programmatically and the one created by xml work together. For example if I call logger.debug("msg") from the programmatically created instance the "msg" will also be received  and evaluated by the xml created instance. I believe this is because they all share the same "root" logger.
In order for the library to work correctly when the user is not using logback and not output to the console I use the following bit of code. It checks to see if the default logger is the only one that exists and removes the console appender if so.
    if (loggerContext.getLoggerList().size() == 1) {
        Logger root= loggerContext.getLogger("ROOT");
        root.detachAppender("console");
    }

The only fatal error I found was when the user program used log4j and imported a class called "slf4j-log4j12". The program complained about multiple instances of slf4j and died. By removing the "slf4j-log4j12" maven library from the project it worked fine.


text:
Q: How to access the source code and/or debug a VSE I have an old Win32 application and I need to inspect its code. This application contains the file "VVM31W.DLL", so it would seem it's a VSE (Visual Smalltalk Enterprise) application. Are there any available tools to inspect VSE executable's code and/or debug it?

A: The task of reverse engineering a VSE executable image may not be actually impossible but I would expect it to be extraordinarily difficult. Before spending the many months of meticulous effort to do this reverse engineering, I would first ask myself how critical it is that I see the source code.  I suspect that virtually any application could be re-implemented more easily than reverse engineering a packaged runtime.
No, there are no tools to help with this.  Yes, it will be very difficult.


text:
Q: Strategy Pattern Implementation Following is the structure of my class
public abstract class BaseUser
{
    protected List<Perm> permissions;
    public abstract void AddPerm(Perm perm);
}

public class NormalUser : BaseUser
{
    public override void AddPerm(Perm perm)
    {
        throw new InvalidOperationException("A normal user cant add permissions");
    }
}

public class SpecialUser : BaseUser
{
    public override void AddPerm(Perm perm)
    {
        if(permissions==null) permissions=new List<Perm>();
            this.permissions.Add(perm);
    }
}

class Container
{
    List<BaseUser> users;
}

What is required:

*

*Container will keep both types of users

*SpecialUser will have the functionality of add permissions - Done

*Normal User will not be allowed add permissions - Done
I have chosen strategy pattern to achieve above
The thing I am not able to achieve is

*Both Types of users will be hydrated from the Database (The users will be initialized with list of default permissions)
Am I right in choosing this pattern in this situation? If yes then how do I address requirement 4?
Many Thanks,
asolvent

A: The example your provided is not really an instance of the strategy pattern, it is just a method override. The strategy pattern involves a context object and a strategy object. Regardless, I would try to avoid the temptation to apply OOP in all possible places. Instead of inheritance consider using a UserType enum and a simple if statement to support the required behavior. This makes it easier to map to a database and also keeps the code simple:
enum UserType {
 Normal,
 Special
}

class User {

public UserType Type { get; set; }

public override void AddPerm(Perm perm){
  switch (this.Type) {
 // logic goes here
  }
 }
}

This type of problem is a recurring theme in using OOP in enterprise data driven applications and I normally try to keep things as simple as possible. Do you really need to derive a base User type to provide the required functionality? Will it have additional behaviors and properties?


text:
Q: Mockito: argThat for methods taking multiple arguments I am trying to use Mockito's argThat API:
verify(mockService).methodA(argThat((List ids, int b) -> ids.get(0).equals("123")));

mockService has methodA which takes two parameters: a List and a primitive integer.
But this gives me an error:

"Imcompatible parameter types in lambda expression".

The reason is that ArgumentMatcher's matches method takes only one argument.
So how can I do verification for such scenarios?

A: You should use an argThat wildcard for each of the inputs:
verify(mockService).methodA(argThat((List ids) -> ids.get(0).equals("123"))
          , argThat((int b) -> b < 1);

I would also suggest you use @ArgumentCaptor which is an alternative to argThat and makes that custom matching a bit more clear: javadoc. Especially if you have to use both of the params at the same conditional statement.