Manual LVM encryption setup with Ubuntu 13.04

Question: I am trying hard to get ubiquity works. The thing is that I want to setup Ubuntu 13.04 on a full encrypted LVM aside a Windows installation. So I can't use the default option of full disk encryption.
The issue is when I try to use a partition as physical encryption volume I always get an error concerning keyfile.
And if I make the partition before launching ubiquity, then I get an error when I try to make the mapping between logical volumes and mount points.
This was working great with alternate CD (or USB) but since they shutdown this Ubuntu image, I'm stuck.
Maybe it is time to look for another Linux distro or maybe someone has a solution...
Answer: Use the server CD image.
You'll get a full fledged advanced installer like the alternate installer, but it won't install any GUI. Install it afterwards using an APT task. E.g. for regular Ubuntu:
sudo apt-get install ubuntu-desktop^

or KDE/Kubuntu:
sudo apt-get install kubuntu-desktop^

(the caret is not a typo). Ubuntu is just a set of packages and while the several flavours install different packages by default, you can just change that.
Ever since 12.04 the separate server flavour of the kernel has been dropped and merged with the desktop flavour, so you don't have to deal with that.
Here's the bug report for implementing manual LVM partitioning in combination with encryption in the desktop installer: [FFe] [UIFe] Manual Partitioning Crypt  and a blueprint: Improving support for LVM & LUKS encryption within Ubiquity.
Answer: I just had success with instructions from here:https://help.ubuntu.com/community/EncryptedFilesystemsViaUbiquity
Basically, you will have to set up your LUKS container and the volumes within the container using command line (cryptsetup, pvcreate, vgcreate, lvcreate), before starting the installer. Then in the installer choose manual partitioning and point it to the LVs you created. The LUKS container needs to be open (cryptsetup luksOpen) during the installation for the installer to see inside it. After the installer finishes, you need to manually add the LUKS container to /etc/crypttab so that the newly installed system knows about it and prompts for password at boot.
Remember that you need to have a /boot partition outside the LUKS container.
It's not pretty, but at least it's possible to do.
Not recommended if this is your first time using cryptsetup and LVM command line tools (or at least, back up any data you want to keep before trying this).
Answer: It is time then to move on then.
Ubuntu installer is broken now. They used Debian installer in the past (up to 12.04) for advanced setups, but now you only have the "unified" installer, made by Canonical, which is simply broken when it comes to encrypted LVM installations. I've tried using my old encrypted LVM volumes, entered passphrase and it simply reformatted them into ext4 partitions without any warning, wiping all my data. There were no option to use encrypted volumes as LVM PVs at all either.
My advice is just to stay away from Ubuntu if you're past oversimplified setups. Both Fedora 18 and Debian 7 do what you want just fine. Debian 7 is being released this weekend, btw.
Comment: Your answer is not very constructive or helpful. Sorry.


Remove text and link from e-mail

Question: I have auto generated receipts coming to my e-mail (Outlook) that I have built rules to forward to different CSR's based text in the body of the e-mail.
There is an "unsubscribe" option and occasionally either our CSR's or their clients are clicking on which removes me from getting these e-mails.
is there a way removing this string of text along with the link?
The string is as follows:
If you no longer wish to receive emails from Self Service Terminal, please click on the 'Unsubscribe' link below:
Unsubscribe
Thanks
Comment: Have you tried [Finding and Replacing Text](https://msdn.microsoft.com/en-us/library/office/aa211953(v=office.11).aspx) also please see
[Help Center > Asking](https://stackoverflow.com/help/how-to-ask)
Answer: Something like this will help:
<code>    With Selection.Find
      .ClearFormatting
      .Text = "If you no longer wish to receive emails from Self Service Terminal, please click on the 'Unsubscribe' link below: Unsubscribe"
      .Replacement.ClearFormatting
      .Replacement.Text = ""
      .Execute Replace:=wdReplaceAll, Forward:=True, _
      Wrap:=wdFindContinue
    End With
</code>
See Om3rs link in the comment for more information on this.

Remove text and link from e-mail


Is it safe to use this dimmer on LED bulbs?

Question: I have a question about dimmer switches for LED flood lights.  My kitchen has six floodlights on a Lutron toggler dimmer switch, model AY-603P.
http://www.lutron.com/en-US/pages/SupportCenter/support.aspx?modelNumber=AY-603P&&SECTION=Documents
Up until now I have had fluorescent lights in them.  The lights needed replacing so I ordered some new ones, however, I accidentally ordered these LED bulbs instead...
https://www.amazon.com/gp/product/B076HXK16H/ref=ppx_yo_dt_b_asin_title_o00__o00_s00?ie=UTF8&psc=1
The LED bulbs I ordered are dimmable so I decided to try them out and they seem to work just fine on my dimmer switch, no buzzing or flickering.  My question is...
Is this safe?  I had read that I should only use LED approved dimmer switches with LED bulbs.  My dimmer model does not say that it is LED compatible, the manual for the Lutron AY-603P dimmer switch says that it can be used with halogen and incandescent lights, it doesn't say anything about LED lights.  Are there any electrical risks to using LED bulbs on a this type of dimmer switch?  Any commentary guidance would be welcome.  Thanks!
Comment: Do the bulbs say "dimmable"?
Comment: it's not a safety problem, it's a performance problem. Non-LED dimmers used with cheap dim-able LEDs might only dim for a portion of the range, most commonly "they won't get very dim". You can also have some issues with dark flicker if it's not completely off. However, high-quality dim-able LEDs have extra smarts inside the bulb to behave correctly with older dimmers, so it's been kind of a confusing back and forth.
Comment: @TomCarpenter Yes they are dimmable LEDs.  I will update my post.
Answer: Nope
From this LED compatibility guide on Lutron's site, the following output.

Further, The service manual you link states clear that

CAUTION: Use "AY-" or "TG-" models only with permanently-installed
  120 V incandescent or halogen fixtures. To avoid overheating and possible damage to other equipment, do not use to control receptacles, fluorescent lighting fixtures, motor-driven appliances, or transformer-supplied appliances.

That's it.  It's not "not saying" about LEDs, it's saying very specifically about LEDs, since it allows only incandescent and halogen (which are incandescent).  Open up "See Aridani/Toggler model numbers", and open up "Dimmers" (the only category), i.e. here, it lists several categories and the results in each echo the above.
Welcome to the world of off-label usage.  Which means UL has not tested this equipment for this usage. It might work, might not, might get magic smoke, it's all on you.
So the ultimate answer to your question is, shrug...
Comment: Actually -- the Ariadni/Toggler dimmers are all phase-cut types
Comment: @ThreePhaseEel Yeah, somehow I took a wrong turn and found myself looking at the wrong data sheet.
Comment: Oh wow.  When I purchased my house they had already installed dimmable fluorescent bulbs on this dimmer switch.  To think all these years I was using fluorescent bulbs when I shouldn't have been.
Comment: @b10hazard: It's possible for a fluorescent or LED lamp assembly to contain circuitry that will make it behave electrically in a manner similar to a low-wattage incandescent lamp, though there are some trade-offs among cost, energy efficiency, and the extent to which their behavior mimics an incandescent lamp.  Unfortunately, there are no standards for measuring how similar an particular lamp assembly's electrical behavior is to an incandescent, nor how closely a switch would require a load's behavior to mimic an incandescent.
Comment: @b10hazard No no, the point of the compatibility guide isn't *safety*, it's *performance* i.e. will the light work well.  They are saying "We tested these and they work great and we warranty our dimmer to work with them".   What you have is like a can of soda that expired 2 months ago (they generally get 9 months)... it's still drinkable but the taste might be off.  If it still tastes good, go for it.
Answer: I don't think anyone can advise you with certainty if this is a good idea, except maybe the manufacturer.
That said, yes, this is safe provided the LED lights are rated at 100 watts or less each. Worst case scenario is the bulbs will fail sooner then they would be expected to.  My guess is that this is fine to do if it works, but if there is annoying flickering you should drive the dimmer on full until you can get a replacement.
There are 2 reasons for my answer -

(Assuming the total load is less then 600 watts, ie the wattage in actual watts the dimmer consumes, not the "incandescent equivalent brightness - - and as you are using LEDs thats a fairly safe assumption) The load is less then the dimmer is capable of handling.  This means it is electrically safe, in as much as you are not going to have heat buildup which the dimmer can't handle.
Mains rated LED bulbs have circuitry in them to handle dimming.  Depending on the manufacturer this circuitry can be quite different.  If the circuits are not compatible with the dimmer, it could cause them to not work correctly or fail early.
The LED dimmer I have has a setting inside it to make adjustments depending on load.  My guess is that this is true of most LED dimmers, and this is needed because LED loads can be way lower then incandescent loads.
Comment: LED bulbs that aren't designed to be dimmed may use a capacitive-dropper circuit which relies upon the mains voltage to rise and fall gradually during each cycle.  Such circuitry would need to be designed to absorb an occasional current spike caused by turning on a light switch when the line voltage is at its peak, but many dimmers designed for incandescent lamps would subject a capacitive-dropper lamp assembly to such stresses 120 times per second.
Answer: If the led lamps are dimmable and are working they will be fine. The normal problems with led's is they draw so little current that many dimmers cause them to glow and or strobe, with 6 your load may be enough that you don't see any problems like you may with only a single lamp on that dimmer.


How to remove all versions of node, including the one installed with brew?

Question: On MacOS I've got a bit of a mess with node, so I'm trying to uninstall all versions of node. Here's what I tried:
$ node --version
-bash: /usr/local/opt/node@8/bin/node: No such file or directory
$
$ which node
/usr/local/bin/node
$ ls -l /usr/local/bin/node
-rwxrwxr-x  1 hielke  admin  30994272 Oct  3 18:55 /usr/local/bin/node
$ /usr/local/bin/node --version
v6.11.4

As you can see, node --version refers to an uninstalled version 8.x of node. When I do which node however, it refers to /usr/local/bin/node, which is a binary of node version 6.x.
And from here I'm left with the following questions:

Why on earth does node --version refer to something different than which node?
And can I simply remove the /usr/local/bin/node binary?
And how can I remove the link to /usr/local/opt/node@8/bin/node?

And most importantly: how can I clean up this mess so that I can install node completely fresh?
Answer:
node --version is referring to something different because your path is pointing there. use echo $PATH to print the path. Edit your path from your bash_profile. use vim ~/.bash_profile to edit your bash profile.
yes, you can just delete /usr/local/bin/node
Edit your bash_profile to change the path to your node

Install the latest version of node you want and just edit
  bash_profile to point the path to where the new binaries are.
Comment: Thanks for the tips. I did that and it works, but now `npm` is still broken. `npm init` gives me `Error: Cannot find module 'process-nextick-args'`. I tried installing that module using `sudo npm install -g process-nextick-args`, but that simply gives me the same error. `which npm` gives me `/usr/local/bin/npm`, which is a symlink to `/usr/local/lib/node_modules/npm/bin/npm-cli.js` instead of one installed with brew. In the folder `/usr/local/opt/node@8/bin/` there's only a `node` binary though. Any idea where I can find the correct `npm` installed with the node version 8 as installed by brew?
Comment: @kramer65 run `whereis node` and `whereis npm` to check all locations where does binaries exists, then follow my answer below and add them to your env PATH
Comment: can you try `npm install npm@latest -g`
Comment: nvm is a great option for installing node.
Answer: in bash whenever you execute an expression or a statement in the shell, it first of all check if there is an alias to the executed command, if there is no alias it checks the environmental ${PATH} variable. In your env path the previous location of node takes precedence in the env path variable, do this for a fix
 $ export PATH="/usr/local/bin/node:${PATH}"

if you want this to apply always edit your ~/.bash_profile or ~/.bashrc file depending on your platform, the location and name might vary
on the current terminal you have to source your rc file
$ source ~/.bash_profile
or
$ source ~/.bashrc

if you want to remove that previous location, you have to check if the node binary still exists at that location, if it does still exists, use the rm command to remove it


How do I add Window Manager From Scratch (WMFS) to the Window Manager selection in the login screen?

Question: how do I add Window Manager From Scratch (WMFS) to the Window Manager selection in the login screen?
I've installed it already and now I want to boot it, but how do I do that?
Regards,
Senad
Answer: From the ubuntu wiki:

Ubuntu 12.04 uses LightDM by default.
Create a new file /usr/share/xsessions/custom.desktop with:
<code>[Desktop Entry]
Name=Xsession
Exec=/etc/X11/Xsession
</code>
You should now have a new session option during login, Xsession will load the user's ~/.xsession file

The above allows you to create and use a .xsession file in your home directory. So now you should create said .xsession file and put the following in it:
<code>exec wmfs
</code>
Then from the login screen you should see a new entry, log in with that and (hopefully) you should see your new, highly minimal window manager. Enjoy!


EJB + JSF (Primefaces) Maven -> Using primefaces jar in EJB -> exception during deploying on Jboss, Eclipse

Question: I need to create querybuilder. I would like to create it on ejb site. To do that I need to use org.primefaces.model.SortOrder. I add dependency to primefaces in ejb POM. After that I've got  "java.lang.NoClassDefFoundError: org/primefaces/model/SortOrder". This dependency works fine in war. Any ideas?
Pom WAR Build part
<code><build>
<plugins>
        <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>2.3.2</version>
        <configuration>
            <source>1.6</source>
            <target>1.6</target>
        </configuration>
    </plugin>

</plugins>
<finalName>JSF</finalName>
</build>

EJB Pom

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>test.com</groupId>
    <artifactId>EJB</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>ejb</packaging>

    <name>EJB</name>

    <properties>
        <endorsed.dir>${project.build.directory}/endorsed</endorsed.dir>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

    <dependencies>
My dependencies with primefaces
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.3.2</version>
<configuration>
    <source>1.6</source>
    <target>1.6</target>
    <compilerArguments>
        <endorseddirs>${endorsed.dir}</endorseddirs>
    </compilerArguments>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-ejb-plugin</artifactId>
<version>2.3</version>
<configuration>
    <ejbVersion>3.1</ejbVersion>

    <archive>
        <manifestEntries>
            <Dependencies>org.slf4j</Dependencies>
        </manifestEntries>
    </archive>

</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<version>2.1</version>
<executions>
    <execution>
        <phase>validate</phase>
        <goals>
            <goal>copy</goal>
        </goals>
        <configuration>
            <outputDirectory>${endorsed.dir}</outputDirectory>
            <silent>true</silent>
            <artifactItems>
                <artifactItem>
                    <groupId>javax</groupId>
                    <artifactId>javaee-endorsed-api</artifactId>
                    <version>6.0</version>
                    <type>jar</type>
                </artifactItem>
            </artifactItems>
        </configuration>
    </execution>
</executions>
</plugin>
</plugins>
<pluginManagement>
<plugins>
<!--This plugin's configuration is used to store Eclipse m2e settings
    only. It has no influence on the Maven build itself. -->
<plugin>
    <groupId>org.eclipse.m2e</groupId>
    <artifactId>lifecycle-mapping</artifactId>
    <version>1.0.0</version>
    <configuration>
        <lifecycleMappingMetadata>
            <pluginExecutions>
                <pluginExecution>
                    <pluginExecutionFilter>
                        <groupId>
                            org.apache.maven.plugins
                        </groupId>
                        <artifactId>
                            maven-dependency-plugin
                        </artifactId>
                        <versionRange>
                            [2.1,)
                        </versionRange>
                        <goals>
                            <goal>copy</goal>
                        </goals>
                    </pluginExecutionFilter>
                    <action>
                        <ignore></ignore>
                    </action>
                </pluginExecution>
            </pluginExecutions>
        </lifecycleMappingMetadata>
    </configuration>
</plugin>
</plugins>
</pluginManagement>
</build>

</project>

EAR is not a maven projekt

  <display-name>EAR</display-name>
  <module>
    <web>
      <web-uri>JSF.war</web-uri>
      <context-root>JSF</context-root>
    </web>
  </module>
  <module>
    <ejb>EJB.jar</ejb>
  </module>
</application>
</code>
Answer: if you need applications which simultaneously use ejb and war, then you must create a ear package which should contain your library. If you do not want to create a third pom (to create ear from your two child), then you may move this library to server.


Why is the HTTP verb POST called POST?

Question: The other verbs all make sense to me, but I don't have much context for "post" as a verb. Is it like post as in Post Office (which makes some sense, although seems like a stretch) or post like post on a bulletin board (makes less sense to me)? Does anyone know who decided on "POST" and why it was selected?
Comment: Because GIVE didn't sound quite as catchy. *-ducks-*
Comment: @JohnSheehan Well actually, it's a HTTP method, not a HTTP verb :-P
Comment: @BoltClock'saUnicorn as in "give it a ..."?
Answer: Well, "post like post on a bulletin board" comes pretty close to the answer, I guess. In the end, that's exactly one of those functionalities this method was designed for. POST is always meant to post stuff to some kind of 'factory' to be handled by it - otherwise you could just use PUT. Let's have a look at RFC2616, Section 9.5:

The POST method is used to request that the origin server accept
  the entity enclosed in the request as a new subordinate of the
  resource    identified by the Request-URI in the Request-Line. POST is
  designed    to allow a uniform method to cover the following
  functions:
  - Annotation of existing resources;

  - Posting a message to a bulletin board, newsgroup, mailing list,
    or similar group of articles;

  - Providing a block of data, such as the result of submitting a
    form, to a data-handling process;

  - Extending a database through an append operation.

Of course this is not the exact definition of why it is called POST, but I think this might give some clues about the idea behind it.
Maybe we could also have a look at some meanings of the word 'post' (http://www.thefreedictionary.com/Post, the 3rd definition) - according to that, post as a verb can mean

To mail (a letter or package)
To inform of the latest news
To transfer (an item) to a ledger in bookkeeping
To make the necessary entries in (a ledger)

And this is exactly what POST does (metaphorically). If you want to send en email, you let your email-provider handle it and then inform you about the state. And this is also the difference between PUT and POST: If the client is in charge of handling the resource, you use PUT (because you know what to put and where to put it).
So, theoretically, if you knew the IP-address of the person you want to send the email to, you wouldn't need your provider to find this stuff out for you. But now, you know what to put, but not exactly where. So in this case, you use POST. You 'inform the server of the latest news' and the server decides where to put it. So you can think of it as 'transfering an item' to a resource that's already present (like a thread in a forum or something) - you just want to append something.
I hope this makes any sense...
Comment: For a moment I thought I was on english.stackexchange.com
Comment: This is an awesome breakdown of why POST makes sense. I suppose unless Tim Berners-Lee wanders in this is about as definitive as it's going to get...
Comment: @KelseyInnis Always glad to help :) And I also hope that Mr. Berners-Lee wouldn't laugh too hard at me for this... :-P
Answer: The POST method is used to request that the origin server accept the entity enclosed in the request as a new subordinate of the resource identified by the Request-URI in the Request-Line. POST is designed to allow a uniform method to cover the following functions:

Annotation of existing resources;
Posting a message to a bulletin board, newsgroup, mailing list, or similar group of articles;
Providing a block of data, such as the result of submitting a form, to a data-handling process;
Extending a database through an append operation.

W3 / POST
REST asks developers to use HTTP methods explicitly and in a way that's consistent with the protocol definition. This basic REST design principle establishes a one-to-one mapping between create, read, update, and delete (CRUD) operations and HTTP methods. According to this mapping:

To create a resource on the server, use POST.
To retrieve a resource, use GET.
To change the state of a resource or to update it, use PUT.
To remove or delete a resource, use DELETE.

IBM / REST
When we are POSTing, we really are sending new data (creating resource) but not going to get it or calling about updates or asking for shredding our older documnets.
Answer: I don't think that post as in 'to post a letter' is much of a stretch. A POST request is a message containing data after all. As to the who, the verbs come from HTTP, so the origins would be the Html spec written by Tim Berners-Lee in 1995.

Why is the HTTP verb POST called POST?


Send array as JSON response after the array is populated by values obtained from mongodb

Question: I am trying to send an array of document IDs as JSON response but the array I obtain as the response is empty. How can I make sure the array is populated first by the document IDs before it is sent as the response?
exports.createItem = async (req,res,next) => {
    let itemsIds = [];
    req.body.forEach( async element => {
        let doc = await Item.findOneAndUpdate({
            type: element.type,
            color: element.color,
            size: element.size
            }, {
            $inc:{stock: element.stock}
            }, {upsert:true, new: true});
        itemsIds.push(doc._id);
        });
    res.status(200).json({
        success: true,
        itemsIds: itemsIds
    })
}

I want to make sure the res.status(200).json({...}) method runs only after all the doc ids are pushed to the mongo DB. Right now I just get the itemsIds as [ ] in the response. How I can make sure itemsIds array is populated by the doc ids first before sending the response?
Answer: The forEach loop contains a callback function, where we should not use async await, use the for of loop to await for the result, push it into the array and then send the response.
exports.createItem = async (req,res,next) => {
    let itemsIds = [];
    for (var element of req.body) {
        let doc = await Item.findOneAndUpdate({
            type: element.type,
            color: element.color,
            size: element.size
            }, {
            $inc:{stock: element.stock}
            }, {upsert:true, new: true});
        itemsIds.push(doc._id);
    }
    res.status(200).json({
        success: true,
        itemsIds: itemsIds
    })
}

Comment: @SagarChilukuri i have updated the answer, please find the answer.
Comment: It works! Thank you. I will mark this answer as the best answer but can you please explain why this method works? Why does it work using for loop instead of forEach() ?
Comment: Once you give a function to forEach, it takes it as a asynchronous call, and its not handled by the main thread any more, so the main thread starts working on the next line, In your case it send the response.


How to use placeholders in dynamic camel-kafka endpoint?

Question: I am using a dynamic endpoint to send messages to Kafka.
<code>   private static final String OUTPUT_TOPIC = "OutputTopic";
   ...

   private void setOutputTopic(Exchange exchange) {
       //some other code
       exchange.setProperty(OUTPUT_TOPIC,"MyKafkaTopic");
   }
   ...
   @Override
   public void configure() {
        from("direct:someEndpoint")
                .process(this::setOutputTopic)
                ...
                .toD("kafka:${exchangeProperty." + OUTPUT_TOPIC + "}");
  }
</code>
With Camel version 3.4.x everything worked fine. After migration to Camel version 3.14.x several tests started to fail due to optimization in KafkaSendDynamicAware that creates kafka endpoint with URI that contains unresolved placeholders and Camel test facilities does not work as before:
<code>@MockEndpointsAndSkip("kafka:MyKafkaTopic")
...

@EndpointInject("mock:kafka:MyKafkaTopic")
private MockEndpoint mockedMyKafkaTopic;
</code>
Could you suggest the proper way how to test dynamic Kafka endpoint in this case?
Answer: You should be able to use the dynamic topic name using the property placeholder syntax <code>{{some.property}}</code>:
<code>@Override
public void configure() {
     from("direct:someEndpoint")
             .process(this::setOutputTopic)
             // ...
             .toD("kafka:{{" + OUTPUT_TOPIC + "}}");
}
</code>
Comment: The problem is that Camel will create Kafka endpoint with endpoint URI: `kafka://$%7BexchangeProperty.OutputTopic%7D` which is not what I would expect in tests. And dynamically resolved topic name will be placed into `KafkaConstants.OVERRIDE_TOPIC` header and checked during message sending in [KafkaProducer](https://github.com/apache/camel/blob/main/components/camel-kafka/src/main/java/org/apache/camel/component/kafka/KafkaProducer.java#L288).


MVC MultiSelect EF many to many Edit

Question: Below is my code that saves a multi select box, it works fine, but when i try to edit a record i get the error below. Whats the best way to add just the additional selected tags, and to remove any unselected tags when editing?

failed because another entity of the same type already has the same primary key value. This can happen when using the 'Attach' method or setting the state of an entity to 'Unchanged' or 'Modified' if any entities in the graph have conflicting key values. This may be because some entities are new and have not yet received database-generated key values. In this case use the 'Add' method or the 'Added' entity state to track the graph and then set the state of non-new entities to 'Unchanged' or 'Modified' as appropriate.

public class Post
{
    public Guid PostId { get; set; }
    public string Name { get; set; }
    public virtual ICollection<Tag> Tags { get; set; }
}

  public class Tag
{
    public int TagId { get; set; }
    public string Name { get; set; }
    public virtual ICollection<Post> Posts { get; set; }
}

public class HomeController : Controller
{
    public ActionResult Create()
    {
        var tags = new List<Tag>()
            {
                new Tag() { TagId = 1, Name = "Planes", Posts = new Collection<Post>() },
                new Tag() { TagId = 2, Name = "Cars", Posts = new Collection<Post>() },
                new Tag() { TagId = 2, Name = "Boats", Posts = new Collection<Post>() }
            };

        ViewBag.MultiSelectTags = new MultiSelectList(tags, "TagId", "Name");

        return View();
    }

    [HttpPost]
    public ActionResult Create(Post post, int[] tags)
    {

           foreach (var tag in tags)
            {
                Tag t = db.ThemeFeatures.Where(t => t.TagId== tag).First();
                themedetails.ThemeFeatures.Add(t);
            }

         context.SaveChanges();

        return RedirectToAction("Create");
    }

}

Create view

@model MvcApplication1.Models.Post
Create
@using (Html.BeginForm("Create", "Home", FormMethod.Post)) {
      Name
      @Html.TextBoxFor(model => model.Name)
Tags For Post
@Html.ListBox("Tags", (MultiSelectList)ViewBag.MultiSelectTags)

<input type="submit" value="Submit Post"/> }

Answer: What you want to do is make sure the entity you're adding child-entities to is attached to the object context. The easiest way to do this is just get a fresh context object using the POSTed ID from your view.
You won't save anything worrying about getting the difference of what the object has versus what the object should have. The easiest way to handle that is to simply clear the object of its child collection and add everything that came back from the POST.
[HttpPost]
public ActionResult Create(Post post, int[] tags)
{
     ...
     var freshPost = db.Posts.Find(post.ID);
     freshPost.Tags.Clear();
     foreach (var tag in tags)
     {
         Tag t = db.ThemeFeatures.Find(tag);
         freshPost.Tags.Add(t);
     }

     context.SaveChanges();
}

MVC MultiSelect EF many to many Edit


Jenkins Build failed - Sonar Maven

Question: After updating Sonar from 5.1 to 5.2 the Jenkins-Build failed.
My Jenkins Sonar-Plugin is version 2.3 and the Maven-Plugin 2.6 (I tried also 2.7.1 but it failed too).
I use Maven 3.0.4 and Jenkins 1.629.
Here is my error:
<code>[ERROR] Failed to execute goal org.codehaus.mojo:sonar-maven-plugin:2.6:sonar (default-cli) on project module.fakturierung: org.sonar.api.resources.Project.getPom()Lorg/apache/maven/project/MavenProject; -> [Help 1]
org.apache.maven.lifecycle.LifecycleExecutionException: Failed to execute goal org.codehaus.mojo:sonar-maven-plugin:2.6:sonar (default-cli) on project module.fakturierung: org.sonar.api.resources.Project.getPom()Lorg/apache/maven/project/MavenProject;
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:217)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:153)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:145)
    at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:84)
    at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:59)
    at org.apache.maven.lifecycle.internal.LifecycleStarter.singleThreadedBuild(LifecycleStarter.java:183)
    at org.apache.maven.lifecycle.internal.LifecycleStarter.execute(LifecycleStarter.java:161)
    at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:320)
    at org.apache.maven.DefaultMaven.execute(DefaultMaven.java:156)
    at org.apache.maven.cli.MavenCli.execute(MavenCli.java:537)
    at org.apache.maven.cli.MavenCli.doMain(MavenCli.java:196)
    at org.apache.maven.cli.MavenCli.main(MavenCli.java:141)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced(Launcher.java:290)
    at org.codehaus.plexus.classworlds.launcher.Launcher.launch(Launcher.java:230)
    at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode(Launcher.java:409)
    at org.codehaus.plexus.classworlds.launcher.Launcher.main(Launcher.java:352)
Caused by: org.apache.maven.plugin.MojoExecutionException: org.sonar.api.resources.Project.getPom()Lorg/apache/maven/project/MavenProject;
    at org.codehaus.mojo.sonar.bootstrap.ExceptionHandling.handle(ExceptionHandling.java:41)
    at org.codehaus.mojo.sonar.bootstrap.RunnerBootstraper.execute(RunnerBootstraper.java:139)
    at org.codehaus.mojo.sonar.SonarMojo.execute(SonarMojo.java:132)
    at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo(DefaultBuildPluginManager.java:101)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:209)
    ... 19 more
Caused by: java.lang.NoSuchMethodError: org.sonar.api.resources.Project.getPom()Lorg/apache/maven/project/MavenProject;
    at org.sonar.plugins.findbugs.FindbugsMavenInitializer.getExcludesFiltersFromPluginConfiguration(FindbugsMavenInitializer.java:57)
    at org.sonar.plugins.findbugs.FindbugsMavenInitializer.execute(FindbugsMavenInitializer.java:52)
    at org.sonar.batch.phases.InitializersExecutor.execute(InitializersExecutor.java:59)
    at org.sonar.batch.phases.PhaseExecutor.executeInitializersPhase(PhaseExecutor.java:156)
    at org.sonar.batch.phases.PhaseExecutor.execute(PhaseExecutor.java:87)
    at org.sonar.batch.scan.ModuleScanContainer.doAfterStart(ModuleScanContainer.java:192)
    at org.sonar.core.platform.ComponentContainer.startComponents(ComponentContainer.java:100)
    at org.sonar.core.platform.ComponentContainer.execute(ComponentContainer.java:85)
    at org.sonar.batch.scan.ProjectScanContainer.scan(ProjectScanContainer.java:258)
    at org.sonar.batch.scan.ProjectScanContainer.scanRecursively(ProjectScanContainer.java:253)
    at org.sonar.batch.scan.ProjectScanContainer.scanRecursively(ProjectScanContainer.java:251)
    at org.sonar.batch.scan.ProjectScanContainer.doAfterStart(ProjectScanContainer.java:243)
    at org.sonar.core.platform.ComponentContainer.startComponents(ComponentContainer.java:100)
    at org.sonar.core.platform.ComponentContainer.execute(ComponentContainer.java:85)
    at org.sonar.batch.bootstrap.GlobalContainer.executeAnalysis(GlobalContainer.java:153)
    at org.sonar.batch.bootstrapper.Batch.executeTask(Batch.java:110)
    at org.sonar.batch.bootstrapper.Batch.execute(Batch.java:76)
    at org.sonar.runner.batch.IsolatedLauncher.execute(IsolatedLauncher.java:48)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at org.sonar.runner.impl.BatchLauncher$1.delegateExecution(BatchLauncher.java:87)
    at org.sonar.runner.impl.BatchLauncher$1.run(BatchLauncher.java:75)
    at java.security.AccessController.doPrivileged(Native Method)
    at org.sonar.runner.impl.BatchLauncher.doExecute(BatchLauncher.java:69)
    at org.sonar.runner.impl.BatchLauncher.execute(BatchLauncher.java:50)
    at org.sonar.runner.api.EmbeddedRunner.doExecute(EmbeddedRunner.java:102)
    at org.sonar.runner.api.Runner.execute(Runner.java:100)
    at org.codehaus.mojo.sonar.bootstrap.RunnerBootstraper.execute(RunnerBootstraper.java:135)
    ... 22 more
[ERROR]
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoExecutionException
[ERROR]
[ERROR] After correcting the problems, you can resume the build with the command
[ERROR]   mvn <goals> -rf :module.fakturierung
</code>
Has anyone an idea or a solution?
Comment: Which version of Jenkins? Which Version of Maven do you use?
Comment: What is the version of sonar-findbugs you are using ? I would recommend to use the latest version .
Comment: Jenkins is version 1.629 and Maven 3.0.4
Comment: Oh okay...i watched and is version an old version. I will try it. Thanks!
Comment: Thanks a lot. Now it works, after updating Findbugs on version 3.3! :)
Answer: Because of the log fragment:
<code>Caused by: java.lang.NoSuchMethodError: org.sonar.api.resources.Project.getPom()Lorg/apache/maven/project/MavenProject;
at
org.sonar.plugins.findbugs.FindbugsMavenInitializer.getExcludesFiltersFromPluginConfiguration(FindbugsMavenInitializer.java:57)
</code>
I guess your problem is related to the SonarQube embedded Findbugs plugin: you might find useful SonarQube embedded Findbugs plugin compatibility.
Comment: It was exactly the Sonarqube Findbugs Plugin. Thanks!
Comment: Hey, what did you do to fix this?

Jenkins Build failed - Sonar Maven


Windows not working after setting up dual boot on Dell Inspiron 5570

Question: I have Dell Inspiron 5570, i5 8th gen, 2 TB Hard drive, 16GB Intel Optane and 8 GB RAM. I tried dual boot my PC with Ubuntu 16.04, but I was not getting any drive details. So I used terminal in live Ubuntu environment with following command:
sudo dmraid -E -r /dev/sda

After that Ubuntu was working and I installed it in a separate partition. But switching to Windows made it go to auto-repair which didn't work. And it said "Automatic Repair couldn't repair you PC"
Screenshot of the log file C:\WINDOWS\System32\Logfiles\Srt\SrtTrail.txt

I was unable to reset Windows without removing my files (didn't even try reset with file removal).
So I tried the following:
Troubleshoot → Advanced Options → Command Prompt. Then I typed:
chkdsk /f /r C:
EXIT

then exit and continue to Windows
But this didn't work though it took about 4-5 hrs to complete.
Then I tried the RegBack method, but I was unable to execute copy . .. command. Probably because my RegBack showed 0 files:

Then I tried using fixboot but access was denied. To get back the access, I don't know what volume to select from the image below:

Kindly tell me what should I do now to start my Windows (in dual boot) without deleting any data. Will fixboot help? If yes, then please tell me which volume should I select. I have already tried with volume 0. Also if there are other solutions, I will be happy to know.
Comment: Possible duplicate of [Unable to boot into Windows after installing Ubuntu, how to fix?](https://askubuntu.com/questions/217904/unable-to-boot-into-windows-after-installing-ubuntu-how-to-fix)
Comment: Tangentially related question, why install Ubuntu 16.04 when 18.04 LTS and 19.10 non-LTS exist? Usually newer releases have better hardware support and as of 19.10 better performance via Gnome 3.34.
Answer: I had the same problem as you... First of all: Are you messing with Veracrypt? Then this solution doesn't apply to you.
At the beginning I suggest to update grub in case of it has old definitions... (But this could also make the matter worse...)
It is obvious that your Windows-Bootloader is broken. ("Always point out the obvious.") If you mean with fixboot the following, then it could and should help.
You've already gotten to the CMD of Windows, so try out the following:
bootrec /fixmbr
bootrec /fixboot
bootrec /rebuildBcD

If that doesn't work: try bootrec /ScanOsIf it doesn't find your Windows, you're in huge problems(that was mine...) So you see the Volume E, on this is the Efi bootloader. Switch to this partition in CMD and retry. And then follow this : https://superuser.com/questions/949219/how-to-fix-the-windows-10-boot-loader-from-windows solution.
If that all failes, I advise: Save all necessary data and reinstall windows, on the same partition. Because the chance of sucess is not that high anymore and even if you're sucessfull probably not worth the work...
But no matter what, at the end you should use update-grubto bring GRUB up-to-date...
I wish you luck, that you don't have to reinstall windows.
Comment: I tried bootrec before. The fixboot access was denied. I tried to fix this issue but the access was still denied. I tried with volume 0 (see last pic attached in original question). Should I change volume? If so, then what should I select?
Comment: Your Microsoft Bootloader ist Probably on Volume 5 (=E. Because of the Size and the Name). (Or on 2 Because of Size and Filesystem)So you should try it with those. But to be honest: I'm not optimistic... If that all fails you should copy all important files to ubuntu and reinstall windows on the same partition (Yes, that is possible, with almost no problems)


Forgot to add Primary Keys

Question: I have duplicated (copied) a table and for some reason Primary Keys wasnt added.
Now I have a lot of new records were added recently with 0 value in the id field. All the previous records does have a unique ID (from 1 to 302979).
How to fix this?
#1062 - Duplicate entry '0' for key 'PRIMARY'

AUTO_INCREMENT wasnt added as well.
CREATE TABLE `result` (
  `id` int(11) NOT NULL DEFAULT '0',
  `status` varchar(50) NOT NULL,
  `status_date` datetime NOT NULL,
  `member_id` int(11) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1

Comment: Can you please post result of `show create table ...` of your table?
Comment: +1, that's really the problem. Does juergen d post helped you? If so, I think my answer is to be deleted
Answer: try
update result
inner join (select @row := (select max(id) from result)) r
set id = (@row := @row + 1)
where id = 0

to correct the wrong ids.
then add auto_increment to your table
ALTER TABLE `result` CHANGE COLUMN `id` `id` INT(11) NOT NULL AUTO_INCREMENT,
ADD PRIMARY KEY (`id`) ;

and then use
ALTER TABLE result AUTO_INCREMENT = 1234;

in which you replace 1234 with the  number you want to start your increment value. It can be the highest id + 1 for instance. You could get that number with
select max(id)+1 from result;

Comment: This did not work `ALTER TABLE result AUTO_INCREMENT = (select max(id)+1 from result);`
Answer: You can export the table to SQL script file. Than you have to create table with key. And then run impoRt again. You should set auto increment property to be true. Not sure whether this is the easiest way, but it's not so hard to do that.
Answer: CREATE an empty copy of your table:
CREATE TABLE `result_copy` (
  `id` int(11) NOT NULL DEFAULT '0',
  `status` varchar(50) NOT NULL,
  `status_date` datetime NOT NULL,
  `member_id` int(11) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;

Add index and autoincrement to this new table:
    ALTER TABLE result_copy CHANGE COLUMN id id INT(11) NOT NULL AUTO_INCREMENT, ADD PRIMARY KEY (id) ;
Insert data: (change the ordering if necessary)
INSERT INTO `result_copy`(status, status_date, member_id)
SELECT status, status_date, member_id FROM `result`
ORDER BY `id` ASC, `status_date` ASC

Check the data in result_copy. If everything is fine, remove the original table and rename the new table:
DROP TABLE `result`;
RENAME TABLE `result_copy` TO `result`;

Forgot to add Primary Keys


Scope of Static Class Variables in Java

Question: I have a static object defined in my logging class, along the lines of:
   class myLoggingClass {
     static java.util.Properties properties;
     ...
     ...
   }

According to my reference book, this means that the properties object is shared by all instances of my class.
I find this definition insufficient.  I'm writing a class that is being invoked more than once in each application on our project.
Further, our project uses several web services running in the same tomcat container.  Each web service may have multiple threads.
The Java Virtual Machine running on the host may also run one or more web service client applications, which run external to tomcat.
So by this definition, I may have tomcat running multiple web services with threads, each having several objects, which may contain an instance of my class.
There may also be one or two web clients running outside of tomcat, but within the same JVM.  Would all of these instances of my class share the same properties object?  That would make it JVM-wide.
If the static object is not JVM-wide, does anyone know at what level each one would exist?  One per tomcat container?  One per web service, and one per standalone web service client application?
The reason: When I update my properties, I'm getting a java.lang.ConcurrentUpdateException from java.util.Properties.
I'm using a static boolean variable to "lock" the properties object when my class updates it, but this is not keeping the exception from occurring.
This leads me to believe that the static object used in my class may not be at the same scoping level as the one used in java.util.Properties...  But that's just a guess.
Thanks for any help.
Answer: Statics aren't "shared by all instances of a class" - they're unrelated to instances; they belong to the type itself. In particular, static variables are perfectly usable without any instances being created.
That gives a clue as to the scope of statics: they're scoped by the Class object representing the containing class, which is in turn scoped by the ClassLoader that loaded it.
Depending on where the library is placed, the static variable may be JVM-wide or web-application wide - or possibly something in between, if Tomcat supports multiple hosting (I can't remember offhand).
Look at the Tomcat documentation for how the libraries are laid out and how they relate to class loaders. For example, here's the Tomcat 6.0 ClassLoader how-to guide, and the equivalent for 5.5.
How does your Boolean "lock" work? You should really use a proper lock (synchronized) to make sure that every use of the properties object (both read and write, including locking for the whole period during which you iterate through it) is appropriately locked.
Instead of changing the "live" Properties object, have you considered treating that as immutable - so when you want to update the properties, you take a copy, change that, and then make the copy the "live" version? You'd still need to prevent two different threads from making changes at the same time (or you'd lose some) but it's likely to make the reading side a lot easier and more efficient.
Answer: You may find that the scope of such a static variable is limited to one per ClassLoader that has loaded your class. I'm not sure how Tomcat arranges its ClassLoaders, so it's hard to say what the extent of the scope will be in that environment.
Answer: The likely cause of your ConcurrentModificationException is that you are iterating thru the values/entries of the Properties object in one thread while another modifies it at the same time. You cannot do this.
Can you elaborate on the locking mechanism that you mention here:

I'm using a static boolean variable to "lock" the properties object when my class updates it, but this is not keeping the exception from occurring.

?
Because it doesn't sound as if you are using the built-in locking and synchronization methods in Java.
Something like this should prevent threads from reading the Properties object while another thread updates it:
static Object lockObject = new Object();

...

synchronized(lockObject) {
     // access the Properties object
}

Note that you will need to do this every time you access the Properties object, either to read it or modify it.
Also I would never recommend static objects to share data among all instances or static lockObjects - global data is evil - but it sounds as if you need this for some reason.
Comment: just wanna add a note here to say that I think Jon Skeet's description of how static variables actually work is spot-on, and I would consider this the true answer to the question.
Answer: Could it be a classloader problem where the jar that contains your class is duplicated in each WEB-INF/lib of your different applications?
If so, I would try to add this jar to Tomcat libs and not to the application.

Scope of Static Class Variables in Java


Games don't fit in screen when launched in full screen mode (show only left-top quarter)

Question: I'm trying to play games on a Windows 8.1 tablet with 1900x1200 resolution.
When I run some games which change resolution I see only their left-top quarter like game thinks that it's still 1900x1200 when it actually uses 800x600.
I tried to set a lower desktop resolution but it didn't affect what happens when I launch these games.
This happens in different games: "Starbound", "Star Wars: Knights of the Old Republic", "Baldurs Gate II".
The tablet has an Intel HD video.
How to fix it?
Comment: Perhaps [**this answer**](http://gaming.stackexchange.com/a/191836/46740) has the solution to your problem?
Comment: Some games will let you hit (left)Alt+Enter once or twice to resolve such issue. Might work for some, or all or none, give it a shot.
Comment: @ИвоНедев no, it doesn't help. I can play some of them in maximized windowed mode but when I press alt+enter or set full screen in options it behaves like I wrote in the question.
Comment: @Nolonar thanks, "Disable display scaling on high DPI settings" works! If you write an answer I will accept it.
Answer: It seems you are experiencing a problem related to DPI scaling, as is usual with most mobile PCs running at resolutions close to or above Full HD (1920 x 1080) due to their relatively small size.
To fix this, you can disable DPI scaling. This answer explains how.

Keep in mind that disabling display scaling can lead to issues, where UI elements are rendered too small to be read. This is arguably a better outcome than not being able to see most of the game, however.


jQuery dynamically select checkbox group onChange

Question: I have a dynamic set of rows with a dropdown and checkboxes in each and need to select all checkboxes onChange if a certain option value is selected.
This works fine for one group but when there's multiple rows and the option value is selected from one row, the onChange is triggering to select all checkboxes from all rows instead of that specific row.
I setup a fiddle to clarify what I mean - pretty sure i need to somehow get a counter of rows and pass in that counter number in the onChange so it doesn't select all checkboxes and only the row the dropdown being changed is in.
http://jsfiddle.net/7brzct64/

        <select name="eventRegistrations[1].eventRegistrationStatusTypeID" id="registrationStatusSelect">
            <option value="1">Pending</option>
            <option value="2">Attended</option>
        </select>

        <input type="checkbox" name="eventRegistrations[1].markAttendance[1].attendanceDate" value="1">9/21/14
        <input type="checkbox" name="eventRegistrations[1].markAttendance[2].attendanceDate" value="2">9/22/14

        <select name="eventRegistrations[2].eventRegistrationStatusTypeID" id="registrationStatusSelect">
            <option value="1">Pending</option>
            <option value="2">Attended</option>
        </select>

        <input type="checkbox" name="eventRegistrations[2].markAttendance[1].attendanceDate" value="1">10/23/14
        <input type="checkbox" name="eventRegistrations[2].markAttendance[2].attendanceDate" value="2">10/24/14

Works fine for first dropdown changed to "Attended" if I hardcode 1 in eventRegistrations[1].
I think need a counter to get each row somehow, loop or do an each() and pass in the couner number based on which dropdown is selected be eventRegistrations[i] based on which is selected
$("select[name^='eventRegistrations[1]']").change(function () {
if ($(this).val() === '2') {
    $("input[name^='eventRegistrations[1]']").prop('checked', true);

    /*
    var regCount = $(":input[name^='eventRegistrations[i]']").length
    for (i = 1; i <= regCount; i++) {
        $("input[name^='eventRegistrations[i]']").prop('checked', true);
    }*/
}
});

Thanks for the help!
Comment: do you need to keep the names like this? Square brackets in the names are quite uncommon
Comment: @k-nut Yes I need to keep the names in the markup the way they are setup like this if possible! Thank you!!
Comment: Okay i will show you a solution soon
Answer: You can bind the change function to all selects. Then you can check which one was used and get the starting string which is identical with the start of the check boxes. Just like this:
$("select").change(function () {
    if ($(this).val() === '2') {
        var start = $(this).attr("name").split(".")[0];
        $("input[name^='" + start + ".markAttendance']").prop('checked', true);
    }
});

http://jsfiddle.net/7brzct64/2/
Comment: This works perfect! @k-nut How could I do the reverse If all dates are selected, change the dropdown value to "Attended"?
Comment: you would bind a change watch on the inputs and then loop over all selects starting with the same string (similar to the other way around) then get the corresponding dropdown (also by name) and change its value
Comment: @Jibes: can you mark the anwer as correct if it fits your needs?
Comment: Thank you very much again for the help! I updated your fiddle above and can get dropdown to change when all selects are checked but am missing something to keep it exclusive to each row - if you have a minute to take a look that would be awesome!
http://jsfiddle.net/7brzct64/5/


Finding $\lim_{x\to+\infty} \int_x^{x+x^a}\frac{dt}{\sqrt t \log t} $

Question: Let $f$ be the integrand and $g$ the integral. It is continuous on $(0,+\infty)$ so it is on $[x,x+x^a]$ for all $x>0$.
The solution states

$f$ is decreasing on $(0,+\infty)$, therefore by the monotonicity of the integral with respect to the integrand, we have $$f(x+x^a)\cdot x^a\le g(x)\le f(x)\cdot x^a.$$

From this, it's easy to conclude, but I don't get how the inequality was derived.

Also, is it true that for $a\le0$, as $x\to+\infty$, we have $$g(x)=\int_0^{x^a}\frac{dt}{\sqrt{t+x}\log(t+x)}\le \int_0^{1}\frac{dt}{\sqrt{t+x}\log(t+x)}\to0$$? I know this agrees with the correct result that $g(x)\to0$ if $a\le1/2$ and $g(x)\to+\infty$ if $a>1/2$.
Answer: The inequality you're asking about is derived from comparing the region of integration to two different rectangles. The expression on the left, $f(x+x^a)\cdot x^a$ is the area of a rectangle whose base is the domain of integration, and whose height is the value of $f$ at the right end. Since $f$ is decreasing, this rectangle is contained in the region of integration, so it's area is less than the integral.
Similarly, the expression $f(x)\cdot x^a$ is the area of a rectangle whose base is the domain of integration, and whose height is given by the value of $f$ at the left end of the domain. This rectangle contains the region of integration, so its area is greater.
Comment: Thank you so much! Just one more thing, does the last paragraph in my question make sense?
Comment: I'm not sure. Did you mean to put exactly the same integral on either side of that $\le$ sign?
Comment: Oops, no, I've corrected the typo
Comment: I see. That makes sense now. For a second, I thought $g$ was the same function as in the first part of the question, but now I see you're defining a new $g(x)$, and what you wrote is certainly true. The inequality holds because $x^a\le 1$, and the second integral goes to $0$ because it's bounded from above by $1/(\sqrt{x}\log x)$.


TelegramBot application stop working with this errors (SocketException,IOException,WebException,HttpRequestException)

Question: I don't know what can i do.My telegrambot project suddenly stop working after about 1 day.with this errors.
please help me,if possible.
<code>Framework Version: v4.0.30319
Description: The process was terminated due to an unhandled exception.
Exception Info: System.Net.Sockets.SocketException
at System.Net.Sockets.Socket.EndReceive(System.IAsyncResult)
at System.Net.Sockets.NetworkStream.EndRead(System.IAsyncResult)

Exception Info: System.IO.IOException
at System.Net.Security._SslStream.EndRead(System.IAsyncResult)
at System.Net.TlsStream.EndRead(System.IAsyncResult)
at System.Net.PooledStream.EndRead(System.IAsyncResult)
at System.Net.Connection.ReadCallback(System.IAsyncResult)

Exception Info: System.Net.WebException
at System.Net.HttpWebRequest.EndGetResponse(System.IAsyncResult)
at System.Net.Http.HttpClientHandler.GetResponseCallback(System.IAsyncResult)

Exception Info: System.Net.Http.HttpRequestException
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(System.Threading.Tasks.Task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(System.Threading.Tasks.Task)
at System.Runtime.CompilerServices.ConfiguredTaskAwaitable1+ConfiguredTaskAwaiter[[System.__Canon, mscorlib, Version=220.127.116.11, Culture=neutral, PublicKeyToken=b77a5c561934e089]].GetResult() at Telegram.Bot.TelegramBotClient+<SendWebRequestAsync>d__1091[[System.__Canon, mscorlib, Version=126.96.36.199, Culture=neutral, PublicKeyToken=b77a5c561934e089]].MoveNext()

Exception Info: System.AggregateException
at System.Threading.Tasks.Task.ThrowIfExceptional(Boolean)
at System.Threading.Tasks.Task1[[System.__Canon, mscorlib, Version=22.214.171.124, Culture=neutral, PublicKeyToken=b77a5c561934e089]].GetResultCore(Boolean) at System.Threading.Tasks.Task1[[System.__Canon, mscorlib, Version=126.96.36.199, Culture=neutral, PublicKeyToken=b77a5c561934e089]].get_Result()
at Mybot.BotForm.RunBot()
at System.Threading.ThreadHelper.ThreadStart_Context(System.Object)
at System.Threading.ExecutionContext.RunInternal(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object, Boolean)
at System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object, Boolean)
at System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object)
at System.Threading.ThreadHelper.ThreadStart()
</code>
Comment: Just `try` `catch`, and ignore error, it's cause by long polling fail
Comment: @Sean Thanks for your reply.I changed my code,it's work now with no error.
Answer: its because of your pooling way. probably your application is out of memory or network connections. you can simply ignore this exception and your operation system will handle it but  if you plan to use this as your long poling method, you should carefully dispose the objects after each request.
i strongly suggest to use webhook instead of get updates method. its so much faster and efficient.
Comment: Thanks @David for your reply.My Bot project is a .net console app.Can i implement webhook in it?
Comment: unfortunately you cant. you should create web api application.
Comment: Thanks a lot .I'll try it .


rke Error: snapshot missing hash but --skip-hash-check=false

Question: I'm trying to restore an etcd snapshot after a power outage but I'm getting the following error.
FATA[0020] [etcd] Failed to restore etcd snapshot: Failed to run etcd restore container, exit status is: 128, container logs: Error: snapshot missing hash but --skip-hash-check=false

I'm running rke etcd snapshot-restore --config rancher-cluster.yaml --name 202008091207.zip
Answer: This issue is caused by the incorrect inclusion of the .zip file extension to the snapshot name parameter.
The snapshot name parameter (--name) should contain the snapshot name, excluding the file extension.
Please try the following command.
rke etcd snapshot-restore --config rancher-cluster.yaml --name 202008091207


Unable to prove an exercise in Continuous functions in Topology

Question: I am self studying Topology from C. Wayne Patty and I am unable to solve the following question in exercise 1.7
Adding image->
I tried by assuming a sequence $x_n$ $ \epsilon $ A which converges to x . I got f($x_n$) = g($x_n$ ) but  I am not able to move forward.
Please give some hint. No need to fully answer it.
Comment: @DonThousand Munkres *does* treat nets very briefly, in a set of supplementary exercises.
Comment: If you know *nets* you can use that argument you want with nets, using that  continuity preserves net convergence and that Hausdorff is unique limits for nets. Sequences will not suffice in general spaces.
Comment: @HennoBrandsma True, but this is a Munkres problem, which is meant to be solved with basic tools and is meant as an initial exploration of Hausdorff spaces.
Answer: The proof writes itself if you use a proof from contradiction:
Suppose, for a contradiction, that $f(x) \neq g(x)$ for some (now fixed) $x \in \overline{A}$.
Then as $Y$ is Hausdorff, there are open, disjoint sets $U,V$ in $Y$ such that $f(x) \in U$ and $g(x) \in V$.
As $f$ is continuous at $x$, there is some open neighbourhood $U_x$ of $x$ such that $$f[U_x] \subseteq U\tag{1}$$
As $g$ is continuous at $x$, there is some open neighbourhood $V_x$ of $x$ such that $$g[V_x] \subseteq V\tag{2}$$
Now $U_x \cap V_x$ is an open neighbourhood of $x$ and as $x \in \overline{A}$, there exists some point $a \in (U_x \cap V_x) \cap A$.
$(1)$ implies (as $a \in U_x$) that $f(a) \in U$. Also, $(2)$ implies that $g(a) \in V$. But then $$f(a) = g(a) \in U \cap V$$
contradicts the disjointness of $U$ and $V$. This contradiction shows that or initial assumption was false and so $f(x)=g(x)$ for all $x \in \overline{A}$.
Answer: Hint
As you're dealing with general topological spaces, you can't use continuity criteria based on sequences.
Use the continuity criteria based on the fact that inverse image of open subsets are open subsets.
Then proceed by contradiction using Hausdorff criteria.
Comment: If you use nets, it *will* work.
Answer: That style of argument has a chance of working if you know that every point in $\bar{A}$ is a limit of points in $A$. This is true if $X$ is a metric space, for instance, but not in general.
As requested I will give hints only.
The approach here depends in part on what you already know. If you know that the diagonal of $Y \times Y$, i.e. the set $\Delta_Y = \{(y,y) \mid y \in Y \}$, is a closed subset of $Y \times Y$ because Y$ is Hausdorff, that will give you a nice method of solution.
Otherwise, to give a more direct proof, I would start by assuming $f(x) \ne g(x)$ for some $x \in \bar{A}$, and apply the fact that $Y$ is Hausdorff to separate the points $f(x)$ and $g(x)$.


Resize image to its initial size

Question: I am using 2 animations.
when the screen is launched, the first animation starts in viewDidLoad.
this animation is applied to 2 images called layer2 and layer3.
func firstAnimation(){
        UIView.animate(withDuration: 1, delay: 0, options:
            UIViewAnimationOptions.repeat , animations: {

                self.layer2.transform = CGAffineTransform(scaleX: 1.5, y: 1.5)
                self.layer3.transform = CGAffineTransform(scaleX: 2, y: 2)
        }, completion: { finished in

        })
    }

when an image called layer0 is long pressed, then firstAnimation() is being stopped by this code:
layer2.layer.removeAllAnimations()
layer3.layer.removeAllAnimations()

and different animation is being applied to layer2 and layer3.
the second animation is
func secondAnimation() {
        UIView.animate(withDuration: 20, delay: 0, options:
            UIViewAnimationOptions.curveEaseOut , animations: {

                self.layer2.transform = CGAffineTransform(scaleX: 10, y: 10)
                self.layer3.transform = CGAffineTransform(scaleX: 10, y: 10)

        }, completion: { finished in

        })
    }

when I want to delete the second animation and launch the first one again, the 2 images layer2 and layer3 are starting from the size that they gained because of the second animation. how to relaunch the first animation with the initial sizes of the images?
Answer: You can reset views that were transformed to their original scale by using CGAffineTransform.identity.
For example:
layer2.transform = .identity

Comment: A perfect solution. Thank u.

Resize image to its initial size


Prevent from unauthenticated user to access page ASP.Net MVC

Question: In my ASP.Net MVC web application any unauthenticated and anonymous user can type a URL ( for example localhost:16621/Controller/Index/1 ) and access that page. How can I prevent from this???
Answer: In ASP.NET MVC, use the AuthorizeAttribute. But you'll probably need a user system that uses a database or authenticates against Google/Facebook using Oauth.
Comment: While I agree with the answer, I didn't get the reason behind using google/facebook (oauth) esp when it is a localhost. Note that there is nothing wrong with your answer.
Comment: @shahkalpesh If you can get over the privacy stuff, using Google/Facebook/[put other Oauth provider here] they can remove a lot of the overhead with user management since the end user won't have yet another account on a website. Also you don't have to roll your own login/logout system, change password, confirm email address, password hashing, etc. Working on localhost is hard to do with oauth providers but you need to start somewhere. And it only works in semi-public sites that don't need to restrict access to known people.
Comment: got it. It is just that the oauth thing might not be what OP is looking for. Thanks for the explaining.
Answer: Take a look at the [Authorize] attribute.
You can find more details here and here.


Image Enlarge on Hover

Question: Code: https://jsfiddle.net/xakhLafd/
Hello,
I'm trying to have an image enlarge on hover and use an ease transition.  It works, but it seems to bug out sometimes. I tried to fix this by setting:
-webkit-transition-property: height,width;

But to no avail.  Also, I'm trying to understand how the author of this code (I got some of the code from a CSS blog) achieves this. I understand how on hover the image changes its width, but I'm not sure why the author is setting negative top and left values.  I have been trying to edit the width, height, top, and left to get the desired size on hover, but it seems to become skewed - probably because I don't understand what the negative top and left values are doing. Can anyone shine some light on this?  I've read some articles on negative margins, but I don't understand what's being done here.
Here's the code:

.thumbnail{
  width: 100px;
  height: 100px;
}
.thumbnail:hover {
    position:relative;
    top:-50px;
    left:-35px;
    width:500px;
    height:auto;
    display:block;
    z-index:999;
    cursor: pointer;
    -webkit-transition-property: all;
    -webkit-transition-duration: 0.3s;
    -webkit-transition-timing-function: ease;
}

Answer: The top:-50px; left:-35px; rule in CSS is used to keep the image's center-point unchanged after it is enlarged. Otherwise, when image is enlarged, you will feel it is moved to right-bottom side.
However, this is not a good design -- width/height change requires calculating new layout and redraw UI elements on every animation frame, which is very expensive (you can check this SO for difference between repaint and reflow). That's why you feel "it seems to bug out sometimes."
A better way is using transform. Please check the jsfiddle that fix  the issue. The new CSS code is:
.thumbnail{
  width: 100px;
  height: 100px;
  display:block;
  z-index:999;
  cursor: pointer;
  -webkit-transition-property: all;
  -webkit-transition-duration: 0.3s;
  -webkit-transition-timing-function: ease;
}
.thumbnail:hover {
    transform: scale(5);
}

Answer: Here is the fiddle I created that fixes the issue. I got rid of position relative and set the height to auto instead of 100px.
here is the code i did.

 .thumbnail{
    width: 100px;
    height: auto;
    position:relative;
 }
 .thumbnail:hover {
     width:500px;
     height:auto;
     display:block;
     z-index:999;
     cursor: pointer;
     -webkit-transition-property: all;
     -webkit-transition-duration: 0.3s;
     -webkit-transition-timing-function: ease;
}

Sorry forgot to update the fiddle here is the new link.
https://jsfiddle.net/xakhLafd/1/
Comment: Thanks, any explanation on the negative top and left?
Comment: I edited my code cause you probably had position relative there for a reason. I also got rid of the top and left so that it remains where it was how you left it.
Comment: Not seeing your changes
Comment: You won't see any changes. All I did was move the position relative to the .thumbnail class and got rid of the left and right so that it remains in it's inherit position. https://jsfiddle.net/xakhLafd/5/
Answer: If you want something simple, this is code I'm working on atm:
.box img {
    margin: 1rem auto;
    border: 2px solid white;
    cursor: pointer;
    transition: all .5s ease;
}

.box img:hover {
    border-radius: 10px;
    transform: scale(1.5);
}

Image Enlarge on Hover


jquery date value has an invalid format. It must be in YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ] when saving to dajngo?

Question: my jquery code goes like ...
$("#datepicker").on("change",function(){
      selectedFrom = $(this).val();
      fromDateInput.value = selectedFrom;
  });

function ajax_call(data){

    data = {
    'from_input' : fromDateInput.value }
}

my model is ...
class Reservation(models.Model):
    res_from = models.DateTimeField(null=True, blank=True)

then my view goes like ...
def reservationview(request):
    if request.method == 'POST':
        from_input = request.POST.get('from_input')
        Reservation.objects.create(res_from = from_input)

Answer: Your view doesn't know how to recognize the input.  There is a utility in dateutil that can help you convert most date/time formats to a datetime.
from dateutil import parser

def reservationview(request):
    if request.method == 'POST':
        from_input = parser.parse(request.POST.get('from_input'))
        Reservation.objects.create(res_from = from_input)


Using the MS Graph 'findMeetingTimes' endpoint with client credential (/application) flow

Question: So I would like to prevent the usage of delegated user authentication flow but still want to use the findMeetingTimes endpoint. But it doesn't seem available for client credential flow, right?
I simply tried to post on this endpoint:
https://graph.microsoft.com/v1.0/findMeetingTimes

But it seems like it doesn't exist. Wrror response message:
"message": "Resource not found for the segment 'findMeetingTimes'."

Is there any workaround for using it with the application flow?
Answer: According to the documentation findMeetingTimes is not supported for Application permission type
Resources:
findMeetingTimes


How to find unlit points or fence leak points where mobs come from?

Question: I've surrounded a village with a 2-high fence and lit it up with torches, and all was hunky-dory until I heard a zombie trying to tear a door down.
It was just one and I dealt with him quickly, but there was a creeper somewhere in the area of the village too. I placed more torches, made the fence taller near "steps" where one could reach the top with a long jump, and... there was the zombie again the next night.
So, either I must have missed something (I fenced off quite a bit of area - I plan to make the village grow quite a bit) or there's some obscure spawning rule I don't know about. How to solve this?
Answer: Are all the roofs well lit too? The zombies could be spawning on them and then jump/fall off.
Another options is to install a mod that shows you the locations where mobs can spawn.
For example: in Zombe's modpack there is a mod that does just that (all other mods in the pack can be disabled if you want). I've read somewhere that NEI(Not Enough Items) has an option to show the dark spots too.
Comment: Thanks. The zombies were spawning on the tower of the church.
Comment: Is there a 3rd party tool to display that? I don't want to go through the pain of installing mods.
Answer: Here's what I do.  I go through and make a grid of torches.  I generally seperate them with 5 squares.  I think you can adjust them out a bit wider, but that's my preference.
For your fence, go throug, from both sides, and find where you can just jump to make it over the fence.  Whereever you're able to make it with just a jump, and zombie can get through.
Answer: You may have witnessed a Zombie Siege, though a siege usually consists of several zombies.
Zombies can spawn in villages at nights, regardless of light levels or distance to the player. There is no known way to proof a village against a siege without breaking villagers' routines. You can always block all doors with a block of anything, trapping guys inside, or raise doors above ground, but the villagers won't be able to enter them either.
The most risky situation is when you are near the village, but not readily available to save the population - whenever you are within 128 meters of a village at night, they are in danger. Sleeping over nights can help, as the world is not simulated while you sleep, it just jumps to the morning for everyone. You also can not replace wooden doors with iron ones, as a house is a wooden door :)
Comment: Yeah, Zombie Sieges don't bring creeper demolitions support squads.
Comment: You may want to reread the question, or else you may receive downvotes. (Disclaimer: I didn't -1)
Comment: @SevenSidedDie Of course they don't. The OP did write he'd lit up some areas after the creeper signting, so my suggestion is still valid. I am not afraid of being downvoted if my answer is misinformative or lazy, and even less afraid of being downvoted for "omg you didn't read my post or whatever, I have to punish you!!!11!". =)
Comment: If it had been a zombie siege, there would have been more zombies. And the zombies aren't relevant to the question: clearly mobs *in general* are spawning and getting in, and detecting/fixing that is the point of the question. Zombie sieges got nothing to do with it. You're welcome to post irrelevant things I suppose, but it's not helping solve the problem any…


Copy directory from user ubuntu to root aws server

Question: I'm very new to this. I'm trying to copy a directory from user ubuntu to root using this command.
scp -i mykey.pem ~/var/www/dj root@ip:/var/www

and it says
Please login as the user "ubuntu" rather than the user "root".

How can I fix this? Thank you in advance.
Comment: The reply seems to be in plain language. Did you try doing what it said?
Comment: Ah ... so you have these files *on the server already*, and you're just trying to move them over? The command you're using is trying to copy from your local computer to remote ...
Comment: Yes, but it says `scp: /var/www/dj/file: Permission denied` this time.
Comment: Does `/var/www/dj/` exist? In your command above, you have `~/var/www/dj`, which would be `/home/{user}/var/www/dj` ...
Comment: Yes, it does exist. So how can I copy from `~/var/www/dj ` to `/var/www/dj/ ` ? it said Permission denied
Comment: User `ubuntu` probably doesn't have write access to `/var/www` on the server, but probably root login over ssh/scp is disabled (which is a good idea security-wise). Copy the folder temporarily to somewhere in `ubuntu`'s home folder on the server, then ssh into the server (again as ubuntu), and mv the folder with `sudo`.
Answer: In the event the files you want to copy are on the server in the ubuntu user's home directory, you can copy the files to the intended location by using sudo with cp (or mv if you would like to move them). You will need to first connect to the server via SSH.

Connect to the server:
ssh -i mykey.pem ubuntu@ip

Copy the files:
sudo cp ~/var/www/dj /var/www

Note: If you would like to move the file rather than copy them, replace cp with mv.
Set the ownership of the files:
sudo chown -R www-data:www-data /var/www

Set the file permission of the files:
sudo chmod -R 755 /var/www


Infinitescroll plugin not triggered in combination with Isotope

Question: I'm trying to make infinitescroll work together with isotope. I've been through the docs and page sources but cannot find the problem. I do see the first items that are initially on the page, but upon scrolling to the very bottom of the page, nothing happens.
My HTML includes a link to the next page (a paginated blog page):

The JavaScript:
  $("#container").isotope({
    itemSelector: '.item',
    isAnimated: true
  });

  $("#container").infinitescroll({
    navSelector: '#page-nav',    // selector for the paged navigation
    nextSelector: '#page-nav a',  // selector for the NEXT link (to page 2)
    itemSelector: '.item',     // selector for all items you'll retrieve
    debug: true,
    },
    function( newElements ) {
      console.log(newElements);
      $("#container").isotope( 'appended', $( newElements ) );
    }
  );

When viewing my page, the console says:
["determinePath", Array[2]]
 jquery.infinitescroll.min.js:1
["Binding", "bind"] jquery.infinitescroll.min.js:1
["math:", 497, 451] jquery.infinitescroll.min.js:1
["math:", 0, 451] jquery.infinitescroll.min.js:1
["heading into ajax", "/blog/full-blog?page=2"] jquery.infinitescroll.min.js:1
Using HTML via .load() method jquery.infinitescroll.min.js:1
XHR finished loading: "http://localhost:4567/blog/full-blog?page=2". jquery.js:8240
["Error", "end"] jquery.infinitescroll.min.js:1
["Binding", "unbind"]

Can anyone explain me what the last two lines mean? Obviously there is an error, but what does end mean? Are there no more pages to load? In my example I have 3 pages with more items to load. Unbind, is the scroll event unbind? Can't find any docs/info about the error logs...
Answer: The line 'heading into ajax' means an ajax request was fired on reaching the bottom.
'XHR Finished Loading' means the ajax request was successful.
'Error' in the 2nd last line means there was no data returned by the ajax request. Make sure the page you are making request to doesnt return empty result. To check, open '/blog/full-blog?page=2' in the browser.


Why is there cold water when flushing sediment from water heater?

Question: We have a large tank conventional water heater. Electric, two elements. We get hot water from it. It's 113F at the kitchen faucet and we can take showers/etc. It does take quite awhile for the initial hot water to arrive, though (I don't know what normal is in this house, though). The heater is only 2 years old.
I went to flush sediment from the drain at the bottom and the water in my bowl is cold. Like - room temperature. Nowhere near 120. This is after hours of non-use. So it seems that only the top element must be doing the heating - right?
I removed the upper and lower panels and checked the thermostats. Seemed fine but increased both slightly (faucet temp now 124). I get a voltage on the lower panel with the power on.
With the power off, I did a continuity test on the lower heating element and I get a tone so it seems fine. (Is it definitely fine? Is there more to test?)
What else could be wrong? Faulty thermostat or controller for the lower element?
Comment: A few years ago, scientists discovered tank water heaters kept at 120F are breeding grounds for bacteria. Sickenings happen all the time - they just aren't correllated because they are usually isolated/random incidents.  This was discovered because the water changes in Flint, Michigan caused a cluster of them at the same place and time.  Now that it's understood, health experts are recommending 140F in the tank, and thermostatic control valve(s) to prevent scalding at the tap.  A side effect will be more useful hot water, since less hot will be used with more cold.
Answer: Cold water is piped to the bottom of hot water tanks and pushes hot water out at the top.
Whenever water leaves the tank, cold water enters at the bottom.
Depending if the cold pipe is close to the drain is why you get cold/cooler water.
Comment: Do you get hot water?   Does it last?   If so, it's working.   Heat rises into thermal layers....unless you mix it.    Quit futzing with it before you break something.
Comment: @GregSmalter, I don't think the answer is stating that "nothing is wrong with the heater", it is stating a fact: when the drain port is opened with the cold supply also open, cold supply water immediately flows to the bottom of the heater via the inlet dip tube. This could *easily* explain a significant temperature difference.
Comment: So are you saying nothing is wrong with the heater? Also how could the water in the bottom be like 60 degrees colder than the target temperature even if we haven't been home for 3 hours?
Answer: To add to the answer by crip659, if the final temperature is as desired then it is not the hot water cylinder.  It has minimal say in the water flow.  The things affecting the flow/lag are

Water Pressure
Diameter of the delivery pipe
Distance from the tank.
Temperature of water in the cylinder.

Buzzing the elements is not enough, you need to measure their impedance (resistance).
For a 3KW element the resistance would be about 16 ohms at 220V or 4 ohms at 110V
Adding for completeness.  It is normal for the hot water to be on the top, which is why you take off hot water from the top. And by default, at least the bottom third of the tank would be cold.

To increase the amount of hot water in the tank, you can lower the thermostat.  For a two-element/thermostat, the outcome is more complex to predict. I suspect it will turn off the top thermostat earlier and lower the water temperature.
To increase the temperature of the hot water, you can increase the thermostat setting.  This would also increase the amount of hot water in the tank, slightly.  Caution - I have been told by plumbers that increasing the temperature too much can cause an early failure of the tank.  There may be a spec on the tank - I am not sure as I have had custom tanks built for myself for the last 25 years.
Comment: I tested the resistance and got 12.5 ohms. I also lowered the bottom thermostat closer to its original position and the tested the sink 4 hours later and the temperature was lower, proving the lower element is doing something.
Comment: I am not sure of the dynamics of 2 elements and 2 thermostats, it would be a lot more complicated.  For a single one, lowering the thermostat would increase the amount of hot water in the tank.  It will not raise its temperature.


Objective C: Multiple Downloads

Question: I am trying to make an app that downloads a pdf file from an online server.
What I did was I created 3 buttons that has 3 different URLs and save it to the app's sandbox and open it in iBooks.
But it crashes the app and I am having this error saying...
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -[NSURL initFileURLWithPath:]: nil string parameter' ***

Here's my code:
On Button Click:
     if (sender.tag == 1) {
        pdfTag = 1;
        pdfSource1 = @"http://myweb.com/folder/folderagain/file1.pdf";
        NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:pdfSource1]];
        NSURLConnection *conn = [[NSURLConnection alloc] init];
        (void)[conn initWithRequest:request delegate:self];

        dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0ul);
        dispatch_async(queue, ^{
            dataSource1 = [NSData dataWithContentsOfURL:[NSURL URLWithString:pdfSource1]];
            dispatch_sync(dispatch_get_main_queue(), ^{
            });
            pdfSourcePath1 = [[self applicationDocumentsDirectory] stringByAppendingPathComponent:@"myPDF1.pdf"];
            NSLog(@"PDF path: %@",pdfSourcePath1);
            [dataSource1 writeToFile:pdfSourcePath1 atomically:YES];
        });

    } else if (sender.tag == 2) {
        pdfTag = 2;
        pdfSource2 = @"http://myweb.com/folder/folderagain/file2.pdf";
        NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:pdfSource2]];
        NSURLConnection *conn = [[NSURLConnection alloc] init];
        (void)[conn initWithRequest:request delegate:self];

        dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0ul);
        dispatch_async(queue, ^{
            dataSource2 = [NSData dataWithContentsOfURL:[NSURL URLWithString:pdfSource2]];
            dispatch_sync(dispatch_get_main_queue(), ^{
            });
            pdfSourcePath2 = [[self applicationDocumentsDirectory] stringByAppendingPathComponent:@"myPDF2.pdf"];
            NSLog(@"PDF path: %@",pdfSourcePath2);
            [dataSource2 writeToFile:pdfSourcePath2 atomically:YES];
        });
    } else if (sender.tag == 3) {
        pdfTag = 3;
        pdfSource3 = @"http://myweb.com/folder/folderagain/file3.pdf";
        NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:pdfSource3]];
        NSURLConnection *conn = [[NSURLConnection alloc] init];
        (void)[conn initWithRequest:request delegate:self];

        dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0ul);
        dispatch_async(queue, ^{
            dataSource3 = [NSData dataWithContentsOfURL:[NSURL URLWithString:pdfSource3]];
            dispatch_sync(dispatch_get_main_queue(), ^{
            });
            pdfSourcePath3 = [[self applicationDocumentsDirectory] stringByAppendingPathComponent:@"myPDF3.pdf"];
            NSLog(@"PDF path: %@",pdfSourcePath3);
            [dataSource3 writeToFile:pdfSourcePath3 atomically:YES];
        });
    }

For opening the file:
     if (pdfTag == 1) {
     NSURL *url = [NSURL fileURLWithPath:pdfSourcePath1];
     docController1 = [UIDocumentInteractionController interactionControllerWithURL:url];

     docController1.delegate = self;

     [docController1 presentOpenInMenuFromRect:btn1.frame inView:self.view animated:YES];
    } else if (pdfTag == 2) {
        NSURL *url = [NSURL fileURLWithPath:pdfSourcePath2];
        docController2 = [UIDocumentInteractionController interactionControllerWithURL:url];

        docController2.delegate = self;

        [docController2 presentOpenInMenuFromRect:btn2.frame inView:self.view animated:YES];
    } else if (pdfTag == 3) {
        NSURL *url = [NSURL fileURLWithPath:pdfSourcePath3];
        docController2 = [UIDocumentInteractionController interactionControllerWithURL:url];

        docController2.delegate = self;

        [docController2 presentOpenInMenuFromRect:btn3.frame inView:self.view animated:YES];
    }

I hope I could find answer.
Comment: According to me `pdfSourcePath1, pdfSourcePath2, pdfSourcePath3` are `nil`. Open file method is getting called before the pdf source path are set inside block code. Try placing debug points.
Comment: Does the error occur on trying to open the file or on download?  Can you log the pdfSourcePath1,2,3 before you build the NSURL for opening.  Finally, your use of GCD directly to do the requests is strange and tough to read.  Look up NSURLConnection sendAsynchronousRequest:....
Comment: @Deepesh my code for opening file is inside connectionDidFinishLoading:(NSURLConnection *)connection
Comment: @danh the error occurs after the download, it should first present a popover that I will open the file in another app (which is iBooks) but it crashes.
Answer: In your code i could not able to see the API initFileURLWithPath  you used anywhere..
Just below is my suggestion for your task,
The below is the code to get the remote Pdf as a NSData using the server file path and store in application sandbox.
     NSData *pdfData = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:bookUrlString]];
     NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
     NSString *documentsDirectory = [paths objectAtIndex:0];
     NSString *filePath = [documentsDirectory stringByAppendingPathComponent:@"myPDF.pdf"];
     [pdfData writeToFile:filePath atomically:YES

As per my understanding for this purpose, this doesn't require any NSURLRequest  or NSURLConnection...
Comment: The code is using both NSURLRequest and NSURLConnection indirectly by using initWithContentsOfURL (which is probably ill-advised).  If the OP intends to release the app, an asynch request should almost certainly be used to fetch a pdf from a web service.
Answer: Networking is a complex task, I will never suggest you to download or upload a file using the -initWithURL method, since is not asynchronous and will block the main thread. You should go with NSURLConnection class and its delegate methods, or the amazing class method that accept just a queue and a completion block. You are doing weird stuff you use NSURLConnection but you use a ..WithURL method, you should go with one one them.
There are different download managers on the web that could help you in whole process, since they wrap the NSURLConnection class and delegate methods.
There is:

AFNetworking link
MKNetworking (my favorite)link
Answer: NSData dataWithContentsOfURL works well as long as the size of the file is small.
I won't suggest you to download large file using this method, instead use NSURLConnection or  AFNetworking.
How to use NSURLConnection and  AFNetworking to download a file are explained in the following answer:
https://stackoverflow.com/a/16454923/2548707
Comment: `dataWithContentsOfURL:` should _never_ be used for retrieving information across the network, regardless of the amount. It blocks the thread; any network problems have a high chance of stalling your application.
Comment: @JoshCaswell that's true.

Objective C: Multiple Downloads


Removing bathroom faucet aerator

Question: When I turn this bathroom faucet on and off, the water flow is somewhat irregular so I tried looking at the aerator to see if it needs cleaning:

What kind of aerator is this and how do I remove it?
It doesn't look like any of the aerators that I can find by searching the web. I'm not sure what manufacturer made this faucet as it has no labels on it. I tried to put a screwdriver in there and turning but was not able to make it move. Do I need a tool specifically for this aerator?
Viewed from above:
Comment: If you don't have a special adjustable  "spanner" wrench I'd insert needle nose pliers into holes in the plastic and turn. You could make a spanner with a liece of wood and two nails protruding from it the right distance apart to fit into holes in the plastic grille. You might be able to slip two nails into the grille and then clamp them in the jaws of needle nose locking pliers
Comment: that only shows the end-on view ... please add a side view
Comment: @jsotola I've added another picture. It's completely smooth, there's no part of the faucet that can be taken apart.
Comment: shine a light inside the end of the tap ... there may be a screw
Comment: @jsotola Good idea! Unfortunately no luck, there doesn't seem to be anything behind the white plastic.
Answer: I'm still not sure what kind of aerator this is but I was able to remove it.
After keeping the tip of the faucet soaked in a small bag of vinegar for a couple of hours, I was able to turn the aerator with a screwdriver but it didn't really feel like it was coming out. The plastic was also brittle and started breaking apart when I tried turning it, so eventually it came out when it broke apart. It looks like this is simply a plug since there appears to be no threading in the faucet.

I'm going to have to see if I can find some kind of replacement for this that will fit in an unthreaded faucet.
Comment: Thanks for posting your solution. Please give yourself a check-mark so others know this one is resolved.
Comment: @FreeMan I've marked it as checked although I don't think the answer I posted really answered the original question well. I haven't been able to find a replacement aerator yet.
Comment: Well, the question was "how do I remove the aerator", not "where do I find a replacement". ;) Thanks!
Comment: Sure. Well if you read the question in it's entirety it's actually about what kind of aerator it is and what tool is required to remove it. Perhaps the title should have been more clear about this. I didn't exactly figure out what tool to use to remove it either since it broke apart when I tried the suggestion given in the comments. Technically I was able to remove it but I think it was clear from the context that I was looking for a method or tool that would not break it.

Removing bathroom faucet aerator


SQL query to filter data by a specific column value with no deduplication

Question: I have a table in a clickhouse database that keeps track of items and their statuses. There can be multiple records with the same name. Each time a record is ingested it is given a status of either 0 or 1. A simplified version of the data  as follows:

name
status

Obi
0

Obi
0

Harold
0

Harold
1

Ann
0

Ann
1

Lily
0

Lily
0

Lily
0

Ron
0

Ron
1

I only want to display the records that have never been given a status of 1, with no de-duplication. The values returned should be:

name
status

Obi
0

Obi
0

Lily
0

Lily
0

Lily
0

What should the query look like in order to accomplish this?
I have tried something like this, but it returns every record that has ever had a status of 0.
SELECT t.*
FROM example_table t
INNER JOIN
(
    SELECT Name
    FROM example_table
    GROUP BY Name
) t2 ON t.Name = t2.Name
WHERE t.findingStatus=0

I have tried variations of the above query but have not had any luck. I was thinking maybe an inner join where the left table has status=0 and the right table where status has never been 0. Not sure how to get that to work. Any help on this is much appreciated. Thanks!
Answer: Try this query:
SELECT *
FROM example_table
WHERE name NOT IN
(
    SELECT name
    FROM example_table
    GROUP BY name
    HAVING countIf(status != 0) > 0
)


Is there a custom way for implementing an object clone function?

Question: I am currently using something like this:
class MyClass:
    def __init__(self, myVar):
        self.myVar = myVar
    def clone(self):
        return MyClass(self.myVar)

Is there a more custom (standard) way of doing this in Python, perhaps by overriding operator __new__ or something of that sort?
I'd rather this function to be an instance function and not a class (static) function, but I'd be happy to hear any suggestion.
Thanks for helping out.
Comment: @Cardstdani: The goal is to return `x.clone()` from a function, in order to avoid the caller function being able to change the contents of `x`.
Comment: Please add more details about the goal of your code.
Answer: A standardised way of doing this in Python is for the caller to call copy.copy(obj) or copy.deepcopy(obj).
Documentation at docs.python.org
As standard, copy() will result in the copied object having references to the same objects that the original did.  deepcopy() will result in the copied object having references to copies of those objects.
To illustrate:
class Example:
    def __init__(self, vals):
        self.vals = vals

import copy
orig = Example([1, 2, 3])
shallow = copy.copy(orig)
deep = copy.deepcopy(orig)
orig.vals.append('surprise')

print(f'orig.vals: {orig.vals}')
print(f'shallow.vals: {shallow.vals}')
print(f'deep.vals: {deep.vals}')

results in:
orig.vals: [1, 2, 3, 'surprise']
shallow.vals: [1, 2, 3, 'surprise']
deep.vals: [1, 2, 3]

Note the difference between the shallow and the deep copy.  shallow.vals still pointed to the list in orig.vals, whereas deep.vals was an independent copy of that list.
Now, for your example class, this is all that is needed: you don't need to add a special method to your class.  But if you wanted cloning behaviour that was more custom, you could implement the __copy__ and/or __deepcopy__ methods in your class.