Multiple selection in a gallery picker

Question: In one of my mobile apps there is an option to edit multiple photos at once.
At the initial screen, the users are presented with a picker view with all of their photos from the gallery. From testing I have made, I found out that people don't actually understand that the picker is a "multiple selection" picker; most of them think it's "single selection".
To try and solve this, I have added a mechanism to preview the users with the already selected photos, but still there is a UX gap that I can't figure out. Here is a illustration of the correct behavior:
Preview of the correct Behaviour
How can I make the multiple selection more obvious for the users?
Answer: Add signifiers to the photos to provide a clue for users, test it and measure the success rate, see the picture:

People need some way of understanding the product or service, some sign of what it is for, what is happening, and what the alternative actions are. People search for clues, for any sign that might help them cope and understand. It is the sign that is importance, anything that might signify meaningful information. Designers need to provide these clues.

Excerpt from Signifiers, not affordances by Don Norman
This is very unobtrusive way to convey multiple selection is possible.
P.S. You can also eliminate the row holding selected images on the top of the screen. Test if check/uncheck interaction is understandable for users.
Comment: Hey Alex! Thank you for responding. That's actually very useful. I had another idea. Let me know what you think. Instead of showing a "disabled" selected state on each photo (which clutters the UI a bit). How about when ever use select a photo, instead of a "tick selected" image, we will show up a number (I.E 1,2,3,4), as the user keep selecting. So when he selects the first photo, it'll have a (1) marked with purple/white colors, and so on. This way we avoid appending a UI element for each of the photos. What do you think?
Comment: @RoiMulia, actually these are not disabled, it's just quick draw. Use non-selected state instead. While your idea is quite good in terms of clue, visualizing the controls for each photo is much strong and straightforward  way to convey the idea of select/unselect interaction. And consistent one! Anyway try the options and choose one which works better. And please, share the result of the testing ). PS. I've updated the image.
Comment: Perfect. Merging both of those will give the best results, I.E : Using your style for "none selected", and when the users selects a photo, using the numeric selection. I think it'll give the desired results. Thank you! :)

Multiple selection in a gallery picker


How can I find the square footage of an irregular driveway?

Question: I need to know the square footage of a long, curving private road with two irregularly shaped adjoining driveways.  I've printed out a bird's eye view of the property with Google, used the exact known dimensions of a house in the photo to establish the scale, then made measurements as best I can on the photo, which indicates the road total is about 6,000 square feet (the red box is about 235' wide and 300' tall):

Is some kind of online tool available that will give me a more accurate estimate?  For example, by outlining a region the tool will tell me the area?  Even a "pixel painting" program that lets me do a flood-fill then tells me the number of pixels used would work.
Answer: Approximately 9,800 square feet, assuming your drawing is accurate. I hastily colored in the image using MS Paint (not perfect, since JPG compression added a bunch of fuzzy grayscale values).
Then using MATLAB with the image processing toolbox:
<code>width = 235; % establish scale parameters
height = 300;
img = imread('areatest.jpg'); % read image in
bwImg = im2bw(img,0.5); % convert from JPG to binary BW
% find black pixels, divide by total image area,
% and scale to square footage depicted in drawing:
dwArea = sum(sum(~bwImg))/numel(bwImg)*width*height;
</code>
You may be able to work this online, with the compile online website. However, I'm not sure if it can read in files from your hard drive.
Comment: Ha just made a comment about the grey scale edges.
Answer: Using the histogram function in photoshop your white inside area is about 11% of the picture and if you include your black outline 12-13%.  You can do the math from there.
Comment: The 13% is fairly close to my answer - comes out to 9,165 sq. ft. Good to know there's another option cheaper than $3000/seat.
Comment: @Doresoom - Yea I said 12-13 and maybe even a tad over 13 actually because of the edges of the line aren't actually "black" and I might not have selected them.  Well I am sure I didn't because I spent like 1 minute on it.  I don't think I would get to 9800 but might be really close.
Comment: Similarly, you can use the histogram function in GIMP.


My tcp client using spring integration not able to get response

Question: I have created tcp client using spring integration I am able to receive  response for my send message . But when I uses  localDateTime.now() to log time I am not able to receive the response of send message . I know this can be solved using time setting to make thread wait. As I am new to spring integration So kindly help me how to do it.
@Configuration
@ComponentScan
@EnableAutoConfiguration
public class Test
{

    protected final Log logger = LogFactory.getLog(this.getClass());

    // **************** Client **********************************************
    @Bean
    public MessageChannel replyChannel()
    {
        return new DirectChannel();
    }

    @Bean
    public MessageChannel sendChannel()
    {
        MessageChannel directChannel = new DirectChannel();
        return directChannel;
    }

    @EnableIntegration
    @IntegrationComponentScan
    @Configuration
    public static class config
    {
        @MessagingGateway(defaultRequestChannel = "sendChannel", defaultReplyChannel = "replyChannel")
        public interface Gateway
        {

            String Send(String in);

        }
    }

    @Bean
    AbstractClientConnectionFactory tcpNetClientConnectionFactory()
    {
        AbstractClientConnectionFactory tcpNetClientConnectionFactory = new TcpNetClientConnectionFactory("localhost",
                9999);
        tcpNetClientConnectionFactory.setSerializer(new UCCXImprovedSerializer());
        tcpNetClientConnectionFactory.setDeserializer(new UCCXImprovedSerializer());
        tcpNetClientConnectionFactory.setSingleUse(true);

        tcpNetClientConnectionFactory.setMapper(new TcpMessageMapper());
        return tcpNetClientConnectionFactory;
    }

    @Bean
    @ServiceActivator(inputChannel = "sendChannel")
    TcpOutboundGateway tcpOutboundGateway()
    {
        TcpOutboundGateway tcpOutboundGateway = new TcpOutboundGateway();
        tcpOutboundGateway.setConnectionFactory(tcpNetClientConnectionFactory());
        tcpOutboundGateway.setReplyChannel(replyChannel());
        return tcpOutboundGateway;
    }

    public static void main(String args[])
    {
        // new LegaServer();
        ConfigurableApplicationContext applicationContext = SpringApplication.run(Test.class, args);
        String temp = applicationContext.getBean(Gateway.class).Send("kksingh");
        System.out.println(LocalDateTime.now()+"output" + temp);

        applicationContext.stop();

    }
}

My custom serialzer and deserialser UCCXImprovedSerializerclass
after updating as per @Garry
 public class UCCXImprovedSerializer implements Serializer<String>, Deserializer<String>
{
     @Override
    public String deserialize(InputStream initialStream) throws IOException
    {

        System.out.println("deserialzier called");
        StringBuilder sb = new StringBuilder();
        try (BufferedReader rdr = new BufferedReader(new InputStreamReader(initialStream)))
        {
            for (int c; (c = rdr.read()) != -1;)
            {
                sb.append((char) c);

            }
        }
        return sb.toString();
    }

    @Override
    public void serialize(String msg, OutputStream os) throws IOException
    {
        System.out.println(msg + "---serialize---" + Thread.currentThread().getName() + "");
        os.write(msg.getBytes());
    }
   }

My server at port 9999 code
   try
        {
            clientSocket = echoServer.accept();
            System.out.println("client connection established..");
            is = new DataInputStream(clientSocket.getInputStream());
            os = new PrintStream(clientSocket.getOutputStream());
            String tempString = "kksingh";
            byte[] tempStringByte = tempString.getBytes();
            byte[] temp = new byte[tempString.getBytes().length];
            while (true)
            {
                is.read(temp);
                System.out.println(new String(temp) + "--received msg is--- " + LocalDateTime.now());
                System.out.println(LocalDateTime.now() + "sending value");
                os.write(tempStringByte);
                break;
            }
        } catch (IOException e)
        {
            System.out.println(e);
        }
    }

My log file for tcp client
2017-06-04 23:10:14.771  INFO 15568 --- [           main] o.s.i.endpoint.EventDrivenConsumer       : started org.springframework.integration.endpoint.EventDrivenConsumer@1f12e153
kksingh---serialize---main
pool-1-thread-1---deserialize----
pool-1-thread-1---deserialize----
pool-1-thread-1---deserialize----
pool-1-thread-1---deserialize----
2017-06-04 23:10:14.812 ERROR 15568 --- [pool-1-thread-1] o.s.i.ip.tcp.TcpOutboundGateway          : Cannot correlate response - no pending reply for localhost:9999:57622:bc98ee29-8957-47bd-bd8a-f734c3ec3f9d
2017-06-04T23:10:14.809output
2017-06-04 23:10:14.821  INFO 15568 --- [           main] o.s.c.support.DefaultLifecycleProcessor  : Stopping beans in phase 0

My log file for server side
client connection established..
kksingh--received msg is--- 2017-06-04T23:10:14.899
2017-06-04T23:10:14.899sending value

when I removed the localdatetime.now() from server and tcpclient  I am able to get response as outputkksingh
o.s.i.endpoint.EventDrivenConsumer       : Adding {logging-channel-adapter:_org.springframework.integration.errorLogger} as a subscriber to the 'errorChannel' channel
2017-06-05 12:46:32.494  INFO 29076 --- [           main] o.s.i.channel.PublishSubscribeChannel    : Channel 'application.errorChannel' has 1 subscriber(s).
2017-06-05 12:46:32.495  INFO 29076 --- [           main] o.s.i.endpoint.EventDrivenConsumer       : started _org.springframework.integration.errorLogger
2017-06-05 12:46:32.746  INFO 29076 --- [           main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8080 (http)
2017-06-05 12:46:32.753  INFO 29076 --- [           main] o.s.i.samples.tcpclientserver.Test       : Started Test in 2.422 seconds (JVM running for 2.716)
2017-06-05 12:46:32.761  INFO 29076 --- [           main] o.s.i.endpoint.EventDrivenConsumer       : Adding {bridge:null} as a subscriber to the 'replyChannel' channel
2017-06-05 12:46:32.762  INFO 29076 --- [           main] o.s.integration.channel.DirectChannel    : Channel 'application.replyChannel' has 1 subscriber(s).
2017-06-05 12:46:32.763  INFO 29076 --- [           main] o.s.i.endpoint.EventDrivenConsumer       : started org.springframework.integration.endpoint.EventDrivenConsumer@1f12e153
kksingh---serialize---main
pool-1-thread-1---deserialize----kksingh
outputkksingh
2017-06-05 12:46:32.837  INFO 29076 --- [           main] o.s.c.support.DefaultLifecycleProcessor  : Stopping beans in phase 0
2017-06-05 12:46:32.839  INFO 29076 --- [           main] o.s.i.endpoint.EventDrivenConsumer       : Removing {bridge:null} as a subscriber to the 'replyChannel' channel
2017-06-05 12:46:32.839  INFO 29076 --- [

Answer: Your deserializer is deserializing multiple packets...
pool-1-thread-1---deserialize----
pool-1-thread-1---deserialize----
pool-1-thread-1---deserialize----
pool-1-thread-1---deserialize----

Which produces 4 reply messsages; the gateway can only handle one reply which is why you see that ERROR message.
You deserializer needs to be smarter than just capturing "available" bytes. You need something in the message to indicate the end of the data (or close the socket to indicate the end).
Comment: In my use case Message not have any character at the end to mark the stream end . So I closed the socket.But I am still getting same thing.Please if you can give example how I can make my deserializer  smatter .
Comment: Garry when i removed the localdatetime.now() from server and client .then I am able to see the response on my client side . logs are updated in the post
Comment: It might affect the timing - you can't assume all the data will arrive in one read - you have to keep reading until `-1` is received (indicating the end of the stream).
Comment: @Garry I have another concern related to the same. If my server maintain the session.Then I want my client not to close the connection after receiving the reply from the server.Or should not start a new connection after for sending  new message to server.
If u can suggest  the configuration changes or provide the link for the same
Comment: `tcpNetClientConnectionFactory.setSingleUse(false);`, but you will need logic in the deserializer to know what the end of each message is.
Comment: ok garry but I have a concern that sometimes i don't receive the -1 unit in input stream instead I get the socket close exception.It will be great if you can suggest any  work around this .
Comment: Garry I also  have raised consequent  question kindly suggest approach
https://stackoverflow.com/questions/44551952/how-to-make-tcp-client-which-send-request-and-receive-response-also-accepts-the
Comment: If you get an exception, it probably means the server reset the connection (abnormal close).


Mongoose find elements with value in subdocuments

Question: My models
ActivityLanguage
language_id: ID
name: String

Activity
price: Int
languages: [ActivityLanguage]

what i want to do is to find the Activities that have an ActivityLanguage with certain language_id.
This works like i need (in mongo):
db.activities.find({"languages.language_id": "59640de1675c1481820a543e" }, {"languages.$": 1})

How can i achieve it in mongoose?
I already tried using:
Activity.find({'languages.language_id': language_id})

and
Activity.find({"languages": {$elemMatch: { language_id: language_id }}})

both of them return an empty array (i already triple checked my database that there are Activities with that condition). I also tried all the answers i found here in StackOverflow without success
How can i achieve it in mongoose?
Answer: You can use Mongoose model.populate
From your example:
Activity.
  find({}).
  populate({
    path: 'languages',
    model: 'ActivityLanguage',
    match: { language_id: ID }  //here you define your language_id criteria
  }).
  exec()

Comment: Thank you for the answer, but it didn't worked. after many hours trying, i couldn't solve the error that appeared from your solution: "cast to objectid failed for value [ActivityLanguage stringified] at path _id for model ActivityLanguage"
Comment: Try using  `findOne` or `findById`, they are not working the same as `find` or try to use some crieriria in find. Maybe its because you recieving multiple documents. Also if you are using Mongoose you have to define a schema for your model. Have you done that?


(Argument list too long) While opening a large list of files using *cat*

Question: I'm trying to do something like
cat */httprobe-subdomains.out | xargs -n1 -I{} -t sh -c 'curl -k -i --write-out "\n++++++++++\nResponse Code: %{response_code}\nRedirection URL: %{redirect_url}\nContent Size: %{size_download}" "http://{}" -L >> response/http-{}.out '

The response is
-bash: /usr/bin/cat: Argument list too long

If I tried to cat */httprobe-subdomains.out the stderr will be the same -bash: /usr/bin/cat: Argument list too long
I wish I had a way to escape this situation and be able to cat all httprobe-subdomains.out files in * folders and give it to xargs to deal with.
Answer: The Argument list too long error is documented in errno(3) (as E2BIG) and related to some execve(2) system call done by your GNU bash shell. Use sysconf(3) with ARG_MAX to query that limit.
You have several approaches:

recompile your Linux kernel to raise that limit.
write some small C program using appropriate syscalls(2) more appropriately, or write some Python script, or some GNU guile script, ... doing the same
increase some limits, but using setrlimit(2) appropriately (perhaps using the shell ulimit builtin).

See also the documentation and the source code of GNU bash
Comment: These suggestions are quite impractical compared to the solutions in the linked duplicate such as using `find`.  And I don't think that adjusting any of the rlimits will help at all.
Comment: The question has a simple solution. Recompiling the kernel, or writing C code, is an over-complicated solution, which would increase, but *not* remove, the upper limit.
Comment: Why the downvotes?
Comment: Several years ago I did recompile my Linux kernel to raise these limits. In practice it helped a big lot
Comment: Thank you for your detailed answer


Remove audio from video

Question: I pick a movie with the image picker . The problem is that i don't know how to remove the audio from the asset . Any idea?
This is the code that i am using to retrieve the movie :
<code>- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {

    NSURL *url =  [info objectForKey:UIImagePickerControllerMediaURL];
    if ([[NSFileManager defaultManager]fileExistsAtPath:movie.id]) {
        [[NSFileManager defaultManager]removeItemAtPath:movie.id error:nil];
        [[NSFileManager defaultManager]removeItemAtPath:movie.convertedID error:nil];
    }
    movie.convertedID=nil;

    [self dismissModalViewControllerAnimated:YES];
    dispatch_async(dispatch_get_main_queue(), ^{
        [self saveNewMovieAt:url];
    });

}
</code>
Comment: did you get any solution so far
Comment: http://stackoverflow.com/questions/33100284/ios-remove-audio-from-video
Answer: better way to Mute MPMoviePlayerController while playing instaed of trying to remove the audio from the asset  :)
As per my knowledge, there is no other way to do it..
<code>[[MPMusicPlayerController applicationMusicPlayer] setVolume:0];

                          or

        [myMPMoviePlayerController setVolume:0];
</code>
Comment: this will not work since i am applying some filters on the movie . Also the user can increase the volume .

Remove audio from video


Opening image file in jsp file useing href

Question: hi i am trying to open the image file in jsp page with this code
abc

but due to some problem this code not working .
when i try this in html page this is working properly . what may the problem ??
is that any other way.
I am new with jsp .
Answer: This is because the browser doesn't allow you to access client files when you are using the http protocol (see more on Same origin policy).  For example:
If you have a browser open with URL http(s)://..... then accessing client files using the local file system doesn't work.
But if the browser URL starts with file:///...  then that means that this is a static page located in the users filesystem, and therefore the browser allows to access the file.
Have a look also here
You can display a picture from the local(server's local filesystem) file system using a Servlet.
Comment: sorry about my English , i use file:/// but it's not opening the image.
Comment: of course it doesn't because the jsp runs on the server and you access it using a client. This will never work with a jsp. (Also note that there is a problem in the path of your img tag - use `//` to display a single `/` for file separator)
Answer: JSP pages runs on a local server.
You can't include or use files on your computer outside of this server (not even using full paths like D:\somefile.png).
Try adding this picture to your local server and include it properly.


Can I survive in How to Survive without killing animals?

Question: The previews for How to Survive show the characters killing animals to avoid starvation.  Is it possible to survive without killing any animals, and if so, at how much of a disadvantage does it place me?
Answer: In the story one of the main missions (at around ~30%) demands you to get meat, meat is only available through hunting. So you won't be able to get through the story.
Around the same time there is a side mission where you are asked to create a bag, which is made from animal hide, again obtained through hunting.
Another side mission demands that you get a cooked fish, which you need to fish for, but this is a side mission, not main mission.
Also, there are enemies which are like crabs that attack you (in the story it's after the meat mission). Don't know if that counts as animals, but they are available in both the story and the challenges, so if it counts, you won't be able to do the challenges as well as they will kill you.
Later on in the story and in the challenges there are "zombie deers" and "zombie ostriches" which attack you. Again, not sure if this counts as animals or not.
There might be more missions where animal parts are needed, I haven't finished the game yet.
Comment: For sustenance, there are white plants that can be cooked to avoid living a carnivorous lifestyle. Roots can also be found and eaten.


Wheel scrolling does not work anymore

Question: I did an apt-get update and upgrade today and now the middle wheel on my mouse doesn't scroll in any program. I've tried finding documentation to get it to work again but to no avail. I even tried using gpointing-device-settings and that did not do the trick. I used xev to determine if the wheel is even being registered as a button and it's button 2. I was able to scroll internet browsers and in other programs, but now I get nothing.
I can open links by clicking the wheel button and I can paste, but no scroll function. I am using a Logitech G620 and up until today the mouse has worked fine.
How to solve this?
Comment: Is there anything suspicious in your System Settings in the Mouse settings? Besides, gpointing-device-settings doesn't work with Gtk3 and seems to be dead (I've emailed their dev mailinglist, and the only answer I received was from a guy who quit the team some years ago and had no idea he still was on that list)
Comment: the_Seppi, I haven't seen anything suspcious in my System Settings.  I also checked the Unity Tweak Tool...nothing there.  Thanks for the reply though.  I completely unistalled the gpointing-device-settings program tool
Answer: I had to unplug the Unifying Receiver and plug it back in :)
Comment: Was the rest of the mouse working including left and right click before replugging?
Comment: Yes it did work
Comment: lol. Such a simple solution but worked perfectly.
Comment: 2 years later and it still helped me.
Answer: open a terminal window and type xev.  an event tester window will pop open and you can see if all of your mouse functions are working.
it will show clicks, scrolls, movements, etc.
after testing my mouse, all of a sudden my scrolling started working again...
Answer: I had a similar circumstance where my HP wireless mouse's wheel stopped working after an update.
Disconnecting the receiver and reconnecting it worked for me.

Wheel scrolling does not work anymore


How to prove that $\dim(\ker(T))=0$ if $\dim(V)=\dim(W)$ for $T: V \rightarrow W$

Question: In the textbook about Math for ML, after rank-nullity theorem, author claims without proof, that

If $\dim(V) = \dim(W)$, then the following three-way equivalence holds:
$\Phi$ is injective
$\Phi$ is surjective
$\Phi$ is bijective
since $\mathrm{Im}(\Phi) \subseteq W$.

I dont' understand how to prove it without stating that: $$\dim(\ker(T)) = 0$$
or it could be proven from: $$\dim(V)=\dim(W)$$
Comment: What about the rank theorem?
Answer: The rank-nullity theorem states that
$$\dim(\ker(\Phi ))+\dim(\text {im}(\Phi ))=\dim(V)$$
If $\Phi $ is injective, then $\dim(\ker(\Phi ))=0$,
$$\dim(\text {im}(\Phi ))=\dim(V)=\dim(W)\Rightarrow \text{im}(\Phi)=W$$
which proves $\Phi $ is surjective, thus bijective.
If $\Phi $ is surjective, then
$$\dim(\text {im}(\Phi ))=\dim(W)=\dim(V)$$
which proves $\dim(\ker(\Phi ))=0$, $\Phi $ is injective, thus bijective.
Comment: Maybe I didn't understand statement in the textbook correctly. But I inderstand it as if dim(V) = dim(W), then some consequences are followed, and that I need to prove that mapping is injective in the first palce. Based on your explanation, statement means that if dim(V) = dim(W), then injectivity means surjectivity means bijectivity and vice versa. So I start from some point (injectivity, surjectivity or bijectivity).
Answer: (1 implies 2) If $T$ is injective, then $\dim {\rm Ker} T = 0$. By rank-nullity, $\dim {\rm Im} T = \dim V - \dim {\rm Ker} T = \dim V$. But by hypothesis, $\dim V = \dim W$, so $\dim {\rm Im} T = \dim W$, showing that $T$ is surjective.
(2 implies 3) If $T$ is surjective, then $\dim {\rm Im} T = \dim W$. By rank-nullity, $\dim {\rm Ker} T = \dim V - \dim {\rm Im} T = \dim V - \dim W$. But by hypothesis, $\dim V = \dim W \implies \dim {\rm Ker} T = 0$, showing that $T$ is injective. Since $T$ is at once surjective and injective, $T$ is bijective.
(3 implies 1) By definition.
Answer: Note that $\Phi$ is injective iff $\dim \ker \Phi = 0$ and $\Phi$ is surjective iff $\dim \operatorname{Im} \Phi = \dim W$. Under the assumption $\dim V = \dim W$, we have by rank-nullity:
$$\dim \ker \Phi + \dim \operatorname{Im} \Phi = \dim V = \dim W.$$
Rearranging,
$$\dim \ker \Phi = \dim W - \dim \operatorname{Im} \Phi.$$
So $\dim \ker \Phi = 0$ iff $\dim W - \dim \operatorname{Im} \Phi = 0$. In other words, $\Phi$ is injective iff it is surjective, so once you have one of the conditions you have both, ie $\Phi$ is bijective.


C++: How to create a member 2D-array of size determined at runtime

Question: I've tried to declare an empty pointer to a pointer, assign to it pointer to allocated during construction memory and iterate over it doing the assignment again, but I'm missing something. Also I wonder if it's possible to do this with the std::array. Attaching the code:
// Cell.h

class Cell {
    char contents;
    bool is_free;
};

// Memory.h

#include "Cell.h"
#include <cstddef>

class Memory {
public:
    Memory(std::size_t nlines, std::size_t ncols);
private:
    Cell **cells;
};

// Memory.cpp

#include "Memory.h"

Memory::Memory(std::size_t nlines, std::size_t ncols):
    cells(new Cell[nlines]) // Cannot initialize a member subobject of type 'Cell **' with an rvalue of type 'Cell *'
{
    for (std::size_t i = 0; i < nlines; ++i)
        cells[i] = new Cell[ncols];
}

In addition I need my array to contain Cells with values char contents = '.', bool is_free = true after it is initialized. Which is the best way to do it?
UPD: I've thought of creating a 2D pseudo-array using a single pointer (not a pointer to a pointer) and accessing a cell with i*ncols + j.
Comment: Error message for initializing cells is pretty informative here. You are trying to assign `Cell[nlines]`  (i.e. a 1D array) to something of type `Cells **` (a 2D array). You need to change this line to `cells(new Cell*[nlines])`
Answer:
Also I'm curious if it's possible to do this with the std::array

You can not, the size of an std::array is specified as a template parameter and your array is dynamically sized.
Rather than dealing with raw pointers, you should look at std::vector for dynamically sized arrays:
std::vector<std::vector<Cell>> cells{ncols, std::vector{nlines, Cell{}}};

The key benefit is that you avoid having to manually allocate and manage memory.

UPD: I've thought of creating a 2D pseudo-array using a single pointer (not a pointer to a pointer) and accessing a cell with i*ncols + j.

This is a much better idea, keeping your data in a single flat vector reduces fragmentation.
std::vector<Cell> cells(nlines*ncols, Cell{});

To make access easier, you can wrap this 1D vector in a class which exposes a operator()(std::size_t row, std::size_t col), that does the conversion from (row, col) indices to the location in the 1d array.
Comment: Ah, I misunderstood, in that case, the first is preferable IMO, but this is a matter of style.
Comment: Thanks. Also I've figured that I don't have to iterate over the array and manually assign each cell. So ```new``` in c++ fills the memory with the elements with their default values?
Comment: And is there any difference between initializing default values in class declaration and its constructor?
Comment: Your question is unclear to me, a code snippet would help. If you mean, is there a difference between 1) `Cell cell1;` and 2) `Cell cell2 = Cell{};`, no they produce the same result for your class.
Comment: ```struct Cell { char contents = '.'; bool is_free = true };``` and ```struct Cell { char contents; bool is_free; Cell(char contents = '.', bool is_free = true) :contents(contents), is_free(is_free) { } };```. I have a feeling they're reciprocal, but I've heard that aggregates cannot have initializers, so I'm curious if there're any more differences.
Comment: The first is a redeclaration of the struct with in-class initialised values for the members, not a construction of an object! The second is what you probably want.
Comment: I meant that the first _replaces_ the initial code, not _adds_ to it. Thanks, now I think both version will suit me.
Answer: You need to write
Memory::Memory(std::size_t nlines, std::size_t ncols)
    :cells(new *Cell[nlines])
{
...
}

(Note the Cell * instead of Cell).
std::array is compile-time fixed array size only, so it is not suitable for your purpose.
I would agree to your edit. Do not an array of pointers for matrices, use the flat array approach with indexing i*ncols + j. This former is more difficult to work with and has higher overhead (due to many new calls).
If you are worried about the multiplications overhead, you could make a look-up table for i*ncols. But I doubt that it is worth it.


Android ble RN4020 app not showing the available devices in some mobile brands

Question: Android app developed for ble RN4020 is not detecting the bluetooth in some mobile brands.
It is working fine in Micromax and Asus.
Comment: in which devices ,its not detecting can you name them
Comment: Redmi devices,moto almost most of the devices
Comment: i already done this in moto-G ,its working fine.did your location is ON or not ?
Comment: location is turned off in mobile..
Comment: even after turning the location ON it is scanning and does not find the device
Comment: is your Micromax and Asus has marshmello ?
Comment: no they are not marshmallow
Comment: As of my experience with BLE, it must detect on Redmi as well. So please Install any other BLE app from play store on the phone that does not detecting the ble presence and check is it the issue with phone or your code.
Comment: It prompts me to enable gps location..how do i enable gps location on / off option in android? Like the one prompts us to connect the bluetooth
Answer: If You're working with Android API 23 and up you need a runtime permission in your app. The permission in the AndroidManifest is not enough.
Hope this will help


IF stament return me FALSE when should return TRUE

Question: Question:

    if ("sometext" == "SOMEtext") {
        echo "TRUE";
    } else {
        echo "FALSE";
    }

It is return me FALSE, when I use double equal.
The only diference are the capital leters...
This if should return TRUE ????
Comment: String comparisons are case sensitive.  Your assumption is incorrect.  Check out this question for a solution:  https://stackoverflow.com/questions/5473542/case-insensitive-string-comparison
Comment: `==` will only change the type if the two operands of that operator are not of the same type, but in your case both operands are a string. When comparing the two strings here, the "s" character is a different character than "S", just like it is different to "š" or whatever variant you try. This means that both strings are not equal to each other.
Answer: You can use strtolower("somestring") in order to compare 2 strings without account for case sensitivity


How do I wire Neutral on a AC disconnect box?

Question: I've looked at multiple AC disconnect boxes, though haven't ordered any yet.
On every one I've seen so far, they have a connection for both phases of the 220v, and also a connection that appears to be for Ground.
Where do I connect Neutral? I'm bringing 10-3wG into the quick-disconnect, and haven't yet purchased the air conditioner itself. Do air conditioners even use Neutral?
Do I just tie the two Neutral together with a wirenut, akin to a regular lightswitch?
Comment: Call it neutral. Do not call it common.  Neutral must be kept separate on each and every circuit.  If you have 2 circuits in the same junction box, you must have 2 groups of neutral - they must not all go together!
Comment: You might have a panel where neutrals and grounds go onto the same bar.  That is a weird exception because neutral and ground are supposed to be bonded in that panel. Normally, neutral and ground must be kept separate from each other (and both brought separately).  You never combine them (except as I say, inside the panel with the main breaker).
Comment: @Harper-ReinstateMonica I'm pretty sure I was just confused, and the bar is just for ground, with neutral either being capped off or twisted and capped to the AC neutral if present.
Answer: Yes, you just tie the neutrals together. There are terminals for ground to allow the box to be grounded. The terminals for the hots, of course, are to allow the disconnect.
Just be careful that the wire it is large enough for the wires involved. Also, if the wires are aluminum, you'll need a special connector, as well as anti-ox compound on all of the connectors.
Comment: The 10-3wG is copper. Won't have a clue about the AC side of things until I purchase one about a year from now.
Answer:
How do I wire Neutral on a AC disconnect box?

Read the instructions that come with the box.

I've looked at multiple AC disconnect boxes, though haven't ordered any yet.

Don't, yet.

On every one I've seen so far, they have a connection for both phases of the 220v, and also a connection that appears to be for Ground.

That's typical.

Where do I connect Neutral?

You probably don't. Cap it off.
What did you attach it to in the electric panel???

I'm bringing 10-3wG into the quick-disconnect

All outdoor A/Cs I'm familiar with simply take 2 hots and a ground; 10/2 would have sufficed.

and haven't yet purchased the air conditioner itself. Do air conditioners even use Neutral?

Bingo, pick out your A/C and then do your electrical per the unit's instructions.

Do I just tie the two Neutral together with a wirenut, akin to a regular lightswitch?

The A/C won't have one so just cap off the extra wire inside the disconnect box.
I think you're getting confused with electric dryers and stoves which usually need 120v for the electronics; the heating elements are 240v.

Picture added per comments:
A 240v appliance with 120v electronics will require a plug like this and the appliance internals will be wired to take the power source they require.
Comment: @JaminGrey That's fine, just cap it off inside the disconnect box. Too much wire is better than not enough =). I edited my answer to explain how 240v appliances get 120v to the electronics. Do note that some appliances have 240v electronics so that's why you always need to read the appliance installation manual to find out exactly what you need.
Comment: Thanks! I have already ran 10-3wG, and wired up the common to the circuit breaker box's common bar like normal. I can just cap it off if the AC doesn't use Common. Do electric dryers and stoves get their 120v from their 240v connection, or do I have to add a seperate 120v outlet behind the stove?
Comment: @JaminGrey most appliances that use both 240 and 120V get the 120 from the 240V supply by using one of the two hot legs combined with neutral.  However appliances do exist that require a separate 120V supply from a separate 15A or 20A breaker.  As with the A/C, it helps to know what you're installing.  If you want to prepare a kitchen or laundry room to be highly adaptable to arbitrary future appliances, ask that question!
Answer: The air conditioners I've seen either use hot and neutral if they are 120 volt, or two hots with no neutral if they are 240 volt. Ground always passes through the disconnect, either via a splice or straight through if it's THHN or similar. The two poles in the disconnect thus are either used for the two hots or for hot and neutral.
Comment: Ground generally does not just pass straight through - if the box is metal (most disconnects are) it must attach to the box to ground it. Neutral can pass through.
Comment: I meant that it is not switched. Yes, the box should be grounded.
Answer: The compressor/condenser unit for a traditional "split system" air conditioner in USA pretty much universally runs on 240 volts. It has no need for a neutral. However...
Code requires a 120 volt outlet within 25 feet of the air conditioning compressor to facilitate service of the air conditioning system (such as recovering refrigerant or drawing a vacuum on the system). The outlet must not be downstream of the disconnect for the compressor (ie it must remain live when the disconnect is pulled). Do you already have such an outlet?
If not, look at disconnect solutions that can also accommodate this service outlet. There are a variety of ways of doing it, but in every case, having the neutral in that 10/3 cable is what makes it possible. Some ideas:

A disconnect box that also has a GFCI receptacle and a 20 amp breaker all in one housing
A small subpanel, in which you install a circuit breaker to serve as the disconnect for the compressor and a second circuit breaker to protect the GFCI service outlet

Do note that not all AC compressors can be served with 10 gauge wire on a maximum 30 amp circuit. Some compressors, around 3 tons and up, may require a 40 amp circuit and corresponding (heavier) wire gauge. I haven't encountered any yet, but I have to expect there might be a few with even higher current requirement.
Answer: Dont confuse yourself.
110/120 has neutral spliced together.
220/240 No neutral
If you have a neutral it can be capped off. However
The AC disconnect is considered service equipment. Just like your main load center.
What that means is your house is basically the electric company and the AC disconnect now becomes your service panel. Based on that per the national electric code. The answer is yes. You could have an incoming neutral wire and connect it to the same ground lug bar with in the AC disconnect box. That is, providing that the AC disconnect is fusible.
If the AC box has either old, solid fuses or a breaker, that means that it is fusible. If it has the little handle that you pull out then it is not. that little handle does not automatically trip. It must be pulled out!
Now, as we roll into the 2020 national electric code, and the need for ground, fault interruption. You will be able to connect the neutral to any ground fault, interruption device.
So if you have a 120 system, you just basically splice the neutrals together.
If you have a 240 V system, then the neutral coming in can just be capped off.
If you have a 240 V system and a AC disconnect that is fusible. It is more advisable to connect that neutral wire and bond it to the ground lug along with the ground wire.
In the event of a ground fault on the AC unit. The excess current can now travel along the neutral wire from the AC disconnect box back to the load center. Which is a secondary measure of safety.
Wilhelm
Comment: "It is more advisable to connect that neutral wire and bond it to the ground lug along with the ground wire." Is flat WRONG! Neutral and ground are ONLY to be grounded at the MAIN panel and no place else.


How to interpret symmetrical $2\times2$ matrix geometrically as a composition of simple transformation?

Question: Let's say I have this matrix:
$$A = \left[
\begin{matrix}
  1&3\\
  3&1
\end{matrix}
\right]$$
I only know simple transformation like reflection, rotation, scaling, and shear. Can I interpret matrix $A$ as a composition of these simple transformation? How?
I have tried to imagine the transformation of matrix $A$ and intuitively, it looks some kind of reflection or rotation with some scaling, but I got stuck because it has -2 and 4 scaling, which makes me confused.
Answer: All symmetric matrices (of any dimenstion, not just $2 \times 2$) can be thought of as a rotation followed by a scaling and/or reflection along each coordinate axes followed by the inverse of the first rotation.
In the case of your matrix, the sequence of transormations is

Rotate by $-\pi/4$
Scale in the $x$-axis direction by $4$ and in the $y$-axis direction by $-2$ (ie., scale by $2$ and then reflect)
Rotate back by $\pi/4$.

As a produce of simple matrices, this is
\begin{align*}
\begin{pmatrix}
1 & 3 \\
3 & 1
\end{pmatrix}
&=
\begin{pmatrix}
\cos(\pi/4) & -\sin(\pi/4) \\
\sin(\pi/4) & \cos(\pi/4)
\end{pmatrix}
\begin{pmatrix}
4 & 0 \\
0 & -2
\end{pmatrix}
\begin{pmatrix}
\cos(-\pi/4) & -\sin(-\pi/4) \\
\sin(-\pi/4) & \cos(-\pi/4)
\end{pmatrix} \\
&= \begin{pmatrix}
1/\sqrt{2} & -1/\sqrt{2} \\
1/\sqrt{2} & 1/\sqrt{2}
\end{pmatrix}
\begin{pmatrix}
4 & 0 \\
0 & -2
\end{pmatrix}
\begin{pmatrix}
1/\sqrt{2} & 1/\sqrt{2} \\
-1/\sqrt{2} & 1/\sqrt{2}
\end{pmatrix}.
\end{align*}
If you haven't seen it already, the writing of a symmetric matrix as this kind of product is a very common and important procedure known as finding its eigendecomposition, where the scaling factors are known as the eigenvalues of the matrix.
Answer: The previous answer is great, but I would also suggest to read up a bit on the Singular Value Decomposition (SVD) to answer your question in more generality, but also because SVD is very important in all kinds of applications right now, and understanding it provides intuition for tons of problems.


Should I finish staining my half-stained deck with rain coming?

Question: We were supposed to have two weeks of perfect weather conditions so I started the process of staining my deck, I cleaned it, sanded it and yesterday applied the first coat to half of it.
Now the weather has changed and the forecast is 70% chances of 5mm of rain that are going to fall two days from now and then so far it seems it's going to be intermittent between rain and sunny.
How should I proceed?

Should I apply the first coat on the second half and the second coat on the first half 48 hours before the rain and then leave it until the rainy days are over before applying the second coat on the second half?
Should I apply the second coat on the second half even though it will be the afternoon before the rainy day?
Should I not do anything and leave the recently sanded deck to get wet and then wait for the rainy days to stop?

I must add that it is very possible that after the rainy days the really hot weather might begin.
Please advise.
Answer: We're thinking of staining our four year old deck soon, and my only credentials are that we've thought about this scenario.
If I were you, I would go ahead and apply the first coat to the remainder of your deck, basically ensuring that all surfaces are evenly covered. If it does rain and screw up everything, at least the screw-up will be consistent.
I realize humidity will be an issue, but are you planning on covering the deck while it's raining? Cover it when raining, let it dry up when sunny.
Comment: Don't cover it with anything that will touch it !!!!!  If the satin is not cured, it will stick and you will have a mess.  Rather have water spots and do a second coat than have to deal with peeled stuck coatings.
Comment: What should I use to cover it? And, wouldn't whatever I use might stick to the paint if it hasn't dry completely?
Comment: Yep... you don't want to let the cover touch your deck surface. How about using the railings as supports for the cover; do make sure you stretch the cover taut, though.
Answer: Maybe too late to ask, but, are you using latex or oil based?  If you are using latex, if you can get it on for 4 to 6 hours before a light rain, it will have dried enough to survive without spotting.  Oil based really needs 12 to 24 hours to set up depending on the temp. Curing time is a lot longer, but the skim drying is much faster for latex than oil.  Good Luck!
Comment: Turns out it was latex based and it was very dry when it started raining. Thank you!
Answer: No! Only apply the coats you know will (hopefully) dry before the rain comes.
I put 2 coats on our huge 40x60 deck. My husband was not happy with it and INSISTED a third coat even though I told him rain was in the forecast. I no sooner got things cleaned up when the sky let loose with a torrential downpour. It bubbled and washed ALL 3 coats off. I have never been so frustrated!
Another hint. Don't apply in direct sunlight. The coating thickens and constantly needs stirred. Now I wait for it to dry so I can start again. Because he didn't listen to his wife (which he seldom does) I have an unnecessary and costly job!


How can I improve LOAD DATA performance on large InnoDB tables?

Question: I have this table with more than 7 million rows and I am LOAD DATA LOCAL INFILE'ing more data in the order of 0.5 million rows at a time into it. The first few times were fast, but this addition is taking increasingly long, probably due to indexing overhead:
CREATE TABLE `orthograph_ests` (
  `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  `digest` char(32) NOT NULL,
  `taxid` int(10) unsigned NOT NULL,
  `date` int(10) unsigned DEFAULT NULL,
  `header` varchar(255) NOT NULL,
  `sequence` mediumblob,
  PRIMARY KEY (`id`),
  UNIQUE KEY `digest` (`digest`),
  KEY `taxid` (`taxid`),
  KEY `header` (`header`)
) ENGINE=InnoDB AUTO_INCREMENT=12134266 DEFAULT CHARSET=latin1

I am developing an application that will run on pre-existing databases. I most likely have no control over server variables unless I make changes to them mandatory (which I would prefer not to), so I'm afraid suggestions like these are of limited use.
I have read that minimizing keys on this table will help. However, I need those keys for later queries. I'm guessing that if I drop and re-create them would take very long as well, but I have not tested this. I have also read that especially the UNIQUE constraint makes the insertion slow. The digest column will take SHA256 digests that must be unique, and I can't make sure there is no collision (very unlikely, I know, but possible).
Would partitioning help, as suggested here? Could I improve the indexing, e.g., by limiting the key length on the digest column? Should I change to MyISAM, which supports DISABLE KEYS during transcactions? What else could I do to improve LOAD DATA performance?
Edit:
After the large insertion, this table is used for SELECTs only, no more writes. This large loading is mostly a once-and-done operation, however about 1,000 datasets (of each 0.5M rows) need to be uploaded before this is finished.
I will be using the digest to look up rows, which is why I indexed that column. If there should be a collision, that individual row should not be uploaded.
Putting the sequence blob in an external file system is probably not a viable option since I cannot easily impose file system changes on the users.
Comment: "very unlikely, I know, but possible" It is more likely that your server has random memory bit flips. You don't need to plan for SHA-256 collisions.
Comment: Please clarify some things:  Is this table to be used as a reference table, or will you be doing production transactions that change it?  Will you regularly load a half a megarow of new data into it, or is this loading a once-and-done operation?  What is the purpose of your digest column -- will you be using the digest to look up rows in production? If your digest does experience a hash collision, what is your recovery plan?   Have you considered putting your sequence column (your blob) in an external file system?
Comment: Whatever microoptimization you do, unless you can access server configuration or replace mechanical HDD subsystem with faster one - nothing will help. People usually forget that computers aren't magical unicorns, and apps using relational databases are usually slow because IOPS floor of the data persistence device is being hit instantly.
Answer: This is indeed a large amount of data you are loading, and you should expect it to take many dozens of hours, especially on general purpose shared server hardware. There's very little magic (unless you work at Google or something) that will make this job anything but a big pain in the neck. So have courage.
It's a reference table. That means you should immediately switch to MyISAM and stay there for this table.  You don't need InnoDB's transactional integrity features, but you do need MyISAM to disable indexing during loading and re-enable it afterward.  Re-enabling indexing will take a long time, so be prepared for that.
You should consider using a shorter hash than SHA-256.  SHA-1 (160 bits) is good.  Believe it or not, MD-5 (128 bits) may also serve.  MD-5 has been cracked so it's not suitable for secure content authentication.  But it's still a useful hash. A shorter hash is a better hash from your perspective.
If you can disable indexing MyISAM style, it probably doesn't matter much whether your digest key is unique. But you might consider allowing it to be non-unique to save time.
It's hard to make a suggestion about partitioning without knowing more about your data and your server hardware.  But considering this is a reference database, it seems like it might be wise just to bite the bullet for a couple of weeks and get it loaded.
If you have plenty of server disk space, you might consider loading each half-megarow chunk into its own table, then inserting it into the big table.  That might prove to be a good way to deal with the possibility that you might have to reload the whole thing some day.
On shared server hardware, it might make sense to use smaller chunks than half a megarow.
You might consider making a separate id / digest table.  Then you could load your data without the digests and get it done quickly.  Then you could write yourself a stored procedure or client that would create the digests in batches of a few thousand rows each until they were done.  This only works if the stuff being digested is in your dataset.
Comment: Thanks a lot for your input and valuable suggestions!
Answer: There are essentially two reasons for data loading to be slow:

Write performance in inserting the data itself.
Read performance reading existing data in order to load existing data in order to modify existing pages while adding new data.

The write performance issues can be addressed by primarily reducing durability and reducing logging. That's what many of the suggestions you'll find, such as the following settings: innodb_flush_log_at_trx_commit=0, innodb_doublewrite=0, innodb_support_xa=0. Reducing the amount of data written can be helpful as well, such as by setting log-bin=0. It also is not really acceptable to expect your customers to change these durability related settings in existing production systems, though. Changing them is more suited to one-shot bulk loading on dedicated systems than periodically adding data to existing systems.
Bulk-loading INSERT (with many rows) or LOAD DATA INFILE seek to reduce write throughput requirements by writing more data in a single transaction, thus reducing the number of syncs to the transaction logs. Reducing write throughput or increasing write performance can only help to an extent though.
It can also generally be helpful to sort the data by PRIMARY KEY before loading, in order to reduce the amount of unnecessary page splits when inserting data into the index structures. However that is of limited use when there are multiple secondary keys, since sorting by PRIMARY KEY will necessarily mean that the data is not sorted by at least one secondary key.
The read performance issues are perhaps more interesting, and are frequently the actual performance problem with loading new data into existing tables, especially where secondary keys are present. The best possible thing would be that all of your existing data fits into memory (innodb_buffer_pool_size is large enough) such that paging data in and out of the cache is not necessary during loading. Given you're talking about only a few million rows, this may be feasible.
Comment: Thanks for the input. I don't understand your point about the read performance issues: Do you mean actual I/O read performance? Because I think that my performance problems are related to indexing overhead. About buffering: that might indeed help, but I am using `LOAD DATA`, which, as far as I know, makes no use of buffer pools.
Comment: In InnoDB, the buffer pool is always used. It is the primary mechanism by which data is cached (as pages, not rows). Basically, if the buffer pool is not large enough to hold all of the existing data, when a write needs to modify data that would be on the same page (the key values are near each other) that page must first be loaded into the buffer pool.
Comment: Thanks for the explanation! However, since I have no access to server variables, I'm afraid your suggestions are of limited use in this situation.


JSoup - Select only one listobject

Question: I'm trying to extract some certain data from a website using JSoup and Java. So far I've been successful in what I'm trying to achieve.

Årgång**2009**

I want to extract what is inside the ** in the above HTML. I can do this by using the code that follows in JSoup:
doc.select("ul.beverageFacts li:lt(1) strong");

I'm using the lt(1) because there are several more list items following that I want to omit.
Now to my problem; there's an optional information tab on the site I'm extracting data from, and it also has a class called "beverageFacts". My code will at the moment extract that data too, which I don't want it to do.
The code is further down in the source of the website, and I've tried to use the indexer :lt(1) here aswell, but it wont work.

 Färg Ljusgul färg.

My overall result is that I extract "2009 Ljusgul färg." instead of only "2009". How can I write my code so it will only extract the first part, which it succesfully does, and omits the rest?
EDIT:
I get the same result using:
 doc.select("ul.beverageFacts li:eq(0) strong");

Thanks,
Z
Answer: You are qualifying only one part, whereas you should qualify both. Try this:
doc.select("ul.beverageFacts:eq(0) li:eq(0) strong");

What you are saying is: give me the first list item of each list of beverages. What you need to say instead is: Give me the first item of the first list of beverages.
Comment: Alright, I've tried that now and it makes sense! Though, that returns the wrong list item, and omits the one I am after!

I took pasted the source here: http://pastebin.com/5muzFQ7i

The information I want is on line 308, while the information that gets extracted is on line 435. Shouldn't the first one in the source be of index 0?

Thanks alot for helping me out! =)

JSoup - Select only one listobject


Sapply over list of matrices - knowing index of current element

Question: I am quite new to R and I have found one vector operation frustrating:
I just want to know an index of current element of the list while using sapply, let's say: to print an index, but all my trials do not work, e.g.:
<code>> test <- sapply(my.list.of.matrices,
                 function(x) print(which(my.list.of.matrices == x)))

Error in which(my.list.of.matrices == x) :
  (list) object cannot be coerced to type 'logical'
In addition: Warning message:
  In my.list.of.matrices == x :
  longer object length is not a multiple of shorter object length
</code>
Comment: it would be nice to be able to do this (i.e. a `.INDEX` special variable of some sort), but I think the canonical way to do this is with `mapply()`
Comment: ...or possibly loop over `seq_along(my.list.of.matrices)` instead.
Comment: Why do you need this?
Comment: I want to refer (in the `function(x)`) to the vector of strings, I mean to vector's element which has THAT (the same as element of list) index.
Comment: @joran, I agree -- your approach is simpler (and hence more robust), but I think mine is marginally more expressive.
Comment: I wanted to be "pro-R" and I tried to use vectors where it is only posssible... Possibly, I do exaggerate. Thank you for the answers!
Answer: That's not possible unless you pass an index vector. sapply and lapply just pass the elements. And in that case it becomes a disguised for-loop.


I can't get right url in asp.net

Question: i need your help.
I have an home button (it exactly is ) in masterpage use for all aspx. Pages is my folder name (it containts my aspx webpages) and it has an "Admin" folder inside (it containts my admin page). It works in all of pages except admin page. when I clicked "Home" from admin page I got "The resource cannot be found." error, and the Url in web browser's address bar is "localhost/Pages/Pages/Home"
I don't know why i get two "Pages" in the Url.
help me please
table>

Trang chủ

Sản Phẩm

Điện thoại

Máy tính bảng

Phụ kiện

Giới thiệu

Góp Ý

Đăng nhập

Đăng kí

                    <asp:Label ID="lblUser" runat="server" Font-Bold="True" ForeColor="White"></asp:Label>

                    <asp:HyperLink ID="HyperQuantri" runat="server" Font-Bold="True" ForeColor="White"
                        NavigateUrl="~/HienThi/ThongTin.aspx">Thông tin</asp:HyperLink>

                    <asp:HyperLink ID="HyperThoat" runat="server" Font-Bold="True" ForeColor="White"
                        Visible="False" NavigateUrl="~/HienThi/Thoat.aspx">Thoát</asp:HyperLink>

Comment: Can you please post an example of your markup with the Home button on it?
Answer: It sounds like you may have some relative pathing issues with your links. This gets particularly tricky when you're using master/child pages or template controls in a site where you have various depths of folders.
Since you're using web controls, try renaming your links using the following format:
~/Pages/Admin/Default.aspx

The ~/ directive will tell ASP.Net to build the path of the link from the root of the site, so no matter which page the control resides on, it will generate the proper link.

I can't get right url in asp.net


How can I quickly spam charge attacks?

Question: I have played SF a long time ago and I have always tended to use the "half-moon" type moves. I have always avoided the charge characters, well, because I can't seem to use them properly.
The issue I have is using the moves in quick succession. A good example would be Ryu vs Guile.
With Ryu, I can really spam hadoukens fast.
With Guile, I can do sonic booms at about half the speed of the hadoukens.
Is there a special technique to doing charge moves quickly?
How long do you need to be holding the "charge" direction for?
Comment: +1 Great question, I have the same trouble. Although I find it a bit easier on sticks on ps3, than the old snes controller. Thumb blisters anyone? :)
Answer: There are several ways of doing charges.
Easiest, of course, is to just hold back/down and let it rip after 2 seconds.
The harder way, is to be charging while doing a jump or attack combination and then letting it rip at the end, which is what you are supposed to do with charge type characters, such as guile and blanka.  Do not be ultra defensive!  Keep them guessing with your pokes, and if they make a mistake, combo into it.
While you will never be able to spam as fast as Ryu or Sagat, there is a way to minimize your charge time via buffering, see this video for a good explanation.
Short description for those who can't, or doesn't want to watch the video:
Instead of doing a back-2seconds-forward sonic boom, you do a back-2seconds-forward-back sonic boom, this allows you to be charging for your next sonic boom while your current sonic boom animation kicks off, and using this technique will allow you to add multiple sonic booms into your combos more effectively.
Comment: "let it rip after 2 seconds" - I thought it was 2 seconds too, but when I check it with the clock, it is about 1 second. Anyway, it works when I count in my head to 2.
Answer: Remember that you can charge not only holding back, you can hold diagonals down-back or up-back, so you can charge while defending (down-back) or while jumping back (up-back).
Buffering is your answer as yx01 said, but let I throw some tips against shotos (who spam a lot of fireballs). I had a lot of problems with this in the past.
I'm not a Guile or Street Fighter expert, but versus shotos, don't enter always in a fireball war, you are in a disvantage.
You can always do a neutral jump (up) and let him get tired. Try to move a little closer to you opponent and let him think that you can jump the fireball and hit him. But don't jump always, just show to him that you can do it.
Try to do a neutral jump and hold back after the jump (you are buffering), when you touch the floor, press forward and punch, sonic boom, then walk forward (show no fear). Get ready for another fireball.
If he throw another, you can jump and hit him or defend.
If he block or the sonic boom hits, you can follow a high punch to bug him.
If he jumps, you can use crouching high punch to counter or jump and air-throw.
Keep a good distance for you not to him and poke him to KO.
In (Super) Street Fighter 4 you can use the focus attack (medium kick + medium punch) to get closer as another option. Remember to cancel the focus attack with a dash (forward, forward) after absorve the fireball.
Answer: No, don't try to Fireball game with Guile on Ryu.  You are on the losing side.
You may fireball one or two with Guile, but vs Ryu fireball, you just need to neutral Jump over it, once a while.  Ryu fireball is much faster than you imagined.
Guile SB is not an offensive tool, you should not use it offensively like Ryu.  the SB is just a move for you to trick your opponent to make mistakes.  Like SB then follow with a hard punch if they try fireball war.
and to your answer, the moment Guile squad down, you should be able to fire second SB.

How can I quickly spam charge attacks?


Is this local variable shadowing/hiding another normal or a bug in Visual Studio?

Question: I've greatly simplified this question as the same problem arises in a simpler case:
#include <iostream>

int height;
int main()
{
    std::cout << height; // Visual Studio debugger shows this value as -858993460
    int height;
}

Seems a problem with the debugger displaying the wrong variable value. The variable value is correct, as printing the variable shows the correct global height value, 0.
Comment: Stripped it down further. The global `height` is initialised to zero by the standard.
Answer: You are correct, the global variable height is not shadowed until the declaration of the automatic variable height in the final statement of main().
std::cout << height; will use the global variable height.
Yes, this is confusing the debugger. It's displaying the value of the local height variable, which in a debug build is initialized to 0xCCCCCCCC, or the -858993460 displayed in decimal mode.
The compiler does the correct thing and fetches the global variable height in the first line of the function, it's just the debugger that is confused.
Comment: Yes... I've just found out that it's the debugger which shows the false value of the local. If I std::cout it seems to print the right value. Ohhh, this is so frustrating. I'm sorry. I should delete this question, it's just a misleading Visual Studio debugger thing.
Comment: @Zebrafish: No, it's a good question and one that actually requires you to paste up the image. It might be an idea to simplify further and submit a bug report to MS.
Comment: I agree, I just tried it in VS2017 and it is definitely a bug in the debugger. If you could report the bug to MS that would be great, and keep the question here in case anyone else runs into it.
Comment: @Zebrafish: I've amended the answer to "catch up" with the question edits.
Comment: @MichaelGeary: I've wiki'd this so other folk can freely make edits to the answer, as we all explore how we can best demonstrate this to MS.


Why my session state in MVC4 suddenly loses data?

Question: I was reading in the following page that continualy WindowsAzure recycle store sessions
Why do my instances recycle when trying to store sessions in co-located Azure cache?
This is my webconfig setting:
<sessionState mode="InProc" timeout="2880" />

I was reading that maybe I have to change the Mode to maintain the session alive, because when I'm using the program, suddenly happens that. Let's going to see later than one hour.
What can I do to avoid this bad user experience?
Answer: If you are running multiple instances, then you are losing session data as the load balancer bounces users between instances.  The "InProc" setting stores the session data on each individual instance and NOT across instances - read more.
If you want to use co-located cache then your config should look something like:

<sessionState mode="Custom" customProvider="AFCacheSessionStateProvider">
  <providers>
    <add name="AFCacheSessionStateProvider"
      type="Microsoft.Web.DistributedCache.DistributedCacheSessionStateStoreProvider, Microsoft.Web.DistributedCache"
      cacheName="shared"
      dataCacheClientName="shared"
      applicationName="AFCacheSessionState"/>
  </providers>
</sessionState>

Read more.
UPDATE: Finally, check that you are using a REAL BLOB connection string in your ServiceConfiguration.cscfg file.  If the connection string says "UseDevelopmentStorage=true", the deployed role will never be able to create/connect to the cache - it will work locally in the emulator though.:
<Setting name="Microsoft.WindowsAzure.Plugins.Caching.ConfigStoreConnectionString" value="UseDevelopmentStorage=true" />

Comment: Sorry for the late, but I spend all these days to implemented it. I create a new azure project where includes my MVC Applicacion and also I added a Cache role (as dedicated role). Is there any problem if I'm not using co-located? I reay don't know the difference between them
Comment: Wait a minute! In fact I'm not running multiple instances, my page is using a Shared Mode with just only instance
Comment: See update added above - recycling ache when deployed is a symptom of having the Cache BLOB configurations string set to "UseDevelopmentStorage=true"


Does a Bijective Commutative transformation on a vector of angles exist?

Question: I have a problem where I have two vectors a and b  representing a list of angles.
I need to find a transformation T where T(a,b) = T(b,a), where T has a distance metric to compare two transformations, and that is inversible : I should be able to retrieve a and b (swapped is ok) from T(a,b)
For example:
a+b, cos(a+b), sin(a)+sin(b), cos(a)*cos(b) or any combinations of these qualify
a.b doesn't qualify because I don't have a metric to compare square angles.
a-b doesn't qualify because it is not commutative
Do you think this is possible?
What I have tried that didn't work:
T(a,b) = {cos(a)*cos(b), cos(a)+cos(b), sin(a)*sin(b), sin(a)+sin(b)}
And solve the system for cos(a) cos(b) sin(a) sin(b). However because it is a quadratic equation, I get two solutions and my two arrays a and b are not consistent anymore, I got two new vectors that have either values from a or from b depending when the determinant of the equations reaches zero.
This was just one idea of transformation that was symmetric so it would satisfy my conditions, but I couldn't get back my original vectors.
Thank you!
Answer: Notation convention: the $k$th element of an array, such as $a$, will be denoted with a subscript, as in $a_k$.

... I get two solutions and my two arrays a and b are not consistent anymore, I got two new vectors that have either values from a or from b depending ...

If you're working with functions of the form $c_k=f(a_k,b_k)$ for some symmetric $f$, this is unavoidable. We can swap $a_1$ and $b_1$, leave all of the other $a_k$ and $b_k$ alone, and the $c_k$ will still be the same. Repeat with $d_k=g(a_k,b_k)$ and the same thing happens; adding more functions will never solve the problem.
So then, we need functions that cross over, and use more than one $k$. Here's an idea:
\begin{align*}c_1 = a_1+b_1\quad d_1=\cos(a_1-b_1) &\\
c_2 = a_2+b_2\quad d_2=\cos(a_2-b_2) &\quad e_2=\cos(a_1+a_2-b_1-b_2)\\
c_3 = a_3+b_3\quad d_3=\cos(a_3-b_3) &\quad e_3=\cos(a_1+a_2+a_3-b_1-b_2-b_3)\end{align*}
and so on. By adding in the third vector there, we know how the angle differences combine, and can tell the difference between the likes of $((x,y),(u,v))$ and $((x,v),(y,u))$ since $|x+y-u-v|\neq |x+v-u-y|$ in general.
Comment: This is what was missing!! Thanks a lot!


Why does my dusk to dawn light go off when the furnace kicks in?

Question: My dusk to dawn light goes off whenever my furnace kicks in throughout the night. It obviously comes back on right away, but it takes a minute or so to be fully restored.
What is the reason behind this and how can I fix this?
Comment: Is the light off the whole time the furnace is running, or does it shut off when the furnace starts and then "immediately" come back on? What type of furnace do you have?
Comment: Just initially when the furnace kicks on. I'm not sure what the brand is, but it is a oil furnace...if that helps.
Comment: Any guess on how old the furnace is?
Comment: I'm not 100% sure, but I do know it is fairly old. We have it serviced every year and the tech came out 2 weeks ago to service it and said that it may be time to at least start thinking about a new furnace because there was starting to be some wear and tear with it. Does this help?
Answer: Understanding the problem
Think of your wiring like a pipe full of water, and each device like a pump. Each pump draws a specific amount of water, but not necessarily the same amount as any of the other pumps, and the water in the pipe can only be supplied at a fixed rate.

When the light turns on, it "pumps" a small amount of water from the supply pipe. This amount is far less than the pipes supply rate, so there is no problem.

When the furnace comes on, it "pumps" a huge amount of water (for a short time). This amount is close to, or greater than the amount of water in the supply pipe. This means there is less water in the pipe for the light, so the light cannot function properly.

This is an over simplified, and arguably inaccurate analogy.
Solving the problem
First off, Having the light on the same circuit as the furnace is not correct. This should be fixed as soon as possible, and will likely solve the problem you are seeing.
This could be an indication that one of the components of the furnace is reaching the end of its life, and needs to be serviced.   High current draws in an appliance are commonly caused by motors. Motors will draw more current while starting than they do when they are running, this is known as inrush current and can quite a bit higher than the devices full-load current.  This large current draw during start-up can be increased if additional force is needed to get the motor spinning, for example if the bearings are going bad.  You'll want to inspect the furnace, and pay close attention to any motors.  Make sure they are properly greased, and working normally.
If this has always been an issue all along, the furnace is probably operating normally and there is nothing to worry about.  If this has only become an issue recently, you may want to inspect your furnace (or have a professional inspect it).
Answer: It sounds like they are on the same circuit or you're having some significant power fluctuations in your house.  Both are bad.
The cause is likely that a power "dip" is resetting either then ambient light detector or the light itself (you didn't say what kind it was).
You'd need an DSO (digital storage oscilloscope) on the line to your light to see what power spikes are appearing when the furnace kicks in, but checking the furnace to make sure it's on a dedicated circuit would be a good start.
Comment: Some multimeters have a min/max mode that can be used to monitor a circuit for surges or voltage dips. An oscilloscope might be overkill, especially if you already have a multimeter.
Answer: Maybe the dusk to dawn timer is set to come on at the same o'clock on a serendipitously-synchronized clock as the furnace thermostat clock.
The light turns off in the morning (dawn) at about the time most digital set-back thermostats are set to increase temperature from the overnight set-back temperature (say, 'heat on' from setback 62 deg to 'at home' 69 degrees starting at 5 or 6 or 7 or 8am, depending on when you wake). Typical dusk to dawn timer settings on a simple electro-mechanical timer switch device might be 5:30 or 6 or 7:30am depending on what time dawn is in your region (and in the current season, if someone has adjusted the timer for daylight time shift).
Comment: At its nominal voltage, a US residential 120V AC branch circuit will deliver near infinite current to all connected loads -- including any circuit faults -- until the instantaneous current has exceeded about 10x the breaker rating (15A or 20A, which is plenty to feed a furnace blower and half a house of 100W lightbulbs), or until the continuous current of 15 or 90 minutes has exceeded about 105% or 100%, respectively, of the 15/20A breaker rating. Shared heater blower/control 120V circuit with a lightbulb would cut the light only if the light or the furnace circuit is faulted.


If $A$ and $B$ are independent, when are they conditionally independent on $C$?

Question: This problem comes from Grimmett's Probability and Random Processes Problem 1.5.5.

Suppose that A and B are conditionally independent events given $C$, and they are also
  conditionally independent given $C^c$, and that $0 < P(C) < 1$. Prove that $A$ and $B$ are
  independent if and only if either
  $$ P(A|C) = P(A|C^c) $$
  or
  $$ P(B|C) = P(B|C^c) $$

My attempt:
I was able to show that if $P(A|C)=P(A|C^c)$, then $A$ and $B$ are independent. I did it by using the Partioning Theorem on $A$ and $B$, multiplying $P(A)$ and $P(B)$, and showing that it was equal to $P(A \cap B)$.
The reverse direction has been much more difficult for me. Intuitively, the statement makes sense. If $A$ and $B$ are separately independent and conditionally independent given $C$, then you would expect either $A$ and $C$ or $B$ and $C$ to be independent, but I can't seem to find the formalism. My attempt was to partition the intersection and get the result algebraically:
$$ P(A)P(B) = P(A \cap B) = P(A \cap B | C)P(C) + P(A \cap B | C^c)P(C^c) $$
$$ = \ldots = \left[P(A|C)-P(A|C^c))\right]P(B \cap C) + P(A | C^c)P(B)$$
I'd like to match terms and say that since $P(BC)$ does not appear in $P(A)P(B)$, then $P(A|C)-P(A|C^c)=0$, but I don't think I can formally.
I may be taking the wrong approach (or an unnecessarily complicated approach). I would appreciate it if anyone could drop a hint on this. Thanks!
Answer: To prove that if $A$ and $B$ are independent, then $P(A|C) = P(A|C^c)$ or $P(B|C) = P(B|C^c)$, you take the difference of $P(A \cap B)$ and $P(A)P(B)$ which we know are equal because $A$ and $B$ are independent.
Write $P(A \cap B)$ conditioned on $C$, and use the fact that $A$ and $B$ are conditionally independent on $C$ to write
$$ P(A \cap B) = P(A|C)P(B|C)P(C) + P(A|C^c)P(B|C^c)P(C^c). $$
Next write $P(A)$ and $P(B)$ conditioned on $C$.
$$ P(A)P(B) = \left[P(A|C)P(C)+P(A|C^c)P(C^c)\right]\left[P(B|C)P(C)+P(B|C^c)P(C^c)\right] $$
$$ = P(A|C)P(B|C)P(C)^2 + \left[P(A|C)P(B|C^c)+P(B|C)P(A|C^c)\right]P(C)P(C^c)+P(A|C^c)P(B|C^c)P(C^c)^2 $$
Now we subtract the two
$$ P(A \cap B) - P(A)P(B) = $$
$$ P(A|C)P(B|C)P(C)(1-P(C)) + P(A|C^c)P(B|C^c)P(C^c)(1-P(C^c)) - \left[P(A|C)P(B|C^c)+P(B|C)P(A|C^c)\right]P(C)P(C^c) $$
$$ = P(C)P(C^c)\left[P(A|C)P(B|C)+P(A|C^c)P(B|C^c)-P(A|C)P(B|C^c)-P(B|C)P(A|C^c)\right]$$
$$ = P(C)P(C^c)\left[(P(A|C)-P(A|C^c)(P(B|C)-P(B|C^c))\right] = 0$$
Since $0 < P(C) < 1$, we must have either $P(A|C)=P(A|C^c)$ or $P(B|C)=P(B|C^c)$.
Answer: I think that $A$ and $B$ are conditionally independent on $C$ does not imply that $A$ and $B$ are conditionally independent on the complementary set of $C$,which means that we cannot derive
$P(AB)=P(A|C)P(B|C)P(C)+P(A|C^c)P(B|C^c)P(C^c). C^c$ represents the complimentary set of $C$.
An example is, we toss flip three times, $A=(HHH, THH, HHT), B=(HHH,TTH,HHT,TTT), C=(HHH, HTH, THH,TTH)$, and $C^c=(HHT,HTT,THT,TTT)$.
In this example, $A$ and $B$ are conditionally independent on $C$, but not on the commplement of $C$.


Insulation in the attic : choice between fire retardant and allergenic

Question: This is for a house in Portugal, where most houses have no insulation. I want to insulate the house (it is quite cold in the winter).
The plan is to lay down some isolation material on the floor of the attic. The attic is completely isolated from the rest of the house. The only way to get to it is from the roof. The floor is very thick concrete (80 cm of concrete).
The range of insulation product is fairly limited, because very few people isolate their house in Portugal. I basically have the following choices:

glass wool
rock wool
synthetic material consisting of several layers of aluminium, polyester and polyethylene

Glass wool is out because rock wool appears superior in all respects.
Rock wool is great because it is fire retardant, but I worry that it might cause allergies to people living in the house (I am not worried about the allergy during installation, only for the people using the house).
The synthetic material seems great, but it is very flammable. Insulation quality is not a criterion because it is comparable.
So I basically have to decide on allergy versus fire retardant properties.
Given the very thick slab of concrete, is it reasonable to not worry about the flammable properties of the synthetic product? Maybe I can consider that the concrete will be protection enough? (it is a country where fires are common, due to high temperatures).
For allergies with rock wool, can anyone speak to that risk? Does the fact that the attic is completely closed from the rest of the house, with no window prevent the risk of allergy?
Comment: I don't understand disregarding fiberglass because there's something better. It's the most commonly installed attic insulation in my northern climate (to R-50 or better).
Comment: I suggest limiting your question to that of allergens escaping the attic. "Speaking to risk" is a subjective discussion and not suited for DIYSE.
Comment: @FreeMan There is a **lot** of misinformation, partial information, urban myths, etc. out there about so many things. Has been for a long time - the internet has only accelerated it. I think it is to the credit of the OP that they asked specific questions in a reasonably reliable site rather than relying on hearsay. I'm sure they're not the only one out there unclear about the difference between *allergies* and *irritants* and so forth.
Comment: Doesn't affect my answer, but are you sure about 80 cm? That is 31 inches - we're talking bomb shelter or bank vault thickness. And [an online calculator](https://www.dumpsters.com/resources/concrete-weight-calculator) says that a 200 square foot (which would be a pretty small house) 80 cm thick concrete slab would weigh 19.5 tons! That is a **lot**. Maybe 8 cm?
Comment: I am not entirely sure, no. I know for sure the walls are 80 cm thick, and I assumed the floor therefore would be as thick. Is that an incorrect inference ?
Comment: I have no strong reason to be worried about allergies. I had the impression that this type of material could be allergenic. I guess I am trying to be cautious, and want to ask questions before doing the work. It seems from the answer and your comment that there is no real need to worry about the allergy, but it seems reasonable to worry about the fire risk. I think I'll go with the rock wool then.
Comment: why are you worried about allergies?   Is the attic not sectioned off from your house?   In the US we would normally not be up in an attic without a mask on and would generally be doing work.   I mean some people do have storage there, if that is your case its a big part of your question.
Comment: @DMoore my worry is that even though it is sectioned off, it could leak from the tile and come back down.
Comment: @isherwood I meant to say that between glass wool and rock wool, I would choose rock wool because it seems better, and the cost difference is not significant. So in my particular case, I have excluded glass wool.
Comment: You need to give us a tile picture that your attic can leak from.   That seems a big issue to me.
Comment: @DMoore I meant to say that it's a normal, traditional tiled roof. So there are always a bit of gap. I worry that maybe some particles from the rock wool could escape from the tile and get down over time. Not sure if my worry is overblown though.
Comment: You are worried that insulation will leave your attic and fall outside?   What would that do?
Comment: Sorry, I am not very clear. My worry is that rockwool releases small particules into the air. These particules could escape the attic (I think mainly via the tiles), and then come down in the garden and eventually in the house. I worry this could cause allergies to people living in the house.
Comment: You've got a good answer, but my question for you is why are you worried about an allergic response to _any_ of the insulation materials you are considering? Are any of these materials known to cause allergic reactions? Are any of the residents known to be highly allergic to a wide variety of materials? Until you're fairly confident that allergic reactions are going to be an issue for you/your family/tenants, don't worry about it in _any_ of the materials you're considering for any around-the-house projects.
Answer: TL;DR Don't worry, be happy, use the rock wool.
I am NOT an expert on insulation, so if anyone has better/more complete information, I will defer to them.
As a general rule, allergies have to do with specific organic materials - e.g., pollen - that cause an actual allergic reaction. This is a specific medical term and, as I understand it, allergies are not normally to minerals, synthetic fibers, etc. In other words, I doubt (but I could be wrong) that rock wool can actually cause an allergic reaction.
On the other hand, there are other types of irritants which can cause rashes (contact dermatitis), lung problems (asbestos being the classic example) and other symptoms, many of them quite serious, that are similar to allergies in certain respects. But they are not allergies.
My gut feeling is that none of these 3 choices (fiberglass, rock wool, synthetic insulation) will cause a true allergy, with the possible exception of outgassing of some chemicals used in production of the material. Such outgassing would be, in my opinion, a total non-issue for residents of a building if the materials are installed in a non-accessed attic. Any outgassing would escape through attic vents and dissipate into the atmosphere at very low levels.
Similarly, any particulate matter that comes out from any of these materials would be essentially indistinguishable from ordinary dust and other particles in the air from a variety of sources - soil, automobile exhaust, fireplaces, etc. In addition, properly installed insulation should have almost no loose particulate matter except as part of the initial installation. That initial installation should include cleanup of any loose particles (e.g., with a shop vacuum). The only exception would be if you used loose-fill (e.g., blown in) insulation, which would not be a good idea with these concerns, and in fact is probably best left to totally concealed spaces such as post-construction fill in external walls.
Fire is an issue. Attics get hot. Sometimes very hot. If (I haven't checked the specs) rock wool is significantly more fire retardant than other materials, use the rock wool. While the concrete should provide a lot of protection - hopefully enough for everyone to exit the building safely in the event of an attic fire - there could still be extensive (and expensive) damage. Best to avoid adding fuel to the fire.
But probably every one of these items has a Prop. 65 warning.
Comment: _According to the State of California, **everything** is bad for you, so please stop eating, drinking, and breathing - they'll all kill you_
Comment: Lol, probably true. Life is a lethal sexually transmitted disease after all. Terrible idea to perpetuate it.


KDE Connect: how to reverse opening ports in ufw?

Question: OS: Kubuntu 16.04 LTS
I've managed to use KDE Connect successfully but I have a question about the ufw settings that are required to allow Kubuntu 16.04 to see my Android.
When I installed Kubuntu, one of the first things I did was to activate ufw and this is the terminal output:
sudo ufw status verbose
sudo password for dkbose:
Status: inactive
sudo ufw enable
Firewall is active and enabled on system startup
sudo ufw default deny
Default incoming policy changed to 'deny'
(be sure to update your rules accordingly)

Then, to use KDE Connect, I had to open certain ports as described in https://community.kde.org/KDEConnect:
sudo ufw allow 1714:1764/udp
sudo ufw allow 1714:1764/tcp
sudo ufw reload

My question is this: I will be using KDE Connect rather infrequently. So how can I reverse the opening of the ports each time I've finished using KDE Connect?
Based on what I read in https://help.ubuntu.com/community/UFW, is running
sudo ufw delete allow 1714:1764/udp
sudo ufw delete allow 1714:1764/tcp

the thing to do?
Do I also need to run
sudo ufw reload

to "update" ufw's rules?
I've seen https://askubuntu.com/a/410225/248158 but I'm not sure that answer is applicable to my question.
Answer: Yes, you can remove any rule by inserting delete into the command like you showed.
No, you don't need to reload ufw to apply rules - ufw is not a service, it "just" generates/saves/deletes proper iptables/ip6tables rules.
You can always check the results with
sudo iptables-save | grep 1714
sudo ip6tables-save | grep 1714

Btw: it might be a good idea to restrict the rules to devices on your local network (especially when you are not behind some sort of NAT-router/firewall), I also added a comment to the rules.
sudo ufw allow proto udp from 192.168.1.0/24 to any port 1714:1764 comment 'kdeconnect'
sudo ufw allow proto tcp from 192.168.1.0/24 to any port 1714:1764 comment 'kdeconnect'
sudo ufw allow proto udp from 2a02:xxxx:xxxx:xxxx::/64 to any port 1714:1764 comment 'kdeconnect'
sudo ufw allow proto tcp from 2a02:xxxx:xxxx:xxxx::/64 to any port 1714:1764 comment 'kdeconnect'

You would delete those rules with
sudo ufw delete allow proto udp from 192.168.1.0/24 to any port 1714:1764
sudo ufw delete allow proto tcp from 192.168.1.0/24 to any port 1714:1764
sudo ufw delete allow proto udp from 2a02:8389:187:7000::/64 to any port 1714:1764
sudo ufw delete allow proto tcp from 2a02:8389:187:7000::/64 to any port 1714:1764

(You can omit the comments)
Comment: Could you please extend the IPv6 bit? Maybe do we need to [use `fc00::/8`](https://serverfault.com/a/216611/407820)? Or [`fe80::/64`](https://askubuntu.com/a/887391/349837)? Also, wouldn't be preferable 192.168.0.0/16, to include other probable LAN IPs?
Comment: Adding `fe80::/64` is your LAN (link local addresses) should fix all local machines.  I don't think `192.168.0.0/16` is usefull, as you probably uses a `/24` netmask for your local network.


What's the point in choking enemies in Metal Gear Solid 4?

Question: I've never played any of the Metal Gear Solid games before and I think I've just made the mistake of jumping straight into MGS4 without a clue. It seems that a few minutes after choking out a guard, he gets back up and immediately calls in reinforcements, so I'm wondering what's the point in choking them out in the first place - wouldn't it be better to find another way past an enemy or just outright kill him, and if so, why is there an option to choke them in the first place?
Also, should I even bother playing the game non-lethally during my first playthrough? Is there any way to permanently keep enemies down without killing them or am I playing the game wrong?
Answer: I don't believe there are any overt game bonuses for playing lethally vs. non-lethally, but there are many intangibles based on playthrough.  There are badges you get at the end of the game based on how you played, for instance, whether you destroyed everything in your path or were silent and stealthy.  There are also specific things you can obtain if you defeat certain bosses non-lethally.  (Again, with no actual bonuses.)
It's been a while since I played, but from what I remember, if you put them down non-lethally and got yourself far enough away before they woke up, no help would get called, or at least it would get called to a place I wasn't at.
As to why it's there...it's to let you play in the style you wish.
Comment: Thanks. It also transpires that they only briefly enter Caution after coming to, not Alert (which doesn't seem to be a problem if you've moved on); I've read up on the different types of enemy alert modes now and have a better understanding on it. I do wish this game did a better job of explaining its mechanics - such as a tutorial - though, but maybe that's my problem for not playing the previous games.
Comment: Speaking of which, all the weapons with blue icons are stun weapons.  Some weapons can take both lethal and stun ammo.  I remember not realizing that for a long time.
Comment: There are 'secret items' that can only be aquired through non-lethal play throughs.
Answer:
What's the point in choking enemies in Metal Gear Solid 4?

If you're playing at The Boss Extreme difficulty level and want to do a complete non-lethal run, you will find that the number non-lethal rounds you can carry are very limited and you cannot by them from Drebin. To save them for tougher situations like boss fights, choking 'smaller' enemies is one of the method.

Also, should I even bother playing the game non-lethally during my first playthrough?

If you feel it's too hard, just do a lethal run first. Then if you want to give yourself more challenges, go gradually from easy non-lethal run to The Boss Extreme non-lethal.

Is there any way to permanently keep enemies down without killing them

One way is to do a hold-up in crouch stance (crouch behind the enemy without being noticed, when close enough, equip a weapon and point at him/her [L1 then R1]), then press R1 without moving the Left stick to grab the enemy, after the grab, release and tap R1 while moving the Left stick to any direction, then do an hold-up again. If you success the enemy will lay on the floor face down and will stay in this position unless you trigger an alert phrase. But there are some areas in which this method does not work, mainly the war zones where the PMC and militia are actively fighting each other.

am I playing the game wrong?

Nope. Lethal or non-lethal, it's all up to you. But there exists some rewards which are available only with non-lethal finishes. One of them is the Solar Gun (awarded by finishing the FROG fight and BB fights non-lethally and get the figure they left), which is a very powerful non-lethal weapon and an essential one for getting the Big Boss Emblem.