Why does my concrete not look smooth

Question: I have laid a concrete slab for the first time. I bought a general purpose, ready mix tub of concrete and followed the instructions (add 400ml water to 5kg of concrete mix)
The end result is disappointing
As you can see, it's patchy and not smooth.
I read and watched countless videos and articles and so I am confused if this the result of my screeding effort
Arrogance would make me think the mix was too stoney.
Ignorance would make me think it wasn't wet enough (or wasn't mixed but I made sure there was no dry concrete)
Common sense would suggest it's my fault and a lack of technique
What would cause concrete to be patchy like this
Comment: Have you tried tamping? Basically tap the concrete, it causes the aggregate to sink and the 'juice' to rise.
Comment: Let me research this. Thank you for the comment
Comment: I did do that thought out. It has been down for 12 hours now so I'm guessing no point in continuing
Answer: The back and forth motion of the screed or float shakes the aggregates and makes the fine ones rise and the big ones sink, which gives a smooth surface. But the concrete has to be more liquid than what you did for that to happen. Then after screeding, before it hardens completely, spray some water on it and finish it with a float.
However if you put too much water in it, you'll have problems, like cracks. So you have to either get the water content "just right" or add some plasticizer which makes it fluid without extra water. You can also vibrate it, but that requires a special tool.
If you intend to tile this, then the rough surface is not a problem. It looks pretty good actually, since if the concrete will be covered, no need to bother with the extra work of making it smooth, all you need is to not have bumps. Tiles will cover roughness and holes just fine. If some aggregates stick out and the tiles stand on them, just smash the aggregates out of the concrete with a hammer.
If you intend to leave it visible, then you can spread a bit of mortar made with fine sand, or self-leveling, to make it smooth if you want.

Why does my concrete not look smooth


How to Enable/Disable button on TinyMCE textbox onkeyup or onkeydown

Question: on a ascx page I have a tinymce editor and a button
<asp:TextBox ID="txtName" runat="server" Width="100%" ></asp:TextBox>
<test:tinymceextender runat="server" ID="TinyMceExtender" TargetControlID="txtName" Theme="Full"> </test:tinymceextender>

<asp:Button ID="btnSave" Text="Save" Enabled="false" runat="server" />

I want to check if, textbox is null, then btnsave should be disable, if textbox is not null its should be enable, for the first time its working(because i am checking it on Page_Load), as I am entering some text and deleting that text using backspace btn is in enable mode only. I tried it to do with onKeyUp, onKeyPress but its working working for TinyMCE
these 2 js I used but its not working
$(document).ready(function () {
    document.getElementById('<%=btnSave.ClientID %>').disabled = true;
    var my_editor = tinymce.get('<%=txtName.ClientID %>');
    if ($(my_editor.getBody()).text() == '') {
        $("#<%=btnSave.ClientID %>").attr('disabled', 'disabled');
    }
    else if ($(my_editor.getBody()).text() != '') {
        $("#<%=btnSave.ClientID %>").removeAttr('disabled');
    }
});

window.onload = function () {
    document.getElementById('<%=btnSave.ClientID %>').disabled = true;
}
function ENABLE_BTN() {
    var EN = tinymce.get('<%=txtName.ClientID %>');
    if (EN == '') {
        document.getElementById('<%=btnSave.ClientID %>').disabled = true;
    } else {
        document.getElementById('<%=btnSave.ClientID %>').disabled = false;
    }
}

calling onkeydown="ENABLE_BTN() on txtName
on F12: my textbox code is looking something like this...
  <fieldset>

  <input id="BasePage_txtName" type="text" style="width: 100%; display: none;"  name="BasePage$txtName" aria-hidden="true">

  Rich Text Area

  </fieldset>

Answer: I would use the keyup event to check if the contents are empty like this. Edit: updated to use TinyMCE's weird eventhandler methods.
$(function () {

  tinyMCE.init({
    // adapt accordingly
    mode : "exact",
    theme : "simple",
    elements : "txtName",
    setup : function(ed) {
               ed.onInit.add(function(ed) {
                     bindKeyUp(ed);
           });}
             });
});

function bindKeyUp(ed) {
 if (tinyMCE.activeEditor) {
    ed.onKeyUp.add(function() {
      $('#btnSave').attr('disabled', !(textBoxEmpty()));
    });
 }
}

function textBoxEmpty() {
 var contentLength = tinyMCE.get('#txtName').getContent();
    if (contentLength.length) {
      return true;
    }
 return false;
}

Comment: not working, debugger is not going on Keyup function when debugging through F12
Comment: I am using tinyMCE.init in a separate js file with extender I can't add it on page level
Comment: I don't see why it would'n work on init if it's done on another page.
Comment: if tinymce is on same page then its working fine, but in my condition, tinymce is on other solution...
Comment: I don't get it. On your particular project, can you control the tinyMCE.init() ?
Comment: thank you its working now... plz check my ans also, I modified a bit in ur's and now its working for me
Answer: $(function () {

 tinyMCE.init({
// adapt accordingly
mode : "exact",
theme : "simple",
elements : "txtName",
setup : function(ed) {
           ed.onInit.add(function(ed) {
                 bindKeyUp(ed);
       });}
         });

});
function bindKeyUp(ed) {
    if (tinyMCE.activeEditor) {
        ed.onKeyUp.add(function () {
            var contentLength = removeHTMLTags(tinyMCE.get('<%=txtName.ClientID %>').getContent());
            if (contentLength.trim().length) {
                document.getElementById('<%=btnSave.ClientID %>').disabled = false;
            }
            else {
                document.getElementById('<%=btnSave.ClientID %>').disabled = true;

            }

        });
    }
}


Map restructuring

Question: In clojure, I can destructure a map like this:
(let [{:keys [key1 key2]} {:key1 1 :key2 2}]
  ...)

which is similar to CoffeeScript's method:
{key1, key2} = {key1: 1, key2: 2}

CoffeeScript can also do this:
a = 1
b = 2
obj = {a, b} // just like writing {a: a, b: b}

Is there a shortcut like this in Clojure?
Answer: It's not provided, but can be implemented with a fairly simple macro:

(defmacro rmap [& ks]
 `(let [keys# (quote ~ks)
        keys# (map keyword keys#)
        vals# (list ~@ks)]
    (zipmap keys# vals#)))

user=> (def x 1)
#'user/x
user=> (def y 2)
#'user/y
user=> (def z 3)
#'user/z
user=> (rmap x y z)
{:z 3, :y 2, :x 1}
Answer: I wrote a simple macro for this in useful, which lets you write that as (keyed [a b]). Or you can parallel the :strs and :syms behavior of map destructuring with (keyed :strs [a b]), which expands to {"a" a, "b" b}.
Comment: useful does indeed look useful! Is there documentation anywhere?
Comment: @benekastah Not really. You can read the source, and look at the tests - most functions are tested in a way that makes it clearish how they're supposed to be used.
Answer: The short answer is: no.
The main reason is that in Clojure, not only keywords but any value can be used as a key in a map. Also, commas are whitespace in Clojure. So {a, b} is the same as {a b} and will result in a map with one key-value pair, where the key is whatever a evaluates to.
You could however write a macro that takes a list of symbols and builds a map with the names of the symbols (converted to keywords) as keys and the evaluations of the symbols as values.
Answer: I don't think that is provided out of the box in clojure .. but hey this is lisp and we can use macros to have something like this:
(defmacro my-map [& s]
    (let [e (flatten (map (fn [i] [(keyword (str i)) i]) s))]
    `(apply hash-map [~@e]))
)

Usage:
(def a 10)
(def b 11)

(def result (my-map a b))

result would be your map

Map restructuring


Syncing Ipod Shuffle

Question: Hello i've tried to sync my ipod shuffle (latest gen) for 2 hours now...
I've tried banshee (I can put music on my device but not listening to it, "use itunes blablabla"), I've tried gtkpod (not launching), Floola (no ipod connected).
How can I proceed ?
Comment: Well, what version of Ubuntu? And what do you mean by gtkpod not launching? Does it segfault?
Comment: 13.04. I mean that after typing gtkpod in a terminal a small window open with the logo of the program but no program after that. I don't know what segfault means.
Comment: Launch gtkpod from a terminal, does it output errors on startup?
Comment: @EliahKagan This is the third iQuestion you've VTC as duplicate tonight. However the dupe is from 2011 and this question and the last is from 2014. Would an answer from 2011 still apply in 2014?
Comment: @WinEunuuchs2Unix Maybe there's a better dupe target for them. I think potentially a specific technical question about libimobiledevice could be answered and we shouldn't automatically dupe that sort of question. But isn't the general answer to the question of how to access features of any particular Apple device on any GNU/Linux OS (besides as a removable disk) still that hopefully libimobiledevice supports and isn't currently broken for it? As you likely know, I have no technical knowledge about libimobiledevice, so I must admit that I could well be wrong. ...Can new answers really be given?
Comment: @EliahKagan You can take that dupe from 2011 and add your own answer or update an existing answer to modern times. I've seen it done many times.
Comment: @WinEunuuchs2Unix As far as I know, [Jon's](https://askubuntu.com/a/87394) and [Tom Brossman's](https://askubuntu.com/a/89265/22949) answers to [that question](https://askubuntu.com/questions/83484/what-is-the-current-state-of-apple-device-iphone-ipod-etc-support) are still accurate and convey the fragmentary nature of Apple device usability ([as does Thomas Ward's answer on this other question](https://askubuntu.com/a/866155)). Do we have answers to general questions about whether or not an Apple mobile device can be used from Ubuntu and how to do it that should be updated or improved?
Comment: @EliahKagan As a general rule of thumb I think if the iDevice is using iOS 10 and the Ubuntu version is 16.04, but the Q&A in question is much much older then updated answers are warranted. You can even take a Ubuntu 12.04 answer and edit it to say "This works in Ubuntu 14.04 and 16.04 as well".
Answer: Answer is simple: Use Amarok.
sudo apt-get install amarok
It is a music player and music manager from the KDE suite.
Once you install it, connect the iPod and it would appear as a local device (with ipod somewhere in its name). Before you can sync, you need to setup your local library. For this: from settings menu, go to Configure Amarok, and then in the collections tab, make sure you tick your local music folder.

Perform full collection rescan by going to Tools menu, and Update Collection.
Now coming back to the iPod section in the left hand side pane, if you right click on an artist/album/genre/song, it would allow you to copy to the local collection. Vice-a-versa, in local collection, if you right click on any artist/album/genre/song, it would allow you to copy it to your ipod.
Refer http://www.howtogeek.com/howto/4791/how-to-use-amarok-to-manage-your-ipod/ for more detailed info on this.
Update: Just read your question once again. If this was prompting you to sell your ipod Shuffle, then definitely no need to do that anymore :) .
Comment: amarok does not recognise my device.

Syncing Ipod Shuffle


How can I retrospectively debug a python exception

Question: I'm looking for a way to debug a python exception "retrospectively". Essentially if my program raises an exception that isn't handled, I want it to save off the program state so I can go back later and debug the problem.
I've taken a look at the pdb docs, and it seems that you can do this, but only if you can interact with the program at the point of the exception. This won't work for me as the program will be run in the background (without a controlling terminal).
My first (doomed!) approach was to put a try/except block at the highest level of my program, and in the except block extract the traceback object from the current exception and write it to disk using pickle. I planned to then write a separate program that would unpickle the object and use pdb.post_mortem to debug the crashed program. But traceback objects aren't pickleable, but I wouldn't expect that to work anyway, as it wouldn't save off the entire program state.
Comment: This doesn't solve your problem by any means but instead of wrapping your whole program in a `try` statement, it might be better to set a handler for uncaught exceptions by assigning it to [`sys.excepthook`](http://docs.python.org/library/sys.html#sys.excepthook).
Answer: As far as I know, there isn't any way to do what you're asking.  That said, it sounds like you might be looking for a remote debugger.  There are a couple of options:

rconsole - This isn't really a debugger, but it allows you to get an interactive prompt inside another process.  This can be useful for debugging purposes.  I haven't tried this, but it looks relatively straightforward.
rpdb2's embedded debugger - This lets you start a debugger and then connect to it from another shell.
Answer: What you can do is use twisted.python and write the traceback to a file, it gives you an exact traceback including the exception
Comment: there's also the `traceback` module. But I don't think that's what the OP wants.
Comment: I'm not sure that does what I'm after. I can dump the traceback to file when the exception is caught, but what I'm really after is a way to interactively debug the program after the fact (like you'd debug a core file with gdb).
Answer: You could create an entirely separate execution environment in the top level:
myEnv = {}
myEnv.update(globals)

Then execute your code within that execution environment.  If an exception occurs you have the traceback (stack) and all the globals, so you can pretty well reconstruct the program state.
Answer: At the moment the exception is caught, before the stack is unwound, the state is available for inspection with the inspect module: http://docs.python.org/2/library/inspect.html
Generically you would use inspect.getinnerframes on your traceback object.  The local variables in each stack frame are available as .f_locals so you can see what they are.
The hard part is serializing all of them correctly: depending on what types you have in the local scope you may or may not be able to pickle them, dump them to JSON, or whatever.
Answer: I hope this helps (it helped me):
import logging, traceback
_logger = logging.getLogger(__name__)

try:
    something_bad()
except Exception as error:
    _logger.exception("Oh no!") # Logs original traceback
    store_exception_somewhere(error)

Also, in Python 3 there are a few new options like raise new_exc from original_exc
 or raise OtherException(...).with_traceback(tb).


HTML CSS Making the background image static

Question: I'd like to make it so the background image stays in the same place (static) while the website scrolls up and down. How do I go about doing this?
Answer: background-attachment: fixed; should do it i believe.
Comment: Note that this won't work correctly with IE6, in case that matters to you.
Comment: Hmm, I seem to remember having issues even on a `body` tag... but the point is, stop using IE6.
Comment: @Corey: Only if applying to an element other than `body` or `html`... But i suppose that could be the case here.


automatically get value in JTextfield1 into JTextfield2 without press enter in Java

Question: I'm trying to create a program in NETBEANS IDE where i can input a value into a JTextField1 & JTextField2, and the SUM will automatically appear into JTextField3 without having to press Enter.
When changing the value of JTextField1 or JTextField2 it will update realtime into JTextField3.
Comment: what have you done thus far?
Answer: Well, if you plan to respond to every key press, then get the underlying Document from the JTextField using getDocument(). Then add a DocumentListener to it. Your document listener will be notified when the document changes.
I suggest you look into these resources:
JTextField
How to write a DoucmentListener
Comment: Plus this resources: http://www.java2s.com/Tutorial/Java/0260__Swing-Event/ListeningtoJTextFieldEventswithaDocumentListener.htm
Comment: Though the `DocumentListener` also captures changes initiated by for example a mouse event (like Paste from a context menu).
Answer: If I interpreted your question correctly, it should be just as easy as:
<code>private JTextField jTextField1 = new JTextField();
jTextField1.addKeyListener(new KeyListener(){
    @Override
    public void keyPressed(KeyEvent arg0) {
            jTextField3.setText(jTextField1.getText());
    }
    @Override
        public void keyReleased(KeyEvent arg0) {
    }
    @Override
        public void keyTyped(KeyEvent arg0) {
    }
});
</code>
For each textfield that needs to be realtime ofc.
Answer: Probably add a KeyListener to JTextField1 and update the text of JTextField2 accordingly. (Although you might need a MouseMotionListener too to handle drags too.)


Objective-C: Xcode Prefix Header (.pch file) redundant #import

Question: Can't I leave out #import "foo.h" in .m file if it's already in the prefix header?
The product still builds successfully when I leave it out. But, I've noticed that the Xcode templates keep them in. Why?
Is the answer the same for #include?
Comment: possible duplicate of [Why do Xcode templates have #imports that duplicate Prefix.pch?](http://stackoverflow.com/questions/6462288/why-do-xcode-templates-have-imports-that-duplicate-prefix-pch)
Answer: I don't know why it does this, but it doesn't hurt because #import protects from double #include by checking if something is already #import-ed or #include-d, so no, the same scenario wouldn't work with #include.


Sendig email with an attachment in Laravel 7 using mail() and fpdf

Question: I am trying to send email with an attachment via mail function and FPDF library.
But when I send it, the email comes just with some strings and encoded characters.
Here is my code bellow:
Code to send email
        $message = "
Please see the attachment.
";

        // a random hash will be necessary to send mixed content
        $separator = md5(time());

        // carriage return type (we use a PHP end of line constant)
        $eol = PHP_EOL;

        // attachment name
        $filename = "test.pdf";

        // encode data (puts attachment in proper format)
        $pdfGenerate = new RelatorioManutencaoController();
        $pdfdoc = $pdfGenerate->imprimir(base64_encode($manutencao->id));
        // return $pdfdoc;
        $attachment = chunk_split(base64_encode($pdfdoc));

        $body = "--".$separator.$eol;
        $body .= "Content-Transfer-Encoding: 7bit".$eol.$eol;
        $body .= "This is a MIME encoded message.".$eol;

        // message
        $body .= "--".$separator.$eol;
        $body .= "Content-Type: text/html; charset=\"iso-8859-1\"".$eol;
        $body .= "Content-Transfer-Encoding: 8bit".$eol.$eol;
        $body .= $message.$eol;

        // attachment
        $body .= "--".$separator.$eol;
        $body .= "Content-Type: application/octet-stream;
        name=\"".$filename."\"".$eol;
        $body .= "Content-Transfer-Encoding: base64".$eol;
        $body .= "Content-Disposition: attachment".$eol.$eol;
        $body .= $attachment.$eol;
        $body .= "--".$separator."--";

        $sender = "firstname.lastname@example.com";
        $emissor = "firstname.lastname@example.com";
        $assunto = "Assunto do email";
        $header = 'MIME-version:1.0' . "\r\n";
        $header .= 'Content-type:text/html; charset=iso-8859-1' . "\r\n";
        $header .= 'From:' . $sender . '<' . $emissor . '>';
        mail($sender, $assunto, $arquivo, $header);
        mail("email@example.com", $assunto, $body, $header);

Someby please help me solving this problem.
Comment: You are probably not building the correct MIME structure. Is there no php library that can take care of these details for you? If you can't use a library, look at the source of an email with a correct attachment and compare that to the source of one of your emails. Try to find the differences in the MIME structures and adjust your code accordingly.
Answer: Try using the command: php artisan make:mail this generates a specific controller for sending mail, in the resources add the mail template and in the controller generated by the command in the build function include the following code :
public function build()
{
    // attach method with a file in your system
    return $this->view('emails.your mail template')
                ->attach('/path/to/file');
}

docs of attachments!
or for inline attach in the html template add this:

    Here is an image:

    embed($pathToImage) }}">

docs of inline-attachments!
to send it, just call this mail handler:
Mail::to($request->user())->send(new YourGenerateMailController());

For more information check the documentation
https://laravel.com/docs/7.x/mail
Comment: Thanks for your answer.
Actually I want to send a pdf file not an image.
And the site is already hosted, and I don't have access to SSH terminal to execute this comand.
Comment: You can generate it manually, or generate it in your local environment and upload it to the server, in the example I also mention an image but you can send any type of file, it should not be specifically an image, I leave you the controller code:

Path: app/Mail/NotifyMail.php

NotifyMail.php

https://laravel.com/docs/9.x/mail#via-public-properties

just copy the html code of that section, that's the structure of the controller


VBA subtracting address

Question: I was just wondering will it be possible to subtract something from an address? I mean like data.Address -1?
I have here a code that would return the address of a cell based on a keyword. what I wanted to do is after finding the keyword (and its address), I would like to subtract 1 from it so that the keyword I am trying to find wont be deleted.
Set ws = Sheets("Target")

lastRow = ws.Range("A" & Rows.Count).End(xlUp).row

wordSearch = "data"

Set aCell = ws.Range("A1:A" & lastRow).Find(What:=wordSearch, LookIn:=xlValues, _
LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlDown, _
MatchCase:=False, SearchFormat:=False)

Sheets("Target").Range("A1:" & aCell.Address).Select
Application.CutCopyMode = False
Selection.delete Shift:=xlUp

Answer: If you try to delete the content of all rows that sit above aCell, try replacing
Sheets("Target").Range("A1:" & aCell.Address).Select

with
Sheets("Target").Range("A1:" & aCell.offset(-1,0).Address).ClearContents

You do not have to select the range so your next two lines can be removed.
In case you are actually trying to delete the rows above aCell and also shift the remaining rows up (instead of just deleting), try
Sheets("Target").Range("A1:" & aCell.Offset(-1, 0).Address).Delete shift:=xlUp

instead of the .ClearContents method.
Comment: ClearContents won't shift them up, which is what Erin does in the original code.
Comment: @DougGlancy - Thank you for pointing out: I amended the original answer accordingly.

VBA subtracting address


Securing a junction box to an exterior brick wall

Question: I was replacing an external wall sconce, and noticed that this octagonal junction box doesn't seem to be affixed to the brick wall around it. There's no visible nails, screws, mortar, etc. around it.
It can wiggle a tiny bit, but interestingly, it's actually really stuck in there, and I have no idea how. I can see some metal protrusions around the box that press up against the brick but that ... doesn't seem legit.
I have 3 questions about this:

From a code perspective... is this legit? (Ontario, Canada, btw.) If not, what would be a proper way to secure it?
What would be an appropriate material to seal these large openings around the box? It seems too large for silicone alone. Perhaps a tube of "mortar repair" compound?
I can see past the box and into the wall cavity behind it, and I don't see any insulation. This is an external wall (obviously), shouldn't it be insulated? Could it be insulated without opening the wall and needing to redo the drywall inside (with some spray foam or something like that)?

BTW I temporarily undid that ground wire, I know it needs to be screwed to the box :)
Comment: Are there metal tabs on the back of the box, or attached by the strain-relief, holding it in place?
Comment: I imagine the *proper* way would be to drill the brick for some screw anchors and screw the sides of the box to the brick.  But I'd probably just use some poly sealant between the (cleaned) brick and box.
Answer: There are definitely some tabs in the back of the box that are securing it to the brick. The screw holes at 12,3,4,6,&10 o'clock appear to have some sort of rivet attachemnts to the tabs. If the box is secure, it's OK.
I'd get some mortar to seal in the box. It will secure the box even more. Where the openings are real small, use some silicone caulk. Adding insulation at this point would be a big job. There's a possibility just that one area lacks it because of the box and sealing around the box will help. Make sure the sconce fits tight up against the wall and caulk it after installation.
In the U.S., that NB cable would be a problem because it's not rated for outdoor use and since it does exit the exterior wall, it would need to be but that's getting real picky.
Comment: My understanding is that while technically NB can't go outside **at all**, many jurisdictions and/or inspectors allow it as long as the box is against or (as in this case) in the wall and the wire is not exposed outside the box.
Comment: @manassehkatz-Moving2Codidact   That's why the term "real picky" was used  but you're right.  :-)
Comment: @JACK Interesting, I'm curious to picture it, do you have any images/links showing what the back of this box looks like? I went ahead and sealed the bigger openings with some mortar, then I'll caulk both the smaller openings, and around the light fixture itself. Follow-up question: should I also caulk all the smaller holes in the box (like the unpopulated screw holes)?


why download a file dont work kept in model pop up?

Question: I am opening some Panel having a some code like this

                        <asp:UpdatePanel ID="updatePnl" runat="server">
                            <ContentTemplate>
                                <asp:LinkButton ID="lnkYurLevel" runat="server" ForeColor="#009999" Text="What are my next steps?"
                                    Font-Size="Medium" OnClick="lnkYurLevel_Click"></asp:LinkButton>
                            </ContentTemplate>
                        </asp:UpdatePanel>

 protected void lnkYurLevel_Click(object sender, EventArgs e)
    {
        if (lblFileName.Text != "")
        {
            string path = Server.MapPath(@"~\downloads\" + lblFileName.Text);
            System.IO.FileInfo file = new System.IO.FileInfo(path);
            if (file.Exists)
            {
                Response.Clear();
                Response.AddHeader("Content-Disposition", "attachment; filename=" + file.Name);
                Response.AddHeader("Content-Length", file.Length.ToString());
                Response.ContentType = "application/octet-stream";
                Response.WriteFile(file.FullName);
                Response.End();
            }
            else
            {
                Response.Write("This file does not exist.");
            }
        }

    }

and on button click i am opening a file that is to be download but that download don't appear, as it was working when not kept in panel that is to be open through model pop up.
Now when it is placed in a panel that is to be open through model pop up. it doesn't work.
What is the reason?
Comment: The file gets created but the save dialog never appears on the client.
Answer: The UpdatePanel that you use, expect very specific data (actually wait a struct with the result) from the post back, and this data are used on javascript to update his content. What you do is to totally break that data and you still expect to work. This can not work and you get a javascript error from the page, from the updatepanel. With other words the update panel gets some data from you that did not know what to do with them.
Comment: so how to make it correct, The file gets created but the save dialog never appears on the client.
Comment: @NoviceToDotNet yes, because of the UpdatePanel that you have warp it.
Comment: @NoviceToDotNet I like to say that way is also not good practice, is an easy solution, but not the correct solution for an asp.net page. Better solution is to use a handle to send the file and you just make the link to this handle with the correct url parametres.
Comment: @NoviceToDotNet And also this `Response.Write("This file does not exist.");` do you ever have see whats and where its going to write it ? make a test to see. Maybe at the end of the page, maybe at the top... but it will be un-readable, except if your page is a empty white.
Answer: An action inside the UpdatePanel won't change the whole Response, just a part of the page. So you cannot expect Response.Write to work. The alternative is to make the button force a full PostBack

Add a PostBackTrigger to the asp:Button like this
<Triggers>
    <asp:PostBackTrigger ControlID="lnkYurLevel" />
</Triggers>

or if you want to do that in code-behind, do this.
ScriptManager.GetCurrent(Page).RegisterPostBackControl(lnkYurLevel);

Comment: @NoviceToDotNet: the first line explains the reason in simple terms. does it not?
Comment: Yes, it does work, but my question is whay i had to define trigger while, when i did not define trigger the break point was getting hit.
Comment: @Aristos: Sorry. I thtought it was somebody just click happy :)


Select within select subquery takes too long

Question: I have 3 tables :

60.000 record Invoice
100.000 record Exchange Rate based on current date
25 record Currency Symbol

table_invoice:
+-----------+-------------+----------+--------------+
| invoice_id | currency_id | amount   | invoice_date |
+------------+-------------+----------+--------------+
|          1 |      2      |     10   | 4/28/2016    |
|          2 |      3      |     30   | 4/29/2016    |
|          3 |      4      |     50   | 4/30/2016    |
|          4 |      2      |     40   | 6/18/2016    |
|          5 |      6      |     25   | 6/20/2016    |
|          6 |      7      |     87   | 6/25/2016    |
|          7 |      4      |     100  | 6/29/2016    |
|          8 |      9      |     45   | 7/14/2016    |
|          9 |      2      |     71   | 9/27/2016    |
|      60000 |      3      |     430  | 1/18/2017    |
+------------+-------------+----------+--------------+

and
table_exchange_rate:
+-----------------+-------------+---------------+--------------------+
| exchange_rate_id | currency_id | exchange_rate | exchange_rate_date |
+------------------+-------------+---------------+--------------------+
|              1   |          2  | 13.352        | 4/25/2016          |
|              2   |          3  | 10.195        | 4/25/2016          |
|              3   |          4  | 14.390        | 4/25/2016          |
|              4   |          5  | 1.720         | 4/25/2016          |
|              5   |          6  | 118           | 4/25/2016          |
|              6   |          7  | 9.468         | 4/25/2016          |
|              7   |          2  | 13.125        | 6/15/2016          |
|              8   |          3  | 10.520        | 6/25/2016          |
|              9   |          4  | 14.800        | 6/25/2016          |
|              10  |          5  | 1.800         | 6/25/2016          |
|              11  |          6  | 120           | 6/25/2016          |
|              12  |          7  | 9.320         | 6/25/2016          |
|           100000 |          7  | 9.500         | 6/25/2016          |
+------------------+-------------+---------------+--------------------+

and
reference_currency:
+-----------------+---------------+-----------------------+
| currency_id      |currency_symbol| currency_name         |
+------------------+---------------+-----------------------+
|              1   |          USD  | US Dollar             |
|              2   |          AUD  | Australian Dollar     |
|              3   |          EUR  | Euro                  |
|              4   |          HKD  | Hong Kong Dollar      |
|              5   |          JPY  | Japan Yen             |
|              6   |          SGD  | Singapore Dollar      |
|              7   |          MYR  | Malaysian Ringgit     |
|              8   |          CHF  | Swiss Franc           |
|              9   |          THB  | Thailand Baht         |
|              10  |          GBP  | Great Britain Pounds  |
|              11  |          SEK  | Swedish Krona         |
|              12  |          CNY  | China Yuan            |
|              25  |          SAR  | Saudi Arabian Riyal   |
+------------------+-------------+-------------------------+

When I run:
SELECT
a.invoice_id AS 'INVOICE_ID',
a.currency_id AS 'CURRENCY_ID',
a.amount AS 'AMOUNT',
a.invoice_date AS 'INVOICE_DATE',
(
SELECT b.exchange_rate FROM table_exchange_rate b
WHERE b.exchange_rate_date <= a.invoice_date AND b.currency_id = a.currency_id
ORDER BY b.exchange_rate_date DESC LIMIT 1) AS 'EXCHANGE RATE'
)
FROM table_invoice a

Result:
`+------------+-------------+----------+--------------+--------------+
| INVOICE_ID | CURRENCY_ID | AMOUNT   | INVOICE_DATE | EXCHANGE_RATE |
+------------+-------------+----------+--------------+---------------+
|          1 |      2      |     10   | 4/28/2016    | 13.352
|          2 |      3      |     30   | 4/29/2016    | 10.195
|          3 |      4      |     50   | 4/30/2016    | 14.390
|          4 |      2      |     40   | 6/18/2016    | 13.125
|          5 |      6      |     25   | 6/20/2016    | 118
|          6 |      7      |     87   | 6/25/2016    | 9.320

`
and the result works fine but it is very slow(approximately > 60sec) with 60k record(table_invoice) looping on 100k record(table_exchange_rate) finding exchange rate at the current date,
If invoice_date can't match with exchange_rate_date or the user doesn't input the exchange rate on the app, it will using exchange rate the latest record already in input before the current date (b.exchange_rate_date <= a.invoice_date AND b.currency_id = a.currency_id)
Can I speed up this query or there any other options? Thank you..
Comment: using joins is usually faster than running subqueries
Comment: show us the EXPLAIN of your query **EXPLAIN SELECT
a.invoice_id AS 'INVOICE_ID',
a.amount AS 'AMOUNT',
(
SELECT b.exchange_rate FROM table_exchange_rate b
WHERE b.exchange_rate_date <= a.invoice_date AND b.currency_id = a.currency_id
ORDER BY b.exchange_rate_date DESC LIMIT 1) AS 'EXCHANGE RATE'
)
FROM table_invoice a;**
Comment: The EXPLAIN on its own isn't much help. We normally need to see SHOW CREATE TABLE statements for each of the relevant tables too. That said, correlated subqueries like this generally perform more poorly than their non-correlated counterparts.
Comment: And see http://meta.stackoverflow.com/questions/333952/why-should-i-provide-an-mcve-for-what-seems-to-me-to-be-a-very-simple-sql-query too!!
Comment: Show the table definitions,not sample data.
Answer: Try same thing with JOIN
select a.invoice 'invoice_id', a.currency_id 'curency_id', a.amount 'amount', a.invoice_date 'invoice_date', ter.exchange_rate ' exchange_rate'
from table_invoice ti
left join table_exchange_rate ter on ter.currency_id = ti.currency_id and ter.exchange_rate_date <= ti.invoice_date

Comment: Doesn't look like the same thing to me. And `LEFT JOIN... <=` is not a realistic construct.


Left shift doesn't work in KSP or other Unity games

Question: I've got an issue in several different unity games: the LeftShift key doesn't recognize, nor does RightShift. Every other key works fine, and LeftShift works in other games and outside of Kerbal.
I'm running Windows 8.1.
Any ideas?
Comment: Have you tried going through the settings and explicitly setting throttle up et al to the left shift key?  Also, I'm thinking this may be an issue related to using a localized keyboard layout instead of Win8 specifically.
Comment: I did. It's fixed, was actually Synergy hijacking the keyboard in a few of the games.
Comment: @TravisOlbrich Can you post that as an answer so that this issue can be marked as solved? Self-answering once you've discovered the answer is totally ok here!
Comment: It seems odd that it would hijack the shift key, but nothing else.  At least you found out what was wrong.
Answer: Synergy was hijacking the shift key. Quitting Synergy solved the issue.
Comment: Oh god I love you so much right now
Comment: Synergy also didn't show any indication that it was running, other than a process in the Task Manager, making this really hard to solve.


How to define a current user?

Question: Is it possible to define a current user?
I found a stored procedure 'sp_mgGetConnectedUsers'. It returns a result set with the only unique field 'Address'. How could I associate an executing query with such 'Address'.
Please advice.
Note: As far as I understand, another way to get the current user is to set a unique application Id for each connection, but I don't like this way much.
Comment: sp_GetSQLStatements returns the user name (along with the SQL statement) as part of its normal output.  Is that what you are looking for?  It seems you could correlate that to the UserName from sp_mgGetConnectedUsers().
Comment: I see that this is already what JD suggested.  I am blind.
Answer: If using a data dictionary you can use the user scalar function:
<code>select user() from system.iota;
</code>
and correlate that with the DictionaryUser field returned from sp_mgGetConnectedUsers.
If not using a dictionary the easiest way would be to use the sp_SetApplicationID and sp_GetApplicationID. Why don't you like that way? It might be easier to help you if we knew what your final goal was. If you just want to see the user associated with a query, execute the sp_GetSQLStatements procedure.
Comment: Yes, you are right Jeremy. My description wasn't quite descriptive, sorry.
Everything I need, is to know who called my SP. And depends on user the different behaviour should be. So, your solution with the scalar function USER() is exactly what I need.
Thank you.
Answer: There are multiple ways to think about the current user.  It depends on how you use Advantage.
The sp_mgGetConnectedUsers output gives the following:
UserName - Computer Name
Dictionary User - User used to login to the ADS Dictionary
Address - IP, IPX or IPC address
OSUserLoginName - Client OS login name
TS Address - IP address of the end-user of the client address
ApplicationID - Uniquely setable ID default=exe name
If you use a Dictionary and each person connects the Dictionary with a Unique Name then Dictionary User would be the way to go (you can also get this by "select user() from system.iota" (or ) for sql scripts etc).  Address and UserName will be the IP Address of the user and Computer Name of the user.  This should help you uniquely identify the user as well.  If your users are coming in via Terminal server you can use the TS Address to identify them in combination with the OSUserLoginName.
I won't go into detail on ApplicationID since you specifically stated that you didn't care for this solution.  But... While you can set this to anything you want the default is the name of the application (i.e. ARC.exe)
Part B of your question is how to associate a query.  The sp_getsqlstatements procedure will return the current active queries (or you could use Remote Server Info in ARC).  This returns the Connection Name which is the same as UserName from sp_mgGetConnectedUsers.  Using the combination you can tell the Computer Name, IP address (or Terminal Adderss), Dictionary UserName, Client OS LoginName, and the application name.

How to define a current user?


What does it mean that "A $G$-torsor is like the group $G$ that forgot its identity element"?

Question: A right $G$-torsor (or a principal homogeneous space) is defined to be a set $X$ together with a free and transitive right $G$-action $\lhd: X\times G \to X$. It is often said that "A $G$-torsor is like the group $G$ that forgot its identity element". What, roughly does this last statement mean? I've had a hard time understanding it because there is no multiplication operation on $X$.
Comment: Do you know how an affine space is like a vector space that forgot about the origin? It's the same thing...
Comment: @IvoTerek unfortunately I've never quite understood affine spaces either! But now (see my answer below) I think I understand $G$-torsors, so therefore, I feel like I understand affine spaces (which are just a special case of $G$-torsor) as well.
Comment: Skimming over it, I think you got the gist of it, yes. See also the first two pages of  https://www.asc.ohio-state.edu/terekcouto.1/texts/associated_connection.pdf
Answer: The group $G$ has a natural structure of $G$-torsor where the application $G\times G\to G$ is simply the multiplication map.
What makes this $G$-torsor special is that it has a distinguished point, namely the neutral element $e\in G$.
Now if you take any $G$-torsor $X$, there is an isomorphism of $G$-torsors $X\simeq G$, but it requires the choice of a distinguished element $x_0\in X$. Indeed, once you choose such an element, you get the isomorphism $G\to X$ defined by
$$g\mapsto g\cdot x_0.$$
So in fact you can say that the map $X\times G\to X$ is the same thing as the multiplication $G\times G\to G$, except that you forgot which element was the neutral element. And once you choose a point in $X$, the correspondence becomes explicit.
It is very analog to the fact that an affine space is a vector space which forgot its origin.
Comment: Is the isomorphism $G\to X$ a set isomorphism or a group isomorphism? If it's a group isomorphism then don't we need to define/inherit a group multiplication on $X$ as well?
Comment: It can't be a group isomorphism because $X$ is not a group. It is a $G$-torsor isomorphism, as stated in the answer.
Answer: This answer is heavily motivated by Torsors Made Easy by Joan Baez.
A right $G$-torsor is a set $X$ together with a free and transitive right $G$-action $\lhd: X\times G \to X$. Here free means for each $x\in X$ that $x\lhd g = x$ means $g=e$, the identity element in $G$. Transitive means that for each $x, y \in X$ that there is a $g\in G$ such that $x\lhd g = y$. Together these two properties mean that for each $x,y\in X$ there is a unique $g\in G$ denoted by $g_{xy}$ such that $x \lhd g_{xy} = y$.
A group has a multiplication operation $\cdot_G: G\times G \to G$. However, we can also define a division operation by
\begin{align}
/_G: G\times G \to G\\
g/_G h \mapsto g\cdot_G h^{-1}.
\end{align}
Because the $G$-action on $X$ in a $G$-torsor is transitive and free we can define a similar division operation $/_X: X\times X \to G$ on $X$:
$$
/:_X X\times X \to G\\
y/_X x \mapsto g_{xy}.
$$
We can see that $x \lhd y/_X x = x \lhd g_{xy} = y$. We can say that group elements measure the quotient or difference between elements in $X$. This is a sense in which a $G$-torsor is like the set $G$.
Now, suppose we select and designate a particular element in $X$ called $x_e \in X$. We can use this element together with the inherited division operation to define an inherited (but non-canonical because of the arbitrariness of $x_e$ in $X$) multiplication operation.
$$
\cdot_X: X\times X \to X\\
x\cdot_X y \mapsto x_e \lhd (x/_X x_e)\cdot_G (y/_X x_e)
$$
Or dropping subscripts and denoting $\cdot_X, \cdot_G, \lhd$ by juxtaposition:
$$
xy = x_e (x/x_e)(y/x_e).
$$
Then the map
$$
\phi:G\to X\\
g\mapsto x_e\lhd g
$$
is a group isomorphism between $G$ and $X$ with the non-canonical multiplication operation $\cdot_X$.

Discussion

A $G$-torsor is like the group $G$ that forgot its identity element

The first obvious similarity between $G$-torsor $X$ and $G$ is that, just like we can multiply an element of $G$ by an element of $G$ and get an element of $G$ we can multiply an element of $X$ by an element of $G$ and get an element of $X$. However, I find this a bit abstract to draw conclusions/intuition from.
The main useful similarity I see between a $G$-torsor $X$ and the group $G$ is that just like we can divide two elements of $G$ and get an element of $G$, we also divide two elements of $X$ and get an element of $G$. This is the sense in which $G$-torsor $X$ is like $G$. Couched in the language of addition/subtraction instead of multiplication/division, we draw the main conclusions from the Baez article. Essentially a $G$-torsor is a space where the absolute value of values in that space is insignificant (like the space of positions), but where we can take differences between elements of that space and get meaningful values in the group $G$ (like $\mathbb{R}^3$). This will be of relevance to gauge theories.
However, the $G$-torsor $X$ is different than $G$ in that there is no multiplication operation between elements of $X$ that returns another element of $X$.Yet again, however, by making a single arbitrary choice of a distinguished element $x_e\in X$ then we can define an inherited group multiplication on $X$ such that $X \simeq G$ under isomorphism $\phi$ and such that $\phi(e) = x_e$.
I'll add my own commentary that instead of saying "A $G$-torsor is like a group $G$ that forgot its identity element" I would prefer to say "A $G$-torsor is a space where you can divide/subtract elements and get elements from the group $G$." If I want to say more I could say "By arbitrarily distinguishing an element of the $G$-torsor then it is straightforward to establish a (non-canonical) isomorphism between the $G$-torsor and $G$ itself".


Why is this command not invoked?

Question: Here is what I consider the relevant part of the ListView in question:
<ListView ItemsSource="{Binding People}" >
    <ListView.View>
        <GridView>
            <GridViewColumn>
                <GridViewColumn.HeaderTemplate>
                    <DataTemplate>
                        <CheckBox IsChecked="{Binding AllSelected}" Command="{Binding ToggleSelectAll}"  CommandParameter="{Binding}" />
                    </DataTemplate>
                </GridViewColumn.HeaderTemplate>
                </GridViewColumn.HeaderTemplate>
                    <GridViewColumn.CellTemplate>
                        <DataTemplate>
                            <CheckBox IsChecked="{Binding IsSelected}" />
                        </DataTemplate>
                    </GridViewColumn.CellTemplate>
                </GridViewColumn>

The first column is thus a checkbox bound to the IsSelected property of the row item, a PickListPerson.
The command is declared in the PersonPickListViewModel as follows:
public DelegateCommand<PersonPickListViewModel> ToggleSelectAll { get; set; } = new DelegateCommand<PersonPickListViewModel>(vm =>
    {
        vm.AllSelected = !vm.AllSelected;
        vm.People.ToList().ForEach(p => p.IsSelected = vm.AllSelected);
    },
    vm => true
);

I pass the viewmodel as the command parameter so as to have access to instance properties of the viewmodel in the static context of the command's action delegate.
Yet when I click the header column checkbox, this command is not invoked. Why could that be?
Comment: Missing OnPropertyChanged inside IsSelected and AllSelected? Maybe too obvious to check.
Comment: I have that on `AllSelected', but `IsSelected` belongs to each member of an `ObservableCollection`, and I expect that collection to handle change notifications for what it is bound to.
Comment: ObservableCollection raises events automatically but only for adding/removing elements. Still for changing properties inside objects in collection you need OnPropertyChanged notification.
Answer: The DataContext at the point you bind the CommandParamter is the item from the People collection. I'm guessing this isn't the PersonPickListViewModel you're expecting. As whatever this type is can't be cast to PersonPickListViewModel the command doesn't get invoked.
Edit after first comment: If your PersonPickListViewModel is at the root of the window, you can use "DataContext Anchoring" to get to it. Simply add a name to your Window (i.e. x:Name="view") and then update your binding to use an ElementName source as follows:
{Binding ElementName=view, Path=DataContext}
Comment: Yes, you are correct. The `PersonPickListViewModel` is the data context for the whole view. How could I specify that as the data context for the header template? I have it specified in the view using ``.
Comment: I have expanded the answer to show how this can be achieved.
Comment: Thank you very much. Gaarg, A whole project without using names, and now I need one. I suppose just one is fine.

Why is this command not invoked?


Select an object at random

Question: How can I randomize the display of the cards that are in my images folder, rather than always displaying a certain card (e.g. 1.png)?
Here is my code. I know how to randomize for numbers, but not in this situation using a set folder.
package java_gui;

import java.awt.GridLayout;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;

public class Images extends JFrame {
    //create JLabels
    JLabel card1 = new JLabel();
    JLabel card2 = new JLabel();
    JLabel card3 = new JLabel();

    public Images(){
        //create GridLayout
        setLayout(new GridLayout(1,4,5,5));
        //set images
        card1.setIcon(new ImageIcon("image/card/card/1.png"));
        card2.setIcon(new ImageIcon("image/card/card/2.png"));
        card3.setIcon(new ImageIcon("image/card/card/3.png"));
        //add JLabels
        add(card1);
        add(card2);
        add(card3);
    }
}

Answer: There is already a good algorithm for shuffling the elements of an array.  Look at the Fisher-Yates shuffle.
Comment: Not only is there already an algorithm, it's baked right into `Collections.shuffle` (http://docs.oracle.com/javase/6/docs/api/java/util/Collections.html#shuffle(java.util.List)).
Answer: In order to randomize the images without repeating them you should first create an array with all the numbers of the images you need. The array would contain:
cardsArrayNumber = {1, 2, 3}

Then then shuffle it:
cardsArrayNumber = {3, 1, 2}

And then go through this array assigning the images:
 card1.setIcon(new ImageIcon("image/card/card/" + String.valueOf(array[0]) + ".png"));
 card2.setIcon(new ImageIcon("image/card/card/" + String.valueOf(array[1]) + ".png"));
 card3.setIcon(new ImageIcon("image/card/card/" + String.valueOf(array[2]) + ".png"));

Tip: It'll be better if your cards are part of an array and you start numbering images from 0, so that you could handle any number of images easily:
for (int i = 0; i < cardsArray.length; i++) {
    cardsArray[i].setIcon(new ImageIcon("image/card/card/" + String.valueOf(array[i]) + ".png"));
}

This is how to shuffle an array and the JavaDoc.

Select an object at random


Is it possible to move a hard drive with Steam games to a new computer?

Question: I've seen a lot of questions asking somewhat the reverse of this question, namely copying games from one PC to another to avoid downloading.  My question is can I just remove my entire hard drive from my current PC and move it into the new PC and get Steam to recognize that all the games are already downloaded?  I'm basically wondering if the way Steam knows which games are installed is tied to the account info in the cloud, or PC-specific information (like registry entries) or some combination.
The specific example: I have a PC with a C: drive and a Z: drive. 90% of my games are on the Z: drive. My new PC has just a C: drive, and I want to put the Z: drive into the computer and just get Steam to see everything there.
Comment: It should work the same as moving a folder from one pc to another, which is technically what you'll be doing but instead of doing it virtually, by copying the folder, you're doing it physically with the HDD itself.
Answer: Yes.  I did it before: simply moved my "Steam disk" from machine A to machine B, then installed Steam on machine B, pointing it to the Steam disk location and voilà.
As an extra precaution, you can also delete the ClientRegistry.blob file to force Steam to scan the steamapps folder and find out what is installed, making sure all the games get found.
Some minor updates (to install the missing files that are not in the Steam library itself) and file integrity checks may occur when you run Steam for the first time.
Comment: Mainly updating to install the missing files that are not in the steam library itself.
Comment: I would recommend deleting the ClientRegistry.blob file before you launch Steam on the new PC.  This will force Steam to scan the steamapps folder to find out what is installed.  It may not be needed, but it will make sure all the games get found.
Comment: Save games might not transfer for some games that don't use cloud storage and store in the user area, unless they are also copied.
Comment: Thanks to both of you. I will attempt this in a few days (unleashing the new build is a Christmas day event :) and will report back.
Comment: You can also tell Steam what folder your Library is.  This will also add any game the registry had added previous to the move.
Answer: If you have all your games in a new library on different HDD than it will work. After you install steam just add a new library and select the one on your another HDD. Steam will check the files and update them if necessary. However I didn't have any luck transferring games stored in my steam folder in program files. Moving or deleting ClientRegistry.blob didn't help then. So next time I would transfer all games from default location to a new library before reinstall so I can just copy the library over later.
Comment: This describes most accurately what I did. I added a new library, using the location on the transferred drive, which was a secondary location, as opposed to the default C: drive location, and it worked immediately.
Answer: the way i found to do it with 100% success is to copy the steam folder to an external disk, then transfer to an already active disk on the new desktop. from there you will open the steam folder and inside you will find an application called "steam.exe" right click and hold, then drag to the desktop and select create shortcut. then just launch from there. the install for new games will default to wherever you copied the folder to, as well as completely eliminating having to reinstall steam, and risk having it wipe your data.


Propel or Doctrine for ZF integration

Question: I have never used any ORM, but the Zend_Db_Table (if you can call it one). I'd like give it a try with some famous ROM and I've only heard of these 2 (Propel and Doctrine).
I tried sometimes in the past but I found it too hard to integrate or maybe I didn't understand how it works.
Now that I'm trying again, I'd like to know which one has easier integration with Zend Framework and which one is easier to work and why
Answer: Doctrine and Propel are definitely the two best know PHP ORM's among some others.
Doctrine has definitely seen some more love from ZF and there is rumors that Doctrine 2 will play a major role in ZF2, though afaik nothing as been confirmed as of this writing.
Here is some links for you to follow:

Integrating Propel with the Zend Framework (2006)
Brandon Savage: The Adventures Of Merging Propel With Zend Framework

and

Ruben Vermeersch: Integrating Zend Framework and Doctrine 1.x
Matthew Weier O'Phinney: Autoloading Doctrine and Doctrine entities from Zend Framework
Doctrine 2 and Zend Framework first date

Also see these two questions that have additional information and links:

Zend Framework 1.9 and Doctrine Integration
Integrate Doctrine with Zend Framework 1.8 app

Should not be hard to find many more for Doctrine.
EDIT very nice one from Phil's comment:

Zend Framework / Doctrine integration suite
Comment: Don't know if it's mentioned in any of the linked posts / articles, but you should also check out this Zend Framework / Doctrine integration suite - https://github.com/beberlei/zf-doctrine
Comment: @Phil very good one. Benjamin Eberlei is actually one of the most active when it comes to integrating Doctrine and ZF and he's contributing to both projects afaik.

Propel or Doctrine for ZF integration


Liquid: Print All Possible Outputs of an `If` or `Case` tag

Question: I'm wondering if there's any way to display all the possible outputs of either an If tag or a case tag, in Liquid. I'd like to be able to display the outputs for editing / debugging purposes.
For example, given:
{% assign foo = allCases %}

{% case foo %}
 {% when 1 %}
  This is the case when foo is 1.
 {% when 2 %}
  This is the case when foo is 2.
{% endcase %}

Where allCases is a value so that the output would be:

This is the case when foo is 1.
This is the case when foo is 2.

N.B. while I used a special value for foo to illustrate the desired output, maybe it could be achieved with a filter, instead? e.g. [% case foo | showAll %]?

Attempted Solution:
I thought that the multi-case support might allow for this, so tried:
{% assign foo = 0 %}

{% case foo %}
 {% when 1, 0 %}
  This is the case when foo is 1 or 0.
 {% when 2, 0 %}
  This is the case when foo is 2 or 0.
{% endcase %}

However, this only returns

This is the case when foo is 1 or 0.

i.e. it goes through the cases until it reaches the first matching case and then stops evaluating other cases. If tags have the same behaviour.
I know this could be achieved using separate if-statements, but was hoping to find a solution that didn't multiply the number of tags, in this way, as it is just for editing / debugging purposes, but is not needed for the final code.
Answer: If this is for debugging purpose you might try this:
{% for i in (0..3) %}
    {% case forloop.index %}
    {% when 1 or 0 %}
        This is the case when index is 1 or 0.
    {% when 2 %}
        This is the case when index is 2.
    {% else %}
        Others
    {% endcase %}
{% endfor %}

The loop allows to you to artificially fulfill all cases.


Allow inserting new data lines but not changing formulas

Question: is there any way how can I allow inserting new data lines for the user (with whom I share sheet) but not changing formulas?
My case: I created formulas for example for dropdown list in lines, other formulas for cells, etc. Now I want to allow the user to insert data to these lines, but I want to prevent him to change these formulas (ideally he should not be able to see or copy these formulas or entire sheet).
I know I can protect sheets/cells but this entirely disables edit for the user.
Is there any way please to accomplish what I need?
Answer: You can protect only selected parts of the sheet.

Go to Data -> Protected sheets and ranges...
Click on Add a sheet or range in the sidebar.
Enter name of the range.
Select Sheet as the option.
Check Except certain cells.
Add all the ranges you want the user to be allowed to edit.

Hope this helps!
Answer: you can have two sheets - one for him/her and one for you. in your sheet you will have all your formulas. then you just connect these two sheets with IMPORTRANGE formulas (for example columns A, B, C from his/her sheet into your A, B, C ...and then your D column with formulas imported into his/her sheet' D column)
another way would be to use ARRAYFORMULA variants for all your formulas which would be sitting in a safe zone on the first row.
Comment: this could work. Thank you! I will try it and then I mark this as an answer. :)


Returning an average of integers only at the list where a string is searched inside a list of lists

Question: I'm a beginner with Python.
Say I have a list of lists in python
    list1 = [['id1','Jane','Doe',100,75,100],['id2','John','Snow',90,87,92],['id3','Peter','Pan',79,81,83]]

How can I search the list of lists for say 'id2' and print a list with only the integers in its list?
This is what I tried
    import numbers
    def list_search(lister,index):
        for i in lister:
            for j in i:
                if j == index:
                    [x for x in i if isinstance(x, numbers.Number)]
        print("Not found: ",index)

Here is the Test for my function
    list_search(list1,'id2')

I was expecting
[90,87,92]
but I got
Not found: id2
Comment: You never print nor store nor return the list you make when `j == index`, and you always print "Not found" at the end of the function
Comment: This line doesn't do anything `[x for x in i if isinstance(x, numbers.Number)]`. You should either print it, or return it.
Answer: This solution stops looping when index is found.
Returns None if index has not been found.
Uses a list-comprehension  to easily create a list.
No need to import Number just test if it's an integer.
A small optimization consists to look for integers starting from the 2nd row (item[:1]) as we know that the first row is the index.
You could even replace 1 by 3 here if you assume that rows 2 and 3 (Jane, Doe) are always string.
def list_search(lister, index):
    for item in lister:
        if item[0] == index:
            return [x for x in item[1:] if isinstance(x, int)]
    return None

That's for the first part that provides you with the integers.
Compute the average given the list is the easiest part.
numbers = list_search(list1, "id2")
print(sum(numbers)/len(numbers))

Answer: This line doesn't do anything:
[x for x in i if isinstance(x, numbers.Number)]

You should either print it, or return it. Plus your function will always shows the message Not found so your code should be like this:
import numbers

list1 = [['id1','Jane','Doe',100,75,100],['id2','John','Snow',90,87,92],['id3','Peter','Pan',79,81,83]]
def list_search(lister,index):
    for i in lister:
        for j in i:
            if j == index:
                return [x for x in i if isinstance(x, numbers.Number)]
    print("Not found: ",index)

my_list = list_search(list1,'id2')

print(my_list)
# print average
print( sum(my_list) / len(my_list))

Output:
[90, 87, 92]
89.66666666666667

Answer: One method using Try except
list1 = [['id1','Jane','Doe',100,75,100],['id2','John','Snow',90,87,92],['id3','Peter','Pan',79,81,83]]
def list_search(list_of_list,index):
    result=[]
    for lis in list_of_list:
        if lis[0]==index:
            for check in lis:
                try:
                    result.append(int(check))
                except ValueError:
                    continue
    return sum(result)/len(result) if result else 0
print(list_search(list1,"id2"))

Output:-
207.6666666

Answer: This is the function that you can write. First look all the first elements and if the first element is equal to what you want then check for integers and append them to the result list. Finally return the result list.
 def func(a, activatedString):
    result = []
    for i in a:
        if i[0] == activatedString:
            for j in i:
                if isinstance(i, int):
                    result.append(j)

    return result

But if you want more short way you can do this:
def func(list1, activatedString):
    return [i for i in [a  for a in list1 if a[0] == activatedString][0]  if isinstance(i, int)]

print(func(list1, "id2"))

Answer: Lets start with getting only integers list:
list1 = [['id1','Jane','Doe',100,75,100],['id2','John','Snow',90,87,92],['id3','Peter','Pan',79,81,83]]

temp_integers = [list(filter(lambda x: isinstance(x, int), list1[i])) for i in range(len(list1))]

Output:
>>> temp_integers
... [[100, 75, 100], [90, 87, 92], [79, 81, 83]]

Then we add a list of their respective means:
temp_means=[np.mean(x) for x in temp_integers]

Output:
>>> temp_means
... [91.66666666666667, 89.66666666666667, 81.0]

Then print corresponding integers to id2 and their mean :
for i in range(len(list1)):
    if 'id2' in list1[i]:
        print(temp_integers[i])
        print(temp_means[i])

Put it all in one function
def list_search(lister,index):
    temp_integers = [list(filter(lambda x: isinstance(x, int), lister[i])) for i in range(len(lister))]
    temp_means=[np.mean(x) for x in temp_integers]

    if all(index not in y for y in lister):
        print("Not found: ",index)
    else:
        for i in range(len(lister)):
            if index in lister[i]:
                print(temp_integers[i])
                print(temp_means[i])

Output
>>> list_search(list1,'id2')
... [90, 87, 92]
... 89.66666666666667

Answer: You can use list comprehension for this:
list1 = [['id1','Jane','Doe',100,75,100],['id2','John','Snow',90,87,92],['id3','Peter','Pan',79,81,83]]

def list_search(lister, index):
    return [j for i in lister for j in i if isinstance(j, int) and i[0] == index]

results = list_search(list1,'id2')
print(results)

average = sum(results)/len(results)
print(average)

# Output:
# [90, 87, 92]
# 89.66666666666667


Ai to Png Using PHP

Question: Is it possible to convert AI to PNG using PHP?
Comment: You can run Image Ready in PHP.
Comment: It depends on the version of Adobe Illustrator format that the AI file is in, but some of them can be saved in PDF compatible formats, so that might help.
Answer: ImageMagick supports conversing from AI to JPG
Comment: Not according to the list http://www.imagemagick.org/script/formats.php ; however it may support AI files saved in PDF compatible formats from versions 10 and up. But then only with Ghostscript.
Comment: Hm, I thought I read that it did, it treated them as vector files. Maybe people were talking about PDF compatible Ai files from Illustrator CS as you said...
Answer: I'm almost sure that GhostView can convert from AI to PNG with the command line interface of ghostview.
The AI-format is just a more organized and stricter version of PostScript, e.g. loop-constructs and other high-level control-flow constructs of the PostScript language are not used.
Answer: Never heard that this can be done.
Most known image processing libraries are ImageMagick and GD, but I really doubt any can raster a proprietary format as AI.

Ai to Png Using PHP


Can I plumb this restaurant sink this way?

Question: Came across a 3 basin restaurant style sink that I am going to use in my basement (homebrewing!).
I'm using CPVC to connect to this faucet but there was originally a short threaded black pipe nipple with washers that went into the faucet from the back side and then a female CPVC connection to the water supply. The black nipples were solid gunk & rust inside so I removed them.
Instead of going back with another black pipe connection, can I not just use  CPVC male adapters straight into the back of the faucet?..is CPVC strong enough to make this connection and hold the faucet to the sink? It seems to hold (see pictures) but I didn't tighten it down very far, only did this as a test.  It seems like there should be a locknut on the back side to hold the
faucet in place and then the threaded plumbing fitting, but no one at the home center could help me find anything like this...should there be one?
Comment: You can get brass nipples at Home Depot. I would not trust plastic to make a mechanical connection to hold the faucet to the sink. You are setting up the conditions for a flood.  But you are planning for the same threads to do double duty--seal the connection and clamp the faucet body to the sink. You need a separate nut to clamp. Some other system is required.
Answer: I have seen this done with bad results due to the weight and abuse a large fixture goes thru with accidentally knocking pots and pans into it. My suggestion would be to use galvanized pipes not black pipes those are for gas lines but I have seen it many times.  The size of galvanized pipe usually in such small size is fully threaded so get one a little longer than needed and add a large pan washer to distribute weight and add a galvanized thin walled nut to add support then add 2 brass angled pex quick connects at 3/4 inch and pex it to your existing pipes with appropriate push in addapters.  This will give strength to the faucets structure and add a way to quick disconnet the bench from the wall if need to be moved or cleaned behind. Just a few ways  I did mine and with casters i can load it onto the lowboy trailer and travel with the shop.☺ Have fun!
Comment: Yes sir but you could also use a conduit nut from the electrical section or 2
Comment: Here is a link https://www.amazon.com/Pipe-Fittings-Locknut/s?ie=UTF8&page=1&rh=n%3A383612011%2Cp_n_feature_four_browse-bin%3A3052055011
Comment: By "thin walled nut" do you mean a "jam nut"?  I can't find anything called a thin walled nut... and will nuts & bolts aisle nuts match the threads on a galvanized pipe nipple?
Comment: Upgrade and use brass nipples. I didn't think anyone used galvanized water pipes anymore.


How to disable dirty checking in Hibernate

Question: Here is a simple code.
I get some Entity from DataBase through JPA repository, do some logic and do not want Hibernate to save it for me:
      @GetMapping("/{id}")
      @Transactional
      public ERespondent getRespondent(@PathVariable Long id) {
          var entity= respondentRepository.findById(id).get();
          entity.setFirstName("weqweqwdq");
          // other logic here..
          return entity;
      }

Set FlushMode in the config file to MANUAL and still see that hibernate does update at the end.
Do I need to do it in one transaction to initiate lazy load collection?
I want to manage my entity by myself and don't want that hibernate to do overhead work like save a copy of the entity in the cache -> check it out for changes -> save it to DB.
Answer: I know 3 options

mark transaction as read-only:

@Transactional(readOnly = true)

detach the entity first:

@Autowired
private EntityManager em;

@Transactional
public ERespondent getRespondent(@PathVariable Long id) {
    var entity= respondentRepository.findById(id).get();
    em.detach(entity); //now it is disconnected from persistence and becomes +- POJO
    entity.setFirstName("weqweqwdq");
    // some other logic
    return entity;
}

Copy the whole object modify and return the copy:

@Transactional
public ERespondent getRespondent(@PathVariable Long id) {
    var entity= respondentRepository.findById(id).get();
    copy=new EResponsend(entity); // you have to implement copy constructor
    copy.setFirstName("weqweqwdq");
    return copy;
}

Comment: to detach entity i need to use EntityManager - it means i need to generate billions boilerplate code .I need to do it for whole application ,not for one method only
Comment: copy entity is not good idea - i want to disable it -because hibernate do it by itself
Comment: @Transactioanl(readOnly=true) its not good idea too,because you cant save enity by yourself then.But all i need it save entity by myself if i want and do not want to do same by Hibernate - I need to disable dirty checking,nothing more....
Comment: Do you want to disable it compleatly applicationwise and never turn it back on again? I was thinking of incidental detachement. After all, JPA is there to actually manage entities, not only to hydrate POJOs with SQL results
Comment: As for detaching via entity manager - you can write aspect to detach objects where needed (its not clear what are your criterias of when to do it and when to dont)
Comment: Yes i want to disable dirty cheking for  applicationwise and never turn it back on again.If you know how to do it please help me with that
Comment: How about writing aspect that will detach entity after repository method invocations?
Comment: sounds good how to do it?but better do turn of dirty cheking
Comment: I dont know if that is even possible.
Comment: Do @Transactioal( readOnly=true) disable dirty checking,that means not only save enitity is not available,its about stop cheking cnanges of entity,stop copy them to persistens context ,etc? am i right?
Comment: Yes, no transaction will be commited.
Comment: but if i do @Transactioal( readOnly=true) ,entity still managed and its not ok -the copy of it still in persistence context.I cheked it out with em.contains( entity) and got true-that not rly good  because it still spending memory and other resourses.
Comment: Sure, the thing is you didnt specify rationale behind this. I have concluded from the snippet that you want to simply modify peristent entity without saving the changes.
Comment: its not about modify - i need to get lazy loaded collections - its only able in transaction,but also in this transaction hibernate do copy of all entities and i guess it checked they states at the end- and its not good for perfomance.Thats why i want to disable dirty cheking - its realy worst thing i saw in IT and no way to turn it off
Answer: You can write an interceptor that clears the entity manager. Then you just annotate a top level class with the interceptor annotation or however this works with Spring (maybe see this article https://www.baeldung.com/cdi-interceptor-vs-spring-aspectj) and should be good to go. Depending on how well you separate your code, you might have to put it on individual methods rather than on class level though or consider splitting code between "read-only" and "write" code paths. I usually do this by moving this "read-only" code into so called DataAccess classes and the "write" code into Service classes.


RESTful web service using Spring Data REST is not working but RESTful web service using Spring MVC is working

Question: PostRepository.java
package com.example.demo.repository;

import com.example.demo.domain.Post;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.query.Param;
import org.springframework.data.rest.core.annotation.RepositoryRestResource;

import java.util.List;

@RepositoryRestResource(collectionResourceRel = "posts", path = "posts")
public interface PostRepository extends CrudRepository<Post, Long> {
        Post findOneByTitle(@Param("title") String title);
        List<Post> findByBodyContaining(@Param("keyword") String keyword);
        }

PostRestController.java
package com.example.demo.web;

import com.example.demo.domain.Post;
import com.example.demo.repository.PostRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
@RestController
public class PostRestController {
    @Autowired
    private final PostRepository postRepository;
    public PostRestController(PostRepository postRepository) {
            this.postRepository = postRepository;
    }
    @RequestMapping(value = "/post/findByTitle")
    public Post findOneByTitle(@RequestParam("title") String title) {
            return postRepository.findOneByTitle(title);
    }
    @RequestMapping(value = "/post/search")
    public List<Post> findByBodyContaining(@RequestParam("keyword") String keyword) {
            return postRepository.findByBodyContaining(keyword);
    }
    @RequestMapping(value = "/post/count")
    public long count() {
            return postRepository.count();
    }
}

All of the below are working
 http://localhost:8080/
 http://localhost:8080/h2-console
 http://localhost:8080/post/search?keyword=Geeky
 http://localhost:8080/post/findByTitle?title=Youtube

But http://localhost:8080/posts is not working (404 error)
I just wanted to learn spring and I know should follow recent guides, but started this one and I've been sitting with this for 3 days, first was javax to jakarta name change that caused huge problem and then this one where @RepositoryRestResource(collectionResourceRel = "posts", path = "posts") seems to be not working, have been looking into solutions for the past 3 hours but nothing seems to work
Answer: To resolve this, you could consider either removing the @RepositoryRestResource annotation from the PostRepository or changing the path in the @RequestMapping annotation for the findByTitle method in PostRestController. Make sure there's no conflicting mapping that could be causing the issue.
Comment: Thanks for the response! So I tried removing the RepositoryRestResource annotation but didn't work. Then changed all paths of RequestMapping annotation but then too http://localhost:8080/posts is not working (404 error)


Brand new AC unit makes whooshing sound and air "chokes"

Question: My brand new AC recently started making a whooshing noise. It sounds kind of like a sudden gust of wind, but it repeats every few seconds. Another way I can think of to describe it: imagine a PC cooler running relatively silent, but still being able to hear it. Now imagine it increasing its RPM noticeably for just around a second. Now imagine it doing this continuously.
It's a ComfortStar split type 12k BTU.
It also doesn't result in air being blown faster but, when you can hear it, if you stand in front of the indoor unit, the air stops coming out for like half a second. Like the unit "chokes".
Things I've noticed and done:

If I lift the front panel by 2-3 cm or more the phenomenon stops! I thought something might be pushing on the filters, or that it's not closing properly, but I can't see any issues...
Efficiency doesn't seem to be affected, it still cools very well, but the sound is annoying.
It only seems to happen on the low or auto fan setting. For example at medium, high or turbo setting seems to result in a steady stream of air uninterrupted by whooshings.
It doesn't always happen. Sometimes I run it for hours with no annoying sound, other times it starts a few minutes after turning on the AC. Sometimes it stops for a while.
I tried recording the sound but my phone doesn't really allow you to notice it when it occurs.
I'm using the AC Unit with the front panel/lid just a bit open, is it wrong or bad for the unit to use it like that? (see picture with a red circle)
Comment: Is this a window unit, or a split system?
Comment: What is meant by your statement that it"chokes when making the sound". What is the sound it is making.
Comment: What type , brand / model? What is a wooshing sound? The only thing I can think of would be a loose squirrel cage blower. But more info would be needed.
Comment: is it level, or sloped slightly down in back (outside)? You want the condensation to run away from the window...
Comment: @ThreePhaseEel Split System
Comment: @d.george I mean, when the whooshing sound appears (every 10-20 seconds sometimes more it's random) the AC kind of chokes and does not blow air out for that second.
Comment: @dandavis it is a split unit
Comment: @EdBeal added a lot more info to the post. please read it and let me know
Answer: I would verify the screw that connects the blower to the blower motor is tight, I have seen where a loose fan (squirrel cage) slipping has caused this exact issue. I don't have time to look it up right now but there is usually a maintenance over ride some times the plastic cutout that looks like a horizontal I on the right lower side. This may allow you to view the problem and I am not sure but may allow for the filter to be removed and will still turn the blower on.
Comment: thanks will try and let you know
Comment: Did you solve it? I have the same problem. I take the lid off and works ok.


Unicity of the limit for weak convergence in different spaces

Question: Let $f_n\in L^4(\mathbb{R})\cap L^3(\mathbb{R})$. Suppose that
$$ f_n\rightarrow f \mbox{  weak in } L^3$$
$$ f_n\rightarrow \tilde{f} \mbox{  weak in } L^4$$
Can i conclude that $f=\tilde{f}$ almost everywhere on $\mathbb{R}$?
This is not clear, because weak convergence doesn't imply convergence a.e along a subsequence. I'm interested also in the case where both convergence are weak*, and in the case where one convergence is weak and the other is weak*.
Thank you for any suggestions.
Answer: Hint: It follows that $$\int\phi f=\int\phi\tilde f$$for  every $\phi\in L^{4/3}\cap L^{3/2}$.
Comment: Thank you, now it's clear. And what about weak* convergence? the same trick doesn't work right?
Comment: @Capublanca I don't see why weak* convergence is any different.
Comment: OK, for sure it's the same in the case $L^4$ and $L^3$. But what if we have $L^1$ (or $L^{\infty})$?
Comment: @Capublanca There's no such thing as weak* convergence in $L^1$, since $L^1$ is not a dual space. What if we have weak convergence in $L^1$ and weak* convergence in $L^\infty$? That's no different - we still have $\int \phi f=\int\phi \tilde f$ for every $\phi\in L^1\cap L^\infty$...
Comment: @Capublanca One might be concerned about the case where we have weak convergence in $L^\infty$, since we don't have a good handle on the dual of $L^\infty$. But that doesn't matter either; it's still true that $L^1\subset (L^\infty)^*$.
Comment: I'm convinced, thank you very much!


How can I deploy multiple wars using the tomcat plugin in maven?

Question: I have two wars which I deploy in two maven projects using tomcat plugin.
I want to do this in one step and be able to deploy more than one war in a single maven project.
How can I do this? any suggestions?
Answer: I'm not in a position to test this, but there are two approaches I can think of. Either may work for you.
Option 1:
In one of the projects you can define the configuration for the tomcat plugin. In the snippet below there are two executions defined, both bound to the pre-integration-test phase (this might not be the best phase to do this, but it seems a good starting point as the war will have been packaged). Each execution will deploy the war defined in its configuration's warFile property.
<project>
  ...
  <build>
    ...
    <plugins>
      ...
      <plugin>
        <groupId>org.codehaus.mojo</groupId>
        <artifactId>tomcat-maven-plugin</artifactId>
        <version>1.0-beta-1</version>
        <executions>
          <execution>
            <id>deploy1</id>
            <phase>pre-integration-test</phase>
            <configuration>
              <warFile>path/to/my/warFile1.war</warFile>
            </configuration>
            <goals>
              <goal>deploy</goal>
            </goals>
          </execution>
          <execution>
            <id>deploy2</id>
            <phase>pre-integration-test</phase>
            <configuration>
              <warFile>path/to/my/warFile2.war</warFile>
            </configuration>
            <goals>
              <goal>deploy</goal>
            </goals>
          </execution>
        </executions>
      </plugin>
      ...
    </plugins>
    ...
  </build>
  ...
</project>

Option 2:
This is probably the better approach. Define one execution in each war (you can omit the warFile element as the default can be used). You can then define a third project with a modules declaration referencing each war project. When the parent is built both wars will be be built and the wars deployed.
The modules declaration for the third project:
<modules>
  <module>relative/path/to/war1</module>
  <module>relative/path/to/war2</module>
<modules>

And the config for each war project:
<project>
  ...
  <build>
    ...
    <plugins>
      ...
      <plugin>
        <groupId>org.codehaus.mojo</groupId>
        <artifactId>tomcat-maven-plugin</artifactId>
        <version>1.0-beta-1</version>
        <executions>
          <execution>
            <id>deploy</id>
            <phase>pre-integration-test</phase>
            <goals>
              <goal>deploy</goal>
            </goals>
          </execution>
        </executions>
      </plugin>
      ...
    </plugins>
    ...
  </build>
  ...
</project>

Maven has some properties you can use to avoid absolute paths.
${maven.repo.local} will resolve to the local repository
${project.basedir} is the project directory (the root of the project)
${project.build.directory} is the build directory (default is "target")
${project.build.outputDirectory} is the directory where compilation output goes (default is "target/classes")

Comment: hey, thank you very much for your suggestion.
I had a followup question. in the pom instead of giving absolute path to the war file is there a way that the war file can be picked up from the local repository or remote repository path.
Comment: I've added some properties to the answer, you can specify a relative path by using ${property}/path/to/reference
Answer: you can create a "super war" and deploy that, as well


Determine if array is in order AND the last element is 0

Question: how can I determine when the first X numbers of an array is in order AND the last element in 0? i.e the array is
1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,0

I currently have this, but this relies on the array always being the same, which isn't very flexibile
const sorted = (array) => {
    const solved = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 0]
    return (JSON.stringify(array) == JSON.stringify(solved))
}

Comment: What is `x` in "the first x numbers"?
Comment: Sorry, that should've probably been capitalised. X numbers (so whether the array is 15, 500 or 15000 numbers long, the first should be in order AND the last should be 0)
Comment: Sorry, what is the *value* of X? Do you mean *all* values except the last, or is there a segment that is excluded from this "first X"?
Comment: Sorry if i'm not being clear, but yes, all values other than the last (which should be 0) should be in order
Comment: OK, so what have you done to do this? You should iterate over the array and compare values. Where did you meet a problem?
Comment: I've given my example, i'm just not sure how else it can be done
Comment: what if you have only one or two elements in the array?
Answer: You could do something as simple as this:

const checkArray = (arr) => {
    if(arr[arr.length-1] != 0){
        return false;
    }
    const nums = arr.slice(0, arr.length - 1);
    const sortedArr = [...nums].sort((a, b) => a - b);
    for (let i = 0; i < nums.length; i++) {
      if(nums[i] != sortedArr[i]){
        return false;
      }
    }
    return true;
}

console.log(checkArray([1,2,3,0])); // true
console.log(checkArray([1,2,3,4])); // false
console.log(checkArray([1,3,2,0])); // false

Basically the steps are:

Check if last element is 0, else do an early return.
Create a sorted version of the first part of the array (the one with the numbers)
Check if the numbers part is equal to the sorted array. If any element is different return false

In the end you return true only if every condition is verified.
This is generic enough so that if in the future you want to change the sorting type you can just act on the sort function (for example if you want to make it descending).
Answer: First define a generic function to verify that a segment of an array is sorted, then define a second function that uses the first to see the first values are sorted, and add a check for the final value:

function isSegmentSorted(array, start=0, end=array.length) {
    for (let i = start + 1; i < end; i++) {
        if (array[i - 1] > array[i]) return false;
    }
    return true;
}

function isSortedWithExtraZero(array) {
    return array.at(-1) === 0 &&
           isSegmentSorted(array, 0, array.length - 1);
}

var array = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,0];
console.log(isSortedWithExtraZero(array));
Answer: We can use every function for that. With !idx we exclude the first index 0, then we check if idx is less than the length of your array. If so, check if it is sorted, else check it it equals to zero.

const solutions = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 0];

const sorted = solutions.every((val, idx, arr) =>
  !idx || (idx < solutions.length - 1 ? arr[idx - 1] <= val : val === 0)
);

console.log(sorted);


linking a fortran code using netcdf3 to netcdf4

Question: some months ago, I posed a question about writing netcdf3 files with netcdf4 code. Now, I have another problem. I have an older fortran code, which runs in serial and is used to interpolate data from one mesh to another. The code is based on using netcdf3 files and I would like to recompile it with netcdf4. the code uses following netcdf functions:
nf_open, nf_put_vara_real etc.
I'm far from being an expert, but as far as I've read, the code should still accept the netcdf4 files with these calls. However, when I try to compile it with netcdf4 I get lots of error messages. The code itself uses netcdf.inc which is in the same folder as the code, the compilation commands are as follows:
gfortran parameter.f90 netcdf_utils.f90 mean_streaks.f90 -L/opt/netcdf/netcdf3/lib/ -lnetcdf  -O2

I then tried just to change netcdf3 to 4 as I have netcdf3 and 4 folders under /opt/netcdf. However, I got for example the following error messages when compiling:
/tmp/ccgwLiTF.o: In function `__netcdf_utils_MOD_read3d':
netcdf_utils.f90:(.text+0x445): undefined reference to `nf_open_'
netcdf_utils.f90:(.text+0x4a0): undefined reference to `nf_get_vara_real_'
netcdf_utils.f90:(.text+0x4b4): undefined reference to `nf_close_'

Does anyone happen to know what I'm missing or how I should link the libraries to get the compilation done?
thanks for the answers in advance
Answer: I found the issue. The thing was that on the cluster I'm using, the netcdf4 was compiled with mpif90, not gfortran. So I changed the gfortran to mpif90 and used changed netcdf3 to netcdf4. I also added other links, for which I used the CMakeList for another code that uses netcdf4. The final working product is:
mpif90 parameter.f90 netcdf_utils.f90 mean_streaks.f90 -I/opt/netcdf/netcdf4/include -L/opt/netcdf/netcdf4/lib -lnetcdff -L/opt/pnetcdf/pnetcdf-1.2.0/lib -L/opt/netcdf/netcdf4/hdf220.127.116.11/lib -lnetcdf -lpnetcdf -lhdf5_hl -lhdf5 -lm -lz -lcurl -O2

thanks for the help, I now have another question which I'll be posting in a while:)
Answer: Add -lnetcdff to your compile command (yes, 2 f's).  In netcdf4 the Fortran symbols end up that library rather than libnetcdf.so.
gfortran parameter.f90 netcdf_utils.f90 mean_streaks.f90 -L/opt/netcdf/netcdf4/lib/ -lnetcdf -lnetcdff -O2

You can verify that the symbols are in that library with a command like
readelf -s libnetcdff.so | grep 'nf_*_'

The output of which, on my installation, includes all of the symbols listed in your error.


Matlab bwlabel not connecting all components

Question: I have this matrix:
ima =  [0 0 0 0 0;
    0 0 0 0 0;
    0 255 255 255 0;
    0 255 255 255 0;
    0 255 0 255 0;
    0 255 0 255 0;
    0 255 255 255 0;
    0 0 0 0 0;
    0 0 0 0 0];
[labels, number] = bwlabel(ima, 4);
labels

The result I get is:
labels =

 0     0     0     0     0
 0     0     0     0     0
 0     1     1     1     0
 0     1     1     1     0
 0     1     0     1     0
 0     1     0     1     0
 0     1     1     1     0
 0     0     0     0     0
 0     0     0     0     0

Why isn't the two zeros surrounded by the ones seen as a different component with a value of 2?
This is what I want:
labels =
 0     0     0     0     0
 0     0     0     0     0
 0     1     1     1     0
 0     1     1     1     0
 0     1     2     1     0
 0     1     2     1     0
 0     1     1     1     0
 0     0     0     0     0
 0     0     0     0     0

Answer: Only the values that are a 1 in your input matrix are considered as components to label. If you want the second output as you've shown, you would need to also apply bwlabel to the inverse of your matrix to label the 0 values.
[labels, number] = bwlabel(ima, 4);

% Compute the labels of the inverse
labels2 = bwlabel(~ima, 4);

% Combine the labels
labels = max(labels, labels2 + number + 1);

If you only want to label 0 values that are completely surrounded by 1's you can do something like this
[labels, number] = bwlabel(ima, 4);

% Find the 0's that are surrounded by 1's and label them
filled = imfill(ima, 'holes');
labels2 = bwlabel(filled & ~ima, 4);

% Combine the labels
labels(filled) = max(labels(filled), labels2(filled) + number + 1);

Comment: I will mark this as correct! Thanks. But the matlab example [link](https://www.mathworks.com/help/images/ref/bwlabel.html) did not use the `~` operator. What was the difference with that example from mines?
Comment: @Jam1 The `~`  is the [`not`](https://www.mathworks.com/help/matlab/ref/not.html) operator and turns all  non-zeros to zero and all zeros to 1. Since `bwlabel` only operates on `1` values, `~` allows it to operate only on 0 values.
Comment: @Jam1 Why can't you?
Comment: Because `imfill` gives me exactly what I want. Professor said we should only use `bwlabel`


Clarification in usage of Regular Expressions in Java

Question: I am new to Regex. Please correct me where am doing wrong in below code.
Also Please suggest some nice books/tutorials in Java-Regex.
public class regexx {
public static void main(String[] args) {
    // TODO Auto-generated method stub
    String s = "Bug 2742";
    if("^Bug [0-9]*".matches(s)){
        System.out.println("eq");
    }else {
        System.out.println("nq");
    }
}
}

Am expecting "eq" as output.But the match is returning false.
Comment: Off topic: Java coding conventions recommend [PascalCase](http://c2.com/cgi/wiki?PascalCase) for class names. Meaning the first letter is a capital letter hence: `regexx` would be `Regexx`. Aside from constants (which should be all caps) all variables and methods should be camelCase. Following these standard conventions allows other Java programmers to easily understand what you code does.
Comment: Oracle official tutorial : http://docs.oracle.com/javase/tutorial/essential/regex/
Comment: @izuriel I like that constructive comment. :)
Comment: [Mastering Regular Expressions (3rd Edition)](http://www.amazon.com/Mastering-Regular-Expressions-Jeffrey-Friedl/dp/0596528124 "By Jeffrey Friedl. Best book on Regex - ever!")
Answer: The regex should be the argument
http://www.tutorialspoint.com/java/java_string_matches.htm
s.matches ("^Bug [0-9]*")

Answer: public boolean matches(String regex)

String#matches()  takes regex as parameter,Not the string which you are doing operation.
You are doing in the reverse while applying regex
For Clarification, I separated that line.
Try
public static void main(String[] args) {
        // TODO Auto-generated method stub
        String s = "Bug 2742";
        boolean matches = s.matches("^Bug [0-9]*");
        if(matches){
            System.out.println("eq");
        }else {
            System.out.println("nq");
        }
    }


How to add a file to a .gz archive and delete the original file?

Question: My files name is <09/12/2020>_master. How would I be able to add this file to a .gz archive and then remove the original file?
Answer: GZip isn't an archive format, it's a compression format.  A .gz file can only contain one compressed file; if you need to put more than one file in at a time, you'll need to pair it with an archive format (such as tar).
Comment: Yep, with the only caveat is you can add/include the content of multiple files in a single gzip archive, but the addition loses its separate identity.
Comment: How would I be able to do that?