Ubuntu 22.10 - "blacklist: Problem blacklisting hash (-13)" message on boot

Question: After upgrading my Ubuntu 22.04 to Ubuntu 22.10, the following sequence of messages started to appear on the boot screen:
<code>blacklist: Problem blacklisting hash (-13)
[...]
blacklist: Problem blacklisting hash (-13)
</code>
This is NOT a blocking error, the boot goes on without any apparent issue and I'm able to use my Ubuntu as usual.
These messages were not present before the upgrade, where does it come from?
My setup:

OS: Ubuntu 22.10 x86_64
Kernel: 5.19.0-21-generic
System manufacturer:  SAMSUNG ELECTRONICS CO., LTD.
System product-name:  450R4E/450R5E/450R4V/450R5V/4450RV
Bios release date:  04/29/2014
Bios version:  P08RBG.216.140429.ZW
SecureBoot: Disabled
CPU: Intel i5-3230M (4) @ 3.2GHz
GPU 1: Intel 3rd Gen Core processor Graphics Controller
GPU 2: NVIDIA GeForce 610M/710M/810M/820M / GT 620M/625M/630M/720M
Comment: I see these messages in Lubuntu 22.10 too.
Comment: Check the Samsung site for a newer BIOS.
Comment: @LorenzKeel Newer kernels sometimes require an updated BIOS, and yours is from 2014. That said, try this... from the GRUB menu, boot to an older kernel, and see if the error goes away. If you have 3 or more kernels to choose from, choose the oldest first, and then try each newer kernel until the error reappears. Report back.
Comment: @heynnema: I've done a fast check and there is not a newer BIOS than the current one. That said, could you explain why do you think that this warning is related to a not-updated BIOS?
Comment: @LorenzKeel See https://bbs.archlinux.org/viewtopic.php?id=278860
Comment: _"These kernel messages should be treated as warning, not error. You should not remove blacklisted hashes (i.e. do not clear secure boot keys), this is a security measure to protect against malicious signatures. These kernel messages now show because we hardened this security mechanism, and it now reveals issues with some firmwares. There is an ongoing kernel patch to update this error message: https://lore.kernel.org/lkml/3b997266-0 … gikod.net/"_ \[[Source](https://bbs.archlinux.org/viewtopic.php?pid=2066881#p2066881)]
Comment: Same Problem here with newer BIOS (HP Version: N86 Ver. 01.55 Date: 04/02/2022) But as my system boots and it seems to be related to the kernel (according to @heynnema s link, mine is 5.19 as well) I just hope it'll "heal itself" with the next kernel updates.
Comment: Getting the same error with a newer BIOS. I am using kernel 6.1.0-060100rc5-generic, which appears to be a requirement for this machine (4th gen thinkbook 13s) to work properly.
Comment: Web search shows this problem to be pretty widespread. It is occurring for me on a 2 year old mother board (Asus Rog Stix Z490-i) with the latest BIOS. From https://email@example.com/T/ it looks like it is harmless and they are working on improving the logs.
Comment: I am also facing the same problem both on Ubuntu 22.10 and Fedora 37.  Both distros are using Gnome 43 version. So I think the problem is related to this newer Gnome 43 virsion, and not to the BIOS version.
Comment: @heynnema I'm having the same problem together with this one https://askubuntu.com/questions/1440379/low-sound-after-upgrading-from-kubuntu-22-04-to-22-10 updated my BIOS to the latest version available everything works well on Win10 boot. can you guide me how to download config and boot with downgraded/earlier kernel version (the latest on v22.04 worked but I don't know what it was) using a dedicated GRUB entry for it? TNX
Comment: @Roey In the Additional Options menu selection in GRUB, do you see older kernels available there to boot? If not, download an older Ubuntu (not Kubuntu) .iso file, burn it to a USB flash device, boot to it, and see if your symptoms are gone.
Comment: Same message started appearing with Ubuntu 22.04.2 LTS on Lenovo ThinkPad X1 Nano Gen 1 / 11th Gen Intel® Core™ i7-1160G7 @ 1.20GHz × 8
Comment: heynnema booted with Kubuntu 22.04.2 USB drive got the same (-13) errors but the sound was fixed
here are the differences between the 2 boots:

``Operating System: Kubuntu 22.04 | Kubuntu 22.10
KDE Plasma Version: 5.24.7 | 5.25.5
KDE Frameworks Version: 5.92.0 | 5.98.0
Qt Version: 5.15.3 | 5.15.6
Kernel Version: 5.19.0-32-generic (64-bit) | 5.19.0-35-generic (64-bit)``
What could be causing the sound problem? It's  not the kernel I've booted 22.10 with 5.19.0-31 and it didn't solve the problem
Comment: Same message reported on Lenovo Thinkpad P14s, with latest BIOS (1.21) and latest stable kernel (5.19). — @Roey if the symptom (-13 errros) are still there with both Ubuntu versions, then for the sound problem is unrelated and you should probably write a new SO question.
Answer: You can safely ignore it.

"These kernel messages should be treated as warning, not error. You should not remove blacklisted hashes (i.e. do not clear secure boot keys), this is a security measure to protect against malicious signatures.
These kernel messages now show because we hardened this security mechanism, and it now reveals issues with some firmwares.
There is an ongoing kernel patch to update this error message: https://email@example.com/"

as reported in source.
This is something that the different manufacturers need to correct in their BIOS/firmware.
The correct approach (of seeing the messages as a Warning instead of an Error) is confirmed in the patch discussion:

"We should not hide EACCES errors. This logs issues, which is correct for duplicate hashes, and can help firmware vendors to fix their database.
I'd really like to see a different log message instead: change the
duplicate entry error code from EACCES to EEXIST, and call pr_warn for
this specific case."

You just need to wait for upgrades from your motherboard producer. (Asus, Dell, Lenovo, etc.)
Or contact their support to report the issue and request a fix.
Comment: just wait for an update, if only it were like that. Then again, you missed Dell which is one of the worst when it comes to BIOS code. I recommend regardless to email vendor support, point it out and ask it explicitly : if nobody asks, nothing wlll likely happen.


Contested Territory on iOS Bloons City

Question: Is the contested territory feature that's on the PC version of Bloons Monkey City also in the iOS version?
Comment: By Bloons City, do you mean Bloons Monkey City?
Comment: Yes sorry about that
Answer: Yes, the contested territory feature is also available in the iOS version, however you need to be connected to a network (wifi or cellular data) for it to work.
Source: I captured the contested territory in the ios version of the game 30 minutes ago.

Contested Territory on iOS Bloons City


I can't load game with my google account!

Question: Yesterday my game was reset and when I tried to load again it does not let me load with google.
When It says sign in with google and you click there the Pokéball keeps spinning over and over and never ends!!
I saw a related question on Arqade, but the answer didn't help me: on my mobile When I go to settings then account and google there is no sign in and security option.
Comment: dont shout and keep calm. try later to check if is a server connection error ...
Answer: It is just a server issue (most probably) sometimes people can log in but all the gyms/stops and nearby Pokemon still won't load when it displays the map. So try again later, if you keep these problems i suggest:
open the Pokemon go app -> click on the red and white pokeball to open the menu -> click on settings.
In settings look for sign out (it's on the bottom) then you will be logged out and can log back in with your google account.
Usually if you experience a reset it means you logged in with an other account (or the server couldn't be reached resulting in the previously described scenario)


get image as jpeg format from excel in c#

Question: how to read image in cell of the excel sheet. This sheet contain .jpeg formated images. I want as they are means in jpeg format. i am using asp.net and c# for this. please guide.
Answer: I recommend reading this tutorial:

Reading Image from Excel file using C# .Net
Comment: Yes, i make a code according this article. but i  am facing new problem. how to get original name of image. please don't suggest Picture.Name property. this is giving me "Picture1" like this names. i need originals///how can i get ??
Comment: Also how to know is R2C1 contain image or null??


Python: Splitting numbers and factor them to 2

Question: This code is to identify if the number factored to 2 for the 4th time, would get 1 or not.
a = int(input())
terms = 4
result = list(map(lambda x: a ** x, range(terms)))
for i in range(terms):
   print(a, "^2 = ", result[i])
if result == 1:
   print('True')
else:
   print('False')

If I input 14, this is the result:
14 ^2 =  1
14 ^2 =  14
14 ^2 =  196
14 ^2 =  2744
False

But I want it to be like this.
1^2 + 4^2 = 17
1^2 + 7^2 = 50
5^2 + 0^2 = 25
2^2 + 5^2 = 29
False

Comment: are you absolutely sure you got "nothing", or were there errors that were raised?
Comment: I'm not sure what do you want, but at least I can say that you compare list and number, which makes no sense
Comment: I got one error which is:
:for b, c in str(a):
ValueError: not enough values to unpack (expected 2, got 1)
Comment: I cannot figure out what you think "for b, c in str(a)" should do. str(a) will just return a, because a is already a string.
Comment: I will edit and put my original code which is working, but it's not the result that I want.
Comment: Python is indees a dynamic language, so the same variable can contain an int or a string **at different times**. But `int` and `str` are different types...
Answer: Try this:
a = str(int(input()))

def split_and_print(a):
    x = [int(y) for y in list(str(a))]
    return sum([y**2 for y in x])

def split_sum_print(a):
    a_split = list(str(a))
    print(' + '.join([x+'^2' for x in a])+ ' = '+str(split_and_print(a)))
    return str(split_and_print(a))

n = 4
for i in range(n):
    a = split_sum_print(a)
if a == '1':
    print(True)
else:
    print(False)

Output:
14
1^2 + 4^2 = 17
1^2 + 7^2 = 50
5^2 + 0^2 = 25
2^2 + 5^2 = 29
False

I made two functions, one responsible for calculation, the other for printing. Then combined them and used a for loop. Change n for different number of iterations.
Answer: First of all, a = str(int(input())) seems quite unnecessary, as input() returns string by itself.
Second, you then cast it to string ... in str(a): once again (again unnecessary).
And third of all, you are iterating over some string (a in this case), which would product a stream of single characters, but your code is written as if you expected tuples instead...?
For example
for char in "abc":
  print(char)

... would print
a
b
c

What you essentially have
for a, b in "abc":
  print(a, b)

... what should happen here?
What do you expect to happen with your code, exactly?


mysql query inserting 3 duplicate records

Question: I am using following code to record hits into a views table, but when I load this page the MySQL query inserts 3 rows at a time, so 1 hit means 3 hits. I am trying to figure it out, but can't get any luck.
    $width = 16;
    $height = 16;

    $id = 30

    $ip = $_SERVER['REMOTE_ADDR'];
    $user_agent = $_SERVER['HTTP_USER_AGENT'];

    //count views

    global $db;

    $sql = 'INSERT INTO '.DB_PREFIX.'views (invoice_id, ip, user_agent)
                                               VALUES ("' . $id . '",
                                                "' . ip2long($ip) . '",
                                                "' . $user_agent . '")';

$db->query($sql);

//display image
header( "Content-type: image/png" );
$img = imagecreate($width, $height);
$background_color = imagecolorallocate($img, 238, 238, 238);
imagepng($img);
imagedestroy($img);

If I replace the display image code with a simple echo "Successfully done!", the problem is fixed and it only inserts one row.
mysql rows
id     invoice_id    ip         user_agent    dnt
35     22           2058457116     Mozilla/5.0   2013-04-17 11:55:12
34     22           2058457116     Mozilla/5.0   2013-04-17 11:55:12
33     22           2058457116     Mozilla/5.0   2013-04-17 11:55:11

Comment: Are you sure you're only calling this script once? Maybe outputting `"Successfully done!"` breaks something somewhere else making it so you call it only once.
Comment: @FritsvanCampen yes only once, i am debugging by calling its direct url in browser.
Comment: Need more data to figure out whats going on: 1.Can you paste the three records getting created each time 2.Exactly which lines of image code are you replacing and do you get successfully done echoed correctly?
Comment: Try changing $sql to something else like $sql_2. Maybe $sql is being passed into another query further down the script
Comment: @Raidenace 1. I am pasting row in question 2.image generation code(from header().... imagedestroy()) and yes i get successfully done echoed correctly
Comment: Where is your display image code? Sounds like the culprit may be in there.
Comment: @richelliot i have tried that too
Comment: @Revent see question and check underneath //display image
Comment: @seoppc Didnt see the rows in the question..
Comment: do a die() after the imagedestroy and see if it still creates duplicate entries
Comment: @Raidenace same issue, even after die() at end
Answer: There's no way the script can insert three rows.
So the only possibility is that the script is run three times.
I would recommend you to check the web server log for accesses to the URL.
Answer: Are you using a templating engine or a CMS of some sort? for example, i've tried Drupal before  and due to the hooks capability of the system, a file might be called more than once.. same as a templating engine. This could be the problem. also, echoing something might stop the other scripts from running because of an error linked to the 'headers already sent' case. that's why even if you do a die() at the end, it will still not work.
Answer: Can your please tell what os and browser you are using for testing.
I once had a similar problem while trying with safari in IOS device.
My code was for downloading an audio. For all OS it was working fine. But for safari in IOS device download code was getting executed multiple times.
Pls check this on other browser and let us know the results.


How would I decode a string that was coded by this program?

Question: This is the code I used to code it
import string

def encode(text,rotate_by):
    s_from = string.ascii_lowercase + string.ascii_uppercase
    s_to = (string.ascii_lowercase[rotate_by:] +
            string.ascii_lowercase[:rotate_by] +
            string.ascii_uppercase[rotate_by:] +
            string.ascii_uppercase[:rotate_by])
    cypher_table = string.maketrans(s_from, s_to)
    cypher_table = string.maketrans(s_from, s_to)
    return text.translate(cypher_table)

text = raw_input("Enter the text to encode: ")
rotate_by = int(raw_input("Rotate by: "))
print encode(text, rotate_by)

How would I decode a string coded by this?
Comment: just reverse the logic
Answer: This is a very simple rotation encoding. You just have to reverse the rotation.
I would try this:
def decode(text, rotate_by):
    s_from = string.ascii_lowercase + string.ascii_uppercase
    s_to = (string.ascii_lowercase[rotate_by:] +
        string.ascii_lowercase[:rotate_by] +
        string.ascii_uppercase[rotate_by:] +
        string.ascii_uppercase[:rotate_by])
    reverse_table = string.maketrans(s_to, s_from)
    return text.translate(reverse_table)

BTW: In your coding, the string.maketrans-line is duplicative.
The important line above is the maketrans-line, because I just reversed the parameters, this should also reverse the translation table. Everything else is similar or equal than the original code.
Answer: Just call encode with the encoded(encrypted) string and the original rotate_by with its sign inversed.
Ex:
>>> encode("hello",3)
'khoor'
>>> encode("khoor",-3)
'hello'


Keystone.js: use one model in multiple sites

Question: I need to create multiple sites using Keystone.js (sites network). I have a reference collection, which should be used on every site as a relationship to models in other network's sites. It's like universal tags list used across all network's site. Hope you understand what I mean. Sorry for my bad english.
Answer: without really understanding your use case i see two potential architectures to explore:

Single keystone instance:
See if you can design your data to use inheritance and try putting
all sites in one keystone instance. IE you could have a parent
"Post" model and then a per site "FooPost", "BarPost" that inherits
from post. This way you could use the stock keystone/mongoose
relationship mechanisms and built-in CRUD bootstraps. Drawback here
is this architecture will make your admin UI and data model more
complicated but i think its a potential solution to "partitioning" a
single keystone instance into separate sites. This might work better
for just a few "sites" on one instance as more then that would just
make the data model and admin UX too complicated to use.
Pros: can use keystone stock CRUD/relationships
Cons: more complicated admin UX, you'll have to manually partition the front    end out yourself to keep the data separate, more complicated data structure using a lot of inheritance
separate keystone instances:
a lightweight way to share non-relational data between separate keystone instances  (like a common tag list) could be to just bootstrap an api wrapper to a "tag" model for each site and add api CRUD calls to each keystone instance API . Then you could maintain the model data across sites by calling the CRUD api via mongoose hooks. There are plenty of examples out there to boostrap keystone CRUD api and you could just make an api CRUD call within the model's post save, post delete, or post update.
To model relationships would be more complicated. I would create a "Link" model on each site that was nothing more then a URL field and an _id. Set up a one to many relationship in the models on each site you are trying to share relationships with and wrap the Link model in a CRUD api. This way you could "link" the models together and they would render out as clickable links on the admin pages. You would have to code a pretty fair amount of hook and API calls but i think this is a potentially feasible architecture for a system that can allow for some transactional data sync tolerance (IE you wouldnt try this type of architecture for anything that requires super tight transactional integrity but its probably ok for social media).
Pros: separation of concerns, cleaner data model, partitioned admin screens (maybe a con for some use cases)
Cons: need to sync data model schema (you can submodule a common keystone models github repo and share it between all sites to fix this problem ive done that before), more api and schema hook code, each site has a separate admin UX, more sysadmin work to run and sync separate instances
Comment: In a multi tenant scenario sir , what would be the best advice you can give ? based on the two choices you have explianed
Answer: I don't think this is possible per-se, however if it's a reference collection then why not just run it on it's own site, and have all the other sites query that one for data?
I tried running two sites in the same instance once. It causes all models with the same names to share a collection in the database, which is not a good thing to be doing really as it means the updates collection that keystone creates will be shared between apps, and also any users (unless you call the users model something different on each site). It's certainly not designed to cope with this.


XRDP on Ubuntu can't work

Question: I'm just trying to apply XRDP to Ubuntu. Before I was applying XRDP to Kali and it works. But when I tried to apply it on Ubuntu it doesn't.
Must I change the session when I connect to the remote desktop?
This was the output service when I tried to start XRDP:
Starting Remote Desktop Protocol server
[20201013-03:48:00] [DEBUG] Testing if xrdp can listen on 0.0.0.0 port 3389.
[20201013-03:48:00] [ERROR] g_tcp_bind(6, 3389) failed bind IPv6 (errno=98) and IPv4 (errno=22).
[20201013-03:48:01] [DEBUG] Closed socket 6 (AF_INET6 :: port 0)
[20201013-03:48:01] [ERROR] Failed to start xrdp daemon, possibly address already in use.

Answer: Read the error messages! They clearly indicate that an XRDP instance is already running, and has grabbed the TCP port that is a requirement.
You must find, and shutdown that XRDP instance.
sudo lsof -i tcp:3389

will find it.
Read man lsof kill pkill xrdp.

XRDP on Ubuntu can't work


if any value in (x, x, x) is bellow x

Question: How can I do a check to see if the value of whatever is in (x, x, x) is below for example 5
<code>for i in range(img.size[0]):  # for every pixel:
    for j in range(img.size[1]):
        if pixels[i,j] != (0, 0, 0) and (1, 0, 0) and (0, 1, 0) and (0, 0, 1) and (1, 1, 0) and (0, 1, 1) and (1, 0, 1) and (1, 1, 1) and (1, 1, 2) and (1, 2, 1) and (2, 1, 1) and (2, 2, 1) and (1, 2, 2) and (2, 1, 2) and (2, 2 ,2):  # if not black:
            pixels[i,j] = (255, 255, 255)  # change to white
</code>
Comment: Your question is unclear. Try provide more information about what you're trying to achieve and what the problem is.
Comment: Your code doesn't work at the moment. `if pixels[i, j] ...` is wrong. See [this question](https://stackoverflow.com/q/15112125/3279716)
Comment: `if x == (0,0,0) or (1,0,0) ... :` is equal to `if  (x == (0,0,0))  or  (1,0,0) ` which is always `True` as a  non empty tuple is Truthy. Use `if x not in (   (1,0,0),(0,1,0), ... )` or check it programatically as Netwave suggested
Answer: Just check your components by iterating over the tuple:
<code>...
if not any(value <= 5 for value in pixels[i,j]):
...
</code>

if any value in (x, x, x) is bellow x


Regex Expression for asp.net

Question: I want regex that matches the following:

1223.00
1,223.11
1,223,333.22
1223333.21
1.00
20.00
300.00
Comment: great, what have you tried..?
Answer: Based on the examples you've given, you can use this.
<code>[\d,\.]+
</code>
Comment: @derp Well I'm assuming that those examples appear in some longer text or are for validation of a string.
Comment: @derp Don't be ridiculous; we don't want to match empty strings. `.+` is obviously much more appropriate :-)
Answer: You could use the below regex,
<code>\d+(?:(?:,\d{3})+)?\.\d{2}
</code>
DEMO

Regex Expression for asp.net


PS4 Streaming to Friends

Question: Is it currently possible to stream live gameplay to friends over PSN? Or is this only possible via Twitch on a public stream?
If someone could go into detail over the options I would appreciate it.
Answer: There isn't that much detail to go into this with. Plain in simple you can only (currently) do a live stream over twitch or the other one, which is not currently syncing in my brain..... So you have two options for now which is twitch or the other. Though you could take clips with the share button and show them like 15 minute segments via facebook or something, but this will take a lot of uploading time.
Comment: Is there an easy way to invite your friends to watch that stream without them having to search for it?
Comment: You can send them the link to your stream, just copy and paste the URL into a message of some sort

PS4 Streaming to Friends


how to append an element as a first child in jquery

Question: lets say i have html something like this..

blablabla

1

2

what i want to do is when i click on any li, then that table should get hide and another table should get appended in place of that table.lets say that table is

blablabla

how to do it in jQuery.
i tried in this way but its adding as a last child of ul.
$('#leftNavigation').append('

blablabla

')

Thanks in advance!!!!
Answer: Use .prepend() or .prependTo() instead.
Check jQuery documentation.
Additional notes
But based on what you're trying to accomplish you should maybe rather use DOM replacement functionality.
Beware
Adding anything else than LI inside an UL or OL is invalid HTML.
I suggest you add an additional LI, give it some ID or CSS class and then manipulate its content.
Comment: thanks...Robert...i know that this not a right html but due to some requirements i am forced to do this...
Comment: @Vivek: Fine by me. If valid HTML is not a requirement and doesn't bother you, then go ahead and use it.


PyPi package versions compatible with Cloud Composer's `apache-airflow-providers-microsoft-azure`

Question: I'm attempting to load a few packages into an instance of Google Cloud Composer 2. I constantly getting dependency or package issues and am unable to get the versions of the packages that function.
The requirements.txt file that keeps failing looks like
apache-airflow-providers-microsoft-azure == 8.3.0
apache-airflow-providers-google <= 10.11.1
numpy == 1.26.2
pandas == 2.1.3
datetime == 5.3

I found that I can load the requirements.txt file directly to the cloud composer environment using
gcloud composer environments update [ENVIROMENT] --location [LOCATION] --update-pypi-packages-from-file requirements.txt  --verbosity=debug

where [ENVIROMENT] is the cloud composer environment and [LOCATION] is the location.
Comment: Hi @user4933, Are you getting any error message while using the `requiremnts.txt` file ? If yes, could you share the error message ?
Answer: In the Cloud Composer environment, the packages for Google Cloud are already installed in the machines.
In your requirements.txt file, you added the following package :
apache-airflow-providers-google <= 10.11.1

And this package already exists in Composer.
The risk is to have conflicts between this version and the version used by Composer.
To check the version used by Composer, you can check this link Composer versions
For each Composer version, you can see all the Python packages with their versions installed in the machines.
Example for the version composer-2.5.2-airflow-2.6.3 of Cloud Composer :

You have to be carreful, the pandas and numpy appear in the list and are already installed in Composer.
It's better to only pass the package concerning Azure :
apache-airflow-providers-microsoft-azure == 8.3.0

Comment: @user4933 have you solved your issue ?


Chunk Loaders In Vanilla Minecraft?

Question: I am creating a custom map in Minecraft, but when I try to set a block, I get the error, "Cannot place block outside of the world." I do believe that this is due to chunks not loading. Is there any kind of Vanilla Chunk Loader that I can use to keep many chunks loaded at the same time? I would prefer if there was no clutter.
I have heard about the Hopper system (I don;t know if it stills works, but then again, it creates too much clutter.
Comment: There are ways to keep chunks loaded, and ways to load unloaded chunks, but not really anything that's less "clutter" than the hopper method.
Comment: Not a definitive answer, but I've had success in the past using `/spreadplayers` to teleport a mob to the location and load these chunks, then immediately running `/setblock`.
Answer: Try to find your spawn chunks, they are always loaded in Minecraft worlds, it is possible to put a block outside of the world if unloaded, but the spawn chunks are always loaded.

Chunk Loaders In Vanilla Minecraft?


FireFox & Chrome CSS Differs

Question: The problem is, the CSS of site is different on FireFox and Chrome..
Fire fox loads it the way i want, but in chrome its messed up ...
I tried adding this to CSS as well,
html, body, div, span, applet, object, iframe,
h1, h2, h3, h4, h5, h6, p, blockquote, pre,
a, abbr, acronym, address, big, cite, code,
del, dfn, em, img, ins, kbd, q, s, samp,
small, strike, strong, sub, sup, tt, var,
b, u, i, center,
dl, dt, dd, ol, ul, li,
fieldset, form, label, legend,
table, caption, tbody, tfoot, thead, tr, th, td,
article, aside, canvas, details, embed,
figure, figcaption, footer, header, hgroup,
menu, nav, output, ruby, section, summary,
time, mark, audio, video {
    margin: 0;
    padding: 0;
    border: 0;
    font-size: 100%;
    font: inherit;
    vertical-align: baseline;
}
/* HTML5 display-role reset for older browsers */
article, aside, details, figcaption, figure,
footer, header, hgroup, menu, nav, section {
    display: block;
}

Im using Visual Studio 2010 so the site is on my localhost...
I tried clearing all cookies/cache...
Tried with a different Chrome based browser.. (SW Iron)... seems to be the same...
This is where the problem is coming..
.categories ul {
    margin: 0; padding: 0;
    float: left;
    width:100%;
}

.categories ul li {
    display: inline;
    float:left;
    padding-top:10px;
}

.categories ul li:nth-child(1) a{
  padding: 0 66.5px 10px 66.5px;
  margin-left:16.375px;
}

.categories ul li:nth-child(4) a{
  padding: 0 69px 10px 69px;
}

.categories ul li:nth-child(6) a:after{
  display:none;
}

.categories ul li:nth-child(7) a{
  margin-left:15.375px;
}

.categories ul li:nth-child(8) a{
  padding: 0 51px 10px 51px;
}

.categories ul li:nth-child(10) a{
  padding: 0 73px 10px 73px;
}

.categories ul li:nth-child(11) a:after{
  display:none;
}

.categories ul li:nth-child(12) a{
  margin-left:16.375px;
  padding: 0 53px 10px 53px;
  border-bottom:none;
}

.categories ul li:nth-child(13) a{
  padding: 0 53px 10px 53px;
  border-bottom:none;
}

.categories ul li:nth-child(14) a{
  border-bottom:none;
}

.categories ul li:nth-child(15) a{
  padding: 0 53px 10px 53px;
  border-bottom:none;
}

.categories ul li:nth-child(16) a{
  border-bottom:none;
}

.categories ul li:nth-child(17) a:after{
  display:none;
}

.categories ul li:nth-child(17) a{
  border-bottom:none;
}

.categories ul li a {
   position : relative;
    float: left;
    text-decoration: none;
    color: white;
    padding-bottom:10px;
    padding-left:40px;
    padding-right: 40px;
    border-bottom: 2px solid #e5e5e5;
}
.categories ul li a:after {
  position: absolute;
  right: 0;
  content: '';
  height: 100%;
  width: 1px;
  background: linear-gradient(to top, black, transparent);
}

 .categories ul li a:hover, .categories ul li .current
 {

background: -moz-linear-gradient(top,  rgba(0,0,0,0) 1%, rgba(255,255,255,0.12) 100%); /* FF3.6+ */
background: -webkit-gradient(linear, left top, left bottom, color-stop(1%,rgba(0,0,0,0)), color-stop(100%,rgba(255,255,255,0.12))); /* Chrome,Safari4+ */
background: -webkit-linear-gradient(top,  rgba(0,0,0,0) 1%,rgba(255,255,255,0.12) 100%); /* Chrome10+,Safari5.1+ */
background: -o-linear-gradient(top,  rgba(0,0,0,0) 1%,rgba(255,255,255,0.12) 100%); /* Opera 11.10+ */
background: -ms-linear-gradient(top,  rgba(0,0,0,0) 1%,rgba(255,255,255,0.12) 100%); /* IE10+ */
background: linear-gradient(to bottom,  rgba(0,0,0,0) 1%,rgba(255,255,255,0.12) 100%); /* W3C */
filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#00000000', endColorstr='#1fffffff',GradientType=0 ); /* IE6-9 */

}

.categories ul li a:visited {
    color: white;
}

Firefox image at top.... Chrome at bottom...
Comment: You went overboard with the CSS if that's the look you were going for. That could be achieved with a lot less.
Comment: Add this as the first style: `* { box-sizing: border-box; margin: 0; padding: 0; }` and then start styling from there.
Comment: @slime, Well i did it the way i knew :/
abhitalks i tried the code you gave, but no change... ?
Comment: Well in that case you have to create an MCVE for your question: http://stackoverflow.com/help/mcve
Answer: I'll just give you the bare bones of what you're looking for:
ul {
    display: block;}

li {
    display: inline-block;
    width: auto;
    height: auto;}

li a {
    display: block;
    padding: 5px 50px;
    font-size: 14px;}

li:after {
    content: '';
    display: inline-block;
    width: 3px;
    height: 10px;
    background: black;}

li:last-child:after {
    display: none;}

If you're just looking for them to stack naturally then you can just adjust the padding in the li a to modify the spacing, but if you're always looking for a certain amount per row, then add some percent widths to the li and if you wanted uneven numbers then that's when you target individual ones.
Answer: According to me, It is font rendering issue. The width of font is differant in Chrome & Firefox. Thus pixel required for same word are differant in Firefox & Chrome.
Along with that the technique you are using is fully wrong. Use are specifying width for each li by adjusting padding. Instead give then equal width for each row. Thus there will be spare space to accomodate change in with of letters.
Updated generalized code should look as follows:
/** General List Styles **/
ul{
    display: block;
    margin:0; padding:0;
    list-style:none;
}

li{
    float:left;
    display:block;
    width:16.66%;
    position:relative;
}

li a{
    display: block;
    font-size: 14px;
}

/** Middle Row Cell (Using 'middle' class on them) **/
li.middle{
    width:20%;
}

/** No Sep Cell (Using 'nosep:after' class on them) **/
li.nosep:after{
    display:none;
}

FireFox & Chrome CSS Differs


How to properly define an extension function in Typescript?

Question: I have a class like this:
export default class UserDto {
    email: string;
    permissions: string[];
    roles: string[];
}

and a d.ts file that defines toUser:
declare global {
    class UserDto {
        toUser(): User;
    }
}

and the function declaration in a regular ts file:
import User from "types/User";
import Activity from "types/Activity";
import Role from "types/Role";
import UserDto from "types/UserDto";

UserDto.prototype.toUser() = function (): User {
    return {
        email: this.email,
        permissions: new Set(this.permissions.map((p) => Activity[p])),
        roles: new Set(this.roles.map((r) => Role[r])),
    };
};

My problem is that when I try to use this extension it doesn't work (and VS Code doesn't recognize it either):
import Role from "types/Role";
import User from "types/User";
import UserDto from "types/UserDto";
import Activity from "types/Activity";
import toUser from "extensions/UserDtoExtensions";

import users from "data/users.json";
import roles from "data/roles.json";

export default function findUser(email: string): User {
    const userDto: UserDto = users[email];
    if (userDto) {
        return userDto.toUser();
    } else {
        return {
            email: "firstname.lastname@example.com",
            permissions: new Set(
                roles.Anonymous.permissions.map((p) => Activity[p])
            ),
            roles: new Set([Role.Anonymous]),
        };
    }
}

I get

TypeError: userDto.toUser is not a function

What am I doing wrong?
What's also interesting is that in the file where I augment the prototype VS Code also says

The left-hand side of an assignment expression must be a variable or a property access.

Why?
Answer:
In the documentation:

Default exports also cannot be augmented, only named exports (since you need to augment an export by its exported name, and default is a reserved word - see #14080 for details)

declare module "types/UserDto", not declare global.

import "extensions/UserDtoExtensions", without toUser from.

I think those should be all the required changes.


Limbo not playing on Ubuntu 16.04 LTS

Question: It's been long I played Limbo and when I saw Inside decided to play it again. I played it on my Windows two years ago, ever since I've been using Ubuntu because of work. I downloaded the .exe and tried running it with wine, installation completes but every time i try to run it, a notification box pops-up with error message:
<code>Vertex shader error: memory:17:8: error: syntax error, unexpected KW_TEXTURE
</code>
please how do I get it to work? thanks.
I also have playOnLinux
Answer: follow these steps: I am assuming you have installed limbo using playonlinux

Click on the game icon inside playonlinux and then click configure.
Go to installed component tab.
Install the following packages:
vcrun2013, dxfullsetup and dotnet45.

Simply put, all those dependencies that this game requires to be playable on windows, must be installed on Linux as well.  P.S. Three package mentioned above worked for me, you might need to install more based on your system.

Limbo not playing on Ubuntu 16.04 LTS


Coloured background given different equation lines in ggplot2

Question: I have a plot that looks as follow:
set.seed(1)
df=data.frame(x=runif(100)*10,y=runif(100)*10)
ggplot(df, aes(x=x, y=y) ) + geom_point() + theme_classic2()+
geom_abline(intercept = 4, slope = 2, color="gray",linetype="dotted")+
geom_abline(intercept = -3, slope = 2, color="gray",linetype="dotted")

I wish to grade the areas over/between/under the dotted line according to what shown in the plot below. What things can I try?
Answer: I think you'll need to just work out the coordinates of the individual polygons and place them under your points:
library(ggplot2)
library(survminer)
#> Warning: package 'survminer' was built under R version 3.6.3
#> Loading required package: ggpubr
#> Loading required package: magrittr

set.seed(1)
df <- data.frame(x = runif(100) * 10, y = runif(100) * 10)
ggplot(df, aes(x = x, y = y)) +
  geom_polygon(data = data.frame(x = c(0, 0, 20, 20), y = c(4, 44, 64, 44)),
               fill = "green") +
  geom_polygon(data = data.frame(x = c(0, 0, 20, 20), y = c(-3, 4, 44, 37)),
               fill = "yellow") +
  geom_polygon(data = data.frame(x = c(0, 0, 20, 20), y = c(-20, -3, 37, -20)),
               fill = "orange") +
  geom_point() +
  theme_classic2() +
  geom_abline(intercept = 4, slope = 2, color = "gray", linetype = "dotted") +
  geom_abline(intercept = -3, slope = 2, color = "gray", linetype = "dotted") +
  coord_cartesian(xlim = c(0, 10), ylim = c(0, 10))

Created on 2020-05-13 by the reprex package (v0.3.0)
Comment: Thanks @A.joh. If you want to use data (including formulas) to draw shapes and colours in ggplot, you need to use a geom. The other options you have here would be geom_ribbon and geom_area. It would certainly be possible to create an easy-to-use solution by wrapping this up in a function or creating a new geom. However, this probably isn't worth doing unless you are going to create a lot of plots like this.
Comment: @A.joh you would use geom_area or geom_ribbon for these. If you want to post a new question with an example of what you're looking for I'd be happy to take a look at a more general solution
Comment: Thanks Allan! It works perfectly. Though, I hoped for a bit more fix solution. If nothing else shows up until the day after tomorrow, I'll accept your answer.
Comment: U are right. That is exactly what I want to do. I'll go with this solution. Thanks!
Comment: Do you have any suggestions on how to handle non-linear functions?
Comment: Thank you! I think I sought out following your guidelines!


Infrastructure for Project Using Prism, RIA, EF

Question: I want to create an infrastructure for a Silverlight project using Prism, RIA, EF
The main structure of my project is as follow:
Silverlight:

Infrastructure
Module A
Module B
Shell

Web:

ServiceA
ServiseB
DataService
MainWebApp

The EF Model Contains in DataService And ServiceA,ServiceB Refrence DataService For Create DomainService Class
ModuleA uses ServiceA as Ria link And ModuleB uses ServiceB as Ria link
ModuleA, ModuleB and shell refrences Infrastructure
But the main problem is Infrastructure Project
Infrastructure needs EF Entity for Create common interface to Modules
but how Infrastructure project references EF entity?
Answer: What I can understand from your problem is you need to have poco entity classes that you can share among your core i.e., Infrastructure and web applications (Silverlight in your case).
How you do this:

You need to create two libraries; one for core and another for silverlight.
Create POCO entities in core library.
Add these poco entities as link in your silverlight library.


C++ type of item

Question: Here is my code:
using namespace std;

class SimpleProduct {
    char look = 'x';
    string name = "Undefined";
    string type = "Undefined";
    string description = "Undefined";
public:
    char getLook() const {return look;}
    string getType() const {return type;}
    string getName() const {return name;}
    string getDescription() const {return description;}
    SimpleProduct(char look = 'x', string &&name = "Undefined", string &&type = "Undefined", string &&description = "Undefined");
    virtual string toString() const;
};

class TallProduct : public SimpleProduct {
public:
    TallProduct(char look, string &&name = "Undefined", string &&type = "Undefined", string &&description = "Undefined");
    string toString() const;
};

All of products are saved in attribute unique_ptr<Product> ***products; of another class and I want to check, whether some specific product is type Product or TallProduct.
So for example:
if (y != 0 && products[x][y-1][position] is type TallProduct) {  //pseudocode
        return 0;
    }

Comment: `unique_ptr ***products;` Please don't be a three star programmer.  Build a NDMatrix class that uses a single dimension vector under the hood so you can have RAII semantics.
Comment: Recommended reading: https://wiki.c2.com/?ThreeStarProgrammer
Comment: If you're using GCC you have the `typeof` operator. https://gcc.gnu.org/onlinedocs/gcc/Typeof.html - Furthermore there is `typeid`. http://www.cplusplus.com/reference/typeinfo/type_info/
Comment: Can you change the class definition? You could add a virtual bool method returning false in the base class and true in the derived class.
Comment: Are you sure you want to take `string&&`s?
Comment: @FinnRayment Isn't `typeof` static? The docs you linked to says it gives the type of an expression, not the dynamic type of an object.
Comment: @LightnessRacesBY-SA3.0 Oups! Indeed it does. I retract half of my statement.
Comment: Since products are unique pointers, could I do something like this?
`products[x][y-1][position].get() == TallProduct`
What syntax should I use here to say that I want to compare it name of the type? Simple 'TallProduct' is not enough.
Answer: If you use dynamic_cast<>, you can check if type is something specific if it is inherited and it is polymorphic.
Here is a small sample:
class A {
    public:
    virtual ~A() {};
};
class B : public A {};
class C : public A {};

int main() {
    A* b = new B();
    C* c = new C();
    std::cout << (dynamic_cast(b) != nullptr) << "\n";
    std::cout << (dynamic_cast(c) != nullptr) << "\n";
}

which creates following output:
1
0

That means b is from type B but c is not.
Comment: @MikeVine yea,just noticed. upading my answer that it works on polymorphic classes.
Answer: To get this to work, you need to do two things:

Add at least one virtual function to your SimpleProduct, so that the hierarchy gets a vtable. You want the virtual destructor here, so that unique_ptr will do it's job properly: virtual ~SimpleProduct() = default
Check the conversion with the pointer-variant of dynamic_cast, i.e. auto tallProduct = dynamic_cast<TallProduct*>(products[x][y-1][position]); You can proceed if the pointer is not nullptr

Note that this is generally considered bad style, because it violates the "Tell, don't ask" mantra of OOP
Comment: Should this do a thing?

`auto tallProduct = dynamic_cast(products[x][y-1][position]);
    if (y != 0 && typeof(tallProduct) == TallProduct) {
        return 0;
    }`
Comment: For this, you want `if (y != 0 && tallProduct != nullptr) { return 0; }`

C++ type of item


How to clearly distinguish a login page from a register page?

Question: I recently conducted a series of user experience evaluation sessions for a prototype application that had been developed with the goal of capturing user experience bottlenecks and other issues.
Each test subject was placed in front of a computer with the application open on the login screen and a series of tasks for the user to complete. The first task required that the user register an account, which has to be achieved via the register screen naturally, but can easily be navigated to via the login screen.
Yet, in two-third of the sessions, the test subject began attempting to register their account via the login page. The subject either realised their error when the system returned an error as they pressed 'Login' or as they were navigating to the second form field.
Here are the respective forms:

Aesthetically, they are quite similar. The only differences are that the register form is, naturally, more lengthy and each form has a different title at the top.
My question is: is there a standardised way in which a login page can be distinguished from a register page, or is this confusion commonplace across different applications?
Answer: I don't see anything wrong with those two pages. They are everything you expect them to be.
You have the titles "Sign in to your account" and "Register your account", you have the buttons clearly stating "Sign in" and "Sign up".

Yet, in two-third of the sessions, the test subject began attempting
  to register their account via the login page

I blame this on your audience for their lack of involvement and trying to finish as fast as possible.
There is no color or layout that instantly says "Hi, I'm the login screen".
I tend to add one more functionality to the login page though. If someone tries to login but there's no user with that email (or in this case, tries to use the login form to register), instead of a classic "error", I display something like:

"Oups, we couldn't find any account registered to this email address,
  do you want with proceed to registration?"

And if the user clicks proceed to registration (or you can add yes/no buttons), it takes them to the register page with the email address already filled in from the login page via a url query string.
Comment: As a side-note. While providing the user with a message saying no accounts are registered with the used email address may be sound from a UX perspective this has consequences security wise. A malicious user can utilize this to enumerate, which email addresses (and through that people) have registered an account. This may be a big deal depending on the nature of the application. From a security perspective it's recommended to NOT provide such detailed response messages on failed login attempts.
Comment: Another link voting against detailed/specific response messages on failed login attempts is this: https://ux.stackexchange.com/a/13523/53671
Answer: Please use "Log in" instead of "Sign in" if you are using "Sign up" word. If you see top brands, they follow this simple rule to avoid confusion with similar looking words. If you use some other words except "Sign up" like "Register" or "Create Account", then "Sign in" is okay.
In placeholder, three dots after text is unnecessary. Also, placeholder text could be different. Like instead of "Enter your E-mail ID", it could be an example like = "Eg: firstname.lastname@example.com". As you are using label, so you can use placeholder area differently.
See text is a vital part of UX. So choose it carefully. Like "Register your account" is a bad text. Instead "Create an account" is clear.
Answer: It is important to differentiate "Sign in" and "Sign up" when the forms are displayed on the same page or box.
If 'Sign In' and 'Sign Up' are close and buttons look too similar and both use the same verb in their labels it's easy for users to get confused. Users might click one instead of the other or they'll spend extra time to distinguish the two buttons.
In that case, you can use the primary style button and the secondary one.
Also, avoid using 'sign up' and 'sign in' on the same page. Instead, make the button distinct from each other by using "Login" and "Register".
If the buttons are displayed on separate pages, I don't see the need for different styles, but you can change the text.
Answer: Simply placing the "New user?..." panel above the login form may prevent the kind of user behaviour you describe.
Comment: The apparent confusion from the users the OP was talking about was that when looking at the login page, they were treating it as the register page. I wasn't suggesting removing the screen titles, just moving the "New user?" panel up below the "Sign in to your account" title to help reinforce the fact that the register page is elsewhere (i.e. via the link).
Comment: How is this different from the "Register your account" vs "Sign in to your account" above the panels?
Comment: Thanks for clarifying - I understand your comment now! :)


ramda js compose with find, pick with trim values

Question: const obj = [
 {id: 1, name:'name1  ', age: 26, city: 'city1     '},
 {id: 2, name:'name2', age: 24, city: 'city2  '},
 {id: 3, name:'  name3', age: 28, city: '      city3  '},
 {id: 4, name:'name4  ', age: 25, city: 'city4  '}
]

i have function like
id might be 1,2,3,4...or..'All'
getData(id, obj) {
  if(id && id !=='All'){
    const res = obj.find((o) => o.id === id)
    return `${res.name.trim()} ${res.city.trim()}`
  } else if(id === 'All') {
    return 'All'
  }
  return ''
}

getData(1, obj) // name1 city1
getData('All', obj) // All

i have tried ramda js to convert the above code,
getData(id, obj) {
  return (id !== 'All') ? compose(R.find(R.propEq('id', id)))(obj) : 'All'
}

expected o/p is
getData(1, obj) => 'name1 city1'
getData('All', obj) => 'All'
getData('', obj) => ''

how to pick(name, city) and trim the values using ramda. any help
Comment: I would want to ask first whether you couldn't scrub your data up front, that is, use the result of `R.map(R.evolve({name: trim, city: trim}))(obj)` for further work.
Answer: You almost got it correct. Don't use compose:
const getData = (id, xs) =>
    typeof id !== "number" ? id :
    R.find(R.propEq("id", id))(xs);

You can't compose a function with a list.
Answer: I would do something like the following
const getData = (id, obj) =>
  id == 'All' : 'All'
  ? R.pipe(
      R.find(R.propEq('id', id)),    // {id: ..., name: '  foo', city: 'bar  '} | null
      R.ifElse(
        R.isNil,                     // if null
        () => '',                    // then ''
        R.pipe(                      // else
          R.props(['name', 'city']), // ['  foo', 'bar  ']
          R.map(R.trim)              // ['foo', 'bar']
          R.join(' ')                // 'foo bar'
        )
      )
    )(obj)

Hope this helps you :)


How do I enchant a bow with Mending and Infinity?

Question: In Minecraft: Xbox One Edition, I wanted to make a bow with Unbreaking III, Flame I, Infinity I, Power V, Punch II, and Mending I, but it won't let me add Mending I. Why won't it allow me to make such a bow?
Comment: Please clarify what you have already tried in detail.
Comment: Are you really playing [Minecraft:Xbox One Edition](https://minecraft.gamepedia.com/Xbox_One_Edition), a game that was discontinued in 2017?
Answer: Infinity and Mending are mutually exclusive, meaning that they cant be on the same bow. You can only pick one between infinite arrows and infinite durability.
Answer: You would have to play in version 1.8. I believe in that time you were actually able to get both Infinity and Mending on one bow, but it has been removed.
Answer: go into version 1.9 enchant the bow to have infinity and mending, then quit and go into whatever version you want. when you load that world you will have the bow. to get it into other worlds utilize the hotbar save function and save it to it. open the bookshelf button in creative and it should be there for other worlds.
Comment: please re read the entire question. this answer does not work
Answer: A skeleton horseman may RARELY drop a bow enchanted with both infinity and mending, but since skeleton horsemen are already so rare and hard to kill, it's almost impossible.
Tips for obtaining the bow:
Skeleton horses may spawn during thunderstorms, prepare yourself with a full set of armour, an enchanted bow and a sword (ideally enchanted with smite and looting). As you approach the skeleton horse, lighting will strike it again and spawn four skeleton horsemen equipped with iron helmets and enchanted bows, kill the riders but DO NOT KILL THE SKELETON HORSES as it is passive and ridable by you. Then if the skeletons are happy they with drop their bow(s).
Comment: This is not possible. Mending and Infinity are incompatible.
Comment: I did some testing myself.. skeleton horsemen will only ever drop bows with power I, unbreaking I, or both.. they won't even drop with infinity or mending.. this is coming from the drops of over 1000 skeleton horsemen. It's impossible via this method.. I also don't believe regular skeletons can spawn with them.. nor do I think one can be fished by chance.. I really do think the devs tied up all loose ends.. it might simply be impossible without commands.
Answer: There are 2 methods of doing this. The first one is to fish almost 7000 times and hope for one. The other way is to try to kill skeletons for them.


file uploaded from openapi swagger not getting received at backend python function

Question: I am trying to take a file from user using Openapi 3.0 and swagger UI. However i am not getting that file for processing in my python function. Below is my code:
code.py
def get_file():
    try:
        file=request.files.getlist('file')[0]
        with open(file, 'r') as fp:
            files = {"file": (file, fp)}
            response = requests.post(server, files=files)
            return response.json()
    except Exception as exc:
        return exc

api.yaml
  /get-result:
    post:
      summary: "A function to get file"
      operationId: "code.get_file"
      requestBody:
      content:
        application/json:
          schema:
            type: string
              format: binary
      responses:
        200:
          description: "executed successfully"
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/myschema"
        500:
          description: Server is down.

I have already referred this link: Upload a file in Swagger and receive at Flask backend
However this is for Openapi 2.0 and didnt help as I am using openapi 3.0
Answer: check if
request.files['file']

can get the file from the request, I'm not sure if the line
file=request.files.getlist('file')[0]

will actually get the correct file (or only a list?)
Answer: Below code changes helped me to get this resolved:
api.yaml
/get-result:
    post:
      summary: "A function to get file"
      operationId: "code.get_file"
      requestBody:
        content:
          multipart/form-data:
            schema:
              type: object
              properties:
                file:
                  type: string
                  format: binary
      responses:
        200:
          description: "executed successfully"
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/myschema"
        500:
          description: Server is down.

In below code.py it was essential to pass the parameter 'file' to the function which is also the field name in openapi specification. Also its important to send file pointer and filename with the post request
code.py
def get_file(file):
    try:
        fp=file.read()
        file.save(file.filename)
        response = requests.post(server, files={"file":(file.filename,fp)})
        return response.json()
    except Exception as exc:
        return exc


Fixing display issues on Intel 82845GL

Question: I have opened up this question on launchpad too, but in the interest of getting a bigger response base I am posting it here, hoping someone will pick it up.
Natty doesn't behave very well with the Intel 82845GL chipset. I booted my old machine with Natty today to test drive it. The specs are:
Processor: Celeron 2.4GHz
Video: Intel 845GL
RAM: 1GB
The first problem is that the display is borked! What do I mean? Well, see for yourself:

If that gets fixed (and it did for a while but is back now), Unity is disabled.
I think these issues are owed to hardware acceleration being disabled...or in other words not the right driver for my hardware. A google search on 'intel 82845GL ubuntu' does return other users having similar problems in the past but I haven't been able to pick out a solution in the many many discussions on the subject- partly owed to my 'linux naivety' I guess...but maybe you can help?
Answer: Unity 2D is designed for old chipsets such as the 845 and 855 intel series.
Your issues are most probably due to buggy old drivers together with Compiz incompatibilities.
Suggest boot into recovery mode - with network support.  Then install unity-2D

How do I install and switch to the Unity 2D desktop?

I have found with my i855 laptop that I need to boot with an extra grub parameter otherwise I get a similar login screwed up display -
can I suggest that you also see if either grub string i915.modeset=0 or i915.modeset=1 works for your PC.  Follow my answer here on how to add it to grub - instructions also include how to fix in grub permanently.
As an alternative to Unity-2D, you could try a light-weight distribution such as Lubuntu (or possibly Xubuntu) which should work much better with very old graphics chipsets such as the i8xx chipsets.
Comment: Yeah, it's down to buggy drivers (& hardware too it seems). I have managed to install and run Unity 2D successfully using the 'nomodeset' option...but the system response is visibly laggy. Any suggestions on what else can be done?
Comment: Both Lucid Karmic will make things worse due to blacklisting and lockup issues - https://wiki.ubuntu.com/X/Bugs/Mavericki8xxStatus     It may be worth experimenting with xubuntu or lubuntu to see if things are better.
Comment: I have now moved to Lubuntu and it is amazing! Probably the right choice for this hardware
Comment: That's good news - I'll add this into my answer.
Answer: The Intel 845 series chips have serious hardware errata.  The Windows drivers at the time and the old Linux driver stack didn't exercise the parts of the hardware that don't work, so didn't run into problems.
The new Linux graphics stack (GEM/KMS/DRI2) exercises these hardware features.  We disabled the Intel driver on your card because of this.  This is why Unity doesn't work for you.  See this answer for more details.
The video mode issue would appear to be a different problem.  Logs (dmesg and /var/log/Xorg.0.log) are the price of admission for debugging that sort of problem.
Comment: When you say hardware errata...do you mean its buggy hardware? (i.e. stuff that can never be resolved?).
I fixed the video problem using 'nomodeset'. I have tried modifying 'xorg.conf' to manually enable the Intel driver as per [this page](https://wiki.ubuntu.com/X/Bugs/Mavericki8xxStatus). This just results in a black screen after splash. What else can I do?
I'll post dmesg and Xorg.log if it can help
Answer: I found this to work for Ubuntu 17.04 on a Dell Inspiron 1100.  It has the 82845GL.  Don't forget to sudo update-grub.
stupid ~ 148# rcsdiff -r1.1 /etc/default/grub
===================================================================
RCS file: /etc/default/RCS/grub,v
retrieving revision 1.1
diff -r1.1 /etc/default/grub
11c11
< GRUB_CMDLINE_LINUX_DEFAULT="quiet splash"
---
> GRUB_CMDLINE_LINUX_DEFAULT="quiet splash acpi=off vga=auto"
25a26,27
> GRUB_GFXMODE=1024x768
> GRUB_GFXPAYLOAD_LINUX=keep
stupid ~ 149#

This is for X version:
stupid ~ 163# X -version

X.Org X Server 1.19.3
Release Date: 2017-03-15
X Protocol Version 11, Revision 0
Build Operating System: Linux 4.4.0-83-generic i686 Ubuntu
Current Operating System: Linux stupid 4.10.0-28-generic #32-Ubuntu SMP Fri Jun 30 05:31:03 UTC 2017 i686
Kernel command line: BOOT_IMAGE=/boot/vmlinuz-4.10.0-28-generic root=UUID=145b8481-54a0-4fc1-b0d4-fe0ce02a3eb3 ro quiet splash acpi=off vga=auto vt.handoff=7
Build Date: 17 July 2017  02:37:53PM
xorg-server 2:1.19.3-1ubuntu1.1 (For technical support please see http://www.ubuntu.com/support)
Current version of pixman: 0.34.0
        Before reporting problems, check http://wiki.x.org
        to make sure that you have the latest version.

Fixing display issues on Intel 82845GL


Recursively search Properties in class decorated by attribute

Question: I would like to get all properties decorated by attribute AggregateAuthorizeIdentifier. It is core functionallity, so should be as fast as posible.
I can search recurvicvely via all properties but I would check all System and 3rd parties libs. But it isn't optimal solution.
Have you met with such a problem?
public class ReadOrderHistoryQuery
{
    public List<string> Ordering { get; set; }

    public Criteria Criteria { get; set; }

    public class Criteria
    {
        [AggregateAuthorizeIdentifier]
        public int UserId { get; set; }

        public string InvoiceId { get; set; }
    }
}

my solution:
    static IEnumerable<PropertyWithAttribute> GetAuthorizeIdentifierAttribute(object command)
    {
        var attributedProperties = GetAuthorizeIdentifierAttribute(command.GetType());
        return attributedProperties;
    }
    static IEnumerable<PropertyWithAttribute> GetAuthorizeIdentifierAttribute(Type type)
    {
        //check current property
        var result = type.GetProperties()
            .Where(prop => Attribute.IsDefined(prop, typeof(AggregateAuthorizeIdentifierAttribute)))
            .Select(p => new PropertyWithAttribute()
            {
                Property = p,
                Attribute = p.GetCustomAttribute<AggregateAuthorizeIdentifierAttribute>(true)
            })
            .ToList();
        //deeper check all properties
        result.AddRange(type.GetProperties()
            .SelectMany(p => GetAuthorizeIdentifierAttribute(p.PropertyType)));
        return result;
    }

Comment: `But it isn't optimal solution.` why do you think that?
Comment: My solution search via all System properties, like String, List, etc. and 3rd parties. It is quite unnecessary.
Answer: Finnaly I achived it with additional type selector (by string).
    const string PropertyTypeStartWithSelector = "Diabdis.";

    static IEnumerable<PropertyWithAttribute> GetAuthorizeIdentifierAttribute(Type type, string propertyPathPrefix)
    {
        var properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
        //check current property
        var result = properties
            .Where(prop => Attribute.IsDefined(prop, typeof(AggregateAuthorizeIdentifierAttribute)))
            .Select(p => new PropertyWithAttribute()
            {
                PropertyPath = propertyPathPrefix == null ? p.Name : $"{propertyPathPrefix}{PropertyPathSeparator}{p.Name}",
                Attribute = p.GetCustomAttribute<AggregateAuthorizeIdentifierAttribute>(true)
            })
            .ToList();

        //check deeper properties, BUT just selector classes
        result.AddRange(properties
            .Where(p => p.DeclaringType.FullName.StartsWith(PropertyTypeStartWithSelector))
            .SelectMany(p => GetAuthorizeIdentifierAttribute(p.PropertyType, propertyPathPrefix == null ? p.Name : $"{propertyPathPrefix}{PropertyPathSeparator}{p.Name}")));
        return result;
    }

Answer: When I need to do something like that, I always do it like this :
object objectToSearch = ...

PropertyInfo[] properties = objectToSearch.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance);
if (properties != null && properties.Length > 0)
{
    properties.ToList().ForEach(p =>
    {
        if (p.GetCustomAttributes(typeof(AggregateAuthorizeIdentifierAttribute), false).Count() == 1)
        {
            // Do something with the property
        }
    });
}

According to that, you can make an extension method to return all the properties of an object that has a specific attribute
Comment: Binding is useful, but does not solve problem with searching within System module (like List, Dictrionaries, etc.)


Adapter in android which is using same overriden method

Question: I am using switch case in which i am setting the adapter which is having same overridden method with duplicate code ,so i want to minimize it .
private void settingAdapter(int position) {
    switch (position) {
        case 0:
            adapter = new SongAdapter(getContext(), false, false)
            {
                @Override
                protected void onOverScrolled() {
                    super.onOverScrolled();
                    if(nextPageCount==null||nextPageCount.isEmpty())
                    {
                        return;
                    }
                    else {
                        int count = Integer.parseInt(nextPageCount);
                        getList(count);
                    }
                }
            };
            customList.setAdapter(adapter);
            break;
        case 1:
            adapter = new ArtistAdapter(getContext(), false, false, false){
                @Override
                protected void onOverScrolled() {
                    super.onOverScrolled();
                    if(nextPageCount==null||nextPageCount.isEmpty())
                    {
                        return;
                    }
                    else {
                        int count = Integer.parseInt(nextPageCount);
                        getList(count);
                    }
                }
            };
            customList.setAdapter(adapter);
            break;
        case 2:
            adapter = new AlbumAdapter(getContext(), false, false){
                @Override
                protected void onOverScrolled() {
                    super.onOverScrolled();
                    if(nextPageCount==null||nextPageCount.isEmpty())
                    {
                        return;
                    }
                    else {
                        int count = Integer.parseInt(nextPageCount);
                        getList(count);
                    }
                }
            };
            customList.setAdapter(adapter);
            break;
        case 3:
            adapter = new PlaylistAdapter(getContext(), false, false){
                @Override
                protected void onOverScrolled() {
                    super.onOverScrolled();
                    if(nextPageCount==null||nextPageCount.isEmpty())
                    {
                        return;
                    }
                    else {
                        int count = Integer.parseInt(nextPageCount);
                        getList(count);
                    }
                }
            };
            customList.setAdapter(adapter);
            break;
    }

}

Answer: Can't you just make all your Adapters extend the same class?
public class BaseAdapter extends SomeAdapterOfYours {
    //... everything needed

    @Override
    protected void onOverScrolled() {
        super.onOverScrolled();
        if(nextPageCount==null||nextPageCount.isEmpty()){
            return;
        }
        else {
            int count = Integer.parseInt(nextPageCount);
            getList(count);
        }
    }
}

And then your custom adapters:
public class ArtistAdapter extends BaseAdapter {
  //custom adapter stuff
}

public class SongAdapter extends BaseAdapter {
  //custom adapter stuff
}

and so on...
Answer: If you are using the same adapter the best strategy is create a CustomAdapter adapter in a class in a new file, import it in your Activity and create a instance every time you need it.
If you don't want to do it, you can control the case when you not setup the adapter and in the default: set it. You only need here one adapter.


Renaming filenames and immediately reading files having issues in php

Question: I have pdf files which are report cards of students.The report card names format is <student full name(which can have spaces)><space><studentID>.I need to download files.For this I have used the following code.
if(file_exists($folder_path.'/') && is_dir(folder_path)) {
    $report_files = glob(folder_path.'/*'.'_*\.pdf' );
    if(count($report_files)>0)
    {
        $result_data = '';
        $result_data = rename_filenamespaces($report_files);
        var_dump($result_data);//this shows the edited filename

        foreach ($result_data as $file) {
            if (strpos($file,$_GET['StudentID']) !== false) {
                 //code for showing the pdf docs to download
            }
        }
    }
}

//function for renaming if filename has spaces
function rename_filenamespaces($location)
{
    $new_location = $location;
    foreach ($location as $file) {
       //check file has spaces and filename has studentID
       if((strpos($file," ")!==false)&& (strpos($file,$_GET['StudentID']) !== false))
       {
           $new_filename = str_replace(" ","-",$file);
           rename($file,$new_filename);
           $new_location = $new_filename;
       }
    }
    return $new_location;
}

The variable $result_data gives me the filename without spaces,but the for each loop is showing Warning:Invalid argument supplied for foreach(). But the filename is changed in the server directory immediately after running the function. This warning shows only for first time. I am unable to solve this.
Answer: $new_location = $new_filename;

$new_location is a array
$new_filename is a string
You have to use $new_location[$index]
or try
foreach ($new_location as &$file) {
...
...
$file = $new_filename;


Equal and not equal in PHP query

Question: I need to show a list of exhibits from a database. Some are events (shows lasting only one day), marked with a checkbox. I don't want to include those.
When running my Query without and selector, I get 103 results.
If I add this line
    AND `event`.`meta_value` = 'on'

I get 23 results (the events). It works well.
If I add that line instead
    AND `event`.`meta_value` != 'on'

I get 12 results. They are not events, but it is missing 68 posts.
I also tried using <> instead of != with a similar result.
Comment: @Skaddict, have you been able to check whether my suggestion was true?
Answer: They other 68 posts most likely have NULL as value, you should also be able to see this for yourself if you check the database. They won't show up with = or != ... If you want to see them you'll have to change your query to specifically look for the attribute being NULL:
AND `event`.`meta_value` IS NULL

Comment: Thanks! I managed to get the missing results with that solution. I still don't know why some events are only fetched using `!= 'on'` but I combined both condition to get all the posts I needed.
Comment: Glad it helped, `NULL` is not seen as a value so you can't compare anything to it. that's why it's not coming up when doing `!=`. Not even `NULL` can be equal to `NULL` ;') found a nice metaphor for it. `NULL` is the abscense of an answer. if you ask 2 people how old they are, and they both refuse to answer you'll have `NULL` for both. that doesn't mean they are of equal age. Nor does that mean they have the same age. There is simply no way to compare the two :) so yes you must do both `!=` and `IS NULL` to get the complete set that you want.
Comment: Thanks for the great answer, that makes so much sense now!

Equal and not equal in PHP query


Grunt Usemin and Concat not working

Question: I have been searching for solution regarding, Grunt Usemin, Copy tools.
Finally i have decided to write it down here.
this might help others.
Html Snippet
<code>  <!-- build:js ${pageContext.request.contextPath}/assets/js/main.js -->
  <!-- app:js -->
  <script src="${pageContext.request.contextPath}/js/script-test-one.js"></script>
  <script src="${pageContext.request.contextPath}/js/script-test-two.js"></script>
  <script src="${pageContext.request.contextPath}/js/script-test-three.js"></script>
  <script src="${pageContext.request.contextPath}/js/script-test-four.js"></script>
  <!-- endapp -->
  <!-- endbuild -->
</code>
Grunt Build Command

grunt build

Output I am getting
<code>└───concat
    ├───${pageContext.request.contextPath}
    │   └───assets
    │       ├───js
    │       └───style
    └───assets
        └───style
</code>
I am getting empty folders, how can i remove ${pageContext.request.contextPath}/ from the path, because when i had removed from html files things are working fine. since we need contextPath before each path this new issue has came up.
Answer: I have come across cdnify grunt tool where i have created to task
Clean --> Will remove ${pageContext.request.contextPath}/ prefix
Dev   --> Will add ${pageContext.request.contextPath}/ prefix
In Between all the others tasks are working smoothly.

Grunt Usemin and Concat not working


GitActions - How do I check if the logged in user is part of a team

Question: In a GitActions YAML file how do I check to see if a User is part of a Team in Github ?
I know that the username can be got via ${{ github.actor }}
Note: The requirement is to allow only specific authorized users to be able to run a job within a workflow. (Say we restrict a step to the DBA team members)
Note: I am aware of Environments and the "Require reviewer" option. But this does not quite fit into the requirement.
Answer: You can use the get-user-teams-membership action for that. A workflow would look something like this.
name: Check user for team affiliation
on:
  pull_request:
    branches:
      - develop
jobs:
  check-user:
    name: Team affiliation
    runs-on: ubuntu-latest
    steps:
      - name: Check user for team affiliation
        uses: tspascoal/get-user-teams-membership@v2
        id: teamAffiliation
        with:
          GITHUB_TOKEN: ${{ secrets.TOKEN }}
          username: ${{ github.actor }}
          team: your-team-name
      - name: Stop workflow if user is no member
        if: ${{ steps.teamAffiliation.outputs.isTeamMember == false }}
        run: |
          echo "You have no rights to trigger this job."
          exit 1

You can also try this with the github-script action. Could be a bit more difficult but also gives you more freedom.
Comment: By adding an output to the job you could use the `if` on the job level of a future job as well. See: https://stackoverflow.com/questions/75612801/my-github-env-changed-but-i-want-it-stable/75613524#75613524


I am getting this error when try to build the apk through Android studio

Question: I am getting this error when trying to build the apk through Android studio. Here is the exception I've got:
FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':My_Service:transformClassesWithJacocoForDebug'.
    > There was a failure while executing work items
       > java.util.concurrent.ExecutionException: org.gradle.workers.internal.DefaultWorkerExecutor$WorkExecutionException: A failure occurred while executing com.android.build.gradle.internal.transforms.JacocoTransform$JacocoWorkerAction

Whereas, there is not such error when I do build through command window using command:
./gradlew assembleRelease assembleReleaseUnsigned

Comment: Without information about you system its really hard to provide help.
Comment: I am running it on ubuntu.
Comment: Version ? Version of Java ... etc, so much more info to be provided
Comment: Android-studio version 3.0.1 java-openjdk version "1.8.0_162" gradle -version 4.1
Comment: The issue is coming once the gradle version is updated from 3.0.0 to 3.1.4
Comment: @SangameshItagi did you find any solution to it ??
Answer: I've created an ImageAsserts of arrow icon where I've removed all variants of dpi. xml file except any-dpi.xml which resulted into this mentioned exception. After removing this exception got resolved.


What could be possible causes behind intermittent ReferenceError/TypeError in browsers?

Question: We have a web application that renders HTML pages and includes some external JavaScript files which define variables like jQuery, $, app etc.
We track client-side JavaScript errors in Bugsnag and sometimes we receive errors like Uncaught ReferenceError: $ is not defined or ReferenceError: Can't find variable: app.
What could be possible causes behind this? Two that I can guess are: user might have clicked "Stop" in browser and JS files didn't completely load but inline JavaScript within page was still executed (is that possible?), or some JavaScript files were blocked by a browser plugin/extension.
We have observed it happening in all major browsers (Firefox/Chrome/Safari etc.), but its occurrence is quite rare - usually once in thousands of requests.
Here is the excerpt from page:

Comment: Those errors are impossible to debug without a sample that reproduces the issue... The error messages themselves are very clear, but there's nothing we can tell you other than that.
Comment: I'm just interested in knowing "possible" causes (that can be generalised for any web page) that may throw this error and whether or not my two hypothesises could be true.
Comment: Those error messages are as general as they get: For some reason, the variable doesn't exist.
Comment: "For some reason" <-- I'm interested in knowing what could be those possible "reasons" specially when it works 99+% of the time and is very likely not an issue with the code itself. I've also added a code sample in question on your recommendation.
Comment: I have the same issue
Answer: One plausible explanation is that certain browser extension is blocking those scripts from loading (e.g., an ad blocker).


vector msg {} not buildingfor C++ in VS Code on Mac

Question: I'm trying to configure VS Code on a Mac (Intel) to develop with C++. I'm following the setup on the VS Code web site. Following all of the steps when I get to the Terminal - Run Build Task the build fails and indicates the it expected a ";" after 'msg'. I can run the same file in XCode with no issues, but VS Code fails. Here's the full code from the VS Code Setup site.
#include <iostream>
#include <vector>
#include <string>

using namespace std;

int main()
{
    vector<string> msg {"Hello", "C++", "World", "from", "VS Code", "and the C++ extension!"};

    for (const string& word : msg)
    {
        cout << word << " ";
    }
    cout << endl;
}

Comment: initializing `std::vector` with initializer list is supported from `c++11` on-wards. Does your compile support `c++11` or later?
Comment: fails how? What is the error message?
Comment: All the error message says is that it expects a " ; " after msg.
Comment: @Harry this is a 2019 MBA and the version for clang++ says:
clang version 12.0.0 (clang-1220.127.116.11)
Comment: https://stackoverflow.com/questions/66680147/how-to-change-c-version-being-used-by-vscode
Answer: I, too, had this same problem/error message with the same source code using my Mac Studio with M1 based on Apple arm64 silicon.
First, the source code comes from a tutorial: Using Clang in Visual Studio Code.
When I run the code, I get this error for vector<string> msg:
expected ';' at end of declaration
range-based for loop is a C++11 extension [-Wc++11-extensions]

Second, as @Harry mentioned in a comment for this question:

initializing std::vector with initializer list is supported from c++11 on-wards.

Solution: add a compiler version to tasks.json that supports vector<string> msg. For me, I used -std=c++17 to the "args" list to solve the problem.  As an FYI, I verified that -std=c++11 also solves the problem. Even -std=c++2b for the 2023 standard works with the Xcode version 14.2 command line extensions.
So, the default tasks.json file created for me in the tutorial from code.visualstudio.com was missing any reference to a compiler version directive.
Here is my updated tasks.json file with the one new element added to the args list:
{
    "tasks": [
        {
            "type": "cppbuild",
            "label": "C/C++: clang++ build active file",
            "command": "/usr/bin/clang++",
            "args": [
                "-fcolor-diagnostics",
                "-fansi-escape-codes",
                "-std=c++17",
                "-g",
                "${file}",
                "-o",
                "${fileDirname}/${fileBasenameNoExtension}"
            ],
            "options": {
                "cwd": "${fileDirname}"
            },
            "problemMatcher": [
                "$gcc"
            ],
            "group": {
                "kind": "build",
                "isDefault": true
            },
            "detail": "Task generated by Debugger."
        }
    ],
    "version": "2.0.0"
}


Can I install the drivers offered by HP on my Laptop using Wine?

Question: I am asking this question because the drivers provided on the HP website will cost me around 1.2 GB of bandwidth download.
Before downloading them I wanted to confirm if it's possible to install the drivers provided by HP because they are for MS Windows.
Comment: Read up on what you need to do to update your BIOS; most times you download a file and execute it or upload it from your BIOS. Has not alot to do with using Ubuntu or Windows or Mac OS. And if your BIOS does not cause you any problems I would leave it alone.
Comment: ofcourse :D thats what au is for :D and we all are more than willing to dump all our knowledge on your lap :+ @ankit
Comment: Not recommended to do so!
Comment: Care to tell us why you think you need to download drivers from the HP website. Mind you: this is NOT windows. Linux uses generic drivers.
Comment: @Ankit Is this for a printer? Wireless connection? You have not specified?
Comment: nope, drivers for my mice, graphics, bios etc.
Comment: Oh. Well then, are any of these things not functioning properly?
Comment: i want to update my BIOS drivers. Laptop shipped with f.42 and now HP offers f.63.
Comment: alright, thanks for the information. I was gathering information for my knowledge. :)
Answer: No.
Besides that... I have 3 HP printers here and not one of them needs special drivers from the HP website. The newest of those 3 is a HP PSC 2170. Printer, scanner and cardreader work out of the box.
Printers work through a generic piece of software called CUPS.

CUPS is the standards-based, open source printing system developed by Apple Inc. for Mac OS® X and other UNIX®-like operating systems

You can add printers from dash by searching for printers. It will show this:

You can add printers manually here ...

but after plugging my printer in it gets automatically detected:

The same goes for your mouse, keyboard. Graphics you can install an extra driver for via dash, additional hardware but this is also a native driver (ie. "built by ubuntu for ubuntu"). BIOS is not OS related so I will leave that one out ;)
The only thing I do know that benefits from a windows driver (but that was 3 releases ago) is your wireless card and only if it is a Microsoft based wireless. But I think that those days are behind us.
Comment: And I would appreciate feedback from the person giving me a downvote.


How to replace the string with defalut date?

Question: I have this code.
  string ED= collection["ED"].Replace(string.Empty,"1/1/2011").Split(',').ToString();

when I do this I am geting this error.
String cannot be of zero length.
Parameter name: oldValue

is that something I am doig wrong here?
thanks
Comment: You cannot use `String.Empty` as the string to replace. You need to have a string that is at least 1 character in length
Comment: Yes its collection arry reggie.
Comment: It looks like the error message told you *exactly* what you're doing wrong. What are you still confused about?
Answer: The first parameter of the Replace method cannot be an empty string.
See the exceptions section of this msdn article.
Without knowing a bit more about what you are trying to achieve it is difficult to help any further. As it stands if the Replace method were to succeed then the Split method would convert the string to an array and then the ToString method would return "System.String[]". I doubt this is the result you are looking for.
Answer: oldValue is the first parameter of Replace() so I'm guessing you can't pass string.Empty to that
Comment: no need to guess. If it were valid what would it to, now that would be a stack overflow.
Answer: string.Replace takes replace all insatances of the first argument with the second argument. So "abcabcabc".Replace("a", "z") becomes "zbczbczbc".
Replacing all instances of the empty string is going to lead to an infinate loop of replacements. "".Replace(string.Empty, "a") replaces the empty string with "a", but there's still an empty string before and after the a, which needs to get replaced and so we have "aaa", but there's still an empty string at the begining and end of the string, as well as between the a's, so replacing those we get "aaaaaaa" etc.
Do you actually mean to use the default date if the value is empty? In which case you want to do something like:
var temp = collection["ED"];
if (string.IsNullOrEmpty(temp)) {
    temp = "1/1/2011";
}
string ED = temp.Split(',').ToString();

Comment: temp.Split(',').ToString(); will return "System.String[]" regardless of what value temp contains. The Split() method converts the string object to an array of strings.
Comment: @Andy Rose True. I hadn't even thought about that part of it, had just copied that verbatim from the OP.
Comment: I think `string ED = string.Join("", temp.Split(','))` would do. I'll wait until I've actually tried it before I update.
Comment: Join would work on an array but I guess the next question would be why not just use .Replace(",", "") to remove unwanted commas?


How to query text file version of LibreOffice Thesaurus in bash (joining lines)

Question: I am trying to write a simple script in bash to query the LibreOffice thesaurus extension as a text file. For each input query string, I want the output to be all the related strings. And I want to do this in bash.
To download and extract the thesaurus, I do
wget "https://extensions.libreoffice.org/assets/downloads/41/1653961771/dict-en-20220601_lo.oxt" # download LO dictionary & thesaurus

unzip -p dict-en-20220601_lo.oxt th_en_US_v2.dat > lo # extract contents of thesaurus to text file

Taking a look at part of the text file:
nine|3
(adj)|9|ix|cardinal (similar term)
(noun)|9|IX|niner|Nina from Carolina|ennead|digit (generic term)|figure (generic term)
(noun)|baseball club|ball club|club|baseball team (generic term)
nine-banded armadillo|1
(noun)|peba|Texas armadillo|Dasypus novemcinctus|armadillo (generic term)
nine-fold|1
(adj)|nonuple|ninefold|multiple (similar term)
nine-membered|1
(adj)|9-membered|membered (similar term)
nine-sided|1
(adj)|multilateral (similar term)|many-sided (similar term)
nine-spot|1
(noun)|spot (generic term)

So for example, I want to be able input
"nine" as a query and have bash return something like
9
ix
cardinal
9
IX
niner
Nina from Carolina
ennead
digit
figure
baseball club
ball club
club
baseball team

I think this should be fairly easy to do using the right syntax with awk  or sed, especially since all of the lines containing query terms do NOT begin with "(" and all of the line containing related terms DO begin with "(".
But I'm still somewhat of a newbie, and haven't been able to figure it out yet. The crux of the matter for me seems to be getting the query term and all related terms onto a single line. From there, I know how to sed my way to victory. But getting to that point has proven challenging for me.
TIA for your help!
p.s. I'm trying to do something similar to this, but my situation is a little different, and I don't understand the syntax well enough to modify it for my needs: https://www.unix.com/unix-for-dummies-questions-and-answers/184649-sed-join-lines-do-not-match-pattern.html
Answer: If I understand your problem, an Awk solution
File search.awk:
#! /usr/bin/awk -f

# This block is executed BEFORE input file treatment.
BEGIN {
    # Field Separator
    FS = "|"
}

# The next blocks are executed for each input file line only if the condition in front of the block is true

# '$1' is the first field/column. Remember, field separator in the pipe (|)
$1 == KEY {
    # Key found, flag it
    flag  = 1
    # Associated words init
    words = ""
    # Do not check the next blocks conditions, process the next line of the input file
    next
}

# If the flag is 1 and the line begins with an open parenthesis.
flag == 1 && $0 ~ /^\(/ {
    # Association found
    # For all associations (field)
    # The line treatment starts with the second field
    idx = 2
    # NF is the Number of Fields in the current line
    while (idx <= NF) {
        # get the current field word (idx in the field number, $ids it is its value)
        word = $idx
        # remove term in parenthesis
        # (in fact, replace all characters after the ' (' token by an empty string)
        gsub(/ \(.*$/, "", word)
        # save it (add it in 'words' string with a coma as separator)
        words = words "," word
        # next field
        idx += 1
    }
}

# If the flag is 1 and the line NOT begins with an open parenthesis.
#  It's the end of KEY treatment
flag == 1 && $0 !~ /^\(/ {
    # End of association
    flag = 0
    # Print Key and words
    if (words != "") {
        print KEY words
    }
    # Reinit words
    words = ""
}

# This block is executed AFTER input file treatment.
END {
    # Special case, last word in thesaurus
    # Print Key and words
    if (words != "") {
        print KEY words
    }
}

Executable with:
chmod +x ./search.awk

Used like this:
./search.awk -v KEY="nine" lo

Output:
nine,9,ix,cardinal,9,IX,niner,Nina from Carolina,ennead,digit,figure,baseball club,ball club,club,baseball team

Comment: It works. Thank you! I can follow the general logic, but I don't understand awk well enough to fully understand what each step is doing (even with your thorough commenting). I would upvote this if I had enough reputation.
Answer: Using sed
$ cat script.sed
N
{
    /\(/ {
        /9/!s/[^|]*\|//
        s/\n/ /
        {
            /[^|]*\|(9\|)/ {
                s//\1/
                s/([^|]*)\|/\1\n/g
                s/\([^)]*\)//
                s/\([^)]*\)//g
                p
            }
        }
    }
}

$ sed -Enf script.sed input_file
nine
9
ix
cardinal
9
IX
niner
Nina from Carolina
ennead
digit
figure
baseball club
ball club
club
baseball team

Comment: When I run this, I get the output (separated by newlines, but they show up as spaces instead in this comment):
`ennead

9
IX
niner
Nina from Carolina
digit
figure

9
 ardinal
nine
9
IX
niner
Nina from Carolina
ennead
digit
figure
nina from carolina

9
IX
niner
Nina from Carolina
ennead
digit
figure
nine
9
ix
cardinal
9
IX
niner
Nina from Carolina
ennead
digit
 igure
baseball club
ball club
club
baseball team

9
IX
Nina from Carolina
ennead
digit
 nineteen
2
`
Answer: This might work for you (GNU sed):
v=nine
sed -n ':a;/^'"${v}"'|/{:b;n;/^[^(]/ba;s/^[^|]*|\| ([^)]*)//g;y/|/\n/;p;bb}' file

Focus on any lines following a match on the input variable.
Fetch the following line and if it does not begin with (, then repeat above.
Otherwise, remove the first field and any values between parens, replace the field separators | by newlines, print the result and repeat.

v=nine # set variable v to `nine`
sed -n ':a # turn off implicit printing and set goto label a
        /^'"${v}"'|/{ # match a line beginning with variable v
          :b # set goto label b
          n # fetch next line (do not print see option -n)
          /^[^(]/ba # goto label a if line does not begin (
          s/^[^|]*|\| ([^)]*)//g # remove first field and parens
          y/|/\n/ # translate | to newline for entire line
          p # print the result
          bb # goto label b
        }' file

To see the sed script in action invoke the --debug option.
Comment: Thanks! This works. Any chance you could break up the code a little bit (spaces or new lines) to help me see how each step is working? I would upvote if I had enough reputation.
Comment: Thanks for adding the explanations. I accepted your answer. The `--debug` option is really helpful. What exactly is a namespace in the context of this particular command?
Comment: @TaylanMorcol a namespace or label is explained [here](https://www.gnu.org/software/sed/manual/sed.html#Branching-and-Cycles).
Comment: Thanks! This answers so many of my `sed` questions.
Answer: Do you mean the number 9? This produces your output. You need to prevent regex characters in the query.
read -p 'query? ' query
[[ $query =~ [[:alnum:]_-]+ ]] &&
sed -n '
/^([^)]*)|\('"$query"'|.*\)/ {s/^([^)]*)|//; s/|/\
/g;p}' lo

Parsing the file properly is more complicated than this though.
Comment: This is doing something weird. When I query "nine", it returns only a partial list of results that is repeated a few times, and in some cases the output has the numeral "9" instead of the word "nine".

To clarify, I want to query the word "nine" (or whatever) in a thesaurus. I could just as well have queried any other word. It just so happens that the chunk of the thesaurus that I pulled out as an example in my original post is for the entry "nine". Perhaps that is where the confusion is coming from?
Comment: @TaylanMorcol Yeah this isn't what you want. I'm interested in this kind of stuff and started working yesterday on a thesaurus lookup CLI for the file you posted. But I can't find documentation for the data format. Roughly it looks like: `word|N` where N is the number of following lines pertaining to `word`. Prefix of each line is word type (`word` as an `adj`, `noun`, etc). Prefixes are split over multiple lines I can't work out why.
Comment: What do you mean the prefixes are split over multiple lines? BTW, the solutions proposed by potong and Arnaud Valmary both worked for me.


When using the TlHelp32 library, how can I print a list of running processes to console?

Question: Imagine this function:
void OutputAllRunningProcessNames()
{
    HANDLE hSnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
    PROCESSENTRY32 procEntry;
    procEntry.dwSize = sizeof(procEntry);
    Process32First(hSnap, &procEntry);
    do
    {
        std::cout << *(const char*)procEntry.szExeFile << std::endl;
    } while (Process32Next(hSnap, &procEntry));
    return;
}

I would expect this to give me a list of all process names however I only get the first letter of each one. I am printing procEntry.szExeFile, casted to a const char* and dereferenced, how do I tell the machine to keep reading the address szExeFile points to until it reaches a null terminator? Thanks.
Edit: It was only printing the first letters because I was dereferencing the const char* instead of passing it to cout and also there was a problem with my header file that was making it give me unicode when i specified ascii.
Answer: Stop dereferencing the pointer and pass the pointer to std::cout.
std::cout << (const char*)procEntry.szExeFile << std::endl;

Comment: Then it looks like there is a byte with value zero after the first letter. You should use ANSI version of the API (functions and structures with `A` suffix) to work with `const char*`.
Comment: same result exactly nice try tho
Comment: Get rid of the type cast, it doesn't belong: `std::cout << procEntry.szExeFile << std::endl;`. If you see a memory address printed instead of string characters, it means you are using the `W` (Unicode) version of the API, so use `std::wcout` instead: `std::wcout << procEntry.szExeFile << std::endl;`