How to fix "the server certificate is not configured properly with HTTP.SYS" on Windows 7?

Question: I'm building a wcf client which consumes a service from a brazilian government institution. This connection uses Soap 1.2 and it needs to be signed with a digital certificate.
The code used for this example is a Console Application using .Net 4.6.1.
The main application is a WPF application (I'm not using IIS). This code works without a problem on Windows 10 but when I try to run it on Windows 7 it gives me the following error:

System.ServiceModel.CommunicationException: An error occurred while making the HTTP request to https://nfce-homologacao.svrs.rs.gov.br/ws/NfeStatusServico/NfeStatusServico2.asmx. This could be due to the fact that the server certificate is not configured properly with HTTP.SYS in the HTTPS case. This could also be caused by a mismatch of the security binding between the client and the server. ---> System.Net.WebException: The underlying connection was closed: An unexpected error occurred on a send. ---> System.IO.IOException: Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host. ---> System.Net.Sockets.SocketException: An existing connection was forcibly closed by the remote host.

This is the client call code:
XmlNode node = null;

var parametro = new TConsStatServ();
parametro.cUF = NFeAPI.XMLSchemas.NfeStatusServico2.Envio.TCodUfIBGE.Item53;
parametro.tpAmb = NFeAPI.XMLSchemas.NfeStatusServico2.Envio.TAmb.Item2;
parametro.versao = "3.10";
parametro.xServ = TConsStatServXServ.STATUS;

var certificate = GetCertificateByName("Certificate Name", false);

string nFeNamespaceName = "http://www.portalfiscal.inf.br/nfe";
string parametroXML = XmlUtil.Serialize(parametro, nFeNamespaceName);

XmlDocument doc = new XmlDocument();
XmlReader reader = XmlReader.Create(new StringReader(parametroXML));
reader.MoveToContent();

node = doc.ReadNode(reader);

nfeCabecMsg soapHeader = new nfeCabecMsg();
soapHeader.cUF = parametro.cUF.ToString().Replace("Item", "");
soapHeader.versaoDados = "3.10";

var soapClient = new NfeStatusServico2SoapClient("NfeStatusServico2Soap");
soapClient.ClientCredentials.ClientCertificate.Certificate = certificate;

XmlNode result = soapClient.nfeStatusServicoNF2(ref soapHeader, node);

Here is my App.config:
<system.serviceModel>
    <bindings>
        <basicHttpBinding>
            <binding name="NfeStatusServico2Soap">
              <security mode="Transport">
                <transport clientCredentialType="Certificate"/>
              </security>
            </binding>
            <binding name="NfeStatusServico2Soap1" />
        </basicHttpBinding>
    </bindings>
    <client>
        <endpoint address="https://nfce-homologacao.svrs.rs.gov.br/ws/NfeStatusServico/NfeStatusServico2.asmx"
            binding="basicHttpBinding" bindingConfiguration="NfeStatusServico2Soap"
            contract="NfeStatusServico2.NfeStatusServico2Soap" name="NfeStatusServico2Soap" />
    </client>
</system.serviceModel>

The GetCertificateByName is helper method I've created to return the X509Certificate2 need by the service.
I've already tried disabling Windows 7 firewall and I went to Programs and Features -> Turn Windows features on or off and enabled the .net 3 framework node for wcf calls.
I have also tried to use a WebReference with a .NET 2.0 application and it gave the same error. I upgraded the code to use wcf in .net 4.6.1 in hope for it to work.
I tried to use fiddler to track the problem and it returns the code 200 but not much help with that.
It's been 5 days and I can't manage to get around this issue. I'm about to drop Windows 7 support on my application because of that.
Comment: It will be better to enable logs and trace in your wcf client code and check the soap request passed and exact response/error message  being received from the wcf service.
Comment: I'll try that. By enabling logs, do you mean writing the code using tracelogs of .net framework or is there any tool I can use out of the box?
Comment: YOu have specific tracer and loger wizard for WCF.Check out this http://csharp-video-tutorials.blogspot.in/2013/11/part-9-how-to-enable-tracing-and_26.html.
Comment: Thank you for pointing that. I'll give it a try for learning purposes. For this problem, a windows update fixed the problem.
Answer: In my case, the problem was that my project was still using .Net Framework 4.0, which does not support TLS 1.1 or 1.2, and the service I was connecting to had turned off support for TLS 1.0 as of Jan 1, 2018. Once I upgraded the project to .Net Framework 4.5 and forced TLS 1.2, everything worked fine.
System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls12;

Comment: Forcing TLS 1.2 works for some people but it's good to know the reason. Most people were saying forcing TLS 1.2 was the solution but without saying why.

In my case, I've already tried that and it didn't work. I was using .NET 4.6 from the beginning. Only the Windows 7 Update fixed that.

Thank you for sharing your solution.
Comment: Yes I upgraded to 4.5 framework and forced Tls12 it worked like a charm! :)
Comment: Nice! So happy this has helped others. I was so screwed the day I had this happen to me and the company of the service I was connecting to had absolutely no idea how to correct the issue.
Answer: In my case activating Windows Update and letting it install all the important updates fixed the problem.
After some research on the HTTP.SYS I've found a Microsoft website saying that HTTP.SYS had some "known issues" and I thought it could've been fixed in some update. For my luck it was the case.
Comment: You don't know which specific update solved the problem, do you? I have several customers with the same problem. Forcing the protocol to use TLS 1.2 didn't work in this case also.
Comment: Our program woks on the majority of our customers, but it gives the message `An error occurred while making the HTTP request to 'https://webservices.producaorestrita.esocial.gov.br/servicos/empregador/enviarloteeventos/WsEnviarLoteEventos.svc'. This could be due to the fact that the server certificate is not configured properly with HTTP.SYS in the HTTPS case. This could also be caused by a mismatch of the security binding between the client and the server.` on some customers machines.
Comment: I will check the one I used. Microsoft had it on their website. I'll come back later and tell you.
Comment: This was the page I've found back in the day: https://support.microsoft.com/en-us/help/2624534/list-of-currently-available-hotfixes-for-http-sys-in-windows-vista-in
Comment: Thank you lamDOM. I've seen that article, but there are some updates mentioned there, and I was hoping to find something more like *"install this update only and solve the problem"*, but I'm asking for our customers to install all important updates via Windows Update by now, but still have no answer if that solved the problem to any of them.
Comment: @PedroGaspar, I see. I didn't have the time to check update by update until it worked. I'd advise to install all important updates since they fix security roles and etc. You could use that as argument to convince them.
Answer: Download IIS Crypto and set suggested changes. While calling set tls 1.2
System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls12;


Flatten image background using OpenCV/Numpy

Question: I am creating an image analysis tool (using Python).
I already have segmented images resulting from Otsu thresholding.
Using the OpenCv kmeans function I reduced the amount of colors in my image to 4.
One of the K-means clusters is supposed to be black background (BGR values [0,0,0] ).
Due to the algorithm of K-means, background pixels are now not [0,0,0] but show pixel values of e.g. [0,2,1].
I want this background cluster to absolute black again. An image is represented as 3D numpy array. Currently I am just iteratively adjusting the background:
    X, Y, Z = img.shape
    for xi in xrange(X):
        for yi in xrange(Y):
            if all([value < 10 for value in img[xi][yi]]):
                img[xi][yi] = np.zeros((1,3), dtype=int)

This is a relatively slow operation. Are there smarter ways to to this, possibly using specialized OpenCV/Numpy functions?
Answer: You could vectorize this operation like this:
In [29]: A = np.random.random_integers(0,10,(2,4,3))

In [30]: A
Out[30]:
array([[[ 5,  9,  1],
        [ 4,  0,  2],
        [ 0,  5,  9],
        [ 8,  7,  8]],

       [[ 1,  6,  7],
        [ 8, 10,  9],
        [ 2, 10,  1],
        [ 9,  2,  3]]])

In [32]: np.all(A < 5, axis=-1)  # I chose a threshold of 5
Out[32]:
array([[False,  True, False, False],
       [False, False, False, False]], dtype=bool)

In [33]: A[np.all(A < 5, axis=-1)] = 100  # and set the values to 100 to easily show what has changed

In [34]: A
Out[34]:
array([[[  5,   9,   1],
        [100, 100, 100],
        [  0,   5,   9],
        [  8,   7,   8]],

       [[  1,   6,   7],
        [  8,  10,   9],
        [  2,  10,   1],
        [  9,   2,   3]]])

By specifying np.all(some_array, axis=-1) you are performing the all operation over the last axis, which is where the RGB values are. You see that there was, in this test array, only one such pixel (at A[0,1]) where that condition was fulfilled.
Comment: This was a nice answer and led me to a solution in 2 lines instead of around 10. Good job!


Why won't the application menu appear in Gnome Panel?

Question: In Gnome Fallback mode, the application launcher menu that is supposed to be in the top left corner is missing. Here's a picture:
How do I get that menu to appear?
Comment: By the way, it's actually called Gnome Panel. "Gnome Fallback" is just a marketing thing to move focus away from the classic desktop and over to the new one, Gnome Shell.
Answer: if you rightclick on the panel you can add the application menu. Here's the easy steps.

right click the panel
click on add
choose what you want, in this case choose menu bar or a custom menu bar for the applications - places - system links.
Comment: you need to hold the alt-key, or super+alt and then right click. To move applets, you press alt (or super+alt) and middle-click and drag.


Which varnish to choose for a first time job (desk)?

Question: I am building desks for my children: a wooden slab on a standing desk frame.
The wooden slab is 160 x 80 x 2 cm and is made of smaller pieces of oak (probably) glued together. They form a nice flat and smooth surface (I can swipe my hand on it slightly, there may be very small shards)

I want to varnish it but this is the first time I am going to do it. So my constraints are:

the work will be done on-site in the room where the desk will stand afterwards
I am an unexperienced DIY-selfer (but willing to learn). This is to say that I am looking for more forgiving solutions
this is intended to be a desk for teenagers, so for books, copybooks, writing, computer etc. → it does not need to be industrial-grade resistant but smooth and still relatively protected

I am now faced with the choice of the varnish. When reading about them, I see that there are three categories of finish : brilliant, satin, mat. It seems that brilliant is the most resistant one.
There is also the problem of the solvants: water and white-spirit based - this is what I saw in France. This OldHouse video (US) mentions another one based off polyurethane. This video (linked to the moment where this is presented) also mentions "lacquer" - whihc does not translate to anything I saw in France.
My main problem is that all these information are complete (even over-complete) but do not address my context: a working desk (or a dinner table - the kind of table where you do everyday things)
EDIT: I also saw that everyone uses a brush, while in the shop I went to a roll is suggested all the time.
FINAL EDIT (for those who may have the same concerns as I had)
I went for a water-based varnish. It has a pseudoplastic behaviour which frankly is more annoying in that case than anything else. It may be useful when varnishing a ceiling (I am not sure this exists at all, but anyway).
I used a 11 cm foam roll. I was at the limit of slipping (as opposed to rolling) so if the surface was smaller (as it was on the edges) I would have had a problem.
I made three layers, grinding first with a 200 paper (I am not sure if this is universal - it is a fine-grained paper, but you still feel the grains). The last two layers were ground with a 500 paper (it feel rather smooth). This includes the last layer - I was wondering whether to leave it as it or to work the sandpaper on it and I finally did. That was the right decision, the surface is very smooth now.
Final effect below, if my children do not get excellent marks this year I would really not understand why :)
Answer: Since you'll be finishing the pieces in the building, lacquer is out.  It stinks to high Heaven and unless you use a pre-catalized lacquer, it is prone to water stains such as condensation from a cold glass of water.
I used to prefer oil based Polyurethane but that can have a strong odor too and that odor can last a while.  For simple, tough, (not fancy) finishes I now prefer a water based Polyurethane such as MINWAX (I know, not supposed to do product recommendations).  It's envrionmentally friendly, easy to clean up brushes, etc. after applying.  It does have some odor, but it usually goes away pretty quick.  It also dries quickly.  It will "raise the grain" a bit on the first coat, so you'll need to sand lightly to knock that back down. Second coat should dry very smooth.  Since this will probably get fairly heavy use I'd go three coats.   No sanding needed between 2nd and 3rd coats unless there are rough spots.
Edit:  Adding that you can use a high quality brush and it will level out pretty well.  Again, don't worry if the first coat ends up a bit rough, that's normal.  Just sand lightly and remove all the dust before 2nd coat.
Comment: *It does have some odor, but it usually goes away pretty quick* How would you estimate "pretty quick"? The tables will be standing in the rooms for a week or so after the work is finished and before the children are back. Also  thanks for mentioning the brush - I forgot about that part in my question (brush vs. roll, I edited the question)
Comment: I also read that the water based ones dry "very quickly" (again, without any precise timing) and that was a drawback, apparently.
Comment: I consider "drying quickly" a benefit. The shorter the time a freshly finished surface is wet the less opportunity for it to attract dust and bugs.   I mean, it doesn't dry so fast that it's a problem. Just work from one side to the other keeping a "wet edge" going.   Not sure about a roller, if I were doing it I'd use a high quality, wide brush. But that's just my prejudices!   Regarding the odor, in my experience the vast majority of the odor is gone in less than a day.   Make sure you have adequate ventilation of the room as it dries.
Comment: @WoJ so you have to work fast enough... if you leave edges to dry then you did not work fast enough. Look at the shape and work out how you will make sure how to keep the edges live.
Comment: Once dry, if you stick your nose right down on the finished surface, you might be able to detect an odor for a few days, but it's very light and not offensive, IMHO.   One more thing:  Given that this will be used (and possibly abused) by kids, it's a forgiving finish to repair.   In a couple of years you might need to clean it up, sand lightly and put on another coat.   Kids are hard on furniture!
Comment: Just looked up MINWAX polyu' specs:  Dry to touch in 4 hours, dry to re-coat 1-2 hours. So it's not like it's gonna flash off dry on you unless it's really hot with low humidity.  Manufacture's wouldn't make a product that's too hard for DIYers to use.
Comment: @GeorgeAnderson: thanks for all the details. Could you please explain "keeping a wet edge"? I am not a native English speakers so the jargon is sometimes hard)
Comment: @WoJ   LOL!  Could have fooled me, you're English is excellent.  But you're right the jargon and different words for the same thing. Like the Brits call an electrical outlet a "socket"!  Anyway...keeping a wet edge just means working from one side of the work piece to the other in a consistent manner. Don't go all over it all at once. Working across the narrower part is best, from one end to the other. Even if you see a spot you don't like on  a previously finished portion, don't go back and "touch it up".  Just deal with it on the next coat, it'll be fine.
Comment: @GeorgeAnderson Your last comment is probably the most important tip you could give.  +  Stay safe out there.
Comment: @JACK Thanks for the compliment!  I like all of your posts, usually spot on (as the Brits would say).   How about an up vote!?  Momma needs a new pair of shoes!  LOL
Comment: @GeorgeAnderson  see the "+"  in my comment?   That means an upvote on your answer, not the comment....   You stay safe out there.
Comment: @JACK: OK, Thanks! Got it!  Still learning about the traditions here.  I DK if there are other ways of knowing who upvoted or downvoted posts.
Comment: @GeorgeAnderson  Not really traditions. Some of us make it known when we UV and DV and why.  Others play mystery person.


How to maintain salesforce session id in visualforce page?

Question: i had written a javascript in home page component.it'll load as soon as we login to the salsforce and its working fine. but if i open Visualforce page it throws "sf:invalid code...invalid session id." How to resolve this issue. following is the session code i used in javascript.
sforce.sessionId = getCookie('sid');
    sforce.connection.sessionId=sforce.sessionId;
Answer: If you want get session id, you can try to use next JS code:
<code>var __sfdcSessionId = '{!GETSESSIONID()}';
</code>


Biogeme fails to install and run on Ubuntu 16.04

Question: I wanted to ask about the installation of one of most important open source freeware for discrete choice modeling data estimation: Biogeme.
I am trying to install it on my machine (Thinkpad x201, 8gb, Intel i5 dual 2.7GHz) running Ubuntu 16.04.
After installing it from the .deb file provided at http://biogeme.epfl.ch/home.html , I run it from a terminal and I get the following:
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
biogeme 2.4 [Mon Nov 2 00:56:45 CET 2015]
Michel Bierlaire, EPFL
-- Compiled by bierlair on Linux
See http://biogeme.epfl.ch
                    !! CFSQP is available !!
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    "In every non-trivial program there is at least one bug."

[12:58:57]patBiogeme.cc:134  Read default.par
Warning:  Error: File sample.dat is missing

Warning:  Error: File sample.dat is missing

Warning:  Error: File sample.dat is missing

while if I try to compile it as explained here: http://biogeme.epfl.ch/install.html
I get the following error while running the make command:
libtool:   error: 'patLegendre.lo' is not a valid libtool object
Makefile:778: set of instructions for "libbisonbiogeme.la" failed

make[2]: *** [libbisonbiogeme.la] Errore 1
Makefile:441: set of instructions for "install-recursive" failed
make: *** [install-recursive] Errore 1

I don't know if anybody can help, any support would be appreciated!
Thank you very much
Comment: In the first instance, try locating + changing to the directory that contains the `sample.dat` file before running the program. If you still want help compiling from source after that, then you will need to post the actual error message.
Comment: I wasn't able to locate it.. Since running  `biogeme` in the terminal generates the `default.par` file every time, maybe it is supposed to do the same with the `sample.dat`? You're right about the error message for compiling, I'll post it thanks.
Comment: Possibly related to https://groups.yahoo.com/neo/groups/biogeme/conversations/topics/1871?l=1
Answer: To install the biogeme program, download the deb file at http://biogeme.epfl.ch/distrib/biogeme_2.4.0-1_amd64.deb and run sudo dpkg -i biogeme_2.4.0-1_amd64.deb. This will install the necessary binaries to your /usr/local/bin directory.
As can be seen in section 4 of page 6 of the PDF at http://biogeme.epfl.ch/documentation/bisonfirstmodel-2.4.pdf, to use the program, you need to provide biogeme with two arguments: a model and a .dat file. Following section 4 of page 6 of the aforementioned PDF, we will use the logit model and the data file for the Swissmetro example, which can be found at http://biogeme.epfl.ch/examples_swissmetro.html. First, download the 01logit model file at http://biogeme.epfl.ch/bison/01logit.mod. Second, download the swissmetro.dat data file at http://biogeme.epfl.ch/swissmetro.dat. Third, run biogeme 01logit swissmetro.dat. Notice that the program will tell you that 01logit.par does not exist and it will try to use default.par instead (and if default.par is missing, it will create it and then use it). This behavior is expected as stated in the second bullet point of page 7 of the aforementioned PDF.
Comment: Thank you very much. This was really useful and also made me understand how the software actually works. Clarified many things. Thank you once
Comment: @AndreaCiccorelli No problem at all!


How can I combine the three queries to one and possibly improve performance

Question: I wish I can get help from this forum, any suggestion is appreciated.
I have a project with some existing sql queries, here are three I think should be combined into only one for the performance optimization purpose.
For the sake of simplicity and confidentiality here are the modified codes:

table1 inner join table2 and left join table22 to generate temp table
from temp table create table cnt with the count for each type
table1 inner join table3, and apply a where clause to generate the final table
.

UPDATE: the key point here is to look for a solution that can minimize the initial data volumn (table1) involved here - which has 8 billion rows, from the where clause added at the end it should be able to restricted to the where clause which will dramatically bring down the size.
UPDATE2: the original queries actually include another left join here, please see the comment below:

 create table table1 (id int, region int, typeid int)
 insert into table1 (id, region, typeid ) values (1,2,1)
 insert into table1 (id, region, typeid ) values (2,3,1)
 insert into table1 (id, region, typeid ) values (3,4,2)
 insert into table1 (id, region, typeid ) values (4,1,2)
 insert into table1 (id, region, typeid ) values (5,1,2)
 insert into table1 (id, region, typeid ) values (6,2,4)

 create table table2 (id int, type varchar(10))
 insert into table2 (id, type) values (1,'A')
 insert into table2 (id, type) values (2,'B')
 insert into table2 (id, type) values (3,'C')
 insert into table2 (id, type) values (4,'D')

table temp is the initial inner join of the two initial tables:
create table temp as
select a.*, b.*
from table1 a  inner join table2 b on a.typeid = b.id

table cnt has the count for each type
create table cnt as
select c.type, count(1) as total
from temp c
group by type

Final table:
create table final as
select a.region, a.type
from table1 a  inner join cnt c on a.type = c.type  where c.total > 2

In the given sample data, the final table should contains only records with type = 2 because type2 has count > 2
Kindly keep in mind the current table1 and table2 contain millions of rows.
Thank you very much.
Comment: If you have appropriate indexes on your large tables, doing this in steps may not be necessary. Depending on your database, a lot of your 'delcarative' code might be unnecessary because the query planner is smart enough to do it for you
Comment: Thanks Nick, we have partitions, index is not applicable to my case.
Comment: Indexes are always applicable for database performance
Answer: You can use CTEs.  So one simplification is:
with cnt as (
      select ?.type, count(*) as total
      from table1 a inner join
           table2 b
           on a.typeid = b.id
      group by a.type
select a.region, a.type
from table1 a inner join
     cnt c
     on a.type = c.type
where c.total > 2;

table2 doesn't contribute to the count, so this can be simplified to:
with cnt as (
      select ?.typeid, count(*) as total
      from table1 a
      group by a.typeid
select a.region, a.typeid
from table1 a inner join
     cnt c
     on a.typeid = c.typeid
where c.total > 2;

And if your window functions further simplifies this:
select a.*
from (select a.*, count(*) over (partition by a.typeid) as cnt
      from table1 a
     ) a
where cnt > 2;

Comment: Thank you but I don't think the final query is correct: table temp is the initial inner join of the two initial tables and table cnt needs to be derived from table temp, your final query doesn't do that.
Comment: @mdivk . . . The `join` is not needed as I read the queries.  It is superfluous.
Comment: Thanks Gordan. without join, how do I filter the table with where clause that the count is needed and the count is from the join?
Comment: @mdivk . . . The count on `typeid` without the `join` should be the same as the count on `type` with the `join`.
Comment: the count would be different (I apologize I should include another left join in my simplified query here)
Answer: This will be faster i believe if you have partition over typeid of table 1:
create table #table1 (id int, region int, typeid int)
    insert into #table1 (id, region, typeid ) values (1,2,1)
    insert into #table1 (id, region, typeid ) values (2,3,1)
    insert into #table1 (id, region, typeid ) values (3,4,2)
    insert into #table1 (id, region, typeid ) values (4,1,2)
    insert into #table1 (id, region, typeid ) values (5,1,2)
    insert into #table1 (id, region, typeid ) values (6,2,4)

--exact your request:
select t.region, t.typeid from #table1 t where t.typeid in (select t.typeid from #table1 t group by t.typeid having count(t.typeid) > 2)
--...and if you need group:
select t.region, t.typeid, count(*)recordcount from #table1 t where t.typeid in (select t.typeid from #table1 t group by t.typeid having count(t.typeid) > 2) group by t.region, t.typeid

drop table #table1

Comment: Thank you, partition is on a different field.
Comment: you can still try the query
Comment: Thanks, suspended it here for now, the real script is too complex and too big


Parsing a list of strings and enumerate them based on line number

Question: Can someone help me take a list of strings and enumerate string values based on line number?
Im trying to figure out how to parse all my known favorite network SSIDs and then assign each SSID a number based on the order from the output. Example:
If I run networksetup -listpreferredwirelessnetworks en0 (on macOS), I get the following output based on my recent Wi-Fi favorites list (Apple calls this the 'Preferred Network' list):
Preferred networks on en0:
Denny's
Hilton Hotel 2465
Hipster Cafe
My_Moms_Basement
Airport_bar
Marriot - Public-5G
OFFICE

I want to parse this output above, search/filter for my corporate SSID ("OFFICE" in this example) and then get its line number (in this case "OFFICE" is listed on line 8 -  if you count the header "Preferred networks on en0:").
Ultimately I want to determine if SSID "OFFICE" is at the top of the list or not, and if it's NOT then I'll use the networksetup command to move it to the top - But I only want to take action if SSID "OFFICE" is not already at the top. Apple considers the top line "index 0" in this context (so line/array counting technically starts with 0,1,2,3 etc).
I have tried wc, sort, and various counting loops but I cant seem to get this to give me the output I want.
Thanks!
Answer: If you want to assign an index to every line of your file, you could use an array (declare -a in bash)
Assuming the lines you mentioned are in a file named "preferred_networks", you could write this to create the array (one entry of the array for every line) :
declare -a ssid
exec 5<./preferred_networks
((i=0))
while read line<&5; do
    ssid[i]=$line
    ((++i))
done

Then you could read your array (containing $i elements) with the following loop:
for j in `seq 0 $i` ; do
 echo ssid[$j]
done


Outlook scan specific folder and save all attachments from e-mails

Question: I have this code to save attachments for selected items(mails) from my Outlook.
I would like to set the specific folder (define it) and Outlook will automatically scan all e-mails in that folder and save attachments.
Any ideas how should I expand this code to work that way?
Public Sub SaveAttachments()

Dim objOL As Outlook.Application
Dim objMsg As Outlook.MailItem
Dim objAttachments As Outlook.Attachments
Dim objItems As Outlook.Items
Dim objSelection As Outlook.Selection
Dim i As Long
Dim lngCount As Long
Dim strFile As String
Dim strFolderpath As String
Dim strDeletedFiles As String

strFolderpath = "C:\Users\gpyko\Desktop\Pentaho project\HDPS RAPORTY"
Set objOL = CreateObject("Outlook.Application")
Set objSelection = objOL.ActiveExplorer.Selection
strFolderpath = strFolderpath & "\Attachments\"

For Each objMsg In objSelection

  Set objAttachments = objMsg.Attachments
  lngCount = objAttachments.Count
  strDeletedFiles = ""

  If lngCount > 0 Then

    For i = lngCount To 1 Step -1

      strFile = objAttachments.Item(i).FileName
      strFile = strFolderpath & strFile
      objAttachments.Item(i).SaveAsFile strFile
      objAttachments.Item(i).Delete

      If objMsg.BodyFormat <> olFormatHTML Then

            strDeletedFiles = strDeletedFiles & vbCrLf & "<file://" & strFile & ">"
      Else
            strDeletedFiles = strDeletedFiles & "
" & "" & strFile & ""
      End If

    Next i

      If objMsg.BodyFormat <> olFormatHTML Then

          objMsg.Body = vbCrLf & "The file(s) were saved to " & strDeletedFiles & vbCrLf & objMsg.Body
      Else
          objMsg.HTMLBody = "
" & "The file(s) were saved to " & strDeletedFiles & "
" & objMsg.HTMLBody
      End If
      objMsg.Save

  End If

Next

ExitSub:
Set objAttachments = Nothing
Set objMsg = Nothing
Set objSelection = Nothing
Set objOL = Nothing
End Sub

Comment: Where are you running the code from? Excel or Outlook ?
Comment: From Outlook right now, but probably I'll run it from Excel combined with other VBA script
Answer: Replace your objSelection with Dim SubFolder As Outlook.MAPIFolder then use
For Each objMsg In SubFolder.Items
also you don't need to create Outlook object if your running your code from Outlook CreateObject("Outlook.Application")
Make sure to update your folder name
Set SubFolder = olNs.GetDefaultFolder(olFolderInbox).Folders("Folder Name")
Option Explicit
Public Sub SaveAttachments()
    Dim olNs As Outlook.NameSpace
    Dim objMsg As Outlook.MailItem
    Dim objAttachments As Outlook.Attachments
    Dim objItems As Outlook.Items
    Dim SubFolder As Outlook.MAPIFolder
    Dim i As Long
    Dim lngCount As Long
    Dim strFile As String
    Dim strFolderpath As String
    Dim strDeletedFiles As String

    strFolderpath = "C:\Users\gpyko\Desktop\Pentaho project\HDPS RAPORTY"

    Set olNs = Application.GetNamespace("MAPI")

    Set SubFolder = olNs.GetDefaultFolder(olFolderInbox).Folders("Folder Name")

    strFolderpath = strFolderpath & "\Attachments\"

    For Each objMsg In SubFolder.Items
        Set objAttachments = objMsg.Attachments
        lngCount = objAttachments.Count
        strDeletedFiles = ""

        If lngCount > 0 Then

            For i = lngCount To 1 Step -1

            strFile = objAttachments.Item(i).FileName
            strFile = strFolderpath & strFile
            objAttachments.Item(i).SaveAsFile strFile
            objAttachments.Item(i).Delete

            If objMsg.BodyFormat <> olFormatHTML Then

                strDeletedFiles = strDeletedFiles & vbCrLf & "<file://" & strFile & ">"
            Else
                strDeletedFiles = strDeletedFiles & "
" & "" & strFile & ""
            End If

            Next i

            If objMsg.BodyFormat <> olFormatHTML Then

                objMsg.Body = vbCrLf & "The file(s) were saved to " & strDeletedFiles & vbCrLf & objMsg.Body
            Else
                objMsg.HTMLBody = "
" & "The file(s) were saved to " & strDeletedFiles & "
" & objMsg.HTMLBody
            End If

            objMsg.Save

        End If
    Next

ExitSub:
    Set objAttachments = Nothing
    Set objMsg = Nothing
    Set SubFolder = Nothing
    Set olNs = Nothing
End Sub

To Run it from Excel.
Option Explicit
Public Sub SaveAttachments()
    Dim App As Outlook.Application
    Dim olNs As Outlook.Namespace
    Dim objMsg As Outlook.MailItem
    Dim objAttachments As Outlook.Attachments
    Dim objItems As Outlook.Items
    Dim SubFolder As Outlook.MAPIFolder
    Dim i As Long
    Dim lngCount As Long
    Dim strFile As String
    Dim strFolderpath As String
    Dim strDeletedFiles As String

    strFolderpath = "C:\Users\gpyko\Desktop\Pentaho project\HDPS RAPORTY"
    Set App = New Outlook.Application
    Set olNs = App.GetNamespace("MAPI")

    Set SubFolder = olNs.GetDefaultFolder(olFolderInbox).Folders("Folder Name")

    strFolderpath = strFolderpath & "\Attachments\"

    For Each objMsg In SubFolder.Items
        Set objAttachments = objMsg.Attachments
        lngCount = objAttachments.Count
        strDeletedFiles = ""

        If lngCount > 0 Then

            For i = lngCount To 1 Step -1

            strFile = objAttachments.Item(i).Filename
            strFile = strFolderpath & strFile
            objAttachments.Item(i).SaveAsFile strFile
            objAttachments.Item(i).Delete

            If objMsg.BodyFormat <> olFormatHTML Then

                strDeletedFiles = strDeletedFiles & vbCrLf & "<file://" & strFile & ">"
            Else
                strDeletedFiles = strDeletedFiles & "
" & "" & strFile & ""
            End If

            Next i

            If objMsg.BodyFormat <> olFormatHTML Then

                objMsg.Body = vbCrLf & "The file(s) were saved to " & strDeletedFiles & vbCrLf & objMsg.Body
            Else
                objMsg.HTMLBody = "
" & "The file(s) were saved to " & strDeletedFiles & "
" & objMsg.HTMLBody
            End If

            objMsg.Save

        End If
    Next

ExitSub:
    Set objAttachments = Nothing
    Set objMsg = Nothing
    Set SubFolder = Nothing
    Set olNs = Nothing
End Sub

Comment: Ok I got it. I used `Set SubFolder = olNs.Folders("mailbox-name").Folders("ARIES")` and it works.
One more time big thank you!
Comment: Thank you! Much appreciate. Yet I still face up an error on line:
 `Set SubFolder = olNs.GetDefaultFolder(olFolderInbox).Folders("ARIES")`
"An object could not be found". Folder name is correct. Maybe i miss something?
Comment: @GrzegorzPyko an object could not be found means your folder name cannot be found.
Comment: yea, but I'm sure that folder name is correct and I have one named that way
Comment: Ok I know where the problem is. The folder I want to scan is at the same rank as Inbox, Drafts, Sent Items etc. So the function and argument `.GetDefaultFolder(olFolderInbox)` won't work.
Comment: You could use `Set SubFolder = olNS.PickFolder` to bring up the Select Folder dialog.


failed disk size increase with LVM

Question: I tried to increase the hard disk of my virtual box machine. On this VM a standard ubuntu installation with LVM was active.

I increased the hard disk with vboxmanage
I increased the partition with gparted
I adapted the LVM with
lvextend -l 100%FREE /dev/mapper/intern-root

Unfortunately, I forgot to execute resize2fs, I restarted the server
Now, the server does not start. It is missing the root device, loading the initramfs shell.
Is there any possibility to reanimate the server or do I have to reinstall the complete system?
Comment: Can you boot from another medium (USB, CDROM, Network),  mount/fix the LVM volume, run `resize2fs`, thne unmount and reboot the server?
Comment: No, unfortunatelly I am not able to mount the device. I am able to boot from an ubuntu live cd and I can see the lvm partition in gparted with "File System: unknown" and an exclamation mark.
Answer: If you didn't execute vgextend before lvextend, the volume group intern should still have the same size and be on the same physical volume.
In my view, the problem is unrelated to extending the LV.
It's just that the physical volume on which the VG is located has been resized so perhaps LVM simply doesn't find the VG.
You may be able to recover from this by booting a rescue system and trying to find the volume group headers on the physical volume. vgck and cgcfgrestore may help here. Perhaps this or that might help. Good luck!
Comment: Unfortunately, I am not able to search for volume group as I am not able to mound the partition starting the rescue disk.

failed disk size increase with LVM


Constants set to Double wont return double

Question: I cant seem to get this set of code to return a double for the answer on CubicCent. I know that the exact answer for 1 Gallon to Cubic Centimeter should be 3785.41178, but it keeps returning with no decimals and my grams function is only returning a single decimal. Thanks in advance.
public class Volume {
public static final double Liters_Per_Gallon = 3.785;
public static final double Cubic_Cent_Per_Liter = 1000.0;
public static final double Ounces_Per_Pound = 16.0;
public static final double Grams_Per_Ounce = 28.35;
private double pounds;
private double gallons;
double grams;
double CubicCent;

/**
 * @return the gallons
 */
public double getGallons() {
    return gallons;
}

/**
 * @param gallons
 *            the gallons to set
 */
public void setGallons(double gallons) {
    this.gallons = gallons;
}

/**
 * @return the pounds
 */
public double getPounds() {
    return pounds;
}

/**
 * @param pounds
 *            the pounds to set
 */
public void setPounds(double pounds) {
    this.pounds = pounds;
}

public double getCubicCent() {
    double liters = gallons * Liters_Per_Gallon;
    CubicCent = liters * Cubic_Cent_Per_Liter;
    return CubicCent;
}
public double getGrams() {
    double ounces = pounds * Ounces_Per_Pound;
    grams = ounces * Grams_Per_Ounce;
    return grams;
}

Comment: The issue is likely to be in how you are printing the result - decimal places are meaningless for double, because it is a binary floating point type. Please strip down the class to what is needed to reproduce the problem and add the code that makes you think you are getting one decimal place.
Answer: To get the answer you want, you need to be more accurate in your Liters_Per_Gallon initialization. For example, using
public static final double Liters_Per_Gallon = 3.785411784;

gives 3785.411784 as the result. You are going to get, to the limits of double accuracy, 1000 times the constant value.
Comment: Awesome, thanks Patricia that fixed it perfectly. I understand now, it was only giving back the result in the same accuracy as the numbers it is doing the calculations on.


Resize a pasted JPEG in a MailItem

Question: I am trying to send a picture from an Excel sheet, but the size is very small.
How could I get a decent size (basically the whole screen)?
Here is the code:
<code>Sub send_as_a_pic()
    'Copy range of interest
    Dim r As Range
    Set r = Range("B2:O23")
    r.Copy

    'Open a new mail item
    Dim outlookApp As Outlook.Application
    Set outlookApp = CreateObject("Outlook.Application")
    Dim outMail As Outlook.MailItem
    Set outMail = outlookApp.CreateItem(olMailItem)

    With outMail
        .To = "firstname.lastname@example.com"
        .CC = ""
        .BCC = ""
        .Subject = "PAC 2017 sales up to date"
    End With

    'Get its Word editor
    outMail.Display
    Dim wordDoc As Word.Document
    Set wordDoc = outMail.GetInspector.WordEditor

    'To paste as picture
    wordDoc.Range.PasteAndFormat wdChartPicture

    'With wordDoc.Range
     '   .LockAspectRatio = True
      '  .Top = wordDoc.Top
       ' .Left = wordDoc.Left
        '.Height = wordDoc.RowHeight
    'End With

End Sub
</code>
Comment: did you try `r.CopyPicture` instead of `r.Copy`? You might also try `wordDoc.Application.CommandBars.ExecuteMSO("PastePNG")`
Answer: it was actually pretty easy, find the answer on develloppez.com:
<code>    For Each shp In wordDoc.InlineShapes
        shp.ScaleHeight = 90
        shp.ScaleWidth = 90
    Next
</code>
Thank you!

Resize a pasted JPEG in a MailItem


Can I use #14 wire on a 20A circuit for a compressor outlet?

Question: Installing a single receptacle, non gfi, on a 20 amp breaker to be used only for a specific piece of equipment (compressor). Compressor specs say, "power consumption will average between 9-11 amps of power and spike near 16 amps". Can I get away with 14 gage wire? This is for a home food Freeze dryer
Comment: The breaker is not there to protect your appliance, it's the to protect the wiring.
Comment: Are we talking an air compressor here, or some sort of refrigeration device? Can you post a photo of the appliance's nameplate if there is an appliance nameplate present, or of the motor's nameplate if there there is no appliance nameplate to be had?
Comment: Also, why are you framing it as "Can I get away with...?" Is the concern having to run out and get materials, or...?
Comment: Added a pic.  I have the 14 gage just don't want go get 12. Time and money
Comment: It's actually a vacuumed pump
Comment: 20 amp breaker? 12 gauge wire, period. There is nothing else to discuss. You might be aware of this funky idea to not overload a 14 awg wire on your 20 amp circuit but the next owner of the house certainly won't. If you want 14 gauge wire then downgrade the breaker to 15 amps. Don't funk with electricity like that. You've probably wasted more time rationalizing this terrible idea and asking this question than it would have taken to install the proper wiring.
Answer: 20A breaker, 12Ga wire. Nothing special about it. The breaker protects the wire, the NEC specifically limits 10, 12 and 14 Ga wire to 30, 20 and 15 Amps respectively.
"Get away with" means you know it's wrong, so, go with what you know, and don't try to "get away with" something wrong, especially something so trivially inexpensive to do right.
Answer: You'll need the 12AWG wire, even under Article 430 rules
For a single motor and nothing else, we start with NEC 430.6(A)(1) to find the motor full load current; this sends us to NEC Table 430.248, which gives us 13.8A for a ¾HP, 115VAC motor like yours.  We then need to look at NEC 430.22, which requires us to multiply that by 125% for a non-duty-cycle rated application, and gives us a minimum circuit ampacity of 17.25A, which exceeds the 15A hard limit on what 14AWG NM can handle.  So, you'll have to use the 12AWG, basically no matter how you slice or dice it.
Answer: Use 12 AWG.
Reason: Later, you or someone else will come across the outlet and think, "Oh Wow! a 20 Amp outlet! and will either plug a lot of stuff into it, or will want to expand the power and add more outlets.
If you spent the extra couple dollars to use the 12 AWG now, you won't have to re do it later! You don't need to be heating the insulation in your walls anyway. (Also I'm pretty sure wire thinner than 12 AWG is not to code for 20A circuits.)
Comment: If the power spike is greater than your rated cable, that could be a problem. I would say, to be safe, go with 12. I dont think your house will blow up if you just use the 14. We all do "good enough" stuff every now and again. However, there is a zero chance of exceeding  the rating of your wire if you just use 12.
Comment: Good thought, however It's temporary. Moving next fall and will take the breaker and with me. Just doing this in the garage.
Answer: NEC 240.4(D) prohibits #14 on a 20A breaker for a receptacle.
If it comes with a standard 15A (NEMA5-15) plug you can run it on 15A breaker and #14 awg receptacle. If you expect to share the circuit with other loads the Use #12 and a 20A.
A 15A breaker doesn't trip right at 15A, it is designed to handle temporary overcurrents. Low overcurrents trip slow, high overcurrents trip fast. Depending on the exact model breaker when you look at an inverse time curve for breakers you will see 107% will likely never trip. Some breakers might be more sensitive than NEMA standards, but not significantly.


Additional mouse buttons do not work with CS:GO

Question: I've been trying to map the buttons on my Roccat Tyon mouse to functions in CS:GO, but it doesn't seem to work. Whether I use Xinput or Dinput (Roccat software) doesn't matter, CS:GO only recognizes the native mouse buttons (left, right & middle click & scroll wheel) and the buttons that are mapped to other keys like Home, PageDn etc.
Help would be appreciated, I've tried setting it as a controller, turning on and off raw input, but nothing seems to work. :(
~Pwuts
Comment: did you used the macro function in the roccat driver?
Comment: I wanted to try that but there are only macro's for CS:Source and CS 1.6
Comment: *edit* I followed Gerret's instructions and now it works. I just can't figure out how I can "press and hold" buttons: the key which they trigger only gets "pressed" once by the macro.
Answer: It seems like CS:GO is not able to recognize the buttons of your mouse. What you can do is to create some macros in your mouse driver.
Keep in mind that I am using the driver tool for the Kone[+] and your driver window may look different from mine. If someone has the same problem but is using a different mouse you can go ahead and try reproducing the same for your driver.
For the first step you have to create a new macro set where you can collect all your CS:GO macros. Just open your driver and execute this 4 steps below.

Click on the Image to enlarge it
After that, select your created macro set and press the new button at the left bottom. To assign something to that macro you press the start record button and press the button which you would use without the mouse. For example the number 3 for the knife.
If you have all function assigned, press the ok button to save your changes. (Keep in mind that you can create more complex things in the macro manager. You also can use the advanced editor.)

The last step is to assign the created macros to a button on your mouse. But before you go ahead and assign a button you should keep in mind that you lose that function on that button.
So you should add all your CS:GO function to a new mouse profile and switch to that profile if you playing CS:GO.
Pro tip: You can assign a profile to the game so everytime you start CS:GO the profile is selected automatically. If you press the WP button this profile is selected automatically if you change to windows.
To assign the function to a button you just select the number of the button you want the function to be and select your macro on there.
Comment: thank you :) It's so simple I'm kind of ashamed that I didn't think of looking into this myself, but thx ;)


Hood placement for gas range

Question: Most appliance companies recommend a distance between 24" and 30" between the range and the hood. However, is this based in anything concrete? I mean, the hood should be powerful enough the provide enough suction for an entire room, plus you can install hoods in the ceiling which is a lot more than 30" from a range, so I'm just wondering if there's something I've missed.
I have an Ilve Nostalgie range and I want to install a Noblesse hood. The contractor says that the hood won't work properly if it's not installed at 30" height maximum, but my Ilve supplier says that it doesn't really matter.
Any thoughts?
Comment: I don't think I've ever seen a proper range hood *in* the ceiling.  *Projecting down* from the ceiling, yes.  I can't imagine that a hood *in* the ceiling would be any other use than a bathroom fart fan.
Comment: A ceiling fan in the kitchen can help an unvented range hood.  The hood filters smoke and oil particles and the ceiling fan significantly reduces steam and odors travelling to other rooms.    It can be installed where it is easy to run a duct outside if that's difficult from the range location.   Either way the range hood needs to be near the stove top, ie, this isn't answering the question, just explaining why a kitchen ceiling fan may not be installed like a range hood.
Comment: A range hood is many times more powerful than an exhaust fan, and if it is in a sealed room, would be so powerful that you end up pulling air in the reverse direction through the exhaust fan, even when it is running.
Comment: @Nelson if you are responding to my comment --- the approach is with an *unvented* range hood, producing no net airflow into or out of the kitchen.  You add a ceiling fan and crack open a window in or near the kitchen (but not right next to the ceiling fan) and you have your cake and eat it: Particulate filtering from the hood, and air flow through the kitchen moving some gases and steam out of the house.  To your point this makes no sense with a vented hood or in a "sealed" kitchen.
Answer: There are two simple factors with opposing relationships:

Work clearance
Vacuum effectiveness

The manufacturer wants the hood as close as possible so it's more effective at scavenging gases, but they know you need clearance to move and cook. That's really it. Fire danger isn't much of a factor until the hood is mere inches from the burners, and who's going to do that?
Regarding reduced effectiveness at greater heights, I'd expect an accelerating reduction in scavenging with height. If you think of your hood's area as a portion of the surface of a sphere centered on the stove top, the further away you go the smaller that is as a portion of the sphere's surface1. It shrinks substantially as the effect of local breezes increases. (Simply walking by pulls a lot of the fumes along with you, out of reach of the hood2.)
Therefore, that 30" number isn't "concrete", but it's notice that you lose a lot of exhaust function if you go beyond it. There's not much science to be applied due to the great potential for variation in local conditions3. Any claims to numbers would necessarily assume averages from a large range of values.

1 It's an oversimplification for sure, but let's take a look using the hood's box area (which may not even be appropriate; the duct opening might be a better reference). The area of a sphere at 24" radius is 1809.6 in2. The portion of a range hood of say 20"x30" is 3.31%. If you move out to 30" it drops to 2.12%. That's a proportion reduction of ~36%. Move out to 36" and you're down to 1.47%, or another 30.6% smaller and less than half what it was at 24". The reduction in effectiveness as a result is compounded by dynamic air movement in the room and time.
2 Beyond its event horizon, if you like.
3 HVAC type and location, room size and shape, window usage and location, door usage and location, ceiling height, human activity, etc., etc. It quickly becomes a study in chaos theory akin to predicting the weather.
Answer: A web-search on "why must a range hood be 30 inches above the range" reveals several results, mostly from manufacturers' websites, explaining that the lower limit is defined by the heat generated by the range, and the upper limit is defined by how much suck the hood blower has and how much range air will be vacuumed up. I could not find a scientific paper on the subject, but there is likely science behind it.
The biggest concern on where to place a particular hood code-wise is using a UL/ETL/equivalent-listed hood and following the manufacturer's instructions. A listed hood has been tested for safety, and the manufacturer's instructions will reflect the safety limits determined by the listing authority.
Mounting the hood outside the instructions' measurements (too low, too high) will make the installation not up to code and not covered by your house's insurance company in the event of an accident.

Hood placement for gas range


Does the set of points in $\mathbb{R}^2$ with at least one rational coordinate have measure zero

Question: Does the set of points in $\mathbb{R}^2$ with at least one rational coordinate have measure zero? I can show easily that $\mathbb{Q}^2$ has measure zero, but this is only easy because $\mathbb{Q}^2$ is countable.
There are uncountably many points in $\mathbb{R}^2$ with one rational coordinate and one irrational coordinate, how do I show that this set has measure zero?
Comment: Can you show that lines in $\mathbb{R}^2$ are Lebesgue measure-zero? Then your set is simply a countable union of measure-zero sets, which is again measure-zero. (For this, even you don't need the full power of the former claim. It is sufficient to show that lines that are parallel to one of the axis have measure zero. As a hint for this, for each $\epsilon > 0$ notice that $\mathbb{R}\times\{0\} \subseteq \bigcup_{n=1}^{\infty} [-2^n, 2^n] \times [-\epsilon/4^n, \epsilon/4^n]$.)
Comment: @SangchulLee A good hint. I personally really like drawing a sombrero instead, instead of having to draw boxes.
Comment: Yes, that works. I can show that, thanks!
Comment: Not entirely sure how you chose the tags on this question.
Comment: @AsafKaragila Haha sorry, I was wondering at first if this set was countable, which it of course isn't. That was on my mind when I chose the cardinality/topology tags, sorry about that!
Answer: The set is equal to $(\mathbb{Q} \times \mathbb{R}) \cup (\mathbb{R} \times \mathbb{Q})$. Try to show that each of these sets has measure zero; in fact, you may find it much easier to just prove the result that
$$A \text{ countable } \implies \mathcal{L}^2 (A \times \mathbb{R}) = 0.$$
Drawing a picture of this is a good start - $A \times \mathbb{R}$ consists of countably many lines, and a line can be fit inside a region of arbitrarily small area.


NestJS: wrap 3rd party decorator & setMetaData in order to use Reflector to check annotation

Question: I am using NestJS to implement a project with TypeScript.
I am using a 3rd party library which provide a decorator called Protected, I can use the decorator to annotate my controller method:
@Protected()
myFunc(){
  ...
}

I have a Guard, in which I want to check whether the annotation is there inside my MyGuard class. I tried:
@Injectable()
export class MyGuard implements CanActivate {
  constructor(private reflector: Reflector) {}

  canActivate(context: ExecutionContext): Promise<boolean> {
    const value = this.reflector.get('Protected', context.getHandler());
    console.log(`VALUE: ${metaValue}`);
    ...
  }
}

The log message shows me VALUE: undefined.  I read the NestJS doc, there is an example of using setMetadata() and then in Guard method use the metadata key to retrieve metadata to check if the annotation is there. However, this is a 3rd party decorator, there is no information for me whether they use any metadata key.
So, I come up with a workaround, I create my own custom decorator which wraps the 3rd party Protected decorator & use my decorator instead on controller method:
import {Protected} from '3rd-party-lib'
import { SetMetadata } from '@nestjs/common';

export const MyProtected = () => {
    Protected();
    SetMetadata(IS_PROTECTED, true);
}

But now, the annotation on controller method raises error:
/**
ERROR: Unable to resolve signature of method decorator when called as an expression.
  This expression is not callable.
    Type 'void' has no call signatures.ts(1241)
**/
@MyProtected()
myFunc(){
  ...
}

My questions:

Is there a way to use Reflector to check whether the 3rd party annotation is presented in the controller method inside MyGuard ?

If there is no way without using setMetadata & since I don't know what metadata key to check due to 3rd party library. How can I setMetadata myself in my custom decorator in order to achieve what I need?
Answer: Why not use Nest's applyDecorators so you can compose the decorator out of several decorators?
export const MyProtected = () => applyDecorators(
  Protected(),
  SetMetadata(IS_PROTECTED, true)
);

Comment: Thanks. Looks great. I am newbie in NestJS , didn't know it. I will try it tomorrow


How to fix undefined symbol error for Digikam on Ubuntu 22.04

Question: I have upgraded a number of computers from Ubuntu 21.10 to 22.04. After the update, I cannot run DigiKam on one of them. I tried to remove, purge and reinstall digikam,  libgdal, and libblosc1 - without success.DigiKam stops before opening any window or even the splash screen.
$ digikam
digikam: symbol lookup error: /lib/libgdal.so.30: undefined symbol: blosc_cbuffer_validate
$

I tried to find that symbol (blosc_cbuffer_validate) in libgdal. The symbol is undefined in the library, indeed, but that is equally the case on my other computers where digikam starts normally.
$ nm -gD /lib/libgdal.so.30 | grep blosc_cbuffer
                 U blosc_cbuffer_validate
$

I was wondering in what way the computer that cannot run DigiKam anymore is different from the others, and can only think of these two differences:

DigiKam was installed before the upgrade to Ubuntu 22.04
It has an AMD Ryzen CPU, whereas the others have Intel i7.

What may be the problem? How can I solve it?
Short of a solution, how could I narrow it down?
Answer: It is defined in libblosc1.
$ sudo apt install libblosc1

And verify with:
$ nm -gD /usr/lib/libblosc.so.1 | grep blosc_cbuffer
0000000000004580 T blosc_cbuffer_complib
0000000000004530 T blosc_cbuffer_metainfo
0000000000004440 T blosc_cbuffer_sizes
00000000000044b0 T blosc_cbuffer_validate
0000000000004570 T blosc_cbuffer_versions

UPDATE: Please provide the output of $ ldd digikam
UPDATE: It is loading the wrong file from /opt which can be fixed with:
$ LD_PRELOAD=/usr/lib/x86_64-linux-gnu/libblosc.so.1 digikam

Or by changing the LD_LIBRARY_PATH or by removing the version in /opt.
Comment: Thanks, will do if nobody comes up with a better solution or explanation rather than a workaround.
Comment: Could you remove your request for more info on your answer (instead of using comments)? Could be useful more info about `nd`, `ldd` and the reasons behind your answer, to help others to find solutions to similar problems. @bogl `dpkg --search /opt/lib/blosc/lib/libblosc.so.1` will search for deb packages using that file.
Comment: I had libblosc1 already installed. Yes, the symbol exists, but that does not impress Digikam. Location is different from yours: /usr/lib/x86_64-linux-gnu/libblosc.so.1. Are you on Ubuntu 22.04 and x86_64?
Comment: @bogl try: `$ LD_PRELOAD=/usr/lib/x86_64-linux-gnu/libblosc.so.1 digikam` and provide the output of `$ ldd digikam` please.
Comment: It starts when pre-loading libblosc.so.1 !
Comment: I hesitate to provide all 413 lines of 'ldd digikam', but the location libblosc seems odd:  libblosc.so.1 => /opt/lib/blosc/lib/libblosc.so.1 (0x00007f1b34066000)
Comment: Great! Don't forget to accept the answer.
Comment: Removing the version in `/opt` will straight up fix it.
Comment: I cannot just remove /opt/lib/blosc/ without knowing what other applications might depend on that version. It would also be worthwhile to know what caused this glitch in the first place.
Comment: @bogl Your bounty expires today.
Comment: Thanks for the hint, @PabloBianchi, but no deb pkg seems to rely on it. I have quite a few applications that are installed in /opt. I assume that one of these installed libblosc there.


Regular expressions multiple matches

Question: I have this text and I want to get the 2 matches from it but the problem is I am always getting only 1 match. This is the sample code in c#
<code>string formattedTag = "{Tag 1}::[FORMAT] asdfa {Tag 2}::[FORMAT]";
var tagMatches = Regex.Matches(formattedTag, @"(\{.+\}\:\:\[.+\])");
</code>
i am expecting to get two matches here "{Tag 1}::[FORMAT]" and "{Tag 2}::[FORMAT]"
but the result of this code is the actual value of the variable formattedTag.
It must be something from regexp pattern so can somebody help me to figure it out?
I will appreciate every help. Thanks in advance!
Comment: be non-greedy, `@"(\{.+?\}\:\:\[.+?\])"`
Comment: +1 For your response Avinash. Using non-greedy operators can be good when a program, or programming language allows it. I don't usually use them because some programs, such as sed or grep don't allow it.
Comment: Thanks Avinash! this one also works. And noted on this non-greedy operators
Answer: You need to use the following regular expression:
<code>(\{[^}]+\}\:\:\[[^]]+\])
</code>
You want to match any character except the closing bracket within your bracketed portions of the string, otherwise the whole string is matched because regular expressions are greedy and attempt to retrieve the longest match.
Comment: oh my.. it works like a charm. Thank you very much Dave!
Comment: `{[^}]+}::\[[^]]+]` is enough.
Answer: <code>  string formattedTag = "{tag 1}::[admin] adfaf{tag 2}::[test.user]";
  var tagMatches = Regex.Matches(formattedTag, @"\{(\w+\s*\d{1,2})\}::\[(.*?)\]");
  foreach(Match item in tagMatches)[enter image description here][1]{
      Console.WriteLine(item.Groups[0]);
      Console.WriteLine(item.Groups[1] + "=" + item.Groups[2]);
  }
</code>

Regular expressions multiple matches


How can I remove the rows with the same first column and lower second column in awk?

Question: I have a list with 2 columns. In some rows I have the same values in the first column. In this case I want to remove the rows with lower values in the second column.
example:
input:
1  10
2  20
3  15
3  5
3  35
4  20

output:
1  10
2  20
3  35
4  20

Comment: please show us the code you have tried
Answer: Yes, sure:
$ awk '{a[$1]=(a[$1]<$2?$2:a[$1])} END {for (i in a) print i, a[i]}' file
1 10
2 20
3 35
4 20

Just keep populating the array a[] with the maximum value of column 2 for a given column 1. Finally, print the result.
This uses the fact that a value defaults to 0 in awk. But it would fail if all values for a certain index were always negative or zero. For this, we have to improve the script a little bit by checking also if the specific index of the array exists:
awk '{a[$1]=(($1 in a) && a[$1]>$2?a[$1]:$2)}
     END {for (i in a) print i, a[i]}' file

Test
$ cat a
1  10
2  20
3  -15
3  -5
3  -35
4  20
$ awk '{a[$1]=(($1 in a) && a[$1]>$2?a[$1]:$2)} END {for (i in a) print i, a[i]}'  a
1 10
2 20
3 -5
4 20

Comment: You are right. I thought about it, but having the sample input with positive values lead me to the "easy" approach.
Comment: In fact I normally think on the easy approach and then add the sanity checks. I just added it, then I noticed it is almost exactly the same you suggested in your previous comment!
Comment: @EdMorton You should either write a book! Or at least start writing canonic question/answers in this site, so that they are easy to find and not "dirtied" by user specific situations. See for example what they did in Unix&Linux: http://meta.unix.stackexchange.com/questions/2708/lets-compile-a-list-of-canonical-qas
Comment: Yeah some day..... At one point I had been contributing solutions to awk.info (see http://awk.info/?EdM) but the guy who owns the site quit so now unfortunately it's unmaintained and I certainly don't want to take THAT job on!
Comment: @fedorqui I think there is no guarantee, that the lines will be printed sorted by index. This may depend on the awk used.
Comment: @Meixner true, this has been discussed in [Why does awk seem to randomize the array?](http://stackoverflow.com/q/20683474/1983854)


UIButton events

Question: using iphone SDK 4.0. I have some UIButtons in a viewcontroller which when touched should play a tone, and when released stop playing the tone. This is done so that the tone length depends on how long the button is held down.
I use the Touch down event for when i call [toneplay start] and the TouchUpInside event
for when i call [toneplay stop].
A problem i have discovered is that if after touching a button i quickly navigate to another viewcontroller ( via tab bar button for example) the TouchUpInside event never fires and so the tone never stops playing unless i navigate back to the screen and hit the same button.
What would be the correct way to do this, the actual method to play the tone doesn't matter here its more which UIButton events i should really be using to get the above functionality.
Thanks
Answer: You also want to hande UIControlEventTouchUpOutside and UIControlEventTouchCancel.
Just think of touching the button, then moving the finger outside and liftig it.

UIButton events


iOS - CLGeocoder without internet connection

Question: I am using CLGeocoder to locate adresses on a map and calculate the user's distance in comparison to a whole bunch of adresses.
Here is the part of the code that uses CLGeocoder:
CLGeocoder *geocoder = [[CLGeocoder alloc] init];
__block float distance;
__block CLLocation *location;
[geocoder geocodeAddressString:adresseFinal completionHandler:^(NSArray *placemarks, NSError *error) {
    if ([placemarks count] > 0) {
        CLPlacemark *placemark = [placemarks objectAtIndex:0];
        location = placemark.location;
        CLLocationCoordinate2D coordinate = location.coordinate;
        distance = [userLocation distanceFromLocation:location];
        [distanceArray addObject:[NSString stringWithFormat:@"%f", distance]];
        MKPointAnnotation *point = [[MKPointAnnotation alloc] init];
        point.coordinate = coordinate;
        point.title = tableNoms[i];
        NSMutableArray *coords = [[NSMutableArray alloc] init];
        [coords addObject:location];
        [coords addObject:userLocation];
        [self.mapView addAnnotation:point];
    }
    dispatch_group_leave(group);
}];

But when I try and use it without internet connection, I get the following error:

Could not determine current country code: Error Domain=NSURLErrorDomain Code=-1009 "The Internet connection appears to be offline." UserInfo=0x7877f930 {NSErrorFailingURLStringKey=http://gsp1.apple.com/pep/gcc, _kCFStreamErrorCodeKey=8, NSErrorFailingURLKey=http://gsp1.apple.com/pep/gcc, NSLocalizedDescription=The Internet connection appears to be offline., _kCFStreamErrorDomainKey=12, NSUnderlyingError=0x7877ed30 "The Internet connection appears to be offline."}

I thought I was able to use localisation without internet (using GPS?)?
Do I have to change something in my code in order to be able to use it?
Thanks a lot !
Answer: Geocoding isn't the same as geolocation. The GPS is used to determine your geolocation and the result of that is a latitude/longitude position. Geocoding is the process of converting between that geolocation and the corresponding address details.
While geolocation doesn't require an Internet connection, geocoding does because it's a lookup on an Apple database to find the address for the geolocation.
Comment: Also, localisation is the process of allowing your app to use multiple languages and as such isn't related to physical locations.
Comment: Thanks for the answer, that is clear enough. Oh and my bad for localisation...stupid mistake. Thanks a lot !


Repeating x and y vectors for use with scatter3()

Question: Currently I have a working 3D mesh() plot. However, the vertical axis lends itself better to an angular representation, so I'm constructing a coordinate transform to cylindrical space, after which I'll plot everything with scatter3().
Currently I have one-dimensional vectors containing all of the possible x and y values; however, they do not repeat (and they need to, to work in scatter3()). I have to flatten my two-dimensional z-matrix using z(:). Is there a quick method to repeat x and y to also be scatter3-compatible?
Thanks...
Answer: Use meshgrid and then flatten:
[X,Y] = meshgrid(x,y);
scatter3(X(:), Y(:), z(:));


tanh transformation of symmetric positive definite matrix

Question: Let a symmetric positive definite matrix $\boldsymbol{S}\in\mathbb{R}^{d\times d}$ be given.
Consider the following transformation: tanh is applied on the off-diagonal entries and the diagonal entries are set to $1$. Is the resulting matrix again positive definite?
Answer: Consider the matrix
$$ S_n=\begin{pmatrix} 4n & 2n & n \\
2n & 4n &  2n\\
n &2n &4n
\end{pmatrix} $$
Then $S_n$ is strictly positive definite as the diagonal is dominating.  The new matrix has the form
$$T_n= \begin{pmatrix} 1 & a_n & b_n \\
a_n & 1 &  a_n \\
b_n &a_n &1
\end{pmatrix} \qquad a_n={e^{2n}-e^{-2n}\over e^{2n}+e^{-2n}},\quad b_n={e^{n}-e^{-n}\over e^{n}+e^{-n}}$$
Then
$$\displaylines{\det T_n= (b_n-1)\,[2a_n^2-b_n-1)\\ =(b_n-1)[(1-b_n)-2(1-a_n)(1+a_n)]}$$
We have $b_n<1$ and
$$1-a_n\approx 2e^{-2n},\qquad 1-b_n\approx 2e^{-n}$$
Hence
$$2a_n^2-b_n-1\approx 2e^{-n} -8e^{-2n}$$
Thus $\det T_n<0$ for large $n.$
Comment: @Philipp123 Thanks. I could have taken the entries $(1,3)$ and $(3,1)$ equal $0.$ Then $b_n=0$ and $\det S_n=-(2a_n^2-1)<0$ for $a_n>2^{-1/2}.$
Comment: Nice answer, thanks, also works for $n=1$ I think, $S_n$ is indeed positive definite even though it is only weakly diagonal dominant


toliet backing up after roter rooter and replaced toliet

Question: Toilet started backing up. Called roter rooter. Unclogged but they suggested it was the toilet (old)  Replaced with new toilet however after my husband used toilet it backed up and wouldn't flush
Comment: Try a different sewer cleaning company. I've had similar issues and ended up talking with a local guy who cleaned out the sewer with a larger "bit" and considerably longer snake than the "big company" guys use and it took care of the problem. The "big company" guys weren't getting at it with the right tools.
Comment: Who replaces a toilet to fix a plug? Only conn artists!
Comment: get a new husband ... lol ... just kidding .... was the toilet tested after installation?
Comment: I'd like to know if you are on a public sewer system, or a private septic system.
Comment: It's one of the above. My money's on them not having got it all the way into the street, not checking it with a camera, or not using a bit that will cut roots. That's assuming you don't have a septic system...
Comment: The question is "How did they clean the drain" then did they go all the way to the street. In the "How" if they used a clean out it could be the section between the clean out and the toilet or and yes I've seen it a blocked vent that goes up to the roof as the toilet has to vent or it will backup and burp in your face. Squirrels like vents..
Answer: Left as an answer because with the information provided I believe you were taken advantage of ( screwed in common terms)
Wow, I would call the bbb and state exactly what you did here. Sounds like a really scum type of business!!!!!!!! Sorry but old toilets have more water and actually clear the piping better,  to tell the truth you should have a case and find a different plumber and get some of your $ back !!!!!!!!
Comment: So true about the old toilets.  I know many people who have regretted replacing their old ones.
Answer: If it were me, I would contact the installer, and have them come back right away, but be incredibly friendly and nice and positive when you contact them.


Cannot Pause Game when app is in the Background State

Question: This may be a really basic question, but I have made a simple game in which the user avoids oncoming obstacles. When I press the home button my app is still running in the background, and because of this the app music continues playing and all my NSTIMERS continue which eventually causes the game character to hits an obstacle).
Can show me how to pause the game when I press the home button or switch to another app (game is in the background state), then resume when the app is in the foreground again?
Comment: Please make sure you read this and try to improve your question: http://stackoverflow.com/help/mcve
Comment: What exactly is incorrect about it?
Comment: @1QuickQuestion I think he wanna know more information about your code. Anyway I left an answer, see if it can help you.
Answer: I don't know how you have been doing your code, but when the user put the app in background you can use this method in AppDelegate.m to know the exact moment:
<code>- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.

    NSLog(@"going to background");
}
</code>
Inside of the method you can set your music to stop and set all the NSTIMERS. And you can use this one:
<code>- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.

    NSLog(@"Back from Foreground");
}
</code>
To know when the user come back from the background to the foreground.
Comment: Thanks J, this was helpful but I actually have something similar to this in my appDelegate. My issue is that I want to call a method to pause the game at the "NSLog(@"going to background");" point and resume at the point of "NSLog(@"Back from Foreground");".
Comment: Oh I got it. I saw you have accepted an answer. That's great :)
Answer: It's Quite Simple...
Use this code:
<code>    [[NSNotificationCenter defaultCenter] addObserver: self
                                         selector: @selector(pauseGameSoUserDoesNotDieForNoReason:)
                                             name: UIApplicationDidEnterBackgroundNotification
                                           object: nil];
</code>
Put it in the setup method of .m file that contains your timers and the method.

Put this in the .m file as well
<code>-(void)pauseGameSoUserDoesNotDieForNoReason:(NSNotification*)theNotification{

}
</code>
This last method:
<code>-(void)pauseGameSoUserDoesNotDieForNoReason:(NSNotification*)theNotification</code>

Is where you put your pausing code.
Note:
This code can be placed in several .m files.
Comment: YOU ARE A LIFE SAVER! Thank you! I figured it was a pretty simple solution! Thanks a lot!


Error: INSERT INTO fails mysql

Question: I have a problem with mySQL I get this error
Notice: Undefined property: PDO::$error in C:\MAMP\htdocs\paresFiles.php on line 33
Error: INSERT INTO `searchtable`(`word`, `array`, `count`) VALUES ( pinocchio , 1 ,-1)

Notice: Undefined property: PDO::$error in C:\MAMP\htdocs\paresFiles.php on line 33
Error: INSERT INTO `searchtable`(`word`, `array`, `count`) VALUES ( alice's adventures in wonderland , 2 ,-1)

Notice: Undefined property: PDO::$error in C:\MAMP\htdocs\paresFiles.php on line 33
Error: INSERT INTO `searchtable`(`word`, `array`, `count`) VALUES ( peter pan , 3 ,-1)

Notice: Undefined property: PDO::$error in C:\MAMP\htdocs\paresFiles.php on line 33
Error: INSERT INTO `searchtable`(`word`, `array`, `count`) VALUES ( snow white , 4 ,-1)

I want to insert to my search table in mysql 3 values and when I insert them I get this error and didn't get any data in my table.
what I need to do to solve this error?
this is my code (for insert data):
include_once 'connect.php';

$dir = "storage";
$title;
$auther;
$fileNum;
// Open a directory, and read its contents
foreach (glob($dir."/*.txt") as $filename) {
    $handle = fopen($filename, "r");
    if ($handle) {
    while (($line = fgets($handle)) !== false) {
        if(substr( $line, 0, 3 ) === "#id")
        {
            $fileNum=substr( $line, 5, 3 );
        }
        if(substr( $line, 0, 6 ) === "#title")
        {
            $title=substr( $line, 8, 100 );
        }
        if(substr( $line, 0, 5 ) === "#name")
        {
            $auther=substr( $line, 8, 12 );
        }
    }
    $titleVal=-1;

    $sql = "INSERT INTO `searchtable`(`word`, `array`, `count`) VALUES     ($title,$fileNum,$titleVal)";

       if ($db->query($sql) === TRUE) {
            echo "New record created successfully";
        } else {
            echo "Error: " . $sql . "
" . $db->error;
        }
    fclose($handle);
 }

connect to mysql:
<?php
    $db = new PDO('mysql:host=localhost;dbname=search;charset=utf8mb4', 'root', 'root');
    if (!$db) {
        die('Could not connect:' . mysql_error());
    }
    echo 'Connected successfully';
?>

Comment: missing quotes in values. Better use prepare statement!!
Comment: like this:  $sql = "INSERT INTO searchtable("word", "array", "count") VALUES ($title,$fileNum,$titleVal)"; ? @Saty
Comment: read http://php.net/manual/en/pdo.prepared-statements.php
Comment: Use PDO::errorInfo() instead of PDO::$error
Comment: @mnv it writes me Notice: Array to string conversion in C:\MAMP\htdocs\paresFiles.php on line 33
Error: INSERT INTO `searchtable`(`word`, `position`, `count`) VALUES ( pinocchio , 1 ,-1)
Comment: @user3488862 Write something like this: `$db->errorInfo()[2]` Read more about: http://php.net/manual/ru/pdo.errorinfo.php
Answer: You should use prepare statements.
Something like this
$sql = "INSERT INTO searchtable (word, array, count) VALUES (:word , :array, :count)";

$statement = $db->prepare($sql);
$statement->exec(array(
    'word' => $title,
    'array' => $fileNum,
    'count' => $titleVal
));

Comment: it writes me
 Fatal error: Uncaught Error: Call to undefined method PDOStatement::exec() in C:\MAMP\htdocs\paresFiles.php:31 Stack trace: #0 {main} thrown in C:\MAMP\htdocs\paresFiles.php on line 31
Comment: Need to change `exec` to `execute`
Comment: @Saty ok I changed it but now I have a new error: Notice: Array to string conversion in C:\MAMP\htdocs\paresFiles.php on line 40
Error: INSERT INTO searchtable (word, position, count) VALUES (:word , :position, :count)
Array
Comment: can you dump the values of `$title`, `$fileNum` and `$titleVal`

Error: INSERT INTO fails mysql


Why service does not have any active Endpoint when install grafana from helm to kubernetes-sigs/kind?

Question: https://github.com/kubernetes-sigs/kind - version 0.4.0
Create kubernetes from kubernetes-sigs/kind
kind create cluster
Creating cluster "kind" ...
 ✓ Ensuring node image (kindest/node:v1.15.0)

kubectl create serviceaccount
kubectl create serviceaccount --namespace kube-system tiller
serviceaccount/tiller created

kubectl create clusterrolebinding
kubectl create clusterrolebinding tiller-cluster-rule --clusterrole=cluster-admin --serviceaccount=kube-system:tiller
clusterrolebinding.rbac.authorization.k8s.io/tiller-cluster-rule created

kubectl patch deploy
kubectl patch deploy --namespace kube-system tiller-deploy -p '{"spec":{"template":{"spec":{"serviceAccount":"tiller"}}}}'
deployment.extensions/tiller-deploy patched

helm init

helm install stable/nginx-ingress

helm install --name grafana stable/grafana --set=ingress.enabled=True,ingress.hosts={grafana.domain.com} --namespace demo --set rbac.create=true

kubectl logs loping-wallaby-nginx-ingress-controller-76d574f8b7-5m6n5
W0629 17:13:59.709497       6 controller.go:797] Service "demo/grafana" does not have any active Endpoint.
[29/Jun/2019:17:14:03 +0000]TCP200000.000
I0629 17:14:45.223234       6 status.go:295] updating Ingress demo/grafana status from [] to [{ }]
I0629 17:14:45.226343       6 event.go:209] Event(v1.ObjectReference{Kind:"Ingress", Namespace:"demo", Name:"grafana", UID:"228cde81-cb97-4313-ad86-90a273b2206d", APIVersion:"extensions/v1beta1", ResourceVersion:"1938", FieldPath:""}): type: 'Normal' reason: 'UPDATE' Ingress demo/grafana

kubectl get ingress --all-namespaces
NAMESPACE   NAME      HOSTS                ADDRESS   PORTS   AGE
demo        grafana   grafana.domain.com             80      3m58s

kubectl get svc --all-namespaces -l app=grafana
NAMESPACE   NAME      TYPE        CLUSTER-IP       EXTERNAL-IP   PORT(S)   AGE
default     grafana   ClusterIP   10.104.203.243   <none>        80/TCP    24m

kubectl get endpoints
NAME                                           ENDPOINTS                      AGE
grafana                                        10.244.0.10:3000               21m
kubernetes                                     172.17.0.2:6443                56m
loping-wallaby-nginx-ingress-controller        10.244.0.8:80,10.244.0.8:443   48m
loping-wallaby-nginx-ingress-default-backend   10.244.0.7:8080                48m

Thanks!
Answer: A few concerns about your current scenario:

You have to check installed nginx-ingress helm chart in order to find out why grafana service resides in separate namespace default and not in demo namespace as per helm deploy parameter --namespace demo.
Since you have not specified in helm install command controller.service.type parameter, Nginx Ingress Controller would be implemented with LoadBalancer type of relevant service, in this case Ingress Controller expects to receive external IP address using cloud provider's load balancer and I assume that your current kubernetes provisioner kubernetes-sigs/kind is not a good choice to adopt outward access to the Kubernetes cluster. Therefore, I would suggest to use NodePort service for Nginx Ingress controller in order to expose 80 and 443 port on some specific port in the host machine.
helm install --name grafana stable/grafana --set=ingress.enabled=True,ingress.hosts={grafana.domain.com} --namespace demo --set rbac.create=true --controller.service.type=NodePort
Issue that you mentioned is more like harmless and doesn't significantly affect the Nginx Ingress Controller's functionality, because it means that for some short period of time Liveness probe for Grafana Pod has not been initiated and target enpoint has not been released during Grafana Helm chart deploy. You can even re-spawn Nginx Ingress controller Pod to justify my assumption.
Answer: you are using type of service as "ClusterIp" , so you will not get external Ip address.
Change the Service type to "Loadbalancer" then you get Ip address which you can browse through internet.
Comment: op was asking about using the ingress controller as a load balancer, not the actual grafana service.


Wubi won't start

Question: Trying to install Ubuntu on old XP computer. It won't boot from CD and when I open CD it won't run Wubi because it isn't a valid Win32 application.
CD works ok on Win7 and Vista machines. Do I  need a different download? Have Ubuntu-12.04.2-desktop-i386.iso
Answer: Run wubi.exe as the adminitrator, when Windows asks for verification, click "Run".
Comment: bodhi.zazen   Thanks for reply. Can't even get to administrator stage as it says Wubi isn't a valid Win32 prog.
Comment: Don't know. But disc was ok on other machines. Just won't boot or run Wubi on the old Xp PC. Where I really want it.

Wubi won't start


Credentials expired for online accounts

Question: I was trying to sync my google calendar with gnome-calendar, for that I added my accounts to ubuntu 20.04 but gnome-calendar didn't sync with them(don't know why) and after than when I restarted my laptop I saw that credentials for all of the accounts were expired.

Any clue why is this happening and why I am not able to sync the calendar?
Comment: How much time has passed since the time you added the account and the time you most recently synchronised your accounts? Google has a hard limit of 1 year for their TLS certificates (as does Mozilla and Apple). Non-corporate Microsoft accounts are usually good until 90+ days of inactivity. Not sure sure about Ubuntu's SSO certificate lifespan.
Comment: hardly 30 min...I added accounts, tried to sync calendars , searched a couple of mins on google, and then restarted
Answer: In my case, i could fix a similar looking problem by executing
$ /usr/libexec/goa-daemon --replace

See this comment on a Red Hat bug report about goa-daemon.
Comment: This was useful for me for configuring pop os with i3 gaps and calendar sync
Answer: I found this may works for you .
Try this:
Remove you Google account from Gnome Settings
Remove ~/.cache and ~/.config/goa-1.0
Sign in again for your Google account from Gnome settings, and give it some seconds to sync
Logout and login or reboot.
Original article https://www.reddit.com/r/gnome/comments/i8hhsj/gnome_calendar_is_not_syncing_with_google/g18hivm/?context=3

Credentials expired for online accounts


Are there limit problems that cannot be solved?

Question: This could mean any of the following:
the limit is unsolvable by algebraic means or by hand (rationalizing or limit laws or squeeze theorem)
the limit is unknown
inspired by:
http://socrates.bmcc.cuny.edu/math/Mzyman/CalcLab2-303.pdf
Answer: If you mean "solve a limit" by calculating the specific value of it, the answer is yes; and there are perhaps a lot more limits than you can calculate by algebraic means.
Consider the following infinite series when $s$ is positive
$$ \zeta(s) = \sum_{n=1}^{\infty}\frac{1}{n^s} $$
We know that $\zeta(1)$ diverges. How about other values of s? They are not easily calculable; most of them requires advanced knowledge in mathematics. For example, $\zeta(2)$ equals $\frac{\pi}{6}$, while the limit itself suggests no connection with $pi$. This surprising result can be proved by multiple methods, the one I know requires some knowledge in Fourier analysis. Until now, we have for even integers $2n$,
$$\zeta (2n)={\frac {(-1)^{n+1}B_{2n}(2\pi )^{2n}}{2(2n)!}} $$
But no general expression has been yet found for odd, or even rational numbers.
Many mathematicians were devoted to study $\zeta(s)$, which is related to the famous unsolved mathematical problem, the Riemann Hypothesis.
Comment: @DonAntonio apologies, that's a typo
Comment: @R You could as well have writtent that $\;\zeta(s)\;$ converges iff  Re$(s)>1\;$
Comment: ahh, the Bessel problem
Answer: Let $a_n$ be the number of times the digit $9$ appears in the first $n$ digits of the decimal expansion of $\pi$. What is
$$
\lim_{n\to\infty}\frac{a_n}{n}?
$$


I can't Install Ubuntu or any Linux distros on my PC

Question: I was using Ubuntu for a long time. Last time I was using Ubuntu and windows dually. But before my project submission final day, there was a problem I faced while using Ubuntu. I reboot my pc for some reasons and then there was some grub related problem encountered. I couldn't sure whether It was grub rescue problem or not. And as I was in a hurry the day before my project submission date so I installed windows quickly without solving that issue.
It was two months earlier incident. Now I am again trying to install different Linux distros on my pc but every time there is a unique problem I am facing right now. I can't install any Linux distro on my pc. It stuck at some certain point. See this screenshot:

Actually, It takes a lot of time to install in a certain phase, more than 2 hours and it's unusual. I tried to install Ubuntu 16.04 LTS, Deepin, Elementary OS but none of these can't install and stuck at the same point!
Even later I am trying to set up Linux by using the virtual machine but there I also face a problem that I haven't encountered before. It shows the following message:

Please help me.
Comment: Looks like two separate issues. I think you should ask two different questions.
Answer: Your CPU supports only 32-bit(x86/i686). You should install only 32-bit(x86/i686) distributions.


Why is the software center in the Debian repositories?

Question: Not that I mind or anything, just out of curiosity. But I noticed today that the Software Center in Ubuntu is actually an upstream package?.
In the description it says

To install or remove software using USC, you need administrator access on the computer.

So, it is referred to Ubuntu Software Center and the screen-shot on the right is taken from Ubuntu.
So, why would it be available in the Debian repositories, what is its use there?
Answer: As you may know, Ubuntu is built upon Debian. LTS releases are based on Debian Testing, while regular releases are based on Debian Unstable. Ubuntu packages are therefore almost always compatible with the respective Debian release.
Ubuntu Software Center is a nice front-end for browsing and searching for packages, and it uses standard .deb downloads/installation on the back-end. It works just as well on Debian as on Ubuntu, and is there as an alternative to Synaptic, etc. for Debian users.

Note: technically, the Debian USC is not an upstream package. In fact, as the filename software-center_5.1.2debian2.1 suggests, it's the Ubuntu (Launchpad) package which is the upstream here!
Answer: The software center is actually available in Debian. In fact, I used it yesterday on Debian Squeeze. The package for debian can be viewed here:
http://packages.debian.org/sid/software-center
Answer: That's normal, usc is opensource and build as .deb to be installed on all debian distributions (ubuntu is one of them)


Will Bing maps right-size the map to an array of coordinates?

Question: What I want to be able to do is pass an array of coordinates to a Bing map, and then have it show all of the waypoints/"pushpins" but only as much "area" as necessary. IOW, if I pass in coordinates that are all contained within eastern Calaveras County, the map should show only that area with very little margins around the outer waypoints. If, OTOH, I pass in an array of waypoints, and one is in Switzerland while others are in Swaziland, the map should be that "zoomed out" - showing from Swaziland to Switzerland, with the waypoints, no more and no less.
Also or thus, I would want the map to be centered: If the array of waypoints were in San Francisco and Lake Tahoe, Elk Grove (or very near it) should be at the center of the map.
Comment: I've mainly been reading about it and planning. Some combination of Windows 8 RC and Visual Studio 2012 are no longer even allowing me to build any app - any time I try, it is stuck in a "background operation" until I terminate VS.
Answer: In the older APIs there was an option to create a bounding rectangle from a set of points but this was not added to the windows store version of the control.  Bounding rectangles still exist, and may be used to set the map extents, but you have to determine the limits manually.
This may change in future updates, but to me the APIs feel a little too light for many scenarios, including the one you ask about.


Cancel button jsf not resetting entity

Question: I'm trying to implement a cancel button to clear the fields from my entity.
Though, when I'm setting the entity to null my fields still keep their value.
Code:
The EntityBB's cancel method (note that the debugger can reach the cancel method):
public void cancelAddStandardLetter() {
    setEntity(null);
    standardLetterInit();
}

this method really sets all the values from the entity back to null and the standardLetterInit method sets some default values that are needed (tried the same method without the standardLetterInit -> same result).
The xhtml page (other inputfields are left out):
<o:form includeRequestParams="true" id="addStandardLetterForm">

    <h:inputTextvalue="#{entityBB.entity.fileName}" styleClass="rInput"/>

    <h:commandButton value="Cancel" immediate="true"
            styleClass="floatRight"
            action="#{entityBB.cancelAddStandardLetter()}" />
</o:form>

After pressing the "cancel" button, the values being typed in the "fileName" field are still there. How can that be?
Comment: Should that *Cancel* button be renamed to *Clear* or *Reset* maybe? Let's keep concepts clear.
Comment: Well, that's one of the things `immediate` does. My point from above was that `o:ignoreValidationFailed` applied to your `h:commandButton` does *only* that, without all the nasty suprises executing your business logic in the Apply Request Values phase brings.
Comment: sounds like you want [o:ignoreValidationFailed](http://showcase.omnifaces.org/taghandlers/ignoreValidationFailed) instead of `immediate="true"` (or simply reload the page and initialize in a `@PostConstruct` method)?
Comment: The logic behind it is more complex then this small setup but the basics are the same. I need to use immediate="true" because there is also a save button etc in it. So I can't but my complete form on ignoreValidation. PostConstruct also can't be used because my entity will already exist before I'm entering this screen. (Bean is viewscoped and this input fields are rendered by a button click.)
Comment: I don't get it. You have a complex form and some fields can be reset by clicking a "Cancel" button. Why do you need to have `immediate` here? The way I've done that is having a `` on the button together with a ``.
Comment: Xtreme Biker, I can't change what the business asks. If they want to name it cancel then I have to name it cancel. Mabi, I thought I would need the immediate true to skip the validation step in the lifecycle. But BalusC's answer seems good and I'm going to try that one out!
Answer: Make sure that the bean is view scoped and use a plain GET button.
<h:button value="Cancel" />

This basically refreshes the page. It'll recreate the view scoped bean instance. No need to submit the whole form. If the input values still appear, then it's either the browser cache or autocomplete/autofill which you in turn can control with respectively a servlet filter and autocomplete="off".
Comment: If I do this, then I'm losing other values in my backingBean that I need to keep. So this doesn't seem an option either. But I'm going to refactor the whole setup to make it easier to maintain the application and that will probably also fix my problem.

Cancel button jsf not resetting entity


Exercise solutions for "3264 and all that"

Question: Please excuse, that this is not exactly a math question, but I do not know of a better forum to ask publicly and I do not want to contact the authors of the abovementioned book before having asked the public:
In the book "3264 and all that" by Eisenbud and Harris, in Chapter 0, page 8, it is said that Francesco Cavazzini prepared solutions for the exercises in the book, which appear on a web site associated to the book.
Unfortunately I was not able to locate this website or another place in the web, where these solutions are given. Does anyone know, where they can be found?
Comment: @JW I talked with prof Harris recently and he said the solutions were not completed due to Cavazzani getting a job in finance and at least temporarily leaving academia.
Comment: @TejasRao, thanks for the update.
Comment: not clear he put the solutions online http://www.math.harvard.edu/~franc/pdfs/CV_cavazzani.pdf  although the book authors expected that
Comment: @WillJagy: The link appears to be broken.
Comment: @JürgenBöhm, did you end up contacting the authors and what did they say? Perhaps you could post it as an answer to your own question.
Answer: You can find the solutions on David Eisenbud's website, solutions here.


Cmake error while building gromacs (ubuntu 14.10 64 bit)

Question: I installed cmake without any error in Ubuntu 14.10 64-bit
I am getting this error while running cmake in gromacs build directory
CMake Error: Could not find CMAKE_ROOT !!!
CMake has most likely not been installed correctly.
Modules directory not found in
/usr/local/bin
CMake Error: Error executing cmake::LoadCache(). Aborting.

How should I proceed?
Comment: @A.B  I used following commands tar xzvf cmake-3.2.2.tar.gz then cd cmake-3.2.2 then ./configure then make and then sudo make install
Comment: How did you installed cmake?
Comment: sorry m new to this so my replies may not be clearly formatted..
Comment: take a look at this http://stackoverflow.com/questions/18615451/cmake-missing-modules-directory it says you just have to export the cmake root env variable.
Answer: Please compile cmake again and use this ./configure (The default value is /usr/local):
sudo make uninstall
make clean
./configure --prefix=/usr
make

And you should use sudo checkinstall and not sudo make install to get a .deb file:
sudo apt-get install checkinstall

It may be that you first need to delete your old cmake installation:
sudo apt-get remove cmake
sudo apt-get remove cmake-data

and than install the compiled version with:
sudo checkinstall

That's all =)
Comment: Thank you for help.. I will get back to you after compiling
Comment: (Reading database ... 173178 files and directories currently installed.)
Preparing to unpack .../cmake_3.2.2-1_amd64.deb ...
Unpacking cmake (3.2.2-1) over (18.104.22.168-0ubuntu6) ...
dpkg: error processing archive /home/rakesh/Downloads/cmake-3.2.2/cmake_3.2.2-1_amd64.deb (--install):
 trying to overwrite '/usr/share/aclocal/cmake.m4', which is also in package cmake-data 188.8.131.52-0ubuntu6
dpkg-deb: error: subprocess paste was killed by signal (Broken pipe)
Errors were encountered while processing:
 /home/rakesh/Downloads/cmake-3.2.2/cmake_3.2.2-1_amd64.deb
(END)
Comment: I am getting this error in the log file after using sudo checkinstall
Comment: @RakeshPandit `sudo apt-get remove cmake` and than `sudo checkinstall`
Comment: @RakeshPandit does it work?
Comment: how can i remove cmake if installed manually and not from ubuntu software centre
Comment: Sorry, cmake-data, see my update
Comment: "A.B. how can i remove cmake-3.2.2 as i've installed it manually and not from the repository
Comment: make[2]: *** No rule to make target 'Utilities/cmcurl/lib/CMakeFiles/cmcurl.dir/build'.  Stop.
CMakeFiles/Makefile2:1414: recipe for target 'Utilities/cmcurl/lib/CMakeFiles/cmcurl.dir/all' failed
make[1]: *** [Utilities/cmcurl/lib/CMakeFiles/cmcurl.dir/all] Error 2
Makefile:146: recipe for target 'all' failed
make: *** [all] Error 2

****  Installation failed. Aborting package creation.

Restoring overwritten files from backup...OK

Cleaning up...OK

Bye... I am getting this error with checkinstall
Comment: Did you after `make uninstall`, run `./configure --prefix=/usr` and `make`?
Comment: ./configure --prefix=/usr  gives following error  CMake Error: Cannot determine link language for target "cmcurl".
CMake Error: CMake can not determine linker language for target: cmcurl
-- Generating done
-- Build files have been written to: /home/rakesh/Downloads/cmake-3.2.2
---------------------------------------------
Error when bootstrapping CMake:
Problem while running initial CMake
---------------------------------------------
Comment: Run a `make clean` before configure. Or remove the folder cmake-3.2.2 folder and start with a new.